diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 65912e849d..a035e0324c 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -57,7 +57,7 @@ For UI changes, include a screenshot or short video. diff --git a/.github/workflows/codex.yml b/.github/workflows/codex.yml index b6f8c120b0..61e8233345 100644 --- a/.github/workflows/codex.yml +++ b/.github/workflows/codex.yml @@ -86,7 +86,7 @@ jobs: git diff ${{ fromJSON(steps.meta.outputs.metadata).base_sha }}...${{ fromJSON(steps.meta.outputs.metadata).head_sha }} Focus on, in order of importance: - 1. Correctness and regressions — broken imports, missing protocol symmetry between `provider-swift/Sources/ProviderCore/Protocol/Messages.swift` (Swift) and `coordinator/protocol/messages.go` (Go), release-bundle consistency across `.github/workflows/release-swift.yml` / `scripts/install.sh` / `LatestProviderVersion`, untested edge cases. + 1. Correctness and regressions — broken imports, missing protocol symmetry between `provider-swift/Sources/ProviderCore/Protocol/` (Swift) and `coordinator/protocol/` (Go), release-bundle consistency across `.github/workflows/release-swift.yml` / `scripts/install.sh` / `LatestProviderVersion`, untested edge cases. 2. Security — leaked secrets, skipped attestation or auth, unsafe eval of user input, weakened sandboxing. 3. Test coverage — per CLAUDE.md every non-trivial change ships with a test; bug fixes ship with a regression test. 4. Adherence to project conventions in `CLAUDE.md` and `CONTRIBUTING.md`. diff --git a/AGENTS.md b/AGENTS.md index d3efd79532..6d0fc2b7ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,40 +6,84 @@ Darkbloom is a decentralized private inference network for Apple Silicon Macs. C ```text coordinator/ Go control plane (packages live at top level, not internal/) -├── cmd/coordinator/ main service entrypoint +├── cmd/coordinator/ startup composition and shutdown (main.go); subsystem setup beside it ├── api/ HTTP + WebSocket handlers -│ ├── consumer.go OpenAI-compatible chat/completions/responses + Anthropic messages -│ ├── provider.go provider registration, heartbeats, attestation, relay -│ ├── billing_handlers.go Stripe/referral/pricing endpoints -│ ├── device_auth.go device code flow for linking providers to user accounts +│ ├── inference_ingress.go live request-owner bindings for all four inference endpoints +│ ├── provider.go provider WS upgrade and attestation roster +│ ├── requestauth/ credential middleware, shared API-key cache and linked-user identity +│ ├── authentication.go current credential/store bindings for the router +│ ├── billing/ billing/referral/pricing/payout HTTP controllers and tests +│ ├── billing_controller.go shared service, store, cache and auth bindings +│ ├── catalog/ model publishing, discovery, aliases and their tests +│ ├── catalog_controller.go shared catalog bindings and runtime publication callback +│ ├── inference_dispatch.go current service and observation bindings for dispatch +│ ├── accounts/ key management/policy, provider device login and invites +│ ├── account_controller.go current account-store/config/auth-cache bindings +│ ├── authorization.go shared in-handler admin authorization +│ ├── httprequest/ bounded JSON decoding shared by controllers │ ├── enroll.go MDM enrollment profile generation -│ ├── invite_handlers.go invite code admin/user flows -│ ├── release_handlers.go binary release registration (GitHub Actions integration) -│ ├── chunk_key_cache.go per-request X25519 shared-key memoization for chunk decrypt -│ ├── stats.go public network stats +│ ├── releases/ release HTTP, artifact validation and discovery (Controller) +│ ├── readiness/ shared ingress count, drain control and readiness (Controller) +│ ├── statearchive/ gated state archive download (Controller) +│ ├── admin_auth.go admin authorization and Privy OTP endpoints +│ ├── provider_frames.go shared inference-frame service and live observation bindings +│ ├── network/ public stats, geography, totals, series and leaderboard refresh state +│ ├── accountfleet/ account provider views, earnings summaries and offline removal +│ ├── operations/ operator telemetry reads, bounded queries, CSV/NDJSON exports │ ├── types/ canonical JSON shapes for consumer-facing endpoints -│ └── server.go route wiring, auth middleware, version gate +│ ├── routes.go HTTP/WS route registration and controller middleware chains +│ ├── http_middleware.go global body caps, CORS and panic recovery +│ ├── http_logging.go request IDs, access logs and bounded HTTP metric labels +│ ├── request_rate_limits.go account/key RPM; token_admission.go configures token limiters +│ └── server.go shared server state, construction and lifecycle ├── apns/ APNs-push code-identity attestation ├── attestation/ Secure Enclave + MDA verification ├── auth/ Privy JWT integration ├── billing/ Stripe (deposits + Connect payouts), referrals ├── config/ AppConfig aggregation of per-package configs ├── env/ shared env-var helpers/constants +├── inference/ ingress/ (consumer preparation, media and token/capacity admission), +│ toolpolicy/ (request policy), response/ (endpoint formatting and relays), +│ settlement/ (reservation, refunds and completion accounting), +│ attempt/ (cancellation, terminal policy and provider feedback), +│ dispatch/ (provider preparation, queue/hedge/failover and commit), +│ providerframe/ (accepted/chunk/terminal handling and shared-key cache) ├── mdm/ MicroMDM client + webhook handling ├── payments/ ledger + pricing (+ baserewards/) +├── providercontrol/session/ per-connection frame dispatch, registration, heartbeat and ordered teardown (Session) +├── providercontrol/trustreuse/ durable device evidence, revocation journal/replay and continuity (Manager) +├── providercontrol/challenge/ connection-local nonces, challenge transport and ordered verification (Session, Verifier) +├── providercontrol/mdmscheduler/ durable MDM/MDA queue, claims, worker budget and exact command ownership (Scheduler) +├── providercontrol/verification/ signed registration, reconnect recovery and MDM/MDA evidence checks (Verifier) +├── providercontrol/codeidentity/ code proofs, APNs budgets/nonces, encrypted resume and continuity (Manager) +├── providercontrol/releasepolicy/ active release generations, binary allowlists and runtime manifest (Manager) ├── profilesign/ CMS-signing of .mobileconfig enrollment profiles ├── protocol/ WebSocket message types shared with provider (type_scan.go: single-parse frame decode) ├── ratelimit/ rate limiting ├── registry/ provider registry, queueing, routing, reputation, token-budget admission, -│ warm-pool controller, two-lane provider WS writer (provider_writer.go), +│ warmpool/ (controller, pressure and target policy), +│ providerwriter/ (two-lane WS writer, handoff and watchdog), +│ faultstate/ (identity gates, cooldowns, breaker, ejection and reset history), +│ admission/ (immutable capacity math), providerversion/ (shared interpreter), +│ cacheattempt/ (request lifetime), cachedirectory/ (receipt/holder transactions), +│ modelloads/ (session command clocks and fleet plan gate), +│ dispatchplan/ (private shortlist, quote correlation and probe settlement), +│ routingcost/ (shared latency tuning, calibration and snapshot calculations), │ routingsim/ (trace-driven routing simulation harness) ├── saferun/ panic-safe goroutine runners ├── stateexport/ consistent encrypted archive of MicroMDM (+ legacy step-ca) state (migration) -├── store/ in-memory or Postgres persistence -├── telemetry/ telemetry event emitter (process logs + Datadog forwarding) +├── store/ compatibility facade for persistence +│ ├── contracts/ domain records and small persistence interfaces +│ ├── memory/ one-lock development/test backend +│ ├── postgres/ durable domain operations, pool and gated backfills +│ │ └── schema/ ordered startup DDL +│ └── cache/ bounded user/model lookup decorator +├── telemetry/ event emitter, metrics/, profiler/, routequeue/, profilequeue/, outcomequeue/ ├── datadog/ Datadog APM / DogStatsD / Logs API client ├── deploy/ container entrypoint (start.sh) -└── internal/e2e/ X25519 request-encryption helpers (+ cross-compat/tamper tests) +└── internal/ + ├── e2e/ X25519 request-encryption helpers (+ cross-compat/tamper tests) + └── inferencefixture/ shared test-only request bodies and independent estimator e2e/ System-level E2E testing framework ├── integration_test.go 14 E2E tests (streaming, billing, encryption, attestation, etc.) @@ -101,6 +145,8 @@ docs/ how-tos, runbooks, reference, architecture, design records model registration (register-model.yml) ``` +Coordinator startup: `coordinator/cmd/coordinator/main.go` (`main`) keeps resource creation and shutdown order visible. Setup functions live in `storage.go`, `registry.go`, `serving.go`, `routing_admission.go`, `routing_deadlines.go`, `rate_limits.go`, `release_policy.go`, `accounts.go`, `provider_trust.go`, `profiling.go`, `prompt_contract.go` and `background.go` in that same command package. See [the startup sequence and source map](docs/architecture/components/coordinator.md#startup-sequence). + ## Current Surface Area - Coordinator HTTP routes include `POST /v1/chat/completions`, `POST /v1/responses`, `POST /v1/completions`, `POST /v1/messages`, `GET /v1/models`, `GET /v1/models/capacity`, billing/pricing endpoints, invite flows, stats, enrollment, device authorization, and release registration endpoints. @@ -109,7 +155,7 @@ docs/ how-tos, runbooks, reference, architecture, design records - Billing logic is split between `coordinator/payments` (ledger + pricing) and `coordinator/billing` (Stripe, referrals). - Providers serve text inference through the Swift `darkbloom` CLI with continuous batching via MLX-Swift. - Model registry data is DB-backed in the coordinator and points to R2 manifests under `https://models.darkbloom.ai`; model bytes are not hardcoded in the provider or UI. -- Streaming hot path: provider frames are decoded in a single parse (`coordinator/protocol/type_scan.go` scans the `type` key; malformed input falls back to a full envelope decode); per-request X25519 shared keys are memoized for chunk decryption and forgotten on request terminal (`coordinator/api/chunk_key_cache.go`); all writes to a provider WebSocket go through a two-lane writer (`coordinator/registry/provider_writer.go`) with a per-connection write watchdog — control frames (challenges, cancels, trust status) take strict (non-preemptive) priority over data frames, FIFO holds only within a lane, and `WriteText` blocks until the frame is on the wire. +- Streaming hot path: provider frames are decoded in a single parse (`coordinator/protocol/type_scan.go` scans the `type` key; malformed input falls back to a full envelope decode); per-request X25519 shared keys are memoized for chunk decryption and forgotten on request terminal (`coordinator/inference/providerframe/chunk_keys.go`); all writes to a provider WebSocket go through a two-lane owner (`coordinator/registry/providerwriter/`, bound by `coordinator/registry/provider_writer.go`) with a per-connection write watchdog — control frames (challenges, cancels, trust status) take strict (non-preemptive) priority over data frames, FIFO holds only within a lane, and `WriteText` blocks until the frame is on the wire. - Observability: Datadog metrics (DogStatsD) for attestation, routing, billing, fleet version, and provider capacity. X-Timing header decomposes per-request latency. ## Building And Testing @@ -197,7 +243,7 @@ Dev coordinator deploy (Google Cloud): see `docs/operations/dev-environment.md`. ## Important Sync Points -- Protocol changes must be mirrored in both `provider-swift/Sources/ProviderCore/Protocol/` and `coordinator/protocol/messages.go`. +- Protocol changes must be mirrored in both `provider-swift/Sources/ProviderCore/Protocol/` and `coordinator/protocol/`. - Telemetry wire types live in three places and MUST stay aligned: - `coordinator/protocol/telemetry.go` (canonical), - `provider-swift/Sources/ProviderCore/Telemetry/` (Swift mirror), @@ -221,7 +267,7 @@ Dev coordinator deploy (Google Cloud): see `docs/operations/dev-environment.md`. - Store selection (`cmd/coordinator/main.go`): the coordinator uses the **Postgres** store whenever `EIGENINFERENCE_DATABASE_URL` is set (prod does — durable across restarts/deploys), and refuses to start without it unless `EIGENINFERENCE_ALLOW_MEMORY_STORE=true`. The in-memory store is the dev/test fallback only (state lost on restart). Note: the live provider *registry* (WebSocket connections/attestation) is always in-process and is rebuilt on reconnect regardless of store. - Request queue timeout is 120 seconds. Initial attestation challenge is sent immediately on registration, then every 5 minutes. - Backend idle timeout is 1 hour (not 10 minutes as some comments may say). -- `handleChunk` never silently drops streamed chunks: when a consumer's chunk buffer is full it gets one 250ms grace window (`chunkOverflowGrace`), then the request is failed with 499 and the provider's generation is cancelled. +- `Service.Chunk` (`coordinator/inference/providerframe/chunk.go`) never silently drops streamed chunks: when a consumer's chunk buffer is full it gets one 250ms grace window (`chunkOverflowGrace`), then the request is failed with 499 and the provider's generation is cancelled. - `hypervisor_active` is retired (#492): current providers no longer send it, but `AttestationResponseMessage.HypervisorActive` and the canonical-status support must keep decoding so signed payloads from older (< v0.6.31) providers still verify. Remove only once the fleet version floor passes v0.6.31. ### Coordinator State Model — Multiple Overlapping Views @@ -231,22 +277,22 @@ Provider state lives in several fields that are read by different code paths wit - `BackendCapacity.Slots` is **authoritative** for the scheduler when present (Swift providers). The scheduler derives `slotState`, `modelLoaded`, token budgets, and observed TPS from it. `WarmModels` is only a fallback for legacy providers without `BackendCapacity`. - `WarmModels` is updated by heartbeats. It is NOT consulted by `snapshotProviderLocked` or `buildCandidateWithReason` when `BackendCapacity` is non-nil. `TriggerModelSwaps` / `hasWarmProviderLocked` checks it as a fallback, and `/v1/me/providers` copies it into API responses. - `CurrentModel` is set from heartbeat `active_model`. A nil/omitted `active_model` means no model is loaded. Stale `CurrentModel` can cause attestation hash mismatches. -- `pendingModelLoads` is checked by `TriggerModelSwaps` planning, cold-spill eligibility (`registry/cold_dispatch.go`), and the warm-pool controller's target math. It is NOT checked by `QuickCapacityCheck`, `ReserveProviderEx`, or `freeMemoryAdmits` — do not assume pending-load state affects routing admission. +- `modelLoads` (`registry/modelloads/Commands`) is checked by `TriggerModelSwaps` planning, cold-spill eligibility (`registry/cold_dispatch.go`), and the warm-pool controller's target math. It is NOT checked by `QuickCapacityCheck`, `ReserveProviderEx`, or `freeMemoryAdmits` — do not assume pending-load state affects routing admission. - Provider-reported slot states include `"running"` (active requests), `"idle"` (loaded, no requests), `"crashed"`, `"reloading"`, and `"idle_shutdown"`. The `"idle"` state means the model IS loaded — treat it the same as `"running"` for warm detection, not as `"unknown"`. - Providers can hold up to `maxModelSlots` models simultaneously (default 3). Do not assume a model swap evicts all other models. -- The provider's memory model is `UnifiedMemoryCap` (`provider-swift/Sources/ProviderCore/Inference/Memory/UnifiedMemoryCap.swift`): hard cap = 0.90 × physical RAM (always leaving ≥ 2 GiB for the OS; `DARKBLOOM_MEM_CAP_FRACTION` override). The model-load gate requires resident weights + incoming weights + headroom (the resolved activation reserve plus 1 GiB minimum KV) ≤ the cap, and a post-load guard unloads a freshly-loaded model whose measured live KV headroom is below the minimum serveable KV. The weights figure at EVERY admit-time gate (load gate, pending-load reservation, startup preload, doctor, and the coordinator's `reportedFreeForLoadAdmits`) is the scanner's padded estimate (disk × 1.2) for every model — the padding covers the LOAD TRANSIENT (shard staging exceeds steady residency). Measured post-load residency lives only in the coordinator's `servabilityMeasuredResidentGiB` (text-only artifacts; canonical values re-measured per engine release, see docs/reports/2026-08-30-activation-floor-measurements.md) and feeds only `coldTokenBudgetEstimate` — the POST-load token-budget arithmetic that converges to warm reports. The `DARKBLOOM_ACTIVATION_RESERVE_GB` env override is **raise-only against the resolved floor**; only programmatic `activationReserveBytes` values (tests) are honored as given. -- The activation reserve inside that cap resolves **per serving set** (≥ the per-model release): `resolvedActivationReserveBytes(modelIDs:)` takes the max over advertised ∪ resident ∪ loading models of each member's **measured floor** (`measuredActivationFloorsBytes`, exact catalog-id match) with the flat 5.5 GiB default for any unmeasured member — so one unmeasured model pins the default, and vision-capable models deliberately have NO measured floor until a vision-inclusive peak is measured (the tower transient rides this reserve; text-decode evidence alone must not lower it). The resolved reserve threads through the load gate, `KVHeadroomProbe`, `GlobalKVCacheBudget` (epoch-stamped pushes — cross-actor delivery is not FIFO), engine KV grants, the heartbeat clamp, `free_for_load_gb`, and doctor **in lockstep**; a consumer left on the flat figure re-creates the admit-then-fail class this design removed. `coordinator/registry/servability.go` mirrors both tables (`servabilityActivationFloorGB` default + `servabilityModelActivationFloorsGB`, selected per (version, model) by `servabilityActivationFloor`; regimes: 3 GiB pre-0.8.0/unknown, flat 5.5 for 0.8.0 ≤ v < `servabilityPerModelFloorMinVersion`, per-model table above it — fail-open toward the larger legacy budget). **The provider table and the coordinator mirror must move in the same commit**, floors and measured weights alike; retuning either side alone silently desyncs admission (the historical score-tensor surcharge incident). A per-SHAPE/formula reserve remains banned on both sides — floors are measured constants, never modelled; the measurement convention must include a ≥ 4k-token B=8 cell (short-prompt cells under-measure the saturated envelope — see `docs/reports/2026-08-30-activation-floor-measurements.md`). +- The provider's memory model is `UnifiedMemoryCap` (`provider-swift/Sources/ProviderCore/Inference/Memory/UnifiedMemoryCap.swift`): hard cap = 0.90 × physical RAM (always leaving ≥ 2 GiB for the OS; `DARKBLOOM_MEM_CAP_FRACTION` override). The model-load gate requires resident weights + incoming weights + headroom (the resolved activation reserve plus 1 GiB minimum KV) ≤ the cap, and a post-load guard unloads a freshly-loaded model whose measured live KV headroom is below the minimum serveable KV. The weights figure at EVERY admit-time gate (load gate, pending-load reservation, startup preload, doctor, and the coordinator's `reportedFreeForLoadAdmits`) is the scanner's padded estimate (disk × 1.2) for every model — the padding covers the LOAD TRANSIENT (shard staging exceeds steady residency). Measured post-load residency lives only in the coordinator's `servabilityMeasuredResidentGiB` (`coordinator/registry/admission/model_memory.go`) (text-only artifacts; canonical values re-measured per engine release, see docs/reports/2026-08-30-activation-floor-measurements.md) and feeds only `admission.Policy.ColdTokenBudgetEstimate` — the POST-load token-budget arithmetic that converges to warm reports. The `DARKBLOOM_ACTIVATION_RESERVE_GB` env override is **raise-only against the resolved floor**; only programmatic `activationReserveBytes` values (tests) are honored as given. +- The activation reserve inside that cap resolves **per serving set** (≥ the per-model release): `resolvedActivationReserveBytes(modelIDs:)` takes the max over advertised ∪ resident ∪ loading models of each member's **measured floor** (`measuredActivationFloorsBytes`, exact catalog-id match) with the flat 5.5 GiB default for any unmeasured member — so one unmeasured model pins the default, and vision-capable models deliberately have NO measured floor until a vision-inclusive peak is measured (the tower transient rides this reserve; text-decode evidence alone must not lower it). The resolved reserve threads through the load gate, `KVHeadroomProbe`, `GlobalKVCacheBudget` (epoch-stamped pushes — cross-actor delivery is not FIFO), engine KV grants, the heartbeat clamp, `free_for_load_gb`, and doctor **in lockstep**; a consumer left on the flat figure re-creates the admit-then-fail class this design removed. `coordinator/registry/admission/model_memory.go` mirrors both tables (`servabilityActivationFloorGB` default + `servabilityModelActivationFloorsGB`, selected per (version, model) by `Policy.ActivationFloor`; regimes: 3 GiB pre-0.8.0/unknown, flat 5.5 for 0.8.0 ≤ v < `servabilityPerModelFloorMinVersion`, per-model table above it — fail-open toward the larger legacy budget). **The provider table and the coordinator mirror must move in the same commit**, floors and measured weights alike; retuning either side alone silently desyncs admission (the historical score-tensor surcharge incident). A per-SHAPE/formula reserve remains banned on both sides — floors are measured constants, never modelled; the measurement convention must include a ≥ 4k-token B=8 cell (short-prompt cells under-measure the saturated envelope — see `docs/reports/2026-08-30-activation-floor-measurements.md`). ### Coordinator Mutation Checklist When adding code that mutates provider state or sends commands (`load_model`, etc.): -1. Enumerate every reader of the fields you're mutating (`BackendCapacity.Slots`, `WarmModels`, `CurrentModel`, `pendingModelLoads`). +1. Enumerate every reader of the fields you're mutating (`BackendCapacity.Slots`, `WarmModels`, `CurrentModel`, `modelLoads`). 2. Check what happens on the failure path — does state get cleaned up on disconnect, timeout, and load failure? 3. Check concurrent access — heartbeats arrive per-provider on separate goroutines; `TriggerModelSwaps` can race with `drainQueuedRequestsForModels`. 4. Check the cleanup path — `Disconnect()` must clear any per-provider state you add. 5. Verify pre-existing invariants: `maxModelSlots`, heartbeat field omission semantics (`nil` vs empty), and the `UnifiedMemoryCap` load gate on the provider side. -6. **Store read-through cache** (`store/cached.go`): `CachedStore` serves `GetUserByAccountID`/`GetUserByPrivyID` and `GetModelRegistryRecord`/`GetModelManifest` from memory and invalidates on the store mutators it overrides. Any NEW `store.Store` method that writes the `users` table or the model-registry tables must be overridden in `CachedStore` to invalidate its domain, or callers read stale data for up to the TTL. Backend-only capabilities discovered by type assertion must go through `store.As` (the decorator implements `Unwrap`). +6. **Store read-through cache** (`store/cache/store.go`): `CachedStore` serves `GetUserByAccountID`/`GetUserByPrivyID` and `GetModelRegistryRecord`/`GetModelManifest` from memory and invalidates on the store mutators it overrides. Any NEW `store.Store` method that writes the `users` table or the model-registry tables must be overridden in `CachedStore` to invalidate its domain, or callers read stale data for up to the TTL. Backend-only capabilities discovered by type assertion must go through `store.As` (the decorator implements `Unwrap`). ## Code Structure & Modularity diff --git a/CHANGELOG.md b/CHANGELOG.md index 67344c5229..b8ca0d98b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,6 @@ - Capture SDK 27 Apple-signed CodeDirectory measurements and require an exact qualified binary/code-hash pair for prospective build approval. Release builds and their provider tests select SDK 27 / Swift 6.4 and record the full CodeDirectory SHA-256; missing or unsupported measurements stay unknown. macOS can identify the exact code without a bundle-version extension. - Forward the latest distinct per-model warm-pool planning snapshot through the coordinator telemetry emitter so Datadog can show target sizing, measured demand, candidate availability and blocker counts. Keep provider identities and request data out of the event. - ## v0.9.3 — App Attest shadow rollout and provider reliability (2026-09-14) Source changes since `v0.9.2`. App Attest remains observational, with APNs and MDM authoritative. @@ -36,6 +35,13 @@ coordinator deployment. #### Coordinator +- **Provider retry forecasts** — Preserve the 30-second retry ceiling for very large provider availability forecasts by bounding milliseconds before rounding. Ordinary retry rounding and the two-second floor are unchanged. + +- **Speculative terminal ordering** — Keep a healthy speculative attempt running when the other provider fails before content. Closed chunk streams inspect their queued error before cancelling the other attempt, so the primary or backup can still complete within the original first-content budget. + +- **Capacity and admission** — Model readiness honors public routing gates while retaining inventory and the fleet-wide health-breaker fallback. Expired capacity probes settle as timeouts; oversized prompt/output sums are rejected without integer wrapping. +- **Throughput and fleet observations** — Reject overflowing occupancy reports from the solo-rate sample pool, read fleet version gauges under the provider lock, and ignore unusable throughput anomaly measurements. Non-finite anomaly overrides retain their defaults. +- **Reconnect verification** — Keep the replacement connection's verification binding when an earlier SecurityInfo attempt finishes checking a cached MDA proof or has no MDA UDID. - **Qwen prompt parity** — Match the provider's Qwen-family handling of required and named tool calls, including catalog aliases and Qwen3-VL, to avoid mismatched thinking controls in cache proofs. - **Repeated-prefix routing** — Prefer a stable cache-capable provider for repeated prefixes only among otherwise equivalent cost, queue and pending-work candidates. Exclude capabilities quarantined after a failed cache proof from this preference, even when heartbeats continue advertising them. Revalidate at reservation and rescan if affinity eligibility changed after selection. Preserve ordinary serving when no unfenced cache candidate is available, along with capacity, deadline, trust and proof gates. Profiler rows identify this preference as `prefix_affinity`. - **Cache opportunity diagnostics** — Report per-model reasons and numerical counts for repeated-prefix demand, usable holders and routing selection. These diagnostics distinguish routing opportunities from actual cache hits and measured latency savings. Add a [consumer guide](docs/consumer/prefix-cache.md) for preserving shared prompt prefixes. @@ -57,23 +63,57 @@ coordinator deployment. - Add negotiated App Attest shadow enrollment and fresh connection assertions, with independent certificate/policy verification, durable counters, and coverage/latency observations. APNs and MDM remain authoritative; shadow success or failure changes no routing, trust, payments, or supported OS floor. - Keep the CLI and app launch flow; add profile-authorized App Attest signing alongside APNs in release and validation workflows. Actual macOS 27 acceptance requires the final signed app on physical hardware. - Accept macOS Developer ID profiles granting only the App Attest CDhash opt-in, including array grants. Preserve existing APNs/keychain entitlements; validate the attested environment on the coordinator even when the optional environment entitlement is absent. +## Unreleased — sweep payout ownership + +- Preserve newer completed payouts when an old automatic sweep failure arrives concurrently. Reopen withdrawals only while the stored paid state still belongs to that exact sweep, without moving ledger funds. ## Unreleased +- **Withdrawal progress ownership** — Preserve newer Stripe withdrawal payment/refund state when a delayed submission response arrives. Compare progress atomically, recognize an already-applied retry, and ask clients to check history after a concurrent update instead of overwriting it. + +- **Remote media recovery** — Release shared byte-budget reservations when a media reader panics, allowing sibling workers to finish and the request to fail instead of hanging. + +- Prevent simultaneous inference requests from exceeding account or API-key token quotas through separate availability checks and charges. Extra output-token reconciliation shares the admission lock, and retry-hint checks no longer consume quota. + +- **Coordinator capacity and admission** — Model readiness honors public routing gates while retaining inventory and the fleet-wide health-breaker fallback. Expired capacity probes settle as timeouts; oversized prompt/output sums are rejected without integer wrapping. +- **Coordinator settings** — Reject non-finite warm-pool and quality-admission values before serving. Ignore non-finite prompt-calibration overrides and bound oversized calibrated estimates before integer conversion. + +- **Inclusive metric buckets** — Count latency samples equal to a histogram upper bound in that bucket. A 5 ms observation now contributes to the 5 ms cumulative bucket in JSON and Prometheus output. + +- **Geolocation failure logs** — Omit the PRO lookup URL and its API key from transport-error diagnostics while retaining the underlying failure cause. + +- Reject generic inference requests with 400 when `n` times the per-choice output token limit exceeds the supported integer range, before token quotas, billing reservations or routing. Ordinary requests retain their existing output limits and admission policy. + +- Keep each streamed reasoning and message item limited to its own text when item types alternate. Completed items and the final output no longer repeat text from earlier items; token usage is unchanged. + +- Ignore inference completions received before provider registration, keeping the WebSocket available for registration instead of closing it through a nil-pointer panic. + +- Return a server error before changing model aliases when namespace, rollout-history or build validation reads fail. Preserve existing alias ownership and retired-build lineage through transient store errors. + +- **Prompt artifact provisioning** — Snapshot catalog file lists and the configured download origin, validate every manifest before sharing a download, and remove read-only staging trees after another cache instance wins publication. + +- **API-key mutation consistency** — Prevent delayed authentication lookups from restoring revoked keys, old limits, or stale disabled-key results after a successful local key update. Keep already-authenticated requests and the ordinary cache lifetime for other coordinator processes unchanged. + +- Keep runtime-hash verification and manifest responses consistent during concurrent release-policy updates. Publish owned immutable hash sets, preserve the active-release union, and serialize fallback merges with live-provider revalidation. + +- Return 500 from uncached public model list, retrieve and OpenRouter feeds when the alias inventory cannot be read, instead of caching missing aliases or advertising hidden builds. Successful feed cache lifetimes remain unchanged. + +- **Model quantization metadata** — Map decorated labels consistently: `bfloat16-gs64` remains `bf16`. Prefer the earliest recognized format, then the longest spelling at that position (`q4-bfloat16` maps to `int4`), so repeated model-list requests cannot change precision metadata with map iteration order. + +- Preserve replacement MDM verification claims, cancellation and retry state when a retired worker finishes after a reconnect. Each attempt now settles only its own claim token, and stale store reads cannot overwrite a newer queued retry. +- Preserve a provider reconnect's verification binding when the prior connection finishes its cached Apple proof check or a missing-UDID fallback. Live and late SecurityInfo grants now share the same generation-aware MDA follow-up. + +- Clear cached prices after a successful local update or deletion, and prevent delayed lookups from restoring the prior rate. Keep existing in-flight work and other coordinator processes' normal cache lifetimes. + - Dev coordinator boot now uses the same validated environment writer as deploys. Failed critical-secret or metadata downloads preserve the existing configuration instead of overwriting it with empty values. -## Unreleased - Provider installation retains the previous app or legacy bundle if restoring it after a failed swap also fails. The installer reports the recovery path instead of deleting the only backup or claiming successful restoration. - Installer downloads use private temporary files and remove incomplete downloads on failure. -## Unreleased - Provider releases use the same profile and signed CLI entitlement checks as signing validation, rejecting unrelated app identities and missing profile expiry before publication. Release registration encodes quoted and multiline tag text as JSON data. -## Unreleased - **Contributor guidance** — Issue forms and the PR template reference the current components, provider commands and review requirements. Go dependency update checks use the repository's root module. -## Unreleased - Model publishing stops before uploads on failed or empty R2 credential reads. Rollback preparation validates registry inputs before copying objects, cleans its local staging on exit, and reaches promotion on macOS Bash. -## Unreleased - The cache soak monitor stops after an interrupt or termination signal and counts cache markers once when log lines arrive across multiple writes. @@ -98,6 +138,7 @@ compatibility checks and outstanding runtime qualification. ### Companion coordinator and console changes +- **Concurrent duplicate-provider detection** — Read each provider's immutable attestation snapshot under its mutex before comparing device serials, so duplicate scans do not race attestation renewal. Matching duplicates still disconnect through the existing cleanup path. - **Warm-pool headroom** — Grow warm replicas from measured headroom before a failed request, using measured occupancy growth, per-model headroom limits and bounded load bursts. Requires a coordinator deployment; the provider release does not activate this policy. - **Earnings navigation** — Keep earnings accessible after removing all linked Macs and display the supported payout-coverage notice. Requires a console deployment. @@ -141,8 +182,19 @@ coordinator and console changes require their own deployments. - **Incoming request accounting** — Add an unsampled request-outcome ledger and bounded admin inspection with explicit coverage and completion evidence. Record recovered HTTP errors and parsed streaming mode, and distinguish completed, incomplete and error response terminals after successful writes while preserving contradictory evidence and earlier content progress. - **Partial network geography** — Keep the stats overview available when request-location or route analytics time out. Refresh geography independently, expose unavailable sections, preserve valid empty maps and restore geography after recovery. +## Unreleased — public model datacenters + +- Exclude private-only self-route providers from public model datacenter countries. Model counts and country metadata now share the same provider eligibility check. + +- Serialize a full transfer-reversal refund with payout completion. Recheck the current withdrawal under its store lock and commit principal/fee refunds with the terminal state, preventing a stale webhook read from refunding an already-paid withdrawal. A failed transaction leaves both balances and withdrawal state unchanged. + +- Credit each Stripe Checkout payment once per account even when its local billing-session metadata is absent or completion bookkeeping fails. Serialize repeated credits across coordinator store connections while preserving non-withdrawable deposits and existing withdrawal refunds. Index ledger identity lookups for large accounts while retaining long-reference support. + ## Unreleased — stats request-flow refresh +- Preserve newer withdrawal settlements when an older instant-payout failure arrives concurrently; payout ownership is rechecked in the store transition. +- Commit invite redemption and balance credit together, so a failed credit leaves the code available for retry. + - Restore Stats refreshes on large usage windows by aggregating request origins before looking up provider locations. Preserve weighted coordinates, request/token counts, and the top-50 flow limit while avoiding large temporary sorts. ## Unreleased — provider console entry diff --git a/CLAUDE.md b/CLAUDE.md index ff814f98c9..2a41454360 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,19 +7,28 @@ Darkbloom is a decentralized private inference network for Apple Silicon Macs. C ``` coordinator/ Go control plane (packages live at top level, not internal/) ├── cmd/coordinator/ main service entrypoint -├── api/ HTTP + WebSocket handlers (consumer.go, provider.go, billing_handlers.go, device_auth.go, invite_handlers.go, release_handlers.go, enroll.go, stats.go, server.go, chunk_key_cache.go, types/) +├── api/ HTTP + WebSocket handlers (consumer.go, provider.go, billing/, billing_controller.go, requestauth/, authentication.go, accounts/, account_controller.go, authorization.go, httprequest/, releases/, statearchive/, readiness/, admin_auth.go, enroll.go, stats.go, server.go, provider_frames.go, operations/, types/) ├── apns/ APNs-push code-identity attestation ├── attestation/ Secure Enclave + MDA attestation verification ├── auth/ Privy JWT verification + user provisioning ├── billing/ Stripe (deposits + Connect payouts), referral system ├── config/ AppConfig aggregation of per-package configs ├── env/ Shared env-var helpers/constants +├── inference/ toolpolicy/, response/, dispatch/, attempt/, settlement/, providerframe/ +│ (request policy, response, dispatch, cancellation, accounting, provider frames) ├── mdm/ MicroMDM integration for device attestation ├── payments/ Internal ledger, pricing tables, base rewards +├── providercontrol/session/ per-connection frame dispatch, registration, heartbeat and ordered teardown (Session) +├── providercontrol/challenge/ connection-local nonces, challenge transport and ordered verification (Session, Verifier) +├── providercontrol/mdmscheduler/ durable MDM/MDA queue, claims, worker budget and exact command ownership (Scheduler) +├── providercontrol/verification/ signed registration, reconnect recovery and MDM/MDA evidence checks (Verifier) +├── providercontrol/codeidentity/ per-device code proofs, APNs budgets/nonces and encrypted resume (Manager) +├── providercontrol/releasepolicy/ active release policy, binary allowlists and runtime manifest (Manager) ├── profilesign/ CMS-signing of .mobileconfig enrollment profiles ├── protocol/ WebSocket message types shared with provider (type_scan.go: single-parse frame decode) ├── ratelimit/ Rate limiting -├── registry/ Provider registry, queueing, routing, reputation, token-budget admission, +├── registry/ Provider registry, queueing, routing, reputation, admission/ capacity math, +│ providerversion/ interpretation, token-budget admission, │ warm-pool controller, two-lane provider WS writer (provider_writer.go), routingsim/ ├── saferun/ Panic-safe goroutine runners ├── stateexport/ Consistent encrypted archive of MicroMDM (+ legacy step-ca) state (migration) @@ -78,6 +87,8 @@ docs/ How-tos, runbooks, reference, architecture, design records The `.external/` directory is reserved for local external checkouts and **must never be committed to d-inference**. The current Swift provider uses in-process MLX, not a vllm-mlx subprocess. +Coordinator startup composition and subsystem setup live in `coordinator/cmd/coordinator/`. `main.go` (`main`) retains resource lifetimes and shutdown; see [the startup sequence and source map](docs/architecture/components/coordinator.md#startup-sequence). + ## Building & Testing ### Coordinator (Go) @@ -210,7 +221,7 @@ CI (`.github/workflows/release-swift.yml`) builds, signs, notarizes, and uploads - **Idle GPU timeout**: Loaded model state is released after 1 hour of no requests to free GPU memory. Lazy-reloaded when the next request arrives. Coordinator can also push `load_model` messages to pre-warm providers. - **Hop-by-hop encryption**: consumer → coordinator is TLS plus optional NaCl Box sealing (`application/eigeninference-sealed+json`); coordinator → provider is a mandatory per-request NaCl Box to the provider's attested X25519 key; provider → coordinator response chunks are encrypted back. The coordinator decrypts consumer bodies in confidential-VM memory for routing and billing and does not log or retain them; the sealed request is decrypted only inside the hardened provider process. Do not write "the coordinator never sees plaintext" — see `docs/architecture/security/encryption.md`. - **Attestation chain**: Secure Enclave P-256 key (persistent, keychain access group bound) → signs attestation blob → coordinator verifies signature (self_signed) → MDM SecurityInfo cross-check (hardware trust) → Apple Enterprise Attestation Root CA signs device cert chain via MDA (mda_verified). `GET /v1/providers/attestation` exposes only privacy-redacted trust status; hardware serials, UDIDs, and raw Apple certificates stay private to providers and the coordinator. -- **Protocol symmetry**: `provider-swift/Sources/ProviderCore/Protocol/` and `coordinator/protocol/messages.go` define the same WebSocket message types. Changes to one must be mirrored in the other. +- **Protocol symmetry**: `provider-swift/Sources/ProviderCore/Protocol/` and `coordinator/protocol/` define the same WebSocket message types. Changes to one must be mirrored in the other. - **Model registry**: Coordinator registry data is DB-backed and points to R2 manifests. The Swift provider downloads the files listed in the manifest from `https://models.darkbloom.ai` and verifies per-file plus aggregate SHA-256. Do not reintroduce hardcoded model catalog lists. - **Billing**: Stripe Checkout deposits credit an internal micro-USD ledger (`coordinator/payments`); Stripe Connect handles provider payouts/withdrawals. Referral system gives referrers a share of platform fees; base rewards live in `payments/baserewards`. (Solana deposits/payouts were removed; the BIP39 mnemonic env var now only derives the coordinator's X25519 encryption key.) - **Request queue**: When all providers are busy, requests queue with 120s timeout. Frontend shows "providers are busy" on 503. 429 with Retry-After returned when fleet is at capacity. @@ -218,7 +229,7 @@ CI (`.github/workflows/release-swift.yml`) builds, signs, notarizes, and uploads - **Challenge timing**: Initial attestation challenge sent immediately on provider registration, then every 5 minutes via ticker. - **Model scan performance**: `ModelScanner` does fast discovery without hashing. Weight hash computed on-demand via `WeightHasher.computeHash(for:)` only for models that need attestation/verification. - **Vision prefill is per-image**: Qwen3-VL's tower attends over whatever it is handed as one sequence with an N×N intermediate, so `EngineV2VisionTowerRun` drives it once per image and evaluates each before building the next. Batching a request's images made peak device memory quadratic in the image count and asked Metal for buffers many times `MTLDevice.maxBufferLength`, which MLX's default `fatalError` handler turned into a dead daemon. `VisionTowerBudget` predicts that peak from the processor's grids and the model's own vision config (the N² multiple is 1 when MLX fuses the head dim, `numHeads` when it falls back to `[1, H, N, N]` scores); the prefill runs under `MLX.withError`, whose handler records and returns — so every `eval` site checks the box rather than relying on the block-exit check. -- **Streaming hot path**: provider frames are decoded in a single parse (`coordinator/protocol/type_scan.go`, envelope-decode fallback); per-request X25519 shared keys are memoized for chunk decrypt and forgotten on request terminal (`api/chunk_key_cache.go`); provider WebSocket writes go through a two-lane writer (`registry/provider_writer.go`) — control frames (challenges, cancels) take strict non-preemptive priority over data frames, FIFO within a lane only, `WriteText` blocks to wire completion. A full consumer chunk buffer gets one 250ms grace window, then the request fails with 499 — chunks are never silently dropped. +- **Streaming hot path**: provider frames are decoded in a single parse (`coordinator/protocol/type_scan.go`, envelope-decode fallback); per-request X25519 shared keys are memoized for chunk decrypt and forgotten on request terminal (`coordinator/inference/providerframe/chunk_keys.go`); provider WebSocket writes go through a two-lane writer (`registry/provider_writer.go`) — control frames (challenges, cancels) take strict non-preemptive priority over data frames, FIFO within a lane only, `WriteText` blocks to wire completion. A full consumer chunk buffer gets one 250ms grace window, then the request fails with 499 — chunks are never silently dropped. - **Device auth**: RFC 8628 device code flow for linking provider machines to user accounts. Provider runs `login`, gets a code, user enters it on the web. - **CI code signing**: GitHub Actions release workflow signs provider binary with Developer ID Application cert, notarizes with Apple, computes SHA-256 hashes after signing. Provisioning profile embedded in .app bundle for persistent SE key. - **Observability**: Datadog DogStatsD metrics for attestation, routing, billing, fleet version, provider capacity. X-Timing JSON header decomposes per-request latency (parse, reserve, route, queue, encrypt, dispatch, provider). @@ -241,7 +252,7 @@ Always think from first principles. When fixing a bug or designing a feature: ## Common Pitfalls -- Protocol changes require updating both `provider-swift/Sources/ProviderCore/Protocol/` (Swift) AND `coordinator/protocol/messages.go` (Go). They must stay in sync. +- Protocol changes require updating both `provider-swift/Sources/ProviderCore/Protocol/` (Swift) AND `coordinator/protocol/` (Go). They must stay in sync. - Telemetry wire types are mirrored in three places: `coordinator/protocol/telemetry.go`, `provider-swift/Sources/ProviderCore/Telemetry/`, and `console-ui/src/lib/telemetry-types.ts`. The field allowlist (`coordinator/api/telemetry_handlers.go`) is the privacy backstop — never add prompt/completion fields. See `docs/architecture/telemetry.md`. - Attestation minimum-requirement checks (Secure Enclave, SIP, Secure Boot) run sequentially and each overwrites `result.Error` — last failure wins. `AuthenticatedRootEnabled` (ARV) is informational only: logged, not enforced. - Store selection (`cmd/coordinator/main.go`): the coordinator uses the **Postgres** store whenever `EIGENINFERENCE_DATABASE_URL` is set (prod does), and refuses to start without it unless `EIGENINFERENCE_ALLOW_MEMORY_STORE=true`. The in-memory store is the dev/test fallback only (state lost on restart). The live provider *registry* (WebSocket connections/attestation) is always in-process and rebuilt on reconnect regardless of store. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ce5360b3e2..979a64502d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -110,7 +110,7 @@ Comments: explain *why*, not *what*. Don't add comments that just restate what t Several surfaces have to stay in sync. If you touch one, check the others: -- **WebSocket protocol**: `provider-swift/Sources/ProviderCore/Protocol/Messages.swift` (Swift) ↔ `coordinator/protocol/messages.go` (Go) ↔ [`docs/reference/protocol-messages.md`](docs/reference/protocol-messages.md). +- **WebSocket protocol**: `provider-swift/Sources/ProviderCore/Protocol/Messages.swift` (Swift) ↔ `coordinator/protocol/` (Go) ↔ [`docs/reference/protocol-messages.md`](docs/reference/protocol-messages.md). - **Provider bundle**: `.github/workflows/release-swift.yml`, canonical `scripts/install.sh`, its generated embed at `coordinator/api/install.sh` (kept identical by `scripts/sync-install-embed.sh`), and the version pair diff --git a/README.md b/README.md index a6a78f604e..caf475c38e 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ flowchart TB CHAL -.-> HW ``` -Providers carry one of three trust levels, surfaced on provider-committed responses via the `X-Provider-Trust-Level` header (alongside `X-Provider-Attested`, `X-Provider-Encrypted`, `X-Provider-Chip`, and `X-Provider-Secure-Enclave`). Pre-commit validation and capacity errors have no selected provider and no provider headers. `POST /v1/chat/completions` can copy the committed header fields into a JSON `metadata` object when the caller sets `metadata_details: true` (or `X-Darkbloom-Metadata-Details: true`). The same object also includes region/country GeoIP of the serving provider (`metadata.location`; not a header; no city, coordinates, lookup source, or raw IPs). See [`dispatch.go:3371-3379`](coordinator/api/dispatch.go#L3371-L3379) and [`response_metadata.go:209-276`](coordinator/api/response_metadata.go#L209-L276). +Providers carry one of three trust levels, surfaced on provider-committed responses via the `X-Provider-Trust-Level` header (alongside `X-Provider-Attested`, `X-Provider-Encrypted`, `X-Provider-Chip`, and `X-Provider-Secure-Enclave`). Pre-commit validation and capacity errors have no selected provider and no provider headers. `POST /v1/chat/completions` can copy the committed header fields into a JSON `metadata` object when the caller sets `metadata_details: true` (or `X-Darkbloom-Metadata-Details: true`). The same object also includes region/country GeoIP of the serving provider (`metadata.location`; not a header; no city, coordinates, lookup source, or raw IPs). See [`commit.go`](coordinator/inference/dispatch/commit.go) (`writeCommittedResponse`) and [`provider_snapshot.go`](coordinator/inference/response/provider_snapshot.go) (`WriteCommittedProviderHeaders`). | Level | Verification | |-------|--------------| diff --git a/console-ui/src/components/payouts/payout-copy.test.ts b/console-ui/src/components/payouts/payout-copy.test.ts index 084468a5a0..342a7ea319 100644 --- a/console-ui/src/components/payouts/payout-copy.test.ts +++ b/console-ui/src/components/payouts/payout-copy.test.ts @@ -137,7 +137,7 @@ describe("classifyOnboardError", () => { describe("classifyDashboardError", () => { // Codes must match the coordinator's existing payout vocabulary - // (stripe_payouts.go / stripe_withdraw.go), not a parallel spelling. + // in coordinator/api/billing/connect_dashboard.go and connect_withdraw.go. it("stripe_account_gone: unlink message + status refresh", () => { const p = classifyDashboardError(new ApiError("your Stripe account no longer exists", "stripe_account_gone", 409)); expect(p.message).toContain("Your Stripe account was closed, so we've unlinked it"); diff --git a/console-ui/src/components/payouts/payout-copy.ts b/console-ui/src/components/payouts/payout-copy.ts index 26ce3b3c86..7a857e28b6 100644 --- a/console-ui/src/components/payouts/payout-copy.ts +++ b/console-ui/src/components/payouts/payout-copy.ts @@ -1,8 +1,9 @@ // User-facing copy for the Stripe payouts flow: maps backend error codes, // withdrawal statuses, and withdraw responses to friendly messages. // -// Backend error codes come from coordinator/api/stripe_withdraw.go and -// stripe_payouts.go via the { error: { type, message, code } } envelope, +// Backend error codes come from coordinator/api/billing/connect_withdraw.go, +// connect_onboarding.go and connect_dashboard.go via the +// { error: { type, message, code } } envelope, // which lib/api/errors.ts parses into ApiError. Keep the code list here in // sync with the coordinator handlers. diff --git a/coordinator/api/account_controller.go b/coordinator/api/account_controller.go new file mode 100644 index 0000000000..1146753564 --- /dev/null +++ b/coordinator/api/account_controller.go @@ -0,0 +1,23 @@ +package api + +import ( + "github.com/eigeninference/d-inference/coordinator/api/accounts" +) + +// Device code constants remain available to existing coordinator integrations. +const ( + DeviceCodeExpiry = accounts.DeviceCodeExpiry + DeviceCodePollInterval = accounts.DeviceCodePollInterval +) + +// accountController binds stateless account operations to current router services. +// Routes retain one controller; store, console URL and admin policy stay live. +func (s *Server) accountController() *accounts.Controller { + return accounts.New(accounts.Dependencies{ + Store: func() accounts.Store { return s.store }, + Logger: s.logger, + ConsoleURL: func() string { return s.consoleURL }, + KeyCache: s.requestAuth, + AuthorizeAdmin: s.requireAdminKey, + }) +} diff --git a/coordinator/api/account_controller_test.go b/coordinator/api/account_controller_test.go new file mode 100644 index 0000000000..f04b15b0f2 --- /dev/null +++ b/coordinator/api/account_controller_test.go @@ -0,0 +1,69 @@ +package api + +import ( + "encoding/json" + "net/http" + "testing" + + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Controller extraction must preserve the runtime bindings that existing tests +// and server wiring can replace after NewServer registers its routes. +func TestAccountControllerUsesCurrentBindings(t *testing.T) { + srv, original := newKeyTestServer(t) + t.Cleanup(srv.Close) + user := &store.User{AccountID: "account-binding-user", PrivyUserID: "did:privy:account-binding", Email: "account-admin@example.com"} + if err := original.CreateUser(user); err != nil { + t.Fatal(err) + } + session := privySession(t, srv, original, user) + handler := srv.Handler() + + t.Run("current store", func(t *testing.T) { + replacement := store.NewMemory(store.Config{}) + srv.store = replacement + w := authContractRequest(t, handler, http.MethodPost, "/v1/keys", session, `{"name":"current-store"}`, http.StatusOK) + var created types.CreateAPIKeyResponse + if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil { + t.Fatal(err) + } + if _, err := replacement.AuthenticateKey(created.Key); err != nil { + t.Fatalf("created key was not written to the current store: %v", err) + } + oldKeys, err := original.ListAPIKeys(user.AccountID) + if err != nil || len(oldKeys) != 0 { + t.Fatalf("route wrote to old store: keys=%d, err=%v", len(oldKeys), err) + } + }) + + t.Run("current console URL", func(t *testing.T) { + for _, console := range []string{"https://console-one.example/", "https://console-two.example"} { + srv.consoleURL = console + w := authContractRequest(t, handler, http.MethodPost, "/v1/device/code", "", "", http.StatusOK) + var got struct { + VerificationURI string `json:"verification_uri"` + } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + want := console + if want[len(want)-1] == '/' { + want = want[:len(want)-1] + } + if got.VerificationURI != want+"/link" { + t.Fatalf("verification URI = %q, want current console %q", got.VerificationURI, want+"/link") + } + } + }) + + t.Run("current admin policy", func(t *testing.T) { + // The outer auth middleware already accepts this session. It is the + // controller's in-handler authorization that must see these changes. + srv.SetAdminEmails([]string{user.Email}) + authContractRequest(t, handler, http.MethodGet, "/v1/admin/invite-codes", session, "", http.StatusOK) + srv.SetAdminEmails(nil) + authContractRequest(t, handler, http.MethodGet, "/v1/admin/invite-codes", session, "", http.StatusForbidden) + }) +} diff --git a/coordinator/api/account_fault_key_test.go b/coordinator/api/account_fault_key_test.go index 72f6be2c6b..58b079bb12 100644 --- a/coordinator/api/account_fault_key_test.go +++ b/coordinator/api/account_fault_key_test.go @@ -38,7 +38,7 @@ func TestAccountLinkedFaultStateSurvivesReconnect(t *testing.T) { const acct = "acct-open-mode" const rawToken = "eigeninference-pt-account-fault-key-test" if err := st.CreateProviderToken(&store.ProviderToken{ - TokenHash: sha256Hash(rawToken), + TokenHash: store.HashKey(rawToken), AccountID: acct, Active: true, }); err != nil { diff --git a/coordinator/api/account_fleet.go b/coordinator/api/account_fleet.go new file mode 100644 index 0000000000..252e0d211e --- /dev/null +++ b/coordinator/api/account_fleet.go @@ -0,0 +1,19 @@ +package api + +import ( + "github.com/eigeninference/d-inference/coordinator/api/accountfleet" + "github.com/eigeninference/d-inference/coordinator/api/readcache" +) + +func (s *Server) newAccountFleet() *accountfleet.Controller { + return accountfleet.New(accountfleet.Dependencies{ + Store: func() accountfleet.Store { return s.store }, + Registry: func() accountfleet.Registry { return s.registry }, + Cache: func() *readcache.Cache { return s.readCache }, + MinVersion: func() string { return s.minProviderVersion }, + LatestVersion: s.latestReleasedVersion, + RequireUser: s.requirePrivyUser, + VersionLess: semverLess, + Logger: s.logger, + }) +} diff --git a/coordinator/api/account_fleet_idle_policy_test.go b/coordinator/api/account_fleet_idle_policy_test.go new file mode 100644 index 0000000000..e518b49d9d --- /dev/null +++ b/coordinator/api/account_fleet_idle_policy_test.go @@ -0,0 +1,80 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/eigeninference/d-inference/coordinator/attestation" + "github.com/eigeninference/d-inference/coordinator/protocol" +) + +// The owner's dashboard needs the idle-memory policy to render a missing +// slot as "sleeping, wakes on demand" (free-when-idle) rather than as a +// warning. The heartbeat value is surfaced per live machine; 0 (always +// ready) must not be collapsed into "absent". +func TestMyProvidersSurfacesIdleUnloadPolicy(t *testing.T) { + srv, st := newKeyTestServer(t) + seedProviderRecord(t, st, "live-p", "SER-IDLE", "acct-1") + + // A linked, attested live connection — heartbeats persist the live + // provider back to the store, so it must carry the owner's account. + live := srv.registry.Register("live-p", nil, &protocol.RegisterMessage{}) + live.SetAttestationResult(&attestation.VerificationResult{SerialNumber: "SER-IDLE"}) + live.Mu().Lock() + live.AccountID = "acct-1" + live.Mu().Unlock() + + fetch := func(stage string) map[string]any { + t.Helper() + r := reqWithUser(http.MethodGet, "/v1/me/providers", "", "acct-1") + w := httptest.NewRecorder() + srv.accountFleet.Providers(w, r) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String()) + } + var resp struct { + Providers []map[string]any `json:"providers"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + for _, p := range resp.Providers { + if p["id"] == "live-p" { + return p + } + } + t.Fatalf("[%s] live-p missing from response: %s", stage, w.Body.String()) + return nil + } + + // Before any heartbeat reports a policy: omitted, not defaulted. + if _, ok := fetch("initial")["idle_unload_mins"]; ok { + t.Fatal("idle_unload_mins present before the provider reported one") + } + + zero := 0 + srv.registry.Heartbeat("live-p", &protocol.HeartbeatMessage{ + Type: protocol.TypeHeartbeat, Status: "idle", IdleUnloadMins: &zero, + }) + if got := fetch("zero")["idle_unload_mins"]; got != float64(0) { + t.Fatalf("idle_unload_mins = %v, want 0 (always ready)", got) + } + + sixty := 60 + srv.registry.Heartbeat("live-p", &protocol.HeartbeatMessage{ + Type: protocol.TypeHeartbeat, Status: "idle", IdleUnloadMins: &sixty, + }) + if got := fetch("sixty")["idle_unload_mins"]; got != float64(60) { + t.Fatalf("idle_unload_mins = %v, want 60", got) + } + + // A legacy-shaped heartbeat (no field) keeps the last reported policy. + srv.registry.Heartbeat("live-p", &protocol.HeartbeatMessage{ + Type: protocol.TypeHeartbeat, Status: "idle", + }) + if got := fetch("legacy")["idle_unload_mins"]; got != float64(60) { + t.Fatalf("idle_unload_mins after legacy heartbeat = %v, want 60 (sticky)", got) + } +} diff --git a/coordinator/api/account_fleet_removal_test.go b/coordinator/api/account_fleet_removal_test.go new file mode 100644 index 0000000000..1fb6aa1aef --- /dev/null +++ b/coordinator/api/account_fleet_removal_test.go @@ -0,0 +1,233 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/attestation" + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// seedProviderRecord persists a provider record for the delete tests. +func seedProviderRecord(t *testing.T, st *store.MemoryStore, id, serial, accountID string) { + t.Helper() + if err := st.UpsertProvider(context.Background(), store.ProviderRecord{ + ID: id, + SerialNumber: serial, + AccountID: accountID, + LastSeen: time.Now(), + }); err != nil { + t.Fatalf("seed provider record: %v", err) + } +} + +type deleteProviderResp struct { + Deleted bool `json:"deleted"` + RowsRemoved int `json:"rows_removed"` +} + +func TestDeleteMyProvider_OwnerSucceeds(t *testing.T) { + srv, st := newKeyTestServer(t) + seedProviderRecord(t, st, "p1", "SER-1", "acct-1") + + r := reqWithUser(http.MethodDelete, "/v1/me/providers/p1", "", "acct-1") + r.SetPathValue("id", "p1") + w := httptest.NewRecorder() + srv.accountFleet.DeleteProvider(w, r) + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String()) + } + var resp deleteProviderResp + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if !resp.Deleted || resp.RowsRemoved != 1 { + t.Fatalf("resp = %+v, want deleted=true rows_removed=1", resp) + } + if strings.Contains(w.Body.String(), "SER-1") || strings.Contains(w.Body.String(), `"serial"`) { + t.Fatalf("delete response exposed serial data: %s", w.Body.String()) + } + + if rec, _ := st.GetProviderBySerial(context.Background(), "SER-1"); rec != nil { + t.Fatal("record still present after delete") + } + recs, _ := st.ListProvidersByAccount(context.Background(), "acct-1") + if len(recs) != 0 { + t.Fatalf("account still has %d records after delete", len(recs)) + } +} + +func TestDeleteMyProvider_CrossAccount403(t *testing.T) { + srv, st := newKeyTestServer(t) + seedProviderRecord(t, st, "p1", "SER-1", "acct-1") + + r := reqWithUser(http.MethodDelete, "/v1/me/providers/p1", "", "acct-2") + r.SetPathValue("id", "p1") + w := httptest.NewRecorder() + srv.accountFleet.DeleteProvider(w, r) + + if w.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403: %s", w.Code, w.Body.String()) + } + if rec, _ := st.GetProviderBySerial(context.Background(), "SER-1"); rec == nil { + t.Fatal("record was deleted by a non-owner") + } +} + +func TestDeleteMyProvider_Anon401(t *testing.T) { + srv, st := newKeyTestServer(t) + seedProviderRecord(t, st, "p1", "SER-1", "acct-1") + + r := httptest.NewRequest(http.MethodDelete, "/v1/me/providers/p1", nil) + r.SetPathValue("id", "p1") + w := httptest.NewRecorder() + srv.accountFleet.DeleteProvider(w, r) + + if w.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want 401: %s", w.Code, w.Body.String()) + } +} + +func TestDeleteMyProvider_NotFound404(t *testing.T) { + srv, _ := newKeyTestServer(t) + + r := reqWithUser(http.MethodDelete, "/v1/me/providers/NOPE", "", "acct-1") + r.SetPathValue("id", "NOPE") + w := httptest.NewRecorder() + srv.accountFleet.DeleteProvider(w, r) + + if w.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404: %s", w.Code, w.Body.String()) + } +} + +func TestDeleteMyProvider_OnlineConflict409(t *testing.T) { + srv, st := newKeyTestServer(t) + seedProviderRecord(t, st, "previous-p", "SER-ON", "acct-1") + + // A reconnect has a distinct session ID. Register asynchronously persists + // its initially unlinked row, so it must not overwrite the owned historical + // row this request deletes. Matching the serial must still yield 409. + live := srv.registry.Register("live-p", nil, &protocol.RegisterMessage{}) + live.SetAttestationResult(&attestation.VerificationResult{SerialNumber: "SER-ON"}) + + r := reqWithUser(http.MethodDelete, "/v1/me/providers/previous-p", "", "acct-1") + r.SetPathValue("id", "previous-p") + w := httptest.NewRecorder() + srv.accountFleet.DeleteProvider(w, r) + + if w.Code != http.StatusConflict { + t.Fatalf("status = %d, want 409: %s", w.Code, w.Body.String()) + } + if rec, err := st.GetProviderRecord(context.Background(), "previous-p"); err != nil || rec == nil || rec.AccountID != "acct-1" || rec.SerialNumber != "SER-ON" { + t.Fatalf("owned historical record changed despite 409: rec=%+v err=%v", rec, err) + } + if srv.registry.GetProvider("live-p") != live { + t.Fatal("live connection was removed despite 409") + } +} + +// TestDeleteMyProvider_MultiRowSameSerial verifies all rows sharing a serial +// (one per reconnect session) are removed in a single call. +func TestDeleteMyProvider_MultiRowSameSerial(t *testing.T) { + srv, st := newKeyTestServer(t) + seedProviderRecord(t, st, "a", "SER-D", "acct-1") + seedProviderRecord(t, st, "b", "SER-D", "acct-1") + + r := reqWithUser(http.MethodDelete, "/v1/me/providers/a", "", "acct-1") + r.SetPathValue("id", "a") + w := httptest.NewRecorder() + srv.accountFleet.DeleteProvider(w, r) + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String()) + } + var resp deleteProviderResp + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.RowsRemoved != 2 { + t.Fatalf("rows_removed = %d, want 2", resp.RowsRemoved) + } +} + +func TestMyProvidersRedactsDeviceIdentity(t *testing.T) { + srv, st := newKeyTestServer(t) + attestationJSON, err := json.Marshal(attestation.VerificationResult{ + SerialNumber: "PRIVATE-SERIAL", + PublicKey: "se-public-key", + }) + if err != nil { + t.Fatalf("marshal attestation: %v", err) + } + certJSON, err := json.Marshal([][]byte{[]byte("identity-bearing-leaf")}) + if err != nil { + t.Fatalf("marshal cert chain: %v", err) + } + if err := st.UpsertProvider(context.Background(), store.ProviderRecord{ + ID: "opaque-provider-id", + AccountID: "acct-1", + SerialNumber: "PRIVATE-SERIAL", + AttestationResult: attestationJSON, + MDACertChain: certJSON, + LastSeen: time.Now(), + }); err != nil { + t.Fatalf("seed provider record: %v", err) + } + + r := reqWithUser(http.MethodGet, "/v1/me/providers", "", "acct-1") + w := httptest.NewRecorder() + srv.accountFleet.Providers(w, r) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String()) + } + for _, secret := range []string{ + "PRIVATE-SERIAL", + "identity-bearing-leaf", + `"serial_number"`, + `"mda_serial"`, + `"mda_udid"`, + `"mda_cert_chain_b64"`, + } { + if strings.Contains(w.Body.String(), secret) { + t.Fatalf("provider dashboard response leaked %q: %s", secret, w.Body.String()) + } + } + if !strings.Contains(w.Body.String(), `"id":"opaque-provider-id"`) { + t.Fatalf("provider response omitted opaque id: %s", w.Body.String()) + } +} + +// TestDeleteMyProvider_RouteWiring exercises the real HTTP path through +// srv.Handler() to catch routing/middleware mistakes (Go 1.22+ method+pattern +// precedence vs the literal GET /v1/me/providers route). +func TestDeleteMyProvider_RouteWiring(t *testing.T) { + srv, st := newKeyTestServer(t) + seedProviderRecord(t, st, "p1", "SER-W", "acct-1") + + ts := httptest.NewServer(srv.Handler()) + defer ts.Close() + + // Unauthenticated request (no Privy token) — requirePrivyAuth must reject it + // without ever reaching the handler. We assert the route resolves to a + // non-404, non-405 status (auth rejection), proving the DELETE pattern is + // registered and distinct from GET /v1/me/providers. + req, err := http.NewRequest(http.MethodDelete, ts.URL+"/v1/me/providers/p1", nil) + if err != nil { + t.Fatalf("new request: %v", err) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("do request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusMethodNotAllowed { + t.Fatalf("DELETE route not wired: status = %d", resp.StatusCode) + } +} diff --git a/coordinator/api/account_fleet_test.go b/coordinator/api/account_fleet_test.go new file mode 100644 index 0000000000..ba85d7d33c --- /dev/null +++ b/coordinator/api/account_fleet_test.go @@ -0,0 +1,131 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Drive the registered Privy routes after changing the dependencies they use. +// Provider removal must consult the current fleet and write the current store. +func TestAccountFleetRoutesUseCurrentBindings(t *testing.T) { + srv, original := newKeyTestServer(t) + t.Cleanup(srv.Close) + user := &store.User{AccountID: "fleet-binding-account", PrivyUserID: "did:privy:fleet-binding", StripeAccountStatus: "ready"} + if err := original.CreateUser(user); err != nil { + t.Fatal(err) + } + session := privySession(t, srv, original, user) + handler := srv.Handler() + call := func(method, path string, wantStatus int) []byte { + t.Helper() + r := httptest.NewRequest(method, path, nil) + r.Header.Set("Authorization", "Bearer "+session) + w := httptest.NewRecorder() + handler.ServeHTTP(w, r) + if w.Code != wantStatus { + t.Fatalf("%s %s: %d %s", method, path, w.Code, w.Body.String()) + } + return w.Body.Bytes() + } + seed := func(st *store.MemoryStore, amount int64, version string) { + t.Helper() + if err := st.RecordProviderEarning(&store.ProviderEarning{ + AccountID: user.AccountID, ProviderID: "fleet-machine", JobID: "binding-job", AmountMicroUSD: amount, + }); err != nil { + t.Fatal(err) + } + if err := st.SetRelease(&store.Release{Version: version, Platform: defaultReleasePlatform, Active: true}); err != nil { + t.Fatal(err) + } + } + readSummary := func(wantMoney int64, wantLatest, wantMinimum string, wantTotal, wantAttention int) { + t.Helper() + var body struct { + AccountID string `json:"account_id"` + PayoutReady bool `json:"payout_ready"` + LifetimeMoney int64 `json:"lifetime_micro_usd"` + Latest string `json:"latest_provider_version"` + Minimum string `json:"min_provider_version"` + Counts struct { + Total int `json:"total"` + Attention int `json:"needs_attention"` + } `json:"counts"` + } + if err := json.Unmarshal(call(http.MethodGet, "/v1/me/summary", http.StatusOK), &body); err != nil { + t.Fatal(err) + } + if body.AccountID != user.AccountID || !body.PayoutReady || body.LifetimeMoney != wantMoney || body.Latest != wantLatest || body.Minimum != wantMinimum || body.Counts.Total != wantTotal || body.Counts.Attention != wantAttention { + t.Fatalf("summary retained an old dependency or lost the authenticated user: %+v", body) + } + } + seed(original, 111, "1.1.0") + srv.SetMinProviderVersion("1.0.0") + readSummary(111, "1.1.0", "1.0.0", 0, 0) + + replacement := store.NewMemory(store.Config{}) + seed(replacement, 222, "2.2.0") + srv.store = replacement + srv.readCache = newTTLCache() + readSummary(222, "2.2.0", "1.0.0", 0, 0) + + fleet := registry.New(srv.logger) + p := fleet.Register("fleet-machine", nil, &protocol.RegisterMessage{Version: "1.5.0"}) + p.Mu().Lock() + p.AccountID = user.AccountID + p.Version = "1.5.0" + p.Status = registry.StatusOnline + p.TrustLevel = registry.TrustHardware + p.Attested = true + p.RuntimeVerified = true + p.Mu().Unlock() + srv.registry = fleet + readSummary(222, "2.2.0", "1.0.0", 1, 0) + srv.SetMinProviderVersion("2.0.0") + readSummary(222, "2.2.0", "2.0.0", 1, 1) + var providers struct { + Providers []struct { + ID string `json:"id"` + } `json:"providers"` + } + if err := json.Unmarshal(call(http.MethodGet, "/v1/me/providers", http.StatusOK), &providers); err != nil { + t.Fatal(err) + } + if len(providers.Providers) != 1 || providers.Providers[0].ID != p.ID { + t.Fatalf("provider route retained its previous fleet: %+v", providers) + } + + windows := store.AccountEarningsWindows{Last24hMicroUSD: 777, Last7dMicroUSD: 888} + cached, err := json.Marshal(windows) + if err != nil { + t.Fatal(err) + } + srv.readCache.Set("me:summary:windows:"+user.AccountID, cached, time.Minute) + var summary struct { + Last24h int64 `json:"last_24h_micro_usd"` + Last7d int64 `json:"last_7d_micro_usd"` + } + if err := json.Unmarshal(call(http.MethodGet, "/v1/me/summary", http.StatusOK), &summary); err != nil { + t.Fatal(err) + } + if summary.Last24h != 777 || summary.Last7d != 888 { + t.Fatalf("summary did not use the current shared cache: %+v", summary) + } + + if err := replacement.UpsertProvider(context.Background(), store.ProviderRecord{ID: p.ID, AccountID: user.AccountID}); err != nil { + t.Fatal(err) + } + call(http.MethodDelete, "/v1/me/providers/"+p.ID, http.StatusConflict) + srv.registry = registry.New(srv.logger) + call(http.MethodDelete, "/v1/me/providers/"+p.ID, http.StatusOK) + if records, err := replacement.ListProvidersByAccount(context.Background(), user.AccountID); err != nil || len(records) != 0 { + t.Fatalf("offline provider remained in the current store: records=%+v err=%v", records, err) + } +} diff --git a/coordinator/api/account_helpers_test.go b/coordinator/api/account_helpers_test.go new file mode 100644 index 0000000000..975b571230 --- /dev/null +++ b/coordinator/api/account_helpers_test.go @@ -0,0 +1,46 @@ +package api + +import ( + "context" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" + "github.com/eigeninference/d-inference/coordinator/auth" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func newKeyTestServer(t *testing.T) (*Server, *store.MemoryStore) { + t.Helper() + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + srv := NewServer(registry.New(logger), st, ServerConfig{}, logger) + return srv, st +} + +// reqWithUser builds a request whose context carries an authenticated user, +// simulating what requirePrivyAuth installs (so we can unit-test the handlers +// without minting a real Privy JWT). +func reqWithUser(method, target, body, accountID string) *http.Request { + var r *http.Request + if body == "" { + r = httptest.NewRequest(method, target, nil) + } else { + r = httptest.NewRequest(method, target, strings.NewReader(body)) + } + ctx := context.WithValue(r.Context(), auth.CtxKeyUser, &store.User{AccountID: accountID}) + ctx = requestcontext.WithAccountID(ctx, accountID) + return r.WithContext(ctx) +} + +func withUser(ctx context.Context, accountID, email string) context.Context { + return context.WithValue(ctx, auth.CtxKeyUser, &store.User{ + AccountID: accountID, + Email: email, + }) +} diff --git a/coordinator/api/account_models.go b/coordinator/api/account_models.go new file mode 100644 index 0000000000..38cfd2a5d9 --- /dev/null +++ b/coordinator/api/account_models.go @@ -0,0 +1,36 @@ +package api + +import ( + "net/http" + "sort" +) + +// handleMySelfRouteModels returns the model ids a self-route(-only) key for +// this account can list and use — the same alias-aware owned live-model view +// GET /v1/models serves to self-route-only keys. The console's API-key picker +// consumes this so the ids it saves into a key's allow-list are exactly the +// ids clients will later see and request: aliases for catalog builds, raw ids +// for off-catalog local models. Deriving the list client-side from raw +// provider advertisements produced allow-lists holding hidden build ids that +// then rejected the listed alias (keyModelAllowed checks the requested name +// before alias resolution). Centralizing here also keeps the eligibility +// filter (freshness, runtime verification, private-text support, owner +// weight-hash servability) in one place instead of three. +func (s *Server) handleMySelfRouteModels(w http.ResponseWriter, r *http.Request) { + user := s.requirePrivyUser(w, r) + if user == nil { + return + } + entries := s.catalogController().OwnedModelEntries(user.AccountID, false) + models := make([]string, 0, len(entries)) + for _, e := range entries { + models = append(models, e.ID) + } + sort.Strings(models) + writeJSON(w, http.StatusOK, selfRouteModelsResponse{Models: models}) +} + +// selfRouteModelsResponse is the GET /v1/me/self-route-models payload. +type selfRouteModelsResponse struct { + Models []string `json:"models"` +} diff --git a/coordinator/api/account_usage.go b/coordinator/api/account_usage.go new file mode 100644 index 0000000000..b10c3975e2 --- /dev/null +++ b/coordinator/api/account_usage.go @@ -0,0 +1,61 @@ +package api + +import ( + "fmt" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/payments" +) + +// handleBalance handles GET /v1/payments/balance. +// Returns the consumer's current balance in both micro-USD and USD. +func (s *Server) handleBalance(w http.ResponseWriter, r *http.Request) { + consumerKey := consumerKeyFromContext(r.Context()) + balance := s.ledger.Balance(consumerKey) + withdrawable := s.store.GetWithdrawableBalance(consumerKey) + + writeJSON(w, http.StatusOK, types.BalanceResponse{ + BalanceMicroUSD: balance, + BalanceUSD: fmt.Sprintf("%.6f", float64(balance)/1_000_000), + WithdrawableMicroUSD: withdrawable, + WithdrawableUSD: fmt.Sprintf("%.6f", float64(withdrawable)/1_000_000), + }) +} + +// handleUsage handles GET /v1/payments/usage. +// Returns the consumer's inference usage history with per-request costs. +// Tries in-memory ledger first (has full detail), falls back to store +// ledger history (persists across restarts but has less detail). +func (s *Server) handleUsage(w http.ResponseWriter, r *http.Request) { + consumerKey := consumerKeyFromContext(r.Context()) + entries := s.ledger.Usage(consumerKey) + + // If in-memory usage is empty (coordinator restarted), build from + // the persisted usage table which has full request details. + if len(entries) == 0 { + usageRecords := s.store.UsageByConsumer(consumerKey) + for _, u := range usageRecords { + jobID := u.RequestID + if jobID == "" { + jobID = u.ProviderID + } + model := u.Model + if u.PublicModel != "" { + model = u.PublicModel + } + entries = append(entries, payments.UsageEntry{ + JobID: jobID, + Model: model, + PromptTokens: u.PromptTokens, + CompletionTokens: u.CompletionTokens, + CostMicroUSD: u.CostMicroUSD, + Timestamp: u.CreatedAt, + }) + } + } + + writeJSON(w, http.StatusOK, types.UsageResponse{ + Usage: entries, + }) +} diff --git a/coordinator/api/accountfleet/controller.go b/coordinator/api/accountfleet/controller.go new file mode 100644 index 0000000000..55c81be6ba --- /dev/null +++ b/coordinator/api/accountfleet/controller.go @@ -0,0 +1,43 @@ +// Package accountfleet owns the account's provider dashboard: persisted and +// live machine views, earnings summaries, reputation and offline removal. +package accountfleet + +import ( + "log/slog" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/readcache" + "github.com/eigeninference/d-inference/coordinator/store" + "golang.org/x/sync/singleflight" +) + +// Dependencies preserves the API's current bindings, authenticated user and +// version policy without exposing its server or unrelated state. +type Dependencies struct { + Store func() Store + Registry func() Registry + Cache func() *readcache.Cache + MinVersion func() string + LatestVersion func() string + RequireUser func(http.ResponseWriter, *http.Request) *store.User + VersionLess func(string, string) bool + Logger *slog.Logger +} + +// Controller shares one per-account earnings flight group across dashboard +// requests. Live provider and durable record ownership stays in their stores. +type Controller struct { + store func() Store + registry func() Registry + readCache func() *readcache.Cache + minVersion func() string + latestVersion func() string + requireUser func(http.ResponseWriter, *http.Request) *store.User + versionLess func(string, string) bool + logger *slog.Logger + summaryWindowsFlights singleflight.Group +} + +func New(d Dependencies) *Controller { + return &Controller{store: d.Store, registry: d.Registry, readCache: d.Cache, minVersion: d.MinVersion, latestVersion: d.LatestVersion, requireUser: d.RequireUser, versionLess: d.VersionLess, logger: d.Logger} +} diff --git a/coordinator/api/accountfleet/counts.go b/coordinator/api/accountfleet/counts.go new file mode 100644 index 0000000000..bc1a2ff5ef --- /dev/null +++ b/coordinator/api/accountfleet/counts.go @@ -0,0 +1,62 @@ +package accountfleet + +import ( + "github.com/eigeninference/d-inference/coordinator/registry" +) + +// fleetCounts aggregates machine counts by status for the dashboard header. +type fleetCounts struct { + Total int `json:"total"` + Online int `json:"online"` // status==online + Serving int `json:"serving"` // status==serving + Offline int `json:"offline"` // status==offline OR never_seen + Untrusted int `json:"untrusted"` // status==untrusted + Hardware int `json:"hardware"` // trust_level==hardware + NeedsAttn int `json:"needs_attention"` // any of: !runtime_verified, trust!=hardware, untrusted, version below min +} + +// tallyCounts updates the fleet aggregate based on one machine's merged state. +func (s *Controller) tallyCounts(c *fleetCounts, mp *providerView, minVersion string) { + c.Total++ + switch mp.Status { + case "serving": + c.Serving++ + case string(registry.StatusOnline): + c.Online++ + case string(registry.StatusUntrusted): + c.Untrusted++ + default: // offline, never_seen + c.Offline++ + } + if mp.TrustLevel == string(registry.TrustHardware) { + c.Hardware++ + } + if s.needsAttention(mp, minVersion) { + c.NeedsAttn++ + } +} + +// needsAttention is the server-side mirror of the client warning logic. It's +// only used for the summary count, not for individual warning text. The UI +// renders detailed warnings from the per-machine payload. +func (s *Controller) needsAttention(mp *providerView, minVersion string) bool { + if mp.Status == string(registry.StatusUntrusted) { + return true + } + if mp.Status == "offline" || mp.Status == "never_seen" { + return true + } + if !mp.RuntimeVerified { + return true + } + if mp.TrustLevel != string(registry.TrustHardware) { + return true + } + if mp.FailedChallenges > 0 { + return true + } + if minVersion != "" && mp.Version != "" && s.versionLess(mp.Version, minVersion) { + return true + } + return false +} diff --git a/coordinator/api/accountfleet/dashboard_queries_test.go b/coordinator/api/accountfleet/dashboard_queries_test.go new file mode 100644 index 0000000000..568e4d778c --- /dev/null +++ b/coordinator/api/accountfleet/dashboard_queries_test.go @@ -0,0 +1,193 @@ +package accountfleet + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/readcache" + "github.com/eigeninference/d-inference/coordinator/auth" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// countingMeStore counts the store calls the /v1/me handlers make. +type countingMeStore struct { + store.Store + windows atomic.Int64 + listProviders atomic.Int64 + getReputation atomic.Int64 + getReputBatch atomic.Int64 +} + +func (c *countingMeStore) AccountEarningsWindows(accountID string, now time.Time) (store.AccountEarningsWindows, error) { + c.windows.Add(1) + return c.Store.AccountEarningsWindows(accountID, now) +} + +func (c *countingMeStore) ListProvidersByAccount(ctx context.Context, accountID string) ([]store.ProviderRecord, error) { + c.listProviders.Add(1) + return c.Store.ListProvidersByAccount(ctx, accountID) +} + +func (c *countingMeStore) GetReputation(ctx context.Context, providerID string) (*store.ReputationRecord, error) { + c.getReputation.Add(1) + return c.Store.GetReputation(ctx, providerID) +} + +func (c *countingMeStore) GetReputations(ctx context.Context, ids []string) (map[string]*store.ReputationRecord, error) { + c.getReputBatch.Add(1) + return c.Store.GetReputations(ctx, ids) +} + +func newMeTestServer(t *testing.T) (*Controller, *countingMeStore) { + t.Helper() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + st := &countingMeStore{Store: store.NewMemory(store.Config{AdminKey: "test-key"})} + reg := registry.New(logger) + cache := readcache.New() + srv := New(Dependencies{ + Store: func() Store { return st }, Registry: func() Registry { return reg }, Cache: func() *readcache.Cache { return cache }, + MinVersion: func() string { return "" }, LatestVersion: func() string { return "" }, + RequireUser: func(_ http.ResponseWriter, r *http.Request) *store.User { return auth.UserFromContext(r.Context()) }, + VersionLess: func(string, string) bool { t.Fatal("unexpected version comparison in earnings fixture"); return false }, + Logger: logger, + }) + return srv, st +} + +func getMySummary(t *testing.T, srv *Controller, accountID string) summaryResponse { + t.Helper() + w := httptest.NewRecorder() + srv.Summary(w, reqWithUser(http.MethodGet, "/v1/me/summary", "", accountID)) + if w.Code != http.StatusOK { + t.Fatalf("status = %d: %s", w.Code, w.Body.String()) + } + var resp summaryResponse + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + return resp +} + +// TestMySummaryWindowsExactBeyondFiveThousandRows: an account with 6,000 +// earnings rows in the last 7 d used to have its 7 d figures summed from a +// 5,000-row page; the aggregate reports all of them. +func TestMySummaryWindowsExactBeyondFiveThousandRows(t *testing.T) { + srv, st := newMeTestServer(t) + const account = "acct-6000" + now := time.Now() + var want7dMoney, want24hMoney int64 + var want24hJobs int64 + for i := range 6_000 { + age := time.Duration(i+1) * 7 * 24 * time.Hour / 6_001 + amount := int64(100 + i%5) + createdAt := now.Add(-age) + if err := st.RecordProviderEarning(&store.ProviderEarning{ + AccountID: account, ProviderID: "node", ProviderKey: "key", + JobID: fmt.Sprintf("job-%d", i), Model: "model", + AmountMicroUSD: amount, CreatedAt: createdAt, + }); err != nil { + t.Fatal(err) + } + want7dMoney += amount + if createdAt.After(now.Add(-24 * time.Hour)) { + want24hMoney += amount + want24hJobs++ + } + } + // The page the old implementation summed cannot hold the whole window. + page, err := st.GetAccountEarnings(account, 5000) + if err != nil || len(page) != 5000 { + t.Fatalf("old row page = %d rows, %v; want 5,000 (truncated)", len(page), err) + } + + resp := getMySummary(t, srv, account) + if resp.Last7dJobs != 6_000 || resp.Last7dMicroUSD != want7dMoney { + t.Fatalf("last 7d = %d jobs / %d micro, want 6000 / %d", resp.Last7dJobs, resp.Last7dMicroUSD, want7dMoney) + } + if resp.Last24hJobs != want24hJobs || resp.Last24hMicroUSD != want24hMoney { + t.Fatalf("last 24h = %d jobs / %d micro, want %d / %d", resp.Last24hJobs, resp.Last24hMicroUSD, want24hJobs, want24hMoney) + } +} + +// TestMySummaryWindowsCachedPerAccount: repeated polls within the cache TTL +// compute the windows once per account; a different account gets its own. +func TestMySummaryWindowsCachedPerAccount(t *testing.T) { + srv, st := newMeTestServer(t) + for _, account := range []string{"acct-a", "acct-b"} { + if err := st.RecordProviderEarning(&store.ProviderEarning{ + AccountID: account, ProviderID: "node-" + account, ProviderKey: "key-" + account, + JobID: "job-" + account, Model: "model", AmountMicroUSD: 500, CreatedAt: time.Now(), + }); err != nil { + t.Fatal(err) + } + } + for range 3 { + if resp := getMySummary(t, srv, "acct-a"); resp.Last24hJobs != 1 || resp.Last24hMicroUSD != 500 { + t.Fatalf("acct-a summary = %+v", resp) + } + } + if got := st.windows.Load(); got != 1 { + t.Fatalf("window aggregates for 3 polls of one account = %d, want 1 (cached %s)", got, mySummaryWindowsCacheTTL) + } + if resp := getMySummary(t, srv, "acct-b"); resp.Last24hJobs != 1 { + t.Fatalf("acct-b summary = %+v", resp) + } + if got := st.windows.Load(); got != 2 { + t.Fatalf("window aggregates after a second account = %d, want 2 (per-account entries)", got) + } +} + +// TestMyProvidersBatchesReputationLookups: a fleet of 20 stored machines is +// served with exactly one provider list and one batched reputation lookup — +// never a reputation read per machine. +func TestMyProvidersBatchesReputationLookups(t *testing.T) { + srv, st := newMeTestServer(t) + const account = "acct-fleet" + ctx := context.Background() + for i := range 20 { + id := fmt.Sprintf("machine-%02d", i) + if err := st.UpsertProvider(ctx, store.ProviderRecord{ + ID: id, AccountID: account, Backend: "mlx-swift", + Hardware: json.RawMessage(`{"chip_name":"Apple M4 Max","memory_gb":64}`), + Models: json.RawMessage(`[]`), + LastSeen: time.Now().Add(-time.Duration(i) * time.Minute), + }); err != nil { + t.Fatalf("upsert provider: %v", err) + } + if err := st.UpsertReputation(ctx, id, store.ReputationRecord{ + TotalJobs: 10 + i, SuccessfulJobs: 10 + i, ChallengesPassed: 3, + }); err != nil { + t.Fatalf("upsert reputation: %v", err) + } + } + + w := httptest.NewRecorder() + srv.Providers(w, reqWithUser(http.MethodGet, "/v1/me/providers", "", account)) + if w.Code != http.StatusOK { + t.Fatalf("status = %d: %s", w.Code, w.Body.String()) + } + var resp providersResponse + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if len(resp.Providers) != 20 { + t.Fatalf("providers = %d, want 20", len(resp.Providers)) + } + for _, p := range resp.Providers { + if p.Reputation.TotalJobs < 10 || p.Reputation.ChallengesPassed != 3 { + t.Fatalf("provider %s reputation not attached: %+v", p.ID, p.Reputation) + } + } + if list, batch, single := st.listProviders.Load(), st.getReputBatch.Load(), st.getReputation.Load(); list != 1 || batch != 1 || single != 0 { + t.Fatalf("store calls: ListProvidersByAccount=%d GetReputations=%d GetReputation=%d, want 1/1/0", list, batch, single) + } +} diff --git a/coordinator/api/accountfleet/identity.go b/coordinator/api/accountfleet/identity.go new file mode 100644 index 0000000000..4f8e8be386 --- /dev/null +++ b/coordinator/api/accountfleet/identity.go @@ -0,0 +1,82 @@ +package accountfleet + +import ( + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// recordIdentity returns the stable identity for a provider record, preferring +// SerialNumber, then SEPublicKey, then the per-session ID as a last resort. +// Two records with the same identity refer to the same physical machine. +func recordIdentity(rec *store.ProviderRecord) string { + if rec.SerialNumber != "" { + return "serial:" + rec.SerialNumber + } + if rec.SEPublicKey != "" { + return "sekey:" + rec.SEPublicKey + } + return "id:" + rec.ID +} + +// liveIdentity computes the same stable identity for a live registry provider +// using the same serial/SE-key precedence so dedup keys are comparable. +func liveIdentity(p *registry.Provider) string { + p.Mu().Lock() + defer p.Mu().Unlock() + if p.AttestationResult != nil { + if p.AttestationResult.SerialNumber != "" { + return "serial:" + p.AttestationResult.SerialNumber + } + if p.AttestationResult.PublicKey != "" { + return "sekey:" + p.AttestationResult.PublicKey + } + } + return "id:" + p.ID +} + +// dedupeRecordsByIdentity collapses ProviderRecord rows that refer to the +// same physical machine, keeping the most recently seen one. The input order +// is the store's LastSeen-DESC order; we honour it for ties. +func dedupeRecordsByIdentity(records []store.ProviderRecord) []store.ProviderRecord { + if len(records) <= 1 { + return records + } + picked := make(map[string]int, len(records)) + for i := range records { + key := recordIdentity(&records[i]) + if existing, ok := picked[key]; !ok || records[i].LastSeen.After(records[existing].LastSeen) { + picked[key] = i + } + } + out := make([]store.ProviderRecord, 0, len(picked)) + for i := range records { + if picked[recordIdentity(&records[i])] == i { + out = append(out, records[i]) + } + } + return out +} + +// liveMatchesEmittedIdentity reports whether the live provider corresponds to +// a machine we already emitted from the persisted-records pass. This avoids +// duplicating a card when a stored record's session ID drifted from the live +// session ID (post-reconnect) but they share a serial/SE key. +func liveMatchesEmittedIdentity(p *registry.Provider, emitted []providerView) bool { + id := liveIdentity(p) + for i := range emitted { + if emittedIdentity(&emitted[i]) == id { + return true + } + } + return false +} + +func emittedIdentity(mp *providerView) string { + if mp.serialNumber != "" { + return "serial:" + mp.serialNumber + } + if mp.SEPublicKey != "" { + return "sekey:" + mp.SEPublicKey + } + return "id:" + mp.ID +} diff --git a/coordinator/api/accountfleet/merge.go b/coordinator/api/accountfleet/merge.go new file mode 100644 index 0000000000..ae2dc4b1cc --- /dev/null +++ b/coordinator/api/accountfleet/merge.go @@ -0,0 +1,68 @@ +package accountfleet + +import ( + "context" + "fmt" + + "github.com/eigeninference/d-inference/coordinator/registry" +) + +// mergeFleet builds a deduplicated list of providerView structs for an account +// by combining persisted ProviderRecords (covers offline machines) with the +// live registry snapshot (status, heartbeat metrics, backend capacity). +func (s *Controller) mergeFleet(ctx context.Context, accountID string) ([]providerView, error) { + records, err := s.store().ListProvidersByAccount(ctx, accountID) + if err != nil { + return nil, fmt.Errorf("list providers by account: %w", err) + } + + // Index live providers by both session ID and stable identity (serial / + // SE key) so reconnected machines — whose session ID differs from the + // stored record's ID — still match their persisted state. + liveByID := make(map[string]*registry.Provider) + liveByIdentity := make(map[string]*registry.Provider) + s.registry().ForEachProvider(func(p *registry.Provider) { + p.Mu().Lock() + if p.AccountID == accountID { + liveByID[p.ID] = p + if p.AttestationResult != nil { + if p.AttestationResult.SerialNumber != "" { + liveByIdentity["serial:"+p.AttestationResult.SerialNumber] = p + } + if p.AttestationResult.PublicKey != "" { + liveByIdentity["sekey:"+p.AttestationResult.PublicKey] = p + } + } + } + p.Mu().Unlock() + }) + + deduped := dedupeRecordsByIdentity(records) + seenIDs := make(map[string]bool, len(deduped)) + seenLive := make(map[string]bool) + out := make([]providerView, 0, len(deduped)) + for i := range deduped { + // Prefer session-ID match; fall back to identity (serial/SE key) + // so reconnected machines correctly show as online. + live := liveByID[deduped[i].ID] + if live == nil { + live = liveByIdentity[recordIdentity(&deduped[i])] + } + mp := buildProvider(&deduped[i], live) + out = append(out, mp) + seenIDs[deduped[i].ID] = true + if live != nil { + seenLive[live.ID] = true + } + } + for id, p := range liveByID { + if seenIDs[id] || seenLive[id] { + continue + } + if liveMatchesEmittedIdentity(p, out) { + continue + } + out = append(out, buildProvider(nil, p)) + } + return out, nil +} diff --git a/coordinator/api/accountfleet/provider_view.go b/coordinator/api/accountfleet/provider_view.go new file mode 100644 index 0000000000..bda8bfd01a --- /dev/null +++ b/coordinator/api/accountfleet/provider_view.go @@ -0,0 +1,250 @@ +package accountfleet + +import ( + "encoding/json" + "time" + + "github.com/eigeninference/d-inference/coordinator/attestation" + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// providerView is the per-machine payload for /v1/me/providers. +type providerView struct { + ID string `json:"id"` + AccountID string `json:"account_id"` + + // Live operational state. Status is "offline" when the machine is not + // currently connected, "never_seen" when it has a stored record but has + // not connected since the coordinator started, otherwise mirrors the + // registry status (online|serving|untrusted). + Status string `json:"status"` + Online bool `json:"online"` + LastHeartbeat *time.Time `json:"last_heartbeat,omitempty"` + + // Identity / hardware + Hardware protocol.Hardware `json:"hardware"` + Models []protocol.ModelInfo `json:"models"` + Backend string `json:"backend,omitempty"` + Version string `json:"version,omitempty"` + serialNumber string + + // Trust & attestation + TrustLevel string `json:"trust_level"` + Attested bool `json:"attested"` + MDAVerified bool `json:"mda_verified"` + // Deprecated: the ACME device-attest-01 leg was removed. Key kept (always + // false) because shipped provider builds decode it as a required field. + ACMEVerified bool `json:"acme_verified"` + SEKeyBound bool `json:"se_key_bound"` + SEPublicKey string `json:"se_public_key,omitempty"` + // ProviderKey is the machine's X25519 E2E public key, used to resolve + // per-node earnings. Same value senders fetch from /v1/encryption-key, so + // it is not a secret on the owner's own dashboard. Present only for + // currently-online machines (it is not persisted on ProviderRecord). + ProviderKey string `json:"provider_key,omitempty"` + SecureEnclave bool `json:"secure_enclave"` + SIPEnabled bool `json:"sip_enabled"` + SecureBootEnabled bool `json:"secure_boot_enabled"` + AuthenticatedRoot bool `json:"authenticated_root_enabled"` + SystemVolumeHash string `json:"system_volume_hash,omitempty"` + MDAOSVersion string `json:"mda_os_version,omitempty"` + MDASEPVersion string `json:"mda_sepos_version,omitempty"` + + // Runtime integrity + RuntimeVerified bool `json:"runtime_verified"` + PythonHash string `json:"python_hash,omitempty"` + RuntimeHash string `json:"runtime_hash,omitempty"` + + // Challenge state + LastChallengeVerified *time.Time `json:"last_challenge_verified,omitempty"` + FailedChallenges int `json:"failed_challenges"` + + // Live snapshot (only set when the machine is currently connected) + SystemMetrics *protocol.SystemMetrics `json:"system_metrics,omitempty"` + BackendCapacity *protocol.BackendCapacity `json:"backend_capacity,omitempty"` + // IdleUnloadMins is the machine's idle-memory policy as reported in its + // heartbeats: 0 = always ready (models stay loaded), N = unloaded after N + // idle minutes and reloaded on demand. Omitted for offline machines and + // for providers too old to report it. Lets the dashboard render a missing + // slot as "sleeping, wakes on demand" instead of a warning. + IdleUnloadMins *int `json:"idle_unload_mins,omitempty"` + WarmModels []string `json:"warm_models,omitempty"` + CurrentModel string `json:"current_model,omitempty"` + PendingRequests int `json:"pending_requests"` + MaxConcurrency int `json:"max_concurrency"` + PrefillTPS float64 `json:"prefill_tps,omitempty"` + DecodeTPS float64 `json:"decode_tps,omitempty"` + + // Reputation + Reputation reputationView `json:"reputation"` + + // Lifetime stats + LifetimeRequestsServed int64 `json:"lifetime_requests_served"` + LifetimeTokensGenerated int64 `json:"lifetime_tokens_generated"` + + // Payout configuration (via Stripe Connect Express) + + // Timestamps + RegisteredAt *time.Time `json:"registered_at,omitempty"` + LastSeen *time.Time `json:"last_seen,omitempty"` +} + +// buildProvider merges a persisted record with the live registry snapshot. +// Either may be nil (a never-connected stored record OR a fresh registration +// that hasn't been persisted yet), but at least one must be non-nil. +func buildProvider(rec *store.ProviderRecord, live *registry.Provider) providerView { + mp := providerView{Status: "never_seen"} + + // 1. Start from the persisted record (covers offline machines). + if rec != nil { + mp.ID = rec.ID + mp.AccountID = rec.AccountID + mp.Backend = rec.Backend + mp.Version = rec.Version + mp.serialNumber = rec.SerialNumber + mp.TrustLevel = rec.TrustLevel + mp.Attested = rec.Attested + mp.MDAVerified = rec.MDAVerified + mp.SEPublicKey = rec.SEPublicKey + // X25519 E2E key from the persisted record so OFFLINE machines still + // resolve per-node earnings. The live branch below overrides + // it with live.PublicKey when the machine is currently connected. + mp.ProviderKey = rec.PublicKey + mp.RuntimeVerified = rec.RuntimeVerified + mp.PythonHash = rec.PythonHash + mp.RuntimeHash = rec.RuntimeHash + mp.LastChallengeVerified = rec.LastChallengeVerified + mp.FailedChallenges = rec.FailedChallenges + mp.LifetimeRequestsServed = rec.LifetimeRequestsServed + mp.LifetimeTokensGenerated = rec.LifetimeTokensGenerated + if !rec.RegisteredAt.IsZero() { + t := rec.RegisteredAt + mp.RegisteredAt = &t + } + if !rec.LastSeen.IsZero() { + t := rec.LastSeen + mp.LastSeen = &t + } + // Decode embedded JSON blobs. + if len(rec.Hardware) > 0 { + _ = json.Unmarshal(rec.Hardware, &mp.Hardware) + } + if len(rec.Models) > 0 { + _ = json.Unmarshal(rec.Models, &mp.Models) + } + // AttestationResult holds chip name, SE flags, OS security, system + // volume hash, etc. Source of truth when we don't have a live snapshot. + if len(rec.AttestationResult) > 0 { + var ar attestation.VerificationResult + if err := json.Unmarshal(rec.AttestationResult, &ar); err == nil { + if ar.SerialNumber != "" { + mp.serialNumber = ar.SerialNumber + } + if ar.PublicKey != "" { + mp.SEPublicKey = ar.PublicKey + } + mp.SecureEnclave = ar.SecureEnclaveAvailable + mp.SIPEnabled = ar.SIPEnabled + mp.SecureBootEnabled = ar.SecureBootEnabled + mp.AuthenticatedRoot = ar.AuthenticatedRootEnabled + mp.SystemVolumeHash = ar.SystemVolumeHash + } + } + // Default to offline; will be overwritten below if we have a live snapshot. + mp.Status = "offline" + } + + // 2. Overlay the live snapshot if present. + if live != nil { + live.Mu().Lock() + mp.ID = live.ID + if live.AccountID != "" { + mp.AccountID = live.AccountID + } + mp.Status = string(live.Status) + mp.Online = live.Status != registry.StatusOffline && live.Status != registry.StatusUntrusted + hb := live.LastHeartbeat + if !hb.IsZero() { + mp.LastHeartbeat = &hb + } + // Hardware / models from the live snapshot are authoritative because + // the provider may have re-registered with new specs. + mp.Hardware = live.Hardware + mp.Models = append([]protocol.ModelInfo{}, live.Models...) + mp.Backend = live.Backend + mp.Version = live.Version + mp.TrustLevel = string(live.TrustLevel) + mp.Attested = live.Attested + mp.MDAVerified = live.MDAVerified + mp.SEKeyBound = live.SEKeyBound + mp.RuntimeVerified = live.RuntimeVerified + mp.PythonHash = live.PythonHash + mp.RuntimeHash = live.RuntimeHash + if !live.LastChallengeVerified.IsZero() { + t := live.LastChallengeVerified + mp.LastChallengeVerified = &t + } + mp.FailedChallenges = live.FailedChallenges + // X25519 E2E key — the earnings table is keyed on this. Persisted on the + // record too, so offline machines resolve earnings; the live + // value is authoritative when connected. + if live.PublicKey != "" { + mp.ProviderKey = live.PublicKey + } + mp.LifetimeRequestsServed = live.Stats.RequestsServed + mp.LifetimeTokensGenerated = live.Stats.TokensGenerated + mp.PrefillTPS = live.PrefillTPS + mp.DecodeTPS = live.DecodeTPS + + if live.AttestationResult != nil { + ar := live.AttestationResult + if ar.SerialNumber != "" { + mp.serialNumber = ar.SerialNumber + } + if ar.PublicKey != "" { + mp.SEPublicKey = ar.PublicKey + } + mp.SecureEnclave = ar.SecureEnclaveAvailable + mp.SIPEnabled = ar.SIPEnabled + mp.SecureBootEnabled = ar.SecureBootEnabled + mp.AuthenticatedRoot = ar.AuthenticatedRootEnabled + mp.SystemVolumeHash = ar.SystemVolumeHash + } + if live.MDAResult != nil { + mp.MDAOSVersion = live.MDAResult.OSVersion + mp.MDASEPVersion = live.MDAResult.SepOSVersion + } + // Live system metrics & backend capacity. + sm := live.SystemMetrics + mp.SystemMetrics = &sm + if live.BackendCapacity != nil { + cap := *live.BackendCapacity + mp.BackendCapacity = &cap + } + if live.IdleUnloadMins != nil { + v := *live.IdleUnloadMins + mp.IdleUnloadMins = &v + } + mp.WarmModels = append([]string{}, live.WarmModels...) + mp.CurrentModel = live.CurrentModel + // Reputation snapshot. + mp.Reputation = reputationView{ + Score: live.Reputation.Score(), + TotalJobs: live.Reputation.TotalJobs, + SuccessfulJobs: live.Reputation.SuccessfulJobs, + FailedJobs: live.Reputation.FailedJobs, + TotalUptimeSeconds: int64(live.Reputation.TotalUptime / time.Second), + AvgResponseTimeMs: int64(live.Reputation.AvgResponseTime / time.Millisecond), + ChallengesPassed: live.Reputation.ChallengesPassed, + ChallengesFailed: live.Reputation.ChallengesFailed, + } + live.Mu().Unlock() + // Concurrency limit lookup acquires its own lock. + mp.PendingRequests = live.PendingCount() + mp.MaxConcurrency = live.MaxConcurrency() + } + + return mp +} diff --git a/coordinator/api/accountfleet/providers.go b/coordinator/api/accountfleet/providers.go new file mode 100644 index 0000000000..1468580ea1 --- /dev/null +++ b/coordinator/api/accountfleet/providers.go @@ -0,0 +1,41 @@ +package accountfleet + +import ( + "net/http" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" +) + +type providersResponse struct { + Providers []providerView `json:"providers"` + LatestProviderVersion string `json:"latest_provider_version"` + MinProviderVersion string `json:"min_provider_version"` + HeartbeatTimeoutSec int `json:"heartbeat_timeout_seconds"` + ChallengeMaxAgeSec int `json:"challenge_max_age_seconds"` +} + +func (s *Controller) Providers(w http.ResponseWriter, r *http.Request) { + user := s.requireUser(w, r) + if user == nil { + return + } + + fleet, err := s.mergeFleet(r.Context(), user.AccountID) + if err != nil { + s.logger.Error("merge fleet failed", "account_id", user.AccountID, "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to list providers")) + return + } + + s.attachStoredReputations(r.Context(), fleet) + + resp := providersResponse{ + Providers: fleet, + LatestProviderVersion: s.latestVersion(), + MinProviderVersion: s.minVersion(), + HeartbeatTimeoutSec: 90, + ChallengeMaxAgeSec: int((6 * time.Minute).Seconds()), + } + httpresponse.WriteJSON(w, http.StatusOK, resp) +} diff --git a/coordinator/api/accountfleet/registry.go b/coordinator/api/accountfleet/registry.go new file mode 100644 index 0000000000..cc3483d00a --- /dev/null +++ b/coordinator/api/accountfleet/registry.go @@ -0,0 +1,10 @@ +package accountfleet + +import "github.com/eigeninference/d-inference/coordinator/registry" + +// Registry supplies current machines and the existing atomic online check / +// stale-entry cleanup used by removal. Provider reads keep their own locks. +type Registry interface { + ForEachProvider(func(*registry.Provider)) + RemoveProviderBySerial(string, bool) bool +} diff --git a/coordinator/api/accountfleet/removal.go b/coordinator/api/accountfleet/removal.go new file mode 100644 index 0000000000..a1a077848a --- /dev/null +++ b/coordinator/api/accountfleet/removal.go @@ -0,0 +1,75 @@ +package accountfleet + +import ( + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" +) + +// DeleteProvider handles DELETE /v1/me/providers/{id}. +// +// Removes an offline/retired machine's persisted record(s) so it stops +// reappearing in GET /v1/me/providers. Ownership-checked: the caller's account +// must own the record. A currently-connected machine is refused with 409 (it +// would just re-register). Billing/uptime history (earnings, usage, sessions) +// is preserved by the store. +func (s *Controller) DeleteProvider(w http.ResponseWriter, r *http.Request) { + user := s.requireUser(w, r) + if user == nil { + return // 401 already written + } + + providerID := strings.TrimSpace(r.PathValue("id")) + if providerID == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "missing provider id")) + return + } + + ctx := r.Context() + + // The public route accepts only the opaque provider session id. Resolve the + // stable hardware identity internally so serials never enter URLs or API + // payloads while reconnect rows are still removed together. + rec, err := s.store().GetProviderRecord(ctx, providerID) + if err != nil || rec == nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "machine not found")) + return + } + if rec.AccountID != user.AccountID { + httpresponse.WriteJSON(w, http.StatusForbidden, httpresponse.ErrorBody("forbidden", "you do not own this machine")) + return + } + + stableIdentity := rec.ID + if rec.SerialNumber != "" { + stableIdentity = rec.SerialNumber + } + + // Refuse if the machine is currently connected — it would re-register and + // the card would return. + if s.registry().RemoveProviderBySerial(stableIdentity, false) { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("conflict", "machine is currently online — stop it before removing")) + return + } + + n, err := s.store().DeleteProvidersBySerial(ctx, user.AccountID, stableIdentity) + if err != nil { + s.logger.Error("delete provider failed", "account_id", user.AccountID, "provider_id", providerID, "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to remove machine")) + return + } + if n == 0 { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "machine not found")) + return + } + + // Best-effort: drop any lingering in-memory entry so an evict-race can't + // re-persist the record we just removed. + s.registry().RemoveProviderBySerial(stableIdentity, true) + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "deleted": true, + "rows_removed": n, + }) +} diff --git a/coordinator/api/accountfleet/reputation.go b/coordinator/api/accountfleet/reputation.go new file mode 100644 index 0000000000..72e7373cb8 --- /dev/null +++ b/coordinator/api/accountfleet/reputation.go @@ -0,0 +1,75 @@ +package accountfleet + +import ( + "context" + "time" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// reputationView is the wire shape for a provider's reputation snapshot. +type reputationView struct { + Score float64 `json:"score"` + TotalJobs int `json:"total_jobs"` + SuccessfulJobs int `json:"successful_jobs"` + FailedJobs int `json:"failed_jobs"` + TotalUptimeSeconds int64 `json:"total_uptime_seconds"` + AvgResponseTimeMs int64 `json:"avg_response_time_ms"` + ChallengesPassed int `json:"challenges_passed"` + ChallengesFailed int `json:"challenges_failed"` +} + +// attachStoredReputations fills in persisted reputation for every machine in +// the fleet that has none from the live registry, with ONE store lookup for +// the whole fleet instead of one per machine (the dashboard polls this every +// 15 s per tab, and the per-machine form was ~78 reputation reads/s in +// production). +func (s *Controller) attachStoredReputations(ctx context.Context, fleet []providerView) { + ids := make([]string, 0, len(fleet)) + for i := range fleet { + if needsStoredReputation(&fleet[i]) { + ids = append(ids, fleet[i].ID) + } + } + if len(ids) == 0 { + return + } + reps, err := s.store().GetReputations(ctx, ids) + if err != nil { + return + } + for i := range fleet { + if !needsStoredReputation(&fleet[i]) { + continue + } + if rep := reps[fleet[i].ID]; rep != nil { + applyStoredReputation(&fleet[i], rep) + } + } +} + +func needsStoredReputation(mp *providerView) bool { + return mp.ID != "" && mp.Reputation.TotalJobs == 0 && mp.Reputation.ChallengesPassed == 0 && mp.Reputation.ChallengesFailed == 0 +} + +func applyStoredReputation(mp *providerView, rep *store.ReputationRecord) { + r := registry.NewReputation() + r.TotalJobs = rep.TotalJobs + r.SuccessfulJobs = rep.SuccessfulJobs + r.FailedJobs = rep.FailedJobs + r.TotalUptime = time.Duration(rep.TotalUptimeSeconds) * time.Second + r.AvgResponseTime = time.Duration(rep.AvgResponseTimeMs) * time.Millisecond + r.ChallengesPassed = rep.ChallengesPassed + r.ChallengesFailed = rep.ChallengesFailed + mp.Reputation = reputationView{ + Score: r.Score(), + TotalJobs: r.TotalJobs, + SuccessfulJobs: r.SuccessfulJobs, + FailedJobs: r.FailedJobs, + TotalUptimeSeconds: int64(r.TotalUptime / time.Second), + AvgResponseTimeMs: int64(r.AvgResponseTime / time.Millisecond), + ChallengesPassed: r.ChallengesPassed, + ChallengesFailed: r.ChallengesFailed, + } +} diff --git a/coordinator/api/accountfleet/request_helpers_test.go b/coordinator/api/accountfleet/request_helpers_test.go new file mode 100644 index 0000000000..45cf229c8b --- /dev/null +++ b/coordinator/api/accountfleet/request_helpers_test.go @@ -0,0 +1,27 @@ +package accountfleet + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" + "github.com/eigeninference/d-inference/coordinator/auth" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// reqWithUser builds a request whose context carries an authenticated user, +// simulating what requirePrivyAuth installs (so we can unit-test the handlers +// without minting a real Privy JWT). +func reqWithUser(method, target, body, accountID string) *http.Request { + var r *http.Request + if body == "" { + r = httptest.NewRequest(method, target, nil) + } else { + r = httptest.NewRequest(method, target, strings.NewReader(body)) + } + ctx := context.WithValue(r.Context(), auth.CtxKeyUser, &store.User{AccountID: accountID}) + ctx = requestcontext.WithAccountID(ctx, accountID) + return r.WithContext(ctx) +} diff --git a/coordinator/api/accountfleet/store.go b/coordinator/api/accountfleet/store.go new file mode 100644 index 0000000000..233f00a3b5 --- /dev/null +++ b/coordinator/api/accountfleet/store.go @@ -0,0 +1,21 @@ +package accountfleet + +import ( + "context" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Store reads account earnings and provider records, and removes only records +// belonging to the supplied account. Financial history remains store-owned. +type Store interface { + GetAccountEarningsSummary(string) (store.ProviderEarningsSummary, error) + AccountEarningsWindows(string, time.Time) (store.AccountEarningsWindows, error) + GetBalance(string) int64 + GetWithdrawableBalance(string) int64 + ListProvidersByAccount(context.Context, string) ([]store.ProviderRecord, error) + GetReputations(context.Context, []string) (map[string]*store.ReputationRecord, error) + GetProviderRecord(context.Context, string) (*store.ProviderRecord, error) + DeleteProvidersBySerial(context.Context, string, string) (int, error) +} diff --git a/coordinator/api/accountfleet/summary.go b/coordinator/api/accountfleet/summary.go new file mode 100644 index 0000000000..c4eb8a389b --- /dev/null +++ b/coordinator/api/accountfleet/summary.go @@ -0,0 +1,75 @@ +package accountfleet + +import ( + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" +) + +// summaryResponse is the page-level dashboard header at /v1/me/summary. +type summaryResponse struct { + AccountID string `json:"account_id"` + AvailableBalanceMicroUSD int64 `json:"available_balance_micro_usd"` + WithdrawableBalanceMicroUSD int64 `json:"withdrawable_balance_micro_usd"` + PayoutReady bool `json:"payout_ready"` + LifetimeMicroUSD int64 `json:"lifetime_micro_usd"` + LifetimeJobs int64 `json:"lifetime_jobs"` + Last24hMicroUSD int64 `json:"last_24h_micro_usd"` + Last24hJobs int64 `json:"last_24h_jobs"` + Last7dMicroUSD int64 `json:"last_7d_micro_usd"` + Last7dJobs int64 `json:"last_7d_jobs"` + Counts fleetCounts `json:"counts"` + LatestProviderVersion string `json:"latest_provider_version"` + MinProviderVersion string `json:"min_provider_version"` +} + +func (s *Controller) Summary(w http.ResponseWriter, r *http.Request) { + user := s.requireUser(w, r) + if user == nil { + return + } + accountID := user.AccountID + + summary, err := s.store().GetAccountEarningsSummary(accountID) + if err != nil { + s.logger.Error("get account earnings summary failed", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to fetch earnings")) + return + } + + windows, err := s.accountEarningsWindows(accountID) + if err != nil { + s.logger.Error("get account earnings windows failed", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to fetch earnings")) + return + } + + fleet, err := s.mergeFleet(r.Context(), accountID) + if err != nil { + s.logger.Error("merge fleet failed", "account_id", accountID, "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to list providers")) + return + } + + counts := fleetCounts{} + for i := range fleet { + s.tallyCounts(&counts, &fleet[i], s.minVersion()) + } + + resp := summaryResponse{ + AccountID: accountID, + AvailableBalanceMicroUSD: s.store().GetBalance(accountID), + WithdrawableBalanceMicroUSD: s.store().GetWithdrawableBalance(accountID), + PayoutReady: user.StripeAccountStatus == "ready", + LifetimeMicroUSD: summary.TotalMicroUSD, + LifetimeJobs: summary.Count, + Last24hMicroUSD: windows.Last24hMicroUSD, + Last24hJobs: windows.Last24hJobs, + Last7dMicroUSD: windows.Last7dMicroUSD, + Last7dJobs: windows.Last7dJobs, + Counts: counts, + LatestProviderVersion: s.latestVersion(), + MinProviderVersion: s.minVersion(), + } + httpresponse.WriteJSON(w, http.StatusOK, resp) +} diff --git a/coordinator/api/accountfleet/summary_cache.go b/coordinator/api/accountfleet/summary_cache.go new file mode 100644 index 0000000000..545c552149 --- /dev/null +++ b/coordinator/api/accountfleet/summary_cache.go @@ -0,0 +1,50 @@ +package accountfleet + +import ( + "encoding/json" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +const mySummaryWindowsCacheTTL = 15 * time.Second + +// accountEarningsWindows coalesces concurrent misses per account. The flight +// group forgets completed calls, so inactive account IDs do not accumulate. +func (s *Controller) accountEarningsWindows(accountID string) (store.AccountEarningsWindows, error) { + key := "me:summary:windows:" + accountID + cached := func() (store.AccountEarningsWindows, bool) { + var windows store.AccountEarningsWindows + if s.readCache() != nil { + if body, ok := s.readCache().Get(key); ok && json.Unmarshal(body, &windows) == nil { + return windows, true + } + } + return windows, false + } + if windows, ok := cached(); ok { + return windows, nil + } + value, err, _ := s.summaryWindowsFlights.Do(key, func() (any, error) { + // Another fill may have completed after this caller observed its miss. + if windows, ok := cached(); ok { + return windows, nil + } + windows, err := s.store().AccountEarningsWindows(accountID, time.Now()) + if err != nil { + return nil, err + } + if s.readCache() != nil { + body, err := json.Marshal(windows) + if err != nil { + return nil, err + } + s.readCache().Set(key, body, mySummaryWindowsCacheTTL) + } + return windows, nil + }) + if err != nil { + return store.AccountEarningsWindows{}, err + } + return value.(store.AccountEarningsWindows), nil +} diff --git a/coordinator/api/accountfleet/summary_concurrency_test.go b/coordinator/api/accountfleet/summary_concurrency_test.go new file mode 100644 index 0000000000..fc60857e29 --- /dev/null +++ b/coordinator/api/accountfleet/summary_concurrency_test.go @@ -0,0 +1,82 @@ +package accountfleet + +import ( + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +type blockingDashboardStore struct { + store.Store + entered chan string + release chan struct{} + calls atomic.Int64 +} + +func (s *blockingDashboardStore) AccountEarningsWindows(account string, now time.Time) (store.AccountEarningsWindows, error) { + s.calls.Add(1) + s.entered <- account + <-s.release + return s.Store.AccountEarningsWindows(account, now) +} + +func TestSummaryConcurrentExpiredMissesCoalescePerAccount(t *testing.T) { + srv, base := newMeTestServer(t) + st := &blockingDashboardStore{Store: base, entered: make(chan string, 64), release: make(chan struct{})} + srv.store = func() Store { return st } + srv.readCache().Set("me:summary:windows:a", []byte(`{}`), -time.Second) + const callers = 30 + var ready, done sync.WaitGroup + ready.Add(callers) + done.Add(callers) + start := make(chan struct{}) + errs := make(chan error, callers+1) + for range callers { + go func() { + defer done.Done() + ready.Done() + <-start + _, err := srv.accountEarningsWindows("a") + errs <- err + }() + } + ready.Wait() + close(start) + select { + case <-st.entered: + case <-time.After(time.Second): + t.Fatal("first query never started") + } + // Other accounts must not wait behind the first account's query. + otherDone := make(chan struct{}) + go func() { defer close(otherDone); _, err := srv.accountEarningsWindows("b"); errs <- err }() + select { + case account := <-st.entered: + if account != "b" { + close(st.release) + done.Wait() + <-otherDone + t.Fatalf("duplicate account query before release: %q", account) + } + case <-time.After(time.Second): + close(st.release) + done.Wait() + <-otherDone + t.Fatal("different account blocked") + } + close(st.release) + done.Wait() + <-otherDone + close(errs) + for err := range errs { + if err != nil { + t.Fatal(err) + } + } + if got := st.calls.Load(); got != 2 { + t.Fatalf("aggregate calls = %d, want one per account", got) + } +} diff --git a/coordinator/api/accounts/controller.go b/coordinator/api/accounts/controller.go new file mode 100644 index 0000000000..f16a29fd2f --- /dev/null +++ b/coordinator/api/accounts/controller.go @@ -0,0 +1,43 @@ +// Package accounts owns API-key management, key access/spend policy, provider +// device login and invite operations. Authentication, route middleware and live +// provider registration remain with their separate owners. +package accounts + +import ( + "log/slog" + "net/http" +) + +// KeyCache is the existing shared authentication cache's mutation interface. +// No account controller keeps a second cache. +type KeyCache interface { + InvalidateKey(string) + InvalidateAllKeys() +} + +// Dependencies keeps runtime store/configuration reads and admin authorization +// connected to the router. The getters and callbacks are required; they preserve +// configuration installed after routes were registered. +type Dependencies struct { + Store func() Store + Logger *slog.Logger + ConsoleURL func() string + KeyCache KeyCache + AuthorizeAdmin func(http.ResponseWriter, *http.Request) bool +} + +// Controller owns account endpoint policy without duplicating authentication, +// store, ledger or provider state. +type Controller struct { + store func() Store + logger *slog.Logger + consoleURL func() string + keyCache KeyCache + authorizeAdmin func(http.ResponseWriter, *http.Request) bool +} + +// New binds account operations to their current services. +func New(d Dependencies) *Controller { + return &Controller{store: d.Store, logger: d.Logger, consoleURL: d.ConsoleURL, + keyCache: d.KeyCache, authorizeAdmin: d.AuthorizeAdmin} +} diff --git a/coordinator/api/accounts/device_approval.go b/coordinator/api/accounts/device_approval.go new file mode 100644 index 0000000000..70aa1f6c81 --- /dev/null +++ b/coordinator/api/accounts/device_approval.go @@ -0,0 +1,65 @@ +package accounts + +import ( + "encoding/json" + "net/http" + "strings" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/auth" +) + +// ApproveDevice approves a device code, linking it to the authenticated user's account. +// POST /v1/device/approve +// Requires Privy auth — the user must be logged in. +func (s *Controller) ApproveDevice(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + if user == nil { + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("auth_error", "Privy authentication required")) + return + } + + var req struct { + UserCode string `json:"user_code"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.UserCode == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request", "user_code is required")) + return + } + + // Normalize: uppercase, trim spaces. + userCode := strings.ToUpper(strings.TrimSpace(req.UserCode)) + + dc, err := s.store().GetDeviceCodeByUserCode(userCode) + if err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("invalid_code", "device code not found — check the code and try again")) + return + } + + if time.Now().After(dc.ExpiresAt) { + httpresponse.WriteJSON(w, http.StatusGone, httpresponse.ErrorBody("expired_code", "this code has expired — run 'darkbloom login' again")) + return + } + + if dc.Status != "pending" { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("already_used", "this code has already been used")) + return + } + + if err := s.store().ApproveDeviceCode(dc.DeviceCode, user.AccountID); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("server_error", "failed to approve device")) + return + } + + s.logger.Info("device approved", + "user_code", userCode, + "account_id", user.AccountID, + "email", user.Email, + ) + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "approved", + "message": "Device linked successfully. Your provider will connect to your account shortly.", + }) +} diff --git a/coordinator/api/accounts/device_codes.go b/coordinator/api/accounts/device_codes.go new file mode 100644 index 0000000000..0833a5b325 --- /dev/null +++ b/coordinator/api/accounts/device_codes.go @@ -0,0 +1,101 @@ +package accounts + +import ( + "crypto/rand" + "encoding/hex" + "fmt" + "math/big" + "net/http" + "strings" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// DeviceCodeExpiry is how long a device code is valid. +const DeviceCodeExpiry = 15 * time.Minute + +// DeviceCodePollInterval is the minimum interval between polls in seconds. +const DeviceCodePollInterval = 5 + +// DeviceCode creates a new device authorization request. +// POST /v1/device/code +// No auth required — the provider CLI is not yet authenticated. +func (s *Controller) DeviceCode(w http.ResponseWriter, r *http.Request) { + // Generate device code (opaque, high-entropy secret). + deviceCodeBytes := make([]byte, 32) + if _, err := rand.Read(deviceCodeBytes); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("server_error", "failed to generate device code")) + return + } + deviceCode := hex.EncodeToString(deviceCodeBytes) + + // Generate user code (short, human-readable, uppercase alphanumeric). + userCode, err := generateUserCode() + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("server_error", "failed to generate user code")) + return + } + + dc := &store.DeviceCode{ + DeviceCode: deviceCode, + UserCode: userCode, + Status: "pending", + ExpiresAt: time.Now().Add(DeviceCodeExpiry), + } + + if err := s.store().CreateDeviceCode(dc); err != nil { + // User code collision — retry once. + userCode, _ = generateUserCode() + dc.UserCode = userCode + if err := s.store().CreateDeviceCode(dc); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("server_error", "failed to create device code")) + return + } + } + + // Build verification URI. If a console URL is configured (separate frontend), + // use that. Otherwise fall back to the coordinator's own host. + var verificationURI string + if s.consoleURL() != "" { + verificationURI = strings.TrimRight(s.consoleURL(), "/") + "/link" + } else { + scheme := "https" + if r.TLS == nil && !strings.Contains(r.Host, "darkbloom.dev") { + scheme = "http" + } + verificationURI = fmt.Sprintf("%s://%s/link", scheme, r.Host) + } + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "device_code": deviceCode, + "user_code": userCode, + "verification_uri": verificationURI, + "expires_in": int(DeviceCodeExpiry.Seconds()), + "interval": DeviceCodePollInterval, + }) + + s.logger.Info("device code created", + "user_code", userCode, + "expires_in", DeviceCodeExpiry.String(), + ) +} + +// generateUserCode creates a short, human-readable code like "ABCD-1234". +func generateUserCode() (string, error) { + // Use alphanumeric chars (no ambiguous chars: 0/O, 1/I/L). + const charset = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" + + code := make([]byte, 8) + for i := range code { + n, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset)))) + if err != nil { + return "", err + } + code[i] = charset[n.Int64()] + } + + // Format as XXXX-XXXX for readability. + return string(code[:4]) + "-" + string(code[4:]), nil +} diff --git a/coordinator/api/accounts/device_test.go b/coordinator/api/accounts/device_test.go new file mode 100644 index 0000000000..12f0c044a5 --- /dev/null +++ b/coordinator/api/accounts/device_test.go @@ -0,0 +1,313 @@ +package accounts + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/auth" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func deviceTestController() (*Controller, store.Store) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{AdminKey: "test-key"}) + srv := New(Dependencies{Store: func() Store { return st }, Logger: logger, ConsoleURL: func() string { return "" }}) + return srv, st +} + +func withUser(ctx context.Context, accountID, email string) context.Context { + return context.WithValue(ctx, auth.CtxKeyUser, &store.User{ + AccountID: accountID, + Email: email, + }) +} + +func TestDeviceCodeGeneration(t *testing.T) { + srv, _ := deviceTestController() + req := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) + w := httptest.NewRecorder() + + srv.DeviceCode(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200, body: %s", w.Code, w.Body.String()) + } + + var resp map[string]any + json.Unmarshal(w.Body.Bytes(), &resp) + + dc := resp["device_code"].(string) + if len(dc) != 64 { + t.Errorf("device_code length = %d, want 64", len(dc)) + } + + uc := resp["user_code"].(string) + if len(uc) != 9 || uc[4] != '-' { + t.Errorf("user_code = %q, want XXXX-XXXX format", uc) + } + + if _, ok := resp["verification_uri"]; !ok { + t.Error("missing verification_uri") + } + if resp["expires_in"].(float64) != DeviceCodeExpiry.Seconds() { + t.Errorf("expires_in = %v, want %v", resp["expires_in"], DeviceCodeExpiry.Seconds()) + } + if resp["interval"].(float64) != DeviceCodePollInterval { + t.Errorf("interval = %v, want %v", resp["interval"], DeviceCodePollInterval) + } +} + +func TestDeviceCodeUniquePerCall(t *testing.T) { + srv, _ := deviceTestController() + seen := make(map[string]bool) + + for range 10 { + req := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) + w := httptest.NewRecorder() + srv.DeviceCode(w, req) + + var resp map[string]any + json.Unmarshal(w.Body.Bytes(), &resp) + dc := resp["device_code"].(string) + if seen[dc] { + t.Error("duplicate device code generated") + } + seen[dc] = true + } +} + +func TestDeviceTokenPending(t *testing.T) { + srv, _ := deviceTestController() + + codeReq := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) + codeW := httptest.NewRecorder() + srv.DeviceCode(codeW, codeReq) + + var codeResp map[string]any + json.Unmarshal(codeW.Body.Bytes(), &codeResp) + + body := fmt.Sprintf(`{"device_code":"%s"}`, codeResp["device_code"].(string)) + tokenReq := httptest.NewRequest(http.MethodPost, "/v1/device/token", strings.NewReader(body)) + tokenW := httptest.NewRecorder() + srv.DeviceToken(tokenW, tokenReq) + + if tokenW.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", tokenW.Code) + } + var tokenResp map[string]any + json.Unmarshal(tokenW.Body.Bytes(), &tokenResp) + if tokenResp["status"] != "authorization_pending" { + t.Errorf("status = %q, want authorization_pending", tokenResp["status"]) + } +} + +func TestDeviceTokenNotFound(t *testing.T) { + srv, _ := deviceTestController() + req := httptest.NewRequest(http.MethodPost, "/v1/device/token", strings.NewReader(`{"device_code":"nonexistent"}`)) + w := httptest.NewRecorder() + srv.DeviceToken(w, req) + if w.Code != http.StatusNotFound { + t.Errorf("status = %d, want 404", w.Code) + } +} + +func TestDeviceTokenMissingField(t *testing.T) { + srv, _ := deviceTestController() + req := httptest.NewRequest(http.MethodPost, "/v1/device/token", strings.NewReader(`{}`)) + w := httptest.NewRecorder() + srv.DeviceToken(w, req) + if w.Code != http.StatusBadRequest { + t.Errorf("status = %d, want 400", w.Code) + } +} + +func TestDeviceApproveAndTokenAuthorized(t *testing.T) { + srv, _ := deviceTestController() + + // Create device code. + codeReq := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) + codeW := httptest.NewRecorder() + srv.DeviceCode(codeW, codeReq) + var codeResp map[string]any + json.Unmarshal(codeW.Body.Bytes(), &codeResp) + deviceCode := codeResp["device_code"].(string) + userCode := codeResp["user_code"].(string) + + // Approve with user context. + approveBody := fmt.Sprintf(`{"user_code":"%s"}`, userCode) + approveReq := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(approveBody)) + approveReq = approveReq.WithContext(withUser(approveReq.Context(), "acct-1", "user@test.com")) + approveW := httptest.NewRecorder() + srv.ApproveDevice(approveW, approveReq) + + if approveW.Code != http.StatusOK { + t.Fatalf("approve status = %d, body: %s", approveW.Code, approveW.Body.String()) + } + + // Poll token — should be authorized. + tokenBody := fmt.Sprintf(`{"device_code":"%s"}`, deviceCode) + tokenReq := httptest.NewRequest(http.MethodPost, "/v1/device/token", strings.NewReader(tokenBody)) + tokenW := httptest.NewRecorder() + srv.DeviceToken(tokenW, tokenReq) + + var tokenResp map[string]any + json.Unmarshal(tokenW.Body.Bytes(), &tokenResp) + if tokenResp["status"] != "authorized" { + t.Errorf("status = %q, want authorized", tokenResp["status"]) + } + token := tokenResp["token"].(string) + if !strings.HasPrefix(token, "eigeninference-pt-") { + t.Errorf("token = %q, want eigeninference-pt- prefix", token) + } + if tokenResp["account_id"] != "acct-1" { + t.Errorf("account_id = %q, want acct-1", tokenResp["account_id"]) + } +} + +func TestDeviceApproveRequiresAuth(t *testing.T) { + srv, _ := deviceTestController() + req := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(`{"user_code":"ABCD-1234"}`)) + w := httptest.NewRecorder() + srv.ApproveDevice(w, req) + if w.Code != http.StatusUnauthorized { + t.Errorf("status = %d, want 401", w.Code) + } +} + +func TestDeviceApproveNotFound(t *testing.T) { + srv, _ := deviceTestController() + req := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(`{"user_code":"ZZZZ-9999"}`)) + req = req.WithContext(withUser(req.Context(), "a1", "")) + w := httptest.NewRecorder() + srv.ApproveDevice(w, req) + if w.Code != http.StatusNotFound { + t.Errorf("status = %d, want 404", w.Code) + } +} + +func TestDeviceApproveAlreadyUsed(t *testing.T) { + srv, _ := deviceTestController() + + codeReq := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) + codeW := httptest.NewRecorder() + srv.DeviceCode(codeW, codeReq) + var codeResp map[string]any + json.Unmarshal(codeW.Body.Bytes(), &codeResp) + userCode := codeResp["user_code"].(string) + + body := fmt.Sprintf(`{"user_code":"%s"}`, userCode) + + // First approval. + req1 := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(body)) + req1 = req1.WithContext(withUser(req1.Context(), "a1", "")) + w1 := httptest.NewRecorder() + srv.ApproveDevice(w1, req1) + if w1.Code != http.StatusOK { + t.Fatalf("first approve: %d", w1.Code) + } + + // Second approval — conflict. + req2 := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(body)) + req2 = req2.WithContext(withUser(req2.Context(), "a1", "")) + w2 := httptest.NewRecorder() + srv.ApproveDevice(w2, req2) + if w2.Code != http.StatusConflict { + t.Errorf("second approve status = %d, want 409", w2.Code) + } +} + +func TestDeviceTokenExpired(t *testing.T) { + srv, st := deviceTestController() + st.CreateDeviceCode(&store.DeviceCode{ + DeviceCode: "expired-code-123", + UserCode: "EXPR-TEST", + Status: "pending", + ExpiresAt: time.Now().Add(-1 * time.Minute), + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/device/token", strings.NewReader(`{"device_code":"expired-code-123"}`)) + w := httptest.NewRecorder() + srv.DeviceToken(w, req) + if w.Code != http.StatusGone { + t.Errorf("status = %d, want 410", w.Code) + } +} + +func TestDeviceApproveExpiredCode(t *testing.T) { + srv, st := deviceTestController() + st.CreateDeviceCode(&store.DeviceCode{ + DeviceCode: "expired-approve", + UserCode: "EXPX-TEST", + Status: "pending", + ExpiresAt: time.Now().Add(-1 * time.Minute), + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(`{"user_code":"EXPX-TEST"}`)) + req = req.WithContext(withUser(req.Context(), "a1", "")) + w := httptest.NewRecorder() + srv.ApproveDevice(w, req) + if w.Code != http.StatusGone { + t.Errorf("status = %d, want 410", w.Code) + } +} + +func TestDeviceApproveCaseInsensitive(t *testing.T) { + srv, _ := deviceTestController() + + codeReq := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) + codeW := httptest.NewRecorder() + srv.DeviceCode(codeW, codeReq) + var codeResp map[string]any + json.Unmarshal(codeW.Body.Bytes(), &codeResp) + userCode := codeResp["user_code"].(string) + + // Approve with lowercase. + body := fmt.Sprintf(`{"user_code":"%s"}`, strings.ToLower(userCode)) + req := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(body)) + req = req.WithContext(withUser(req.Context(), "a1", "")) + w := httptest.NewRecorder() + srv.ApproveDevice(w, req) + if w.Code != http.StatusOK { + t.Errorf("lowercase approve status = %d, want 200", w.Code) + } +} + +func TestGenerateUserCodeFormat(t *testing.T) { + for range 20 { + code, err := generateUserCode() + if err != nil { + t.Fatalf("generateUserCode: %v", err) + } + if len(code) != 9 || code[4] != '-' { + t.Errorf("code = %q, want XXXX-XXXX format", code) + } + for _, c := range strings.ReplaceAll(code, "-", "") { + if c == '0' || c == 'O' || c == '1' || c == 'I' || c == 'L' { + t.Errorf("code %q contains ambiguous char %q", code, c) + } + } + } +} + +func TestSha256HashDeterministic(t *testing.T) { + h1 := sha256Hash("test-input") + h2 := sha256Hash("test-input") + if h1 != h2 { + t.Error("sha256Hash should be deterministic") + } + if len(h1) != 64 { + t.Errorf("hash length = %d, want 64", len(h1)) + } + h3 := sha256Hash("different") + if h1 == h3 { + t.Error("different inputs should produce different hashes") + } +} diff --git a/coordinator/api/accounts/device_tokens.go b/coordinator/api/accounts/device_tokens.go new file mode 100644 index 0000000000..bf580b6d3e --- /dev/null +++ b/coordinator/api/accounts/device_tokens.go @@ -0,0 +1,90 @@ +package accounts + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "net/http" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httprequest" + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// DeviceToken polls for a device authorization result. +// POST /v1/device/token +// No auth required — security comes from the device_code being secret. +func (s *Controller) DeviceToken(w http.ResponseWriter, r *http.Request) { + var req struct { + DeviceCode string `json:"device_code"` + } + if !httprequest.DecodeJSON(w, r, httprequest.ControlPlaneBodyLimit, &req) { + return + } + if req.DeviceCode == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request", "device_code is required")) + return + } + + dc, err := s.store().GetDeviceCode(req.DeviceCode) + if err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("invalid_grant", "device code not found")) + return + } + + // Check expiry. + if time.Now().After(dc.ExpiresAt) { + httpresponse.WriteJSON(w, http.StatusGone, httpresponse.ErrorBody("expired_token", "device code has expired")) + return + } + + switch dc.Status { + case "pending": + // RFC 8628: "authorization_pending" — not yet approved. + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "authorization_pending", + }) + + case "approved": + // Generate a long-lived provider token. + tokenBytes := make([]byte, 32) + if _, err := rand.Read(tokenBytes); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("server_error", "failed to generate token")) + return + } + rawToken := "eigeninference-pt-" + hex.EncodeToString(tokenBytes) + tokenHash := sha256Hash(rawToken) + + pt := &store.ProviderToken{ + TokenHash: tokenHash, + AccountID: dc.AccountID, + Label: "device-" + dc.UserCode, + Active: true, + } + if err := s.store().CreateProviderToken(pt); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("server_error", "failed to create token")) + return + } + + s.logger.Info("provider token issued", + "account_id", dc.AccountID, + "user_code", dc.UserCode, + ) + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "authorized", + "token": rawToken, + "account_id": dc.AccountID, + }) + + default: + httpresponse.WriteJSON(w, http.StatusGone, httpresponse.ErrorBody("expired_token", "device code is no longer valid")) + } +} + +// sha256Hash returns the hex-encoded SHA-256 digest. +func sha256Hash(s string) string { + h := sha256.Sum256([]byte(s)) + return hex.EncodeToString(h[:]) +} diff --git a/coordinator/api/accounts/invites.go b/coordinator/api/accounts/invites.go new file mode 100644 index 0000000000..47d311e489 --- /dev/null +++ b/coordinator/api/accounts/invites.go @@ -0,0 +1,190 @@ +package accounts + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// CreateInvite handles POST /v1/admin/invite-codes. +func (s *Controller) CreateInvite(w http.ResponseWriter, r *http.Request) { + if !s.authorizeAdmin(w, r) { + return + } + + var req struct { + Code string `json:"code"` + AmountUSD float64 `json:"amount_usd"` + MaxUses int `json:"max_uses"` + ExpiresAt string `json:"expires_at,omitempty"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + + if req.AmountUSD <= 0 { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "amount_usd must be positive")) + return + } + + // Auto-generate code if empty + code := strings.ToUpper(strings.TrimSpace(req.Code)) + if code == "" { + b := make([]byte, 4) + rand.Read(b) + code = "INV-" + strings.ToUpper(hex.EncodeToString(b)) + } + + amountMicroUSD := int64(req.AmountUSD * 1_000_000) + if req.MaxUses < 0 { + req.MaxUses = 0 + } + if req.MaxUses == 0 { + req.MaxUses = 1 // default single-use + } + + ic := &store.InviteCode{ + Code: code, + AmountMicroUSD: amountMicroUSD, + MaxUses: req.MaxUses, + Active: true, + CreatedAt: time.Now(), + } + + if req.ExpiresAt != "" { + t, err := time.Parse(time.RFC3339, req.ExpiresAt) + if err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid expires_at: "+err.Error())) + return + } + ic.ExpiresAt = &t + } + + if err := s.store().CreateInviteCode(ic); err != nil { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("conflict", err.Error())) + return + } + + s.logger.Info("invite code created", "code", code, "amount_usd", req.AmountUSD, "max_uses", req.MaxUses) + httpresponse.WriteJSON(w, http.StatusCreated, map[string]any{ + "code": code, + "amount_usd": fmt.Sprintf("%.2f", float64(amountMicroUSD)/1_000_000), + "max_uses": req.MaxUses, + "expires_at": ic.ExpiresAt, + }) +} + +// ListInvites handles GET /v1/admin/invite-codes. +func (s *Controller) ListInvites(w http.ResponseWriter, r *http.Request) { + if !s.authorizeAdmin(w, r) { + return + } + + codes := s.store().ListInviteCodes() + type codeView struct { + Code string `json:"code"` + AmountUSD string `json:"amount_usd"` + MaxUses int `json:"max_uses"` + UsedCount int `json:"used_count"` + Active bool `json:"active"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + CreatedAt time.Time `json:"created_at"` + } + + views := make([]codeView, len(codes)) + for i, c := range codes { + views[i] = codeView{ + Code: c.Code, + AmountUSD: fmt.Sprintf("%.2f", float64(c.AmountMicroUSD)/1_000_000), + MaxUses: c.MaxUses, + UsedCount: c.UsedCount, + Active: c.Active, + ExpiresAt: c.ExpiresAt, + CreatedAt: c.CreatedAt, + } + } + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"invite_codes": views}) +} + +// DeactivateInvite handles DELETE /v1/admin/invite-codes. +func (s *Controller) DeactivateInvite(w http.ResponseWriter, r *http.Request) { + if !s.authorizeAdmin(w, r) { + return + } + + var req struct { + Code string `json:"code"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON")) + return + } + if req.Code == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "code is required")) + return + } + + if err := s.store().DeactivateInviteCode(req.Code); err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", err.Error())) + return + } + + s.logger.Info("invite code deactivated", "code", req.Code) + httpresponse.WriteJSON(w, http.StatusOK, map[string]string{"status": "deactivated"}) +} + +// RedeemInvite handles POST /v1/invite/redeem. +func (s *Controller) RedeemInvite(w http.ResponseWriter, r *http.Request) { + var req struct { + Code string `json:"code"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON")) + return + } + + code := strings.ToUpper(strings.TrimSpace(req.Code)) + if code == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "code is required")) + return + } + + accountID := requestcontext.AccountID(r.Context()) + + // Get the invite code to know the amount + ic, err := s.store().GetInviteCode(code) + if err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "invalid invite code")) + return + } + + // Claim and credit together; a failed balance write leaves the invite usable. + if err := s.store().RedeemInviteCode(code, accountID); err != nil { + if errors.Is(err, store.ErrInviteCredit) { + s.logger.Error("failed to credit invite balance", "account", accountID, "code", code, "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to credit balance")) + } else { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", err.Error())) + } + return + } + + balance := s.store().GetBalance(accountID) + s.logger.Info("invite code redeemed", "code", code, "account", accountID, "amount_micro_usd", ic.AmountMicroUSD) + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "credited_usd": fmt.Sprintf("%.2f", float64(ic.AmountMicroUSD)/1_000_000), + "balance_usd": fmt.Sprintf("%.6f", float64(balance)/1_000_000), + }) +} diff --git a/coordinator/api/accounts/key_inputs.go b/coordinator/api/accounts/key_inputs.go new file mode 100644 index 0000000000..7f7e06fbf1 --- /dev/null +++ b/coordinator/api/accounts/key_inputs.go @@ -0,0 +1,144 @@ +package accounts + +import ( + "encoding/json" + "math" + "strings" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// createAPIKeyRequest is the POST /v1/keys (and rotate inherit) body. Money is +// supplied in USD; the wire never sees the secret after the create response. +type createAPIKeyRequest struct { + Name string `json:"name"` + LimitUSD *float64 `json:"limit_usd"` + LimitReset string `json:"limit_reset"` + RPMLimit *int64 `json:"rpm_limit"` + ITPMLimit *int64 `json:"itpm_limit"` + OTPMLimit *int64 `json:"otpm_limit"` + AllowedModels []string `json:"allowed_models"` + SelfRouteOnly bool `json:"self_route_only"` + ExpiresAt *time.Time `json:"expires_at"` +} + +// usdToMicro converts a USD dollar amount to micro-USD (rounded). +func usdToMicro(usd float64) int64 { return int64(math.Round(usd * 1_000_000)) } + +// microToUSD converts micro-USD to a USD float. +func microToUSD(micro int64) float64 { return float64(micro) / 1_000_000 } + +// validateKeyLimitInputs sanity-checks user-supplied limit values. Returns a +// human-readable error string (empty when valid). +func validateKeyLimitInputs(reset string, limitUSD *float64, rpm, itpm, otpm *int64, expiresAt *time.Time) string { + switch reset { + case "", store.KeyResetNone, store.KeyResetDaily, store.KeyResetWeekly, store.KeyResetMonthly: + default: + return "limit_reset must be one of: none, daily, weekly, monthly" + } + if limitUSD != nil && *limitUSD < 0 { + return "limit_usd must be >= 0" + } + if rpm != nil && *rpm < 0 { + return "rpm_limit must be >= 0" + } + if itpm != nil && *itpm < 0 { + return "itpm_limit must be >= 0" + } + if otpm != nil && *otpm < 0 { + return "otpm_limit must be >= 0" + } + if expiresAt != nil && !expiresAt.IsZero() && expiresAt.Before(time.Now()) { + return "expires_at must be in the future" + } + return "" +} + +// applyKeyPatch merges a presence-aware PATCH body into an existing key record. +// Returns a human-readable error string on invalid input (empty when ok). +func applyKeyPatch(k *store.APIKey, patch map[string]json.RawMessage) string { + if raw, ok := patch["name"]; ok { + var name string + if err := json.Unmarshal(raw, &name); err != nil { + return "invalid value for name" + } + k.Name = strings.TrimSpace(name) + } + if raw, ok := patch["disabled"]; ok { + var disabled bool + if err := json.Unmarshal(raw, &disabled); err != nil { + return "invalid value for disabled" + } + k.Disabled = disabled + } + if raw, ok := patch["limit_reset"]; ok { + var reset string + if err := json.Unmarshal(raw, &reset); err != nil { + return "invalid value for limit_reset" + } + k.LimitReset = store.NormalizeResetWindow(reset) + } + if raw, ok := patch["limit_usd"]; ok { + if string(raw) == "null" { + k.LimitMicroUSD = nil + } else { + var usd float64 + if err := json.Unmarshal(raw, &usd); err != nil { + return "invalid value for limit_usd" + } + if usd < 0 { + return "limit_usd must be >= 0" + } + m := usdToMicro(usd) + k.LimitMicroUSD = &m + } + } + if raw, ok := patch["allowed_models"]; ok { + if string(raw) == "null" { + k.AllowedModels = nil + } else { + var models []string + if err := json.Unmarshal(raw, &models); err != nil { + return "invalid value for allowed_models" + } + k.AllowedModels = models + } + } + if raw, ok := patch["self_route_only"]; ok { + var v bool + if err := json.Unmarshal(raw, &v); err != nil { + return "invalid value for self_route_only" + } + k.SelfRouteOnly = v + } + for field, dst := range map[string]**int64{ + "rpm_limit": &k.RPMLimit, + "itpm_limit": &k.ITPMLimit, + "otpm_limit": &k.OTPMLimit, + } { + if raw, ok := patch[field]; ok { + if string(raw) == "null" { + *dst = nil + } else { + var v int64 + if err := json.Unmarshal(raw, &v); err != nil { + return "invalid value for " + field + } + *dst = &v + } + } + } + if raw, ok := patch["expires_at"]; ok { + if string(raw) == "null" { + k.ExpiresAt = nil + } else { + var t time.Time + if err := json.Unmarshal(raw, &t); err != nil { + return "invalid value for expires_at (use RFC 3339)" + } + k.ExpiresAt = &t + } + } + return "" +} diff --git a/coordinator/api/accounts/key_policy.go b/coordinator/api/accounts/key_policy.go new file mode 100644 index 0000000000..e921444624 --- /dev/null +++ b/coordinator/api/accounts/key_policy.go @@ -0,0 +1,50 @@ +package accounts + +import ( + "context" + "fmt" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// KeyModelAllowed returns false when the calling key restricts models via an +// allow-list that does not include the requested model. Account-scoped/legacy +// keys (no key in context) and keys without an allow-list always pass. +func KeyModelAllowed(ctx context.Context, model string) bool { + k := requestcontext.APIKey(ctx) + if k == nil || len(k.AllowedModels) == 0 { + return true + } + for _, m := range k.AllowedModels { + if m == model { + return true + } + } + return false +} + +// CheckKeySpendCap reports whether charging additionalMicroUSD to the calling +// key would exceed its per-key spend cap in the current window. It returns +// (message, ok); ok=false means the request must be rejected with 402. The +// per-account balance ledger is still the hard atomic ceiling — this is the +// soft, per-key sub-cap, enforced against settled usage (so concurrent +// in-flight requests are eventually-consistent, never over the account balance). +func CheckKeySpendCap(ctx context.Context, additionalMicroUSD int64, usage KeyUsage) (string, bool) { + k := requestcontext.APIKey(ctx) + if k == nil || k.ID == "" || k.LimitMicroUSD == nil { + return "", true + } + since := store.KeySpendWindowStart(k.LimitReset, time.Now()) + spent := usage.KeySpendSince(k.ID, since) + if spent+additionalMicroUSD > *k.LimitMicroUSD { + window := store.NormalizeResetWindow(k.LimitReset) + if window == store.KeyResetNone { + window = "total" + } + return fmt.Sprintf("API key spend limit reached (%s cap $%.2f, used $%.2f) — raise this key's limit or use another key", + window, microToUSD(*k.LimitMicroUSD), microToUSD(spent)), false + } + return "", true +} diff --git a/coordinator/api/accounts/key_projection.go b/coordinator/api/accounts/key_projection.go new file mode 100644 index 0000000000..f05b775be6 --- /dev/null +++ b/coordinator/api/accounts/key_projection.go @@ -0,0 +1,42 @@ +package accounts + +import ( + "time" + + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// apiKeyToResponse projects a stored key into its masked API representation, +// computing the current-window spend and remaining budget. +func (s *Controller) apiKeyToResponse(k *store.APIKey) types.APIKeyResponse { + resp := types.APIKeyResponse{ + ID: k.ID, + Name: k.Name, + Label: k.Label, + Disabled: k.Disabled, + LimitReset: store.NormalizeResetWindow(k.LimitReset), + RPMLimit: k.RPMLimit, + ITPMLimit: k.ITPMLimit, + OTPMLimit: k.OTPMLimit, + AllowedModels: k.AllowedModels, + SelfRouteOnly: k.SelfRouteOnly, + ExpiresAt: k.ExpiresAt, + CreatedAt: k.CreatedAt, + LastUsedAt: k.LastUsedAt, + } + since := store.KeySpendWindowStart(resp.LimitReset, time.Now()) + spent := s.store().KeySpendSince(k.ID, since) + resp.UsageUSD = microToUSD(spent) + if k.LimitMicroUSD != nil { + limitUSD := microToUSD(*k.LimitMicroUSD) + resp.LimitUSD = &limitUSD + remaining := *k.LimitMicroUSD - spent + if remaining < 0 { + remaining = 0 + } + remUSD := microToUSD(remaining) + resp.RemainingUSD = &remUSD + } + return resp +} diff --git a/coordinator/api/accounts/keys.go b/coordinator/api/accounts/keys.go new file mode 100644 index 0000000000..a756257325 --- /dev/null +++ b/coordinator/api/accounts/keys.go @@ -0,0 +1,197 @@ +package accounts + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/auth" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// ListKeys handles GET /v1/keys — lists the caller's keys (masked). +func (s *Controller) ListKeys(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + if user == nil { + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("auth_error", "authentication required")) + return + } + keys, err := s.store().ListAPIKeys(user.AccountID) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("server_error", "failed to list keys")) + return + } + out := make([]types.APIKeyResponse, 0, len(keys)) + for i := range keys { + out = append(out, s.apiKeyToResponse(&keys[i])) + } + httpresponse.WriteJSON(w, http.StatusOK, types.APIKeyListResponse{Object: "list", Data: out}) +} + +// CreateKey handles POST /v1/keys — mints a new named, optionally +// limited key. The raw secret is returned exactly once. +func (s *Controller) CreateKey(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + if user == nil { + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("auth_error", + "API key creation requires a Privy account — authenticate with a Privy access token")) + return + } + + var req createAPIKeyRequest + if r.Body != nil { + // A missing/empty body is allowed (creates a default unnamed key). + if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("bad_request", "invalid JSON body")) + return + } + } + if msg := validateKeyLimitInputs(req.LimitReset, req.LimitUSD, req.RPMLimit, req.ITPMLimit, req.OTPMLimit, req.ExpiresAt); msg != "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("bad_request", msg)) + return + } + + opts := store.APIKeyCreate{ + Name: strings.TrimSpace(req.Name), + LimitReset: store.NormalizeResetWindow(req.LimitReset), + RPMLimit: req.RPMLimit, + ITPMLimit: req.ITPMLimit, + OTPMLimit: req.OTPMLimit, + AllowedModels: req.AllowedModels, + SelfRouteOnly: req.SelfRouteOnly, + ExpiresAt: req.ExpiresAt, + } + if req.LimitUSD != nil { + m := usdToMicro(*req.LimitUSD) + opts.LimitMicroUSD = &m + } + + raw, rec, err := s.store().CreateAPIKey(user.AccountID, opts) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("server_error", "failed to create key")) + return + } + httpresponse.WriteJSON(w, http.StatusOK, types.CreateAPIKeyResponse{ + Key: raw, + Data: s.apiKeyToResponse(rec), + }) +} + +// GetKey handles GET /v1/keys/{id}. +func (s *Controller) GetKey(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + if user == nil { + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("auth_error", "authentication required")) + return + } + id := r.PathValue("id") + k, err := s.store().GetAPIKeyByID(user.AccountID, id) + if err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "key not found")) + return + } + httpresponse.WriteJSON(w, http.StatusOK, s.apiKeyToResponse(k)) +} + +// GetCallingKey handles GET /v1/key — returns the metadata for the API +// key used to authenticate the request (OpenRouter parity). +func (s *Controller) GetCallingKey(w http.ResponseWriter, r *http.Request) { + k := requestcontext.APIKey(r.Context()) + if k == nil || k.ID == "" { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", + "no key metadata — this endpoint requires API key authentication")) + return + } + httpresponse.WriteJSON(w, http.StatusOK, s.apiKeyToResponse(k)) +} + +// UpdateKey handles PATCH /v1/keys/{id} — sparse update of a key's +// name, disabled flag, limits, reset window, expiry, and model allow-list. +func (s *Controller) UpdateKey(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + if user == nil { + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("auth_error", "authentication required")) + return + } + id := r.PathValue("id") + existing, err := s.store().GetAPIKeyByID(user.AccountID, id) + if err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "key not found")) + return + } + + // Decode into a presence map so we can distinguish "field omitted" (leave + // unchanged) from "field set to null" (clear the limit). + var patch map[string]json.RawMessage + if err := json.NewDecoder(r.Body).Decode(&patch); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("bad_request", "invalid JSON body")) + return + } + if msg := applyKeyPatch(existing, patch); msg != "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("bad_request", msg)) + return + } + if msg := validateKeyLimitInputs(existing.LimitReset, nil, existing.RPMLimit, existing.ITPMLimit, existing.OTPMLimit, existing.ExpiresAt); msg != "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("bad_request", msg)) + return + } + + // Bump the auth-cache generation before AND after the mutation so a + // concurrent request cannot keep authenticating with a stale (e.g. + // just-disabled) cached record. + s.keyCache.InvalidateAllKeys() + updated, err := s.store().UpdateAPIKey(user.AccountID, id, *existing) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("server_error", "failed to update key")) + return + } + s.keyCache.InvalidateAllKeys() + httpresponse.WriteJSON(w, http.StatusOK, s.apiKeyToResponse(updated)) +} + +// DeleteKey handles DELETE /v1/keys/{id} — permanently deletes a key. +func (s *Controller) DeleteKey(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + if user == nil { + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("auth_error", "authentication required")) + return + } + id := r.PathValue("id") + s.keyCache.InvalidateAllKeys() + if err := s.store().RevokeAPIKeyByID(user.AccountID, id); err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "key not found")) + return + } + s.keyCache.InvalidateAllKeys() + httpresponse.WriteJSON(w, http.StatusOK, types.RevokeKeyResponse{Status: "revoked"}) +} + +// RotateKey handles POST /v1/keys/{id}/rotate — mints a fresh secret +// carrying the same limits and metadata, then deletes the old key. The new +// secret is returned exactly once. +func (s *Controller) RotateKey(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + if user == nil { + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("auth_error", "authentication required")) + return + } + id := r.PathValue("id") + // Bump the auth-cache generation before AND after the mutation so the old + // secret stops authenticating the instant rotation commits. + s.keyCache.InvalidateAllKeys() + raw, rec, err := s.store().RotateAPIKey(user.AccountID, id) + if err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "key not found")) + return + } + s.keyCache.InvalidateAllKeys() + httpresponse.WriteJSON(w, http.StatusOK, types.CreateAPIKeyResponse{ + Key: raw, + Data: s.apiKeyToResponse(rec), + }) +} diff --git a/coordinator/api/accounts/keys_legacy.go b/coordinator/api/accounts/keys_legacy.go new file mode 100644 index 0000000000..79baaa16f0 --- /dev/null +++ b/coordinator/api/accounts/keys_legacy.go @@ -0,0 +1,65 @@ +package accounts + +import ( + "encoding/json" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/auth" +) + +// CreateLegacyKey handles POST /v1/auth/keys — creates a new consumer API key. +// Requires Privy authentication. The key is linked to the user's account so +// requests made with the key are billed to the same account. +func (s *Controller) CreateLegacyKey(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + if user == nil { + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("auth_error", + "API key creation requires a Privy account — authenticate with a Privy access token")) + return + } + + key, err := s.store().CreateKeyForAccount(user.AccountID) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("server_error", "failed to create key")) + return + } + httpresponse.WriteJSON(w, http.StatusOK, types.CreateKeyResponse{ + APIKey: key, + AccountID: user.AccountID, + }) +} + +// RevokeLegacyKey handles DELETE /v1/auth/keys — revokes an API key. +// The caller must own the key (same account). Requires Privy auth so a +// compromised API key cannot revoke legitimate keys. +func (s *Controller) RevokeLegacyKey(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + if user == nil { + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("auth_error", "authentication required")) + return + } + + var body struct { + Key string `json:"key"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Key == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("bad_request", "provide {\"key\": \"sk-db-...\"}")) + return + } + + owner := s.store().GetKeyAccount(body.Key) + if owner != user.AccountID { + httpresponse.WriteJSON(w, http.StatusForbidden, httpresponse.ErrorBody("forbidden", "you can only revoke your own keys")) + return + } + + if !s.store().RevokeKey(body.Key) { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "key not found or already revoked")) + return + } + s.keyCache.InvalidateKey(body.Key) + + httpresponse.WriteJSON(w, http.StatusOK, types.RevokeKeyResponse{Status: "revoked"}) +} diff --git a/coordinator/api/accounts/keys_test.go b/coordinator/api/accounts/keys_test.go new file mode 100644 index 0000000000..acb0da25cb --- /dev/null +++ b/coordinator/api/accounts/keys_test.go @@ -0,0 +1,196 @@ +package accounts + +import ( + "context" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/api/requestauth" + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/auth" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func newKeyTestController(t *testing.T) (*Controller, *store.MemoryStore) { + t.Helper() + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + srv := New(Dependencies{Store: func() Store { return st }, Logger: logger, ConsoleURL: func() string { return "" }, KeyCache: requestauth.New()}) + return srv, st +} + +// reqWithUser builds a request whose context carries an authenticated user, +// simulating what requirePrivyAuth installs (so we can unit-test the handlers +// without minting a real Privy JWT). +func reqWithUser(method, target, body, accountID string) *http.Request { + var r *http.Request + if body == "" { + r = httptest.NewRequest(method, target, nil) + } else { + r = httptest.NewRequest(method, target, strings.NewReader(body)) + } + ctx := context.WithValue(r.Context(), auth.CtxKeyUser, &store.User{AccountID: accountID}) + ctx = requestcontext.WithAccountID(ctx, accountID) + return r.WithContext(ctx) +} + +func TestHandleCreateAndListAPIKeys(t *testing.T) { + srv, _ := newKeyTestController(t) + + // Create a key with a $10 monthly cap. + body := `{"name":"prod","limit_usd":10,"limit_reset":"monthly","rpm_limit":120}` + w := httptest.NewRecorder() + srv.CreateKey(w, reqWithUser(http.MethodPost, "/v1/keys", body, "acct-1")) + if w.Code != http.StatusOK { + t.Fatalf("create status = %d, body=%s", w.Code, w.Body.String()) + } + var created types.CreateAPIKeyResponse + if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil { + t.Fatalf("decode create: %v", err) + } + if !strings.HasPrefix(created.Key, store.KeyPrefix) { + t.Errorf("returned secret %q missing prefix", created.Key) + } + if created.Data.LimitUSD == nil || *created.Data.LimitUSD != 10 { + t.Errorf("limit_usd = %v, want 10", created.Data.LimitUSD) + } + if created.Data.LimitReset != "monthly" { + t.Errorf("limit_reset = %q", created.Data.LimitReset) + } + if created.Data.RPMLimit == nil || *created.Data.RPMLimit != 120 { + t.Errorf("rpm_limit = %v", created.Data.RPMLimit) + } + if strings.Contains(created.Data.Label, created.Key[10:40]) { + t.Errorf("label leaks secret: %q", created.Data.Label) + } + + // List shows exactly one key (masked, no secret). + w = httptest.NewRecorder() + srv.ListKeys(w, reqWithUser(http.MethodGet, "/v1/keys", "", "acct-1")) + if w.Code != http.StatusOK { + t.Fatalf("list status = %d", w.Code) + } + var list types.APIKeyListResponse + if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil { + t.Fatalf("decode list: %v", err) + } + if len(list.Data) != 1 { + t.Fatalf("list len = %d, want 1", len(list.Data)) + } + if strings.Contains(w.Body.String(), created.Key) { + t.Error("list response must not contain the raw secret") + } +} + +func TestHandleUpdateAndDisableViaPatch(t *testing.T) { + srv, _ := newKeyTestController(t) + + w := httptest.NewRecorder() + srv.CreateKey(w, reqWithUser(http.MethodPost, "/v1/keys", `{"name":"a","limit_usd":5}`, "acct-1")) + var created types.CreateAPIKeyResponse + json.Unmarshal(w.Body.Bytes(), &created) + id := created.Data.ID + + // PATCH: disable + clear the limit (limit_usd: null) + rename. + patch := `{"name":"renamed","disabled":true,"limit_usd":null}` + r := reqWithUser(http.MethodPatch, "/v1/keys/"+id, patch, "acct-1") + r.SetPathValue("id", id) + w = httptest.NewRecorder() + srv.UpdateKey(w, r) + if w.Code != http.StatusOK { + t.Fatalf("patch status = %d, body=%s", w.Code, w.Body.String()) + } + var updated types.APIKeyResponse + json.Unmarshal(w.Body.Bytes(), &updated) + if updated.Name != "renamed" { + t.Errorf("name = %q", updated.Name) + } + if !updated.Disabled { + t.Error("key should be disabled") + } + if updated.LimitUSD != nil { + t.Errorf("limit_usd should be cleared, got %v", *updated.LimitUSD) + } +} + +func TestHandleRotateAPIKey(t *testing.T) { + srv, st := newKeyTestController(t) + + w := httptest.NewRecorder() + srv.CreateKey(w, reqWithUser(http.MethodPost, "/v1/keys", `{"name":"a","limit_usd":7,"limit_reset":"weekly"}`, "acct-1")) + var created types.CreateAPIKeyResponse + json.Unmarshal(w.Body.Bytes(), &created) + oldID := created.Data.ID + oldSecret := created.Key + + r := reqWithUser(http.MethodPost, "/v1/keys/"+oldID+"/rotate", "", "acct-1") + r.SetPathValue("id", oldID) + w = httptest.NewRecorder() + srv.RotateKey(w, r) + if w.Code != http.StatusOK { + t.Fatalf("rotate status = %d, body=%s", w.Code, w.Body.String()) + } + var rotated types.CreateAPIKeyResponse + json.Unmarshal(w.Body.Bytes(), &rotated) + if rotated.Key == oldSecret { + t.Error("rotate must mint a new secret") + } + if rotated.Data.ID == oldID { + t.Error("rotate must produce a new key id") + } + // Limits carried over. + if rotated.Data.LimitUSD == nil || *rotated.Data.LimitUSD != 7 || rotated.Data.LimitReset != "weekly" { + t.Errorf("limits not carried over: %+v", rotated.Data) + } + // Old key gone. + if _, err := st.AuthenticateKey(oldSecret); err == nil { + t.Error("old secret should be revoked after rotate") + } + // New key authenticates. + if _, err := st.AuthenticateKey(rotated.Key); err != nil { + t.Errorf("new secret should authenticate: %v", err) + } +} + +func TestHandleDeleteAPIKeyScoping(t *testing.T) { + srv, _ := newKeyTestController(t) + + w := httptest.NewRecorder() + srv.CreateKey(w, reqWithUser(http.MethodPost, "/v1/keys", `{"name":"a"}`, "acct-1")) + var created types.CreateAPIKeyResponse + json.Unmarshal(w.Body.Bytes(), &created) + id := created.Data.ID + + // Another account cannot delete it. + r := reqWithUser(http.MethodDelete, "/v1/keys/"+id, "", "acct-2") + r.SetPathValue("id", id) + w = httptest.NewRecorder() + srv.DeleteKey(w, r) + if w.Code != http.StatusNotFound { + t.Fatalf("cross-account delete status = %d, want 404", w.Code) + } + + // Owner can. + r = reqWithUser(http.MethodDelete, "/v1/keys/"+id, "", "acct-1") + r.SetPathValue("id", id) + w = httptest.NewRecorder() + srv.DeleteKey(w, r) + if w.Code != http.StatusOK { + t.Fatalf("owner delete status = %d, want 200", w.Code) + } +} + +func TestHandleCreateAPIKeyRejectsBadInput(t *testing.T) { + srv, _ := newKeyTestController(t) + w := httptest.NewRecorder() + srv.CreateKey(w, reqWithUser(http.MethodPost, "/v1/keys", `{"limit_reset":"hourly"}`, "acct-1")) + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 for bad reset window", w.Code) + } +} diff --git a/coordinator/api/accounts/store.go b/coordinator/api/accounts/store.go new file mode 100644 index 0000000000..6dc7180cf3 --- /dev/null +++ b/coordinator/api/accounts/store.go @@ -0,0 +1,51 @@ +package accounts + +import ( + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// KeyUsage reads settled usage for the existing soft per-key spend cap. +// The account ledger remains the atomic balance ceiling. +type KeyUsage interface{ KeySpendSince(string, time.Time) int64 } + +// KeyStore supplies key records, scoped mutations and settled usage. +type KeyStore interface { + KeyUsage + CreateKeyForAccount(string) (string, error) + GetKeyAccount(string) string + RevokeKey(string) bool + CreateAPIKey(string, store.APIKeyCreate) (string, *store.APIKey, error) + ListAPIKeys(string) ([]store.APIKey, error) + GetAPIKeyByID(string, string) (*store.APIKey, error) + UpdateAPIKey(string, string, store.APIKey) (*store.APIKey, error) + RevokeAPIKeyByID(string, string) error + RotateAPIKey(string, string) (string, *store.APIKey, error) +} + +// DeviceStore persists device approvals and issued provider tokens. +type DeviceStore interface { + CreateDeviceCode(*store.DeviceCode) error + GetDeviceCode(string) (*store.DeviceCode, error) + GetDeviceCodeByUserCode(string) (*store.DeviceCode, error) + ApproveDeviceCode(string, string) error + CreateProviderToken(*store.ProviderToken) error +} + +// InviteStore owns atomic invite redemption and reads the resulting balance. +type InviteStore interface { + CreateInviteCode(*store.InviteCode) error + GetInviteCode(string) (*store.InviteCode, error) + ListInviteCodes() []store.InviteCode + DeactivateInviteCode(string) error + RedeemInviteCode(string, string) error + GetBalance(string) int64 +} + +// Store composes only the persistence domains used by account operations. +type Store interface { + KeyStore + DeviceStore + InviteStore +} diff --git a/coordinator/api/admin_auth.go b/coordinator/api/admin_auth.go new file mode 100644 index 0000000000..72c5e50539 --- /dev/null +++ b/coordinator/api/admin_auth.go @@ -0,0 +1,93 @@ +package api + +import ( + "crypto/subtle" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/auth" +) + +// isAdminAuthorized checks if the request is from an admin. +// Accepts either Privy admin (email in admin list) OR EIGENINFERENCE_ADMIN_KEY. +func (s *Server) isAdminAuthorized(w http.ResponseWriter, r *http.Request) bool { + // Check admin key first (no Privy needed). + token := extractBearerToken(r) + if token != "" && s.adminKey != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.adminKey)) == 1 { + return true + } + + // Check Privy admin. + user := auth.UserFromContext(r.Context()) + if user != nil && s.isAdmin(user) { + return true + } + + writeJSON(w, http.StatusForbidden, errorResponse("forbidden", "admin access required")) + return false +} + +// handleAdminAuthInit handles POST /v1/admin/auth/init. +// Sends an OTP code to the given email via Privy. Used by the admin CLI. +func (s *Server) handleAdminAuthInit(w http.ResponseWriter, r *http.Request) { + if s.privyAuth == nil { + writeJSON(w, http.StatusServiceUnavailable, errorResponse("not_configured", "Privy auth not configured")) + return + } + + var req struct { + Email string `json:"email"` + } + if !decodeCappedJSON(w, r, maxControlPlaneBodyBytes, &req) { + return + } + if req.Email == "" { + writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "email is required")) + return + } + + if err := s.privyAuth.InitEmailOTP(req.Email); err != nil { + s.logger.Error("admin auth: OTP init failed", "email", req.Email, "error", err) + writeJSON(w, http.StatusInternalServerError, errorResponse("otp_error", "failed to send OTP: "+err.Error())) + return + } + + s.logger.Info("admin auth: OTP sent", "email", req.Email) + writeJSON(w, http.StatusOK, map[string]any{ + "status": "otp_sent", + "email": req.Email, + }) +} + +// handleAdminAuthVerify handles POST /v1/admin/auth/verify. +// Verifies the OTP code and returns a Privy access token for admin use. +func (s *Server) handleAdminAuthVerify(w http.ResponseWriter, r *http.Request) { + if s.privyAuth == nil { + writeJSON(w, http.StatusServiceUnavailable, errorResponse("not_configured", "Privy auth not configured")) + return + } + + var req struct { + Email string `json:"email"` + Code string `json:"code"` + } + if !decodeCappedJSON(w, r, maxControlPlaneBodyBytes, &req) { + return + } + if req.Email == "" || req.Code == "" { + writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "email and code are required")) + return + } + + token, err := s.privyAuth.VerifyEmailOTP(req.Email, req.Code) + if err != nil { + s.logger.Warn("admin auth: OTP verification failed", "email", req.Email, "error", err) + writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", "OTP verification failed: "+err.Error())) + return + } + + s.logger.Info("admin auth: login successful", "email", req.Email) + writeJSON(w, http.StatusOK, map[string]any{ + "token": token, + "email": req.Email, + }) +} diff --git a/coordinator/api/admin_balance_adjustment.go b/coordinator/api/admin_balance_adjustment.go deleted file mode 100644 index 2eaeca941f..0000000000 --- a/coordinator/api/admin_balance_adjustment.go +++ /dev/null @@ -1,80 +0,0 @@ -package api - -import ( - "encoding/json" - "net/http" - "strconv" - - "github.com/eigeninference/d-inference/coordinator/store" -) - -// handleAdminCredit grants non-withdrawable inference credit. -func (s *Server) handleAdminCredit(w http.ResponseWriter, r *http.Request) { - s.handleAdminBalanceAdjustment(w, r, false) -} - -// handleAdminReward grants withdrawable earnings. -func (s *Server) handleAdminReward(w http.ResponseWriter, r *http.Request) { - s.handleAdminBalanceAdjustment(w, r, true) -} - -// Both admin adjustments share authorization, validation and account lookup. -// Their ledger operation and response fields remain explicitly separate. -func (s *Server) handleAdminBalanceAdjustment(w http.ResponseWriter, r *http.Request, withdrawable bool) { - if !s.isAdminAuthorized(w, r) { - return - } - - var req struct { - Email string `json:"email"` - AmountUSD string `json:"amount_usd"` - Note string `json:"note"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "invalid JSON: "+err.Error())) - return - } - if req.Email == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "email is required")) - return - } - amountFloat, err := strconv.ParseFloat(req.AmountUSD, 64) - if err != nil || amountFloat <= 0 { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "amount_usd must be a positive number")) - return - } - amountMicroUSD := int64(amountFloat * 1_000_000) - - user, err := s.store.GetUserByEmail(req.Email) - if err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("not_found", "no user found with email: "+req.Email)) - return - } - - action, entryType, credit := "credit", store.LedgerAdminCredit, s.store.Credit - if withdrawable { - action, entryType, credit = "reward", store.LedgerAdminReward, s.store.CreditWithdrawable - } - ref := string(entryType) - if req.Note != "" { - ref += ":" + req.Note - } - if err := credit(user.AccountID, amountMicroUSD, entryType, ref); err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to "+action+": "+err.Error())) - return - } - s.logger.Info("admin "+action+" applied", "email", req.Email, "account_id", user.AccountID, - "amount_micro_usd", amountMicroUSD, "note", req.Note) - response := map[string]any{ - "ok": true, "account_id": user.AccountID, "email": user.Email, - "withdrawable": withdrawable, - "balance_after": float64(s.store.GetBalance(user.AccountID)) / 1_000_000, - } - if withdrawable { - response["rewarded_usd"] = amountFloat - response["withdrawable_after"] = float64(s.store.GetWithdrawableBalance(user.AccountID)) / 1_000_000 - } else { - response["credited_usd"] = amountFloat - } - writeJSON(w, http.StatusOK, response) -} diff --git a/coordinator/api/admin_state_export.go b/coordinator/api/admin_state_export.go deleted file mode 100644 index afbbf9ef4c..0000000000 --- a/coordinator/api/admin_state_export.go +++ /dev/null @@ -1,218 +0,0 @@ -package api - -import ( - "crypto/sha256" - "crypto/subtle" - "io" - "net/http" - "os" - "strconv" - "strings" - "time" - - "github.com/eigeninference/d-inference/coordinator/env" - "github.com/eigeninference/d-inference/coordinator/stateexport" -) - -// State-export env vars (all namespaced under env.EnvPrefix == "EIGENINFERENCE"). -const ( - // envStateExportEnabled is the master switch. When != "true" the route 404s. - envStateExportEnabled = env.EnvPrefix + "_STATE_EXPORT_ENABLED" - // envStateExportRecipient is an age recipient ("age1..."). When set, output is - // encrypted to it; this is the default-secure path. - envStateExportRecipient = env.EnvPrefix + "_STATE_EXPORT_RECIPIENT" - // envStateExportAllowPlaintext permits a raw (unencrypted) zip ONLY when no - // recipient is configured. Must be explicitly "true". - envStateExportAllowPlaintext = env.EnvPrefix + "_STATE_EXPORT_ALLOW_PLAINTEXT" - // envStateExportRoot overrides the export root (primarily for tests). - envStateExportRoot = env.EnvPrefix + "_STATE_EXPORT_ROOT" -) - -// resolveStateExportRoot picks the directory to archive: -// EIGENINFERENCE_STATE_EXPORT_ROOT -> USER_PERSISTENT_DATA_PATH -> /mnt/disks/userdata. -func resolveStateExportRoot() string { - return env.FirstNonEmpty( - os.Getenv(envStateExportRoot), - os.Getenv("USER_PERSISTENT_DATA_PATH"), - "/mnt/disks/userdata", - ) -} - -// envTrue reports whether the named env var is set to "true" (case-insensitive, -// trimmed). Used for the boolean state-export gates. -func envTrue(name string) bool { - b, _ := strconv.ParseBool(strings.TrimSpace(os.Getenv(name))) - return b -} - -// handleAdminStateExport handles GET /v1/admin/state-export — it streams a -// consistent (and, by default, encrypted) archive of the coordinator's sealed -// on-disk state under /data for migration off EigenCloud (DAR-70). -// -// Triple gate, fail-closed, in order: -// 1. master switch (404 when off — route stays invisible/inert), -// 2. admin auth (admin-key only; Privy admin is intentionally NOT accepted), -// 3. output protection (encrypt to recipient, else 412 unless plaintext allowed). -func (s *Server) handleAdminStateExport(w http.ResponseWriter, r *http.Request) { - start := time.Now() - - // (a) Master switch — 404 when disabled so the route is indistinguishable - // from an unregistered path. - if !envTrue(envStateExportEnabled) { - http.NotFound(w, r) - return - } - - // (b) Admin auth — ADMIN KEY ONLY (constant-time), modeled on - // requireAdminKey's bearer-token check. This endpoint exfils the CA private - // key, so we deliberately do NOT accept the Privy-admin path: a compromised - // Privy admin email must not be able to pull the CA key. (The route is also - // not wrapped in Privy auth middleware, so auth.UserFromContext is nil here - // regardless.) - token := extractBearerToken(r) - // Hash both sides to a fixed 32 bytes before the constant-time compare so the - // check leaks neither the admin key's contents nor its length. (A bare - // ConstantTimeCompare returns early when the two byte slices differ in - // length — a minor timing side-channel on key length. This is the CA-key - // exfil endpoint, so close it.) - providedDigest := sha256.Sum256([]byte(token)) - expectedDigest := sha256.Sum256([]byte(s.adminKey)) - if s.adminKey == "" || subtle.ConstantTimeCompare(providedDigest[:], expectedDigest[:]) != 1 { - writeJSON(w, http.StatusForbidden, errorResponse("forbidden", "admin access required")) - s.logger.Warn("state-export: unauthorized access attempt", - "remote_addr", r.RemoteAddr, "authorized", false) - return - } - - // (c) Output protection. Encrypted by default. - recipientStr := strings.TrimSpace(os.Getenv(envStateExportRecipient)) - allowPlaintext := envTrue(envStateExportAllowPlaintext) - encrypted := recipientStr != "" - - if !encrypted && !allowPlaintext { - writeJSON(w, http.StatusPreconditionFailed, errorResponse("precondition_failed", - "set "+envStateExportRecipient+" to an age recipient, or set "+ - envStateExportAllowPlaintext+"=true to download unencrypted")) - s.logger.Warn("state-export: refused (no recipient, plaintext not allowed)", - "remote_addr", r.RemoteAddr, "authorized", true, "encrypted", false) - return - } - - // Stage (below) resolves (EvalSymlinks) + stats the root and returns a clean - // error mapped to a pre-stream 500, so no separate os.Stat pre-check here. - root := resolveStateExportRoot() - - // Compute the download filename / content-type BEFORE writing headers. - epoch := strconv.FormatInt(time.Now().Unix(), 10) - var filename, contentType string - if encrypted { - filename = "darkbloom-state-" + epoch + ".zip.age" - contentType = "application/octet-stream" - } else { - filename = "darkbloom-state-" + epoch + ".zip" - contentType = "application/zip" - } - - // Validate the recipient up front (before any header is written) so a parse - // failure is a clean 500 rather than a half-written stream. - if encrypted { - if err := stateexport.ValidateRecipient(recipientStr); err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("export_error", - "state export recipient is misconfigured")) - // Do not log the recipient material; log only that parsing failed. - s.logger.Error("state-export: recipient parse failed", - "remote_addr", r.RemoteAddr, "authorized", true, "encrypted", true) - return - } - } - - // PHASE A — snapshot+validate every *.db into a controlled staging dir BEFORE - // writing any response status/bytes. Any failure here is fail-clean: we emit a - // real 500 and the client gets ZERO archive bytes. This is what closes the - // "partial archive after 200" + "/tmp leak" findings: copies live in one - // staging dir we always RemoveAll, and a torn db that can't snapshot aborts - // the whole export up front. - arch := stateexport.NewArchiver() - arch.Logger = s.logger - // Propagate the request context (no artificial deadline — a legit large - // export must not be truncated by a timer) so a client disconnect cancels the - // snapshot/walk cleanly. - staged, stageErr := arch.Stage(r.Context(), root) - if stageErr != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("export_error", - "state export could not produce a consistent snapshot")) - s.logger.Error("state-export: staging failed (no bytes written)", - "remote_addr", r.RemoteAddr, "authorized", true, "encrypted", encrypted, - "root", root, "error", stageErr.Error()) - return - } - // Always release the staging dir + validated db copies, even on a mid-stream - // failure or panic. - defer staged.Cleanup() - - // PHASE B — only now commit to a 200 and stream the zip. - w.Header().Set("Content-Type", contentType) - w.Header().Set("Content-Disposition", `attachment; filename="`+filename+`"`) - w.WriteHeader(http.StatusOK) - - // Writer chain (streamed, never buffered): - // archiver -> [age encrypt] -> countingWriter -> http.ResponseWriter - // The counter wraps the response so it tallies the actual bytes sent to the - // client (ciphertext when encrypted). - counter := &countingWriter{w: w} - - var sink io.Writer = counter - var ageWriter io.WriteCloser - if encrypted { - aw, err := stateexport.EncryptWriter(counter, recipientStr) - if err != nil { - // Headers already sent; we can only abort the stream. - s.logger.Error("state-export: age writer init failed after headers", - "remote_addr", r.RemoteAddr, "error", err.Error()) - return - } - ageWriter = aw - sink = aw - } - - res, archErr := arch.Write(r.Context(), staged, sink) - - // For encrypted streams, MUST close the age writer to flush the final chunk. - if ageWriter != nil { - if cerr := ageWriter.Close(); cerr != nil && archErr == nil { - archErr = cerr - } - } - - if archErr != nil { - // Headers/body already in flight — cannot change status. Log the failure; - // the truncated stream signals the error to the client. - s.logger.Error("state-export: archive failed mid-stream", - "remote_addr", r.RemoteAddr, "authorized", true, "encrypted", encrypted, - "bytes", counter.n, "files", res.Files, "error", archErr.Error()) - return - } - - s.logger.Info("state-export: completed", - "remote_addr", r.RemoteAddr, - "authorized", true, - "encrypted", encrypted, - "files", res.Files, - "snapshotted_dbs", res.SnapshottedDBs, - "bytes", counter.n, - "duration_ms", time.Since(start).Milliseconds(), - "outcome", "ok", - ) -} - -// countingWriter tallies bytes written for the audit log without buffering. -type countingWriter struct { - w io.Writer - n int64 -} - -func (c *countingWriter) Write(p []byte) (int, error) { - n, err := c.w.Write(p) - c.n += int64(n) - return n, err -} diff --git a/coordinator/api/admin_state_export_test.go b/coordinator/api/admin_state_export_test.go deleted file mode 100644 index b9f93092e5..0000000000 --- a/coordinator/api/admin_state_export_test.go +++ /dev/null @@ -1,505 +0,0 @@ -package api - -import ( - "archive/zip" - "bytes" - "context" - "fmt" - "io" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "sync" - "testing" - "time" - - "filippo.io/age" - bolt "go.etcd.io/bbolt" - - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" -) - -// notZip reports whether b is NOT a zip (no PK\x03\x04 magic). A negative-path -// response (401/403/404/412/500) must contain ZERO archive bytes. -func notZip(b []byte) bool { - return !bytes.HasPrefix(b, []byte("PK\x03\x04")) -} - -const stateExportAdminKey = "dar70-admin-key" - -// newStateExportServer builds a real Server with the admin key set, wired to a -// fresh export root. It returns the httptest server URL and the export root. -func newStateExportServer(t *testing.T) (*httptest.Server, string) { - t.Helper() - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - srv.SetAdminKey(stateExportAdminKey) - - root := buildStateExportRoot(t) - t.Setenv(envStateExportRoot, root) - - ts := httptest.NewServer(srv.Handler()) - t.Cleanup(ts.Close) - return ts, root -} - -// buildStateExportRoot lays down a representative /data tree with a real bbolt db. -func buildStateExportRoot(t *testing.T) string { - t.Helper() - root := t.TempDir() - - writeFile(t, filepath.Join(root, "step-ca", "config", "ca.json"), `{"authority":{}}`) - writeFile(t, filepath.Join(root, "step-ca", "secrets", "password"), "eigeninference-step-ca") - writeFile(t, filepath.Join(root, "step-ca", "certs", "root_ca.crt"), "ROOT") - writeFile(t, filepath.Join(root, "step-ca", "certs", "intermediate_ca.crt"), "INT") - writeFile(t, filepath.Join(root, "step-ca", "certs", "intermediate_ca_key"), "INTKEY") - - writeFile(t, filepath.Join(root, "micromdm", "push.crt"), "PUSH") - writeFile(t, filepath.Join(root, "micromdm", "push.key"), "PUSHKEY") - writeFile(t, filepath.Join(root, "micromdm", "config"), "CFG") - writeFile(t, filepath.Join(root, "micromdm", ".push_imported"), "") - seedBolt(t, filepath.Join(root, "micromdm", "micromdm.db")) - - writeFile(t, filepath.Join(root, "step-ca.log"), "log") - writeFile(t, filepath.Join(root, "micromdm", "micromdm.log"), "log") - - return root -} - -func writeFile(t *testing.T, path, content string) { - t.Helper() - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(path, []byte(content), 0o600); err != nil { - t.Fatal(err) - } -} - -func seedBolt(t *testing.T, path string) { - t.Helper() - db, err := bolt.Open(path, 0o600, &bolt.Options{Timeout: time.Second}) - if err != nil { - t.Fatal(err) - } - defer db.Close() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("Devices")) - if err != nil { - return err - } - return b.Put([]byte("serial-1"), []byte("payload-1")) - }); err != nil { - t.Fatal(err) - } -} - -func getExport(t *testing.T, url, bearer string) *http.Response { - t.Helper() - req, err := http.NewRequest(http.MethodGet, url+"/v1/admin/state-export", nil) - if err != nil { - t.Fatal(err) - } - if bearer != "" { - req.Header.Set("Authorization", "Bearer "+bearer) - } - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Fatal(err) - } - return resp -} - -func zipEntries(t *testing.T, b []byte) map[string][]byte { - t.Helper() - zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) - if err != nil { - t.Fatalf("open zip: %v", err) - } - out := map[string][]byte{} - for _, f := range zr.File { - if f.FileInfo().IsDir() { - continue - } - rc, _ := f.Open() - data, _ := io.ReadAll(rc) - rc.Close() - out[f.Name] = data - } - return out -} - -// assertNoArchiveBytes reads the whole body and fails if it looks like a zip. -func assertNoArchiveBytes(t *testing.T, resp *http.Response) { - t.Helper() - body, err := io.ReadAll(resp.Body) - if err != nil { - t.Fatalf("read body: %v", err) - } - if !notZip(body) { - t.Fatalf("negative response (%d) leaked archive bytes (%d bytes, zip magic present)", - resp.StatusCode, len(body)) - } -} - -// (a) 404 when the master switch is unset — and no archive bytes. -func TestStateExport_DisabledReturns404_DAR70(t *testing.T) { - ts, _ := newStateExportServer(t) - // envStateExportEnabled deliberately not set. - resp := getExport(t, ts.URL, stateExportAdminKey) - defer resp.Body.Close() - if resp.StatusCode != http.StatusNotFound { - t.Fatalf("disabled: got %d, want 404", resp.StatusCode) - } - assertNoArchiveBytes(t, resp) -} - -// Disabled + missing/wrong admin key still 404 — the route is invisible -// regardless of auth (master switch precedes auth). -func TestStateExport_DisabledMasksAuth404_DAR70(t *testing.T) { - ts, _ := newStateExportServer(t) - // envStateExportEnabled deliberately not set. - for _, key := range []string{"", "wrong-key"} { - resp := getExport(t, ts.URL, key) - if resp.StatusCode != http.StatusNotFound { - resp.Body.Close() - t.Fatalf("disabled with key=%q: got %d, want 404", key, resp.StatusCode) - } - assertNoArchiveBytes(t, resp) - resp.Body.Close() - } -} - -// (b) 403 with missing/wrong admin key; success with the correct key. Negative -// responses must contain zero archive bytes. -func TestStateExport_AdminAuth_DAR70(t *testing.T) { - ts, _ := newStateExportServer(t) - t.Setenv(envStateExportEnabled, "true") - t.Setenv(envStateExportAllowPlaintext, "true") - - // Missing key. - resp := getExport(t, ts.URL, "") - if resp.StatusCode != http.StatusForbidden { - resp.Body.Close() - t.Fatalf("missing key: got %d, want 403", resp.StatusCode) - } - assertNoArchiveBytes(t, resp) - resp.Body.Close() - - // Wrong key. - resp = getExport(t, ts.URL, "wrong-key") - if resp.StatusCode != http.StatusForbidden { - resp.Body.Close() - t.Fatalf("wrong key: got %d, want 403", resp.StatusCode) - } - assertNoArchiveBytes(t, resp) - resp.Body.Close() - - // Correct key. - resp = getExport(t, ts.URL, stateExportAdminKey) - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - t.Fatalf("correct key: got %d, want 200", resp.StatusCode) - } -} - -// (c) 412 when no recipient and plaintext not allowed — and no archive bytes. -func TestStateExport_PreconditionFailed_DAR70(t *testing.T) { - ts, _ := newStateExportServer(t) - t.Setenv(envStateExportEnabled, "true") - // No recipient, no plaintext allowance. - resp := getExport(t, ts.URL, stateExportAdminKey) - defer resp.Body.Close() - if resp.StatusCode != http.StatusPreconditionFailed { - t.Fatalf("got %d, want 412", resp.StatusCode) - } - assertNoArchiveBytes(t, resp) -} - -// HTTP-level root-missing -> 500 with no archive bytes (root resolves to a path -// that does not exist). -func TestStateExport_RootMissing500_DAR70(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - srv.SetAdminKey(stateExportAdminKey) - ts := httptest.NewServer(srv.Handler()) - t.Cleanup(ts.Close) - - t.Setenv(envStateExportRoot, filepath.Join(t.TempDir(), "does-not-exist")) - t.Setenv(envStateExportEnabled, "true") - t.Setenv(envStateExportAllowPlaintext, "true") - - resp := getExport(t, ts.URL, stateExportAdminKey) - defer resp.Body.Close() - if resp.StatusCode != http.StatusInternalServerError { - t.Fatalf("missing root: got %d, want 500", resp.StatusCode) - } - assertNoArchiveBytes(t, resp) -} - -// resolveStateExportRoot precedence: -// EIGENINFERENCE_STATE_EXPORT_ROOT -> USER_PERSISTENT_DATA_PATH -> /mnt/disks/userdata. -func TestResolveStateExportRootPrecedence_DAR70(t *testing.T) { - // Default when nothing is set. - t.Setenv(envStateExportRoot, "") - t.Setenv("USER_PERSISTENT_DATA_PATH", "") - if got := resolveStateExportRoot(); got != "/mnt/disks/userdata" { - t.Fatalf("default = %q, want /mnt/disks/userdata", got) - } - // USER_PERSISTENT_DATA_PATH wins over the hardcoded default. - t.Setenv("USER_PERSISTENT_DATA_PATH", "/persist") - if got := resolveStateExportRoot(); got != "/persist" { - t.Fatalf("with USER_PERSISTENT_DATA_PATH = %q, want /persist", got) - } - // Explicit override wins over everything. - t.Setenv(envStateExportRoot, "/explicit") - if got := resolveStateExportRoot(); got != "/explicit" { - t.Fatalf("with override = %q, want /explicit", got) - } -} - -// HTTP-level encrypted export through a SYMLINKED root still captures children -// (mirrors prod start.sh `ln -sfn $PERSIST /data`). -func TestStateExport_SymlinkedRoot_DAR70(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - srv.SetAdminKey(stateExportAdminKey) - ts := httptest.NewServer(srv.Handler()) - t.Cleanup(ts.Close) - - real := buildStateExportRoot(t) - link := filepath.Join(t.TempDir(), "data-link") - if err := os.Symlink(real, link); err != nil { - t.Fatalf("symlink: %v", err) - } - t.Setenv(envStateExportRoot, link) - t.Setenv(envStateExportEnabled, "true") - t.Setenv(envStateExportAllowPlaintext, "true") - - resp := getExport(t, ts.URL, stateExportAdminKey) - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - t.Fatalf("symlinked root: got %d, want 200", resp.StatusCode) - } - body, err := io.ReadAll(resp.Body) - if err != nil { - t.Fatal(err) - } - files := zipEntries(t, body) - if _, ok := files["micromdm/micromdm.db"]; !ok { - t.Fatal("symlinked-root archive missing micromdm.db (EvalSymlinks not applied)") - } -} - -// (d) plaintext allowed -> valid zip; tree matches, *.log excluded, -// .push_imported included, bolt db opens ReadOnly with intact buckets/keys. -func TestStateExport_PlaintextZip_DAR70(t *testing.T) { - ts, _ := newStateExportServer(t) - t.Setenv(envStateExportEnabled, "true") - t.Setenv(envStateExportAllowPlaintext, "true") - - resp := getExport(t, ts.URL, stateExportAdminKey) - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - t.Fatalf("got %d, want 200", resp.StatusCode) - } - if ct := resp.Header.Get("Content-Type"); ct != "application/zip" { - t.Fatalf("content-type = %q, want application/zip", ct) - } - if cd := resp.Header.Get("Content-Disposition"); !bytes.Contains([]byte(cd), []byte(".zip\"")) { - t.Fatalf("content-disposition = %q, want a .zip filename", cd) - } - - body, err := io.ReadAll(resp.Body) - if err != nil { - t.Fatal(err) - } - files := zipEntries(t, body) - - for _, name := range []string{ - "step-ca/config/ca.json", - "step-ca/secrets/password", - "micromdm/push.crt", - "micromdm/.push_imported", - "micromdm/micromdm.db", - } { - if _, ok := files[name]; !ok { - t.Errorf("missing %q in archive", name) - } - } - for _, name := range []string{"step-ca.log", "micromdm/micromdm.log"} { - if _, ok := files[name]; ok { - t.Errorf("%q should be excluded", name) - } - } - - // The bolt db in the zip opens ReadOnly with intact data. - dbBytes := files["micromdm/micromdm.db"] - tmp := filepath.Join(t.TempDir(), "out.db") - if err := os.WriteFile(tmp, dbBytes, 0o600); err != nil { - t.Fatal(err) - } - db, err := bolt.Open(tmp, 0o400, &bolt.Options{ReadOnly: true, Timeout: 2 * time.Second}) - if err != nil { - t.Fatalf("open extracted db: %v", err) - } - defer db.Close() - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("Devices")) - if b == nil { - t.Fatal("Devices bucket missing") - } - if got := b.Get([]byte("serial-1")); !bytes.Equal(got, []byte("payload-1")) { - t.Fatalf("serial-1 = %q, want payload-1", got) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// (e) recipient set -> output is an age stream that decrypts to a valid zip. -func TestStateExport_EncryptedToRecipient_DAR70(t *testing.T) { - ts, _ := newStateExportServer(t) - id, err := age.GenerateX25519Identity() - if err != nil { - t.Fatal(err) - } - t.Setenv(envStateExportEnabled, "true") - t.Setenv(envStateExportRecipient, id.Recipient().String()) - - resp := getExport(t, ts.URL, stateExportAdminKey) - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - t.Fatalf("got %d, want 200", resp.StatusCode) - } - if ct := resp.Header.Get("Content-Type"); ct != "application/octet-stream" { - t.Fatalf("content-type = %q, want application/octet-stream", ct) - } - if cd := resp.Header.Get("Content-Disposition"); !bytes.Contains([]byte(cd), []byte(".zip.age\"")) { - t.Fatalf("content-disposition = %q, want a .zip.age filename", cd) - } - - cipher, err := io.ReadAll(resp.Body) - if err != nil { - t.Fatal(err) - } - // Must NOT be a plain zip (PK\x03\x04 magic). - if bytes.HasPrefix(cipher, []byte("PK\x03\x04")) { - t.Fatal("output looks like a plain zip — encryption did not happen") - } - - dr, err := age.Decrypt(bytes.NewReader(cipher), id) - if err != nil { - t.Fatalf("decrypt: %v", err) - } - plain, err := io.ReadAll(dr) - if err != nil { - t.Fatalf("read decrypted: %v", err) - } - files := zipEntries(t, plain) - if _, ok := files["micromdm/micromdm.db"]; !ok { - t.Fatal("decrypted archive missing micromdm.db") - } - if _, ok := files["step-ca/config/ca.json"]; !ok { - t.Fatal("decrypted archive missing ca.json") - } -} - -// (f) consistency: continuous writes to the LIVE db during export; the snapshot -// in the (decrypted) zip must open and pass Check(). -func TestStateExport_ConsistencyUnderWrites_DAR70(t *testing.T) { - ts, root := newStateExportServer(t) - id, err := age.GenerateX25519Identity() - if err != nil { - t.Fatal(err) - } - t.Setenv(envStateExportEnabled, "true") - t.Setenv(envStateExportRecipient, id.Recipient().String()) - - // Open the live db RW and hammer it with writes (mirrors MicroMDM). - dbPath := filepath.Join(root, "micromdm", "micromdm.db") - live, err := bolt.Open(dbPath, 0o600, &bolt.Options{Timeout: time.Second}) - if err != nil { - t.Fatal(err) - } - defer live.Close() - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - for { - select { - case <-ctx.Done(): - return - default: - } - _ = live.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("Churn")) - if err != nil { - return err - } - return b.Put([]byte("k"), []byte(time.Now().String())) - }) - } - }() - - resp := getExport(t, ts.URL, stateExportAdminKey) - cipher, _ := io.ReadAll(resp.Body) - resp.Body.Close() - cancel() - wg.Wait() - - if resp.StatusCode != http.StatusOK { - t.Fatalf("got %d, want 200", resp.StatusCode) - } - dr, err := age.Decrypt(bytes.NewReader(cipher), id) - if err != nil { - t.Fatalf("decrypt: %v", err) - } - plain, err := io.ReadAll(dr) - if err != nil { - t.Fatal(err) - } - files := zipEntries(t, plain) - dbBytes, ok := files["micromdm/micromdm.db"] - if !ok { - t.Fatal("snapshot db missing from archive") - } - tmp := filepath.Join(t.TempDir(), "snap.db") - if err := os.WriteFile(tmp, dbBytes, 0o600); err != nil { - t.Fatal(err) - } - // Validate with a recover-wrapped walk, NOT tx.Check(): on a genuinely torn - // copy Check() panics in an internal goroutine and would crash the whole - // `go test` binary instead of failing this test. - if err := validateBoltCopy(tmp); err != nil { - t.Fatalf("snapshot in archive failed validation: %v", err) - } -} - -// validateBoltCopy opens a bolt copy ReadOnly and walks every bucket, recovering -// from any panic (a torn copy can fault the mmap walk). It mirrors the -// production validator in package stateexport but lives here because that -// validator is unexported. -func validateBoltCopy(path string) (retErr error) { - defer func() { - if rec := recover(); rec != nil { - retErr = fmt.Errorf("bolt validation panicked (torn/corrupt copy): %v", rec) - } - }() - db, err := bolt.Open(path, 0o400, &bolt.Options{ReadOnly: true, Timeout: 2 * time.Second}) - if err != nil { - return err - } - defer db.Close() - return db.View(func(tx *bolt.Tx) error { - return tx.ForEach(func(_ []byte, b *bolt.Bucket) error { - return b.ForEach(func(_, _ []byte) error { return nil }) - }) - }) -} diff --git a/coordinator/api/admin_telemetry.go b/coordinator/api/admin_telemetry.go deleted file mode 100644 index 1ab1f5fd1b..0000000000 --- a/coordinator/api/admin_telemetry.go +++ /dev/null @@ -1,492 +0,0 @@ -// Admin read + download endpoints for routing telemetry. -// -// These handlers expose the coordinator's routing-decision and rejection -// telemetry for offline analysis and calibration. They are admin-gated and -// metadata-only: no prompt or response content is recorded or exported, so -// every column is safe to download in bulk. See -// docs/design/routing-telemetry-and-calibration.md. - -package api - -import ( - "encoding/csv" - "encoding/json" - "net/http" - "strconv" - "strings" - "time" - - "github.com/eigeninference/d-inference/coordinator/store" -) - -// defaultBrowseLimit caps how many records the JSON browse handlers return when -// the caller does not pass an explicit ?limit=. Exports are uncapped by default. -const defaultBrowseLimit = 1000 - -// --- Handlers ------------------------------------------------------------- - -// handleAdminRoutes serves GET /v1/admin/routes: a JSON page of routing -// decision records in the requested time window, with optional filtering by -// provider, model, and outcome. -func (s *Server) handleAdminRoutes(w http.ResponseWriter, r *http.Request) { - if !s.requireAdminKey(w, r) { - return - } - q := r.URL.Query() - records := filterRouteRecords( - s.store.InferenceRouteRecordsSince(parseSince(r)), - q.Get("provider"), q.Get("model"), q.Get("outcome"), q.Get("final_status"), - ) - records = capRecords(records, parseLimit(r, defaultBrowseLimit)) - writeJSON(w, http.StatusOK, map[string]any{ - "object": "list", - "count": len(records), - "data": records, - }) -} - -// handleAdminRoutesExport serves GET /v1/admin/routes/export: a streamed CSV -// (default) or NDJSON download of routing decision records. -func (s *Server) handleAdminRoutesExport(w http.ResponseWriter, r *http.Request) { - if !s.requireAdminKey(w, r) { - return - } - q := r.URL.Query() - records := filterRouteRecords( - s.store.InferenceRouteRecordsSince(parseSince(r)), - q.Get("provider"), q.Get("model"), q.Get("outcome"), q.Get("final_status"), - ) - records = capRecords(records, parseLimit(r, 0)) - - format := exportFormat(r) - setExportHeaders(w, "routes", format) - if format == "ndjson" { - if err := writeNDJSON(w, records); err != nil { - s.logger.Error("admin routes ndjson export failed", "error", err) - } - return - } - if err := writeRouteCSV(w, records); err != nil { - s.logger.Error("admin routes csv export failed", "error", err) - } -} - -// handleAdminRejections serves GET /v1/admin/rejections: a JSON page of -// rejected-request records in the requested time window, with optional -// filtering by reason, model, and could_have_served. -func (s *Server) handleAdminRejections(w http.ResponseWriter, r *http.Request) { - if !s.requireAdminKey(w, r) { - return - } - q := r.URL.Query() - records := filterRejectionRecords( - s.store.RejectionRecordsSince(parseSince(r)), - q.Get("reason"), q.Get("model"), q.Get("could_have_served"), - ) - records = capRecords(records, parseLimit(r, defaultBrowseLimit)) - writeJSON(w, http.StatusOK, map[string]any{ - "object": "list", - "count": len(records), - "data": records, - }) -} - -// handleAdminRejectionsExport serves GET /v1/admin/rejections/export: a streamed -// CSV (default) or NDJSON download of rejected-request records. -func (s *Server) handleAdminRejectionsExport(w http.ResponseWriter, r *http.Request) { - if !s.requireAdminKey(w, r) { - return - } - q := r.URL.Query() - records := filterRejectionRecords( - s.store.RejectionRecordsSince(parseSince(r)), - q.Get("reason"), q.Get("model"), q.Get("could_have_served"), - ) - records = capRecords(records, parseLimit(r, 0)) - - format := exportFormat(r) - setExportHeaders(w, "rejections", format) - if format == "ndjson" { - if err := writeNDJSON(w, records); err != nil { - s.logger.Error("admin rejections ndjson export failed", "error", err) - } - return - } - if err := writeRejectionCSV(w, records); err != nil { - s.logger.Error("admin rejections csv export failed", "error", err) - } -} - -// --- Request parsing helpers --------------------------------------------- - -// parseSince resolves the ?since= query parameter to an absolute lower-bound -// timestamp. It accepts either a Go duration relative to now (e.g. "24h", -// "168h") or an RFC3339 timestamp. When absent or unparseable it defaults to -// the last 24 hours. -func parseSince(r *http.Request) time.Time { - raw := strings.TrimSpace(r.URL.Query().Get("since")) - if raw != "" { - if d, err := time.ParseDuration(raw); err == nil { - if d < 0 { - d = -d - } - return time.Now().Add(-d) - } - if t, err := time.Parse(time.RFC3339, raw); err == nil { - return t - } - } - return time.Now().Add(-24 * time.Hour) -} - -// maxBrowseLimit bounds the caller-supplied ?limit= so a single browse response -// can't be asked to materialize an unreasonable number of rows. It matches the -// store-side read cap; the store never returns more than that regardless. -const maxBrowseLimit = 50000 - -// parseLimit reads ?limit= as a non-negative row cap, clamped to maxBrowseLimit. -// A missing or invalid value falls back to def; a value of 0 (or def == 0) means -// "no in-memory cap" (the store still hard-caps the underlying read). -func parseLimit(r *http.Request, def int) int { - raw := strings.TrimSpace(r.URL.Query().Get("limit")) - if raw == "" { - return def - } - n, err := strconv.Atoi(raw) - if err != nil || n < 0 { - return def - } - if n > maxBrowseLimit { - return maxBrowseLimit - } - return n -} - -// exportFormat returns the normalized ?format= value: "ndjson" when explicitly -// requested, otherwise "csv" (the default). -func exportFormat(r *http.Request) string { - if strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("format")), "ndjson") { - return "ndjson" - } - return "csv" -} - -// setExportHeaders sets the download Content-Type and a timestamped attachment -// filename for the given base name ("routes"/"rejections") and format. -func setExportHeaders(w http.ResponseWriter, base, format string) { - ext, ctype := "csv", "text/csv" - if format == "ndjson" { - ext, ctype = "ndjson", "application/x-ndjson" - } - filename := base + "-" + time.Now().UTC().Format(time.RFC3339) + "." + ext - w.Header().Set("Content-Type", ctype) - w.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(filename)) -} - -// capRecords truncates in to at most limit rows. limit <= 0 means no cap. -func capRecords[T any](in []T, limit int) []T { - if limit > 0 && len(in) > limit { - return in[:limit] - } - return in -} - -// --- Filters -------------------------------------------------------------- - -// filterRouteRecords applies the optional in-memory filters supported by the -// routes endpoints. Empty filter values are ignored. model matches either the -// concrete Model or the consumer-facing PublicModel. -func filterRouteRecords(in []store.InferenceRouteRecord, provider, model, outcome, finalStatus string) []store.InferenceRouteRecord { - if provider == "" && model == "" && outcome == "" && finalStatus == "" { - return in - } - out := make([]store.InferenceRouteRecord, 0, len(in)) - for _, rec := range in { - if provider != "" && rec.ProviderID != provider { - continue - } - if model != "" && rec.Model != model && rec.PublicModel != model { - continue - } - if outcome != "" && rec.Outcome != outcome { - continue - } - if finalStatus != "" && rec.FinalStatus != finalStatus { - continue - } - out = append(out, rec) - } - return out -} - -// filterRejectionRecords applies the optional in-memory filters supported by the -// rejections endpoints. Empty filter values are ignored. model matches either -// RequestedModel or ResolvedModel; couldHaveServed filters on the boolean only -// when it is exactly "true" or "false". -func filterRejectionRecords(in []store.RejectionRecord, reason, model, couldHaveServed string) []store.RejectionRecord { - var wantServed *bool - switch strings.ToLower(strings.TrimSpace(couldHaveServed)) { - case "true": - v := true - wantServed = &v - case "false": - v := false - wantServed = &v - } - if reason == "" && model == "" && wantServed == nil { - return in - } - out := make([]store.RejectionRecord, 0, len(in)) - for _, rec := range in { - if reason != "" && rec.ReasonCode != reason { - continue - } - if model != "" && rec.RequestedModel != model && rec.ResolvedModel != model { - continue - } - if wantServed != nil && (rec.CouldHaveServed == nil || *rec.CouldHaveServed != *wantServed) { - continue - } - out = append(out, rec) - } - return out -} - -// --- NDJSON --------------------------------------------------------------- - -// writeNDJSON encodes one JSON object per line. json.Encoder.Encode appends a -// newline after each value, yielding newline-delimited JSON, and streams each -// record straight to w. -func writeNDJSON[T any](w http.ResponseWriter, records []T) error { - enc := json.NewEncoder(w) - for i := range records { - if err := enc.Encode(records[i]); err != nil { - return err - } - } - return nil -} - -// --- CSV ------------------------------------------------------------------ - -// routeCSVHeader lists the route export columns in struct-field order. -var routeCSVHeader = []string{ - "request_id", "attempt", "provider_id", "model", "public_model", - "consumer_key_hash", "key_id", "outcome", - "cost_ms", "state_ms", "queue_ms", "pending_ms", "backlog_ms", - "this_req_ms", "health_ms", "ttft_ms", "best_ttft_ms", - "effective_queue", "candidate_count", "capacity_rejections", - "model_too_large_rejections", "vision_rejections", "ttft_rejections", - "effective_tps", "static_tps", - "provider_status", "provider_trust_level", "provider_version", - "hardware_chip", "hardware_chip_family", "hardware_tier", - "memory_gb", "gpu_cores", "cpu_cores", - "system_memory_pressure", "system_cpu_usage", "system_thermal_state", - "gpu_memory_active_gb", "gpu_memory_peak_gb", "gpu_memory_cache_gb", - "slot_state", "backend_running", "backend_waiting", - "active_token_budget_used", "active_token_budget_max", "queued_token_budget", - "estimated_prompt_tokens", "requested_max_tokens", - "requires_vision", "has_tools", "self_route_only", "prefer_owner", - "provider_region", "consumer_region", - "final_status", "error_code", "error_class", "error_reason", - "prompt_tokens", "completion_tokens", "reasoning_tokens", "cost_micro_usd", - "actual_ttft_ms", "dispatch_to_first_chunk_ms", "total_duration_ms", - "parse_ms", "reserve_ms", "route_ms", "encrypt_ms", "queue_wait_ms", "dispatch_ms", - "actual_decode_tps", "admitted_but_failed", "used_backup", "backup_won", - "created_at", "updated_at", -} - -// writeRouteCSV streams a header row followed by one row per record to w, then -// flushes and reports any write error. -func writeRouteCSV(w http.ResponseWriter, records []store.InferenceRouteRecord) error { - cw := csv.NewWriter(w) - if err := cw.Write(routeCSVHeader); err != nil { - return err - } - for i := range records { - if err := cw.Write(guardCSVRow(routeCSVRow(records[i]))); err != nil { - return err - } - } - cw.Flush() - return cw.Error() -} - -// routeCSVRow flattens one record into CSV cells matching routeCSVHeader. -func routeCSVRow(rec store.InferenceRouteRecord) []string { - return []string{ - rec.RequestID, - csvInt(rec.Attempt), - rec.ProviderID, - rec.Model, - rec.PublicModel, - rec.ConsumerKeyHash, - rec.KeyID, - rec.Outcome, - csvFloat(rec.CostMs), - csvFloat(rec.StateMs), - csvFloat(rec.QueueMs), - csvFloat(rec.PendingMs), - csvFloat(rec.BacklogMs), - csvFloat(rec.ThisReqMs), - csvFloat(rec.HealthMs), - csvFloat(rec.TTFTMs), - csvFloat(rec.BestTTFTMs), - csvInt(rec.EffectiveQueue), - csvInt(rec.CandidateCount), - csvInt(rec.CapacityRejections), - csvInt(rec.ModelTooLargeRejections), - csvInt(rec.VisionRejections), - csvInt(rec.TTFTRejections), - csvFloat(rec.EffectiveTPS), - csvFloat(rec.StaticTPS), - rec.ProviderStatus, - rec.ProviderTrustLevel, - rec.ProviderVersion, - rec.HardwareChip, - rec.HardwareChipFamily, - rec.HardwareTier, - csvInt(rec.MemoryGB), - csvInt(rec.GPUCores), - csvInt(rec.CPUCores), - csvFloat(rec.SystemMemoryPressure), - csvFloat(rec.SystemCPUUsage), - rec.SystemThermalState, - csvFloat(rec.GPUMemoryActiveGB), - csvFloat(rec.GPUMemoryPeakGB), - csvFloat(rec.GPUMemoryCacheGB), - rec.SlotState, - csvInt(rec.BackendRunning), - csvInt(rec.BackendWaiting), - csvI64(rec.ActiveTokenBudgetUsed), - csvI64(rec.ActiveTokenBudgetMax), - csvI64(rec.QueuedTokenBudget), - csvInt(rec.EstimatedPromptTokens), - csvInt(rec.RequestedMaxTokens), - csvBool(rec.RequiresVision), - csvBool(rec.HasTools), - csvBool(rec.SelfRouteOnly), - csvBool(rec.PreferOwner), - rec.ProviderRegion, - rec.ConsumerRegion, - rec.FinalStatus, - csvInt(rec.ErrorCode), - rec.ErrorClass, - rec.ErrorReason, - csvInt(rec.PromptTokens), - csvInt(rec.CompletionTokens), - csvInt(rec.ReasoningTokens), - csvI64(rec.CostMicroUSD), - csvFloat(rec.ActualTTFTMs), - csvFloat(rec.DispatchToFirstChunkMs), - csvFloat(rec.TotalDurationMs), - csvFloat(rec.ParseMs), - csvFloat(rec.ReserveMs), - csvFloat(rec.RouteMs), - csvFloat(rec.EncryptMs), - csvFloat(rec.QueueWaitMs), - csvFloat(rec.DispatchMs), - csvFloat(rec.ActualDecodeTPS), - csvBool(rec.AdmittedButFailed), - csvBool(rec.UsedBackup), - csvBool(rec.BackupWon), - csvTime(rec.CreatedAt), - csvTime(rec.UpdatedAt), - } -} - -// rejectionCSVHeader lists the rejection export columns in struct-field order. -var rejectionCSVHeader = []string{ - "request_id", "endpoint", "stage", "reason_code", "http_status", - "consumer_key_hash", "key_id", "client_class", - "requested_model", "resolved_model", "stream", "n", - "estimated_prompt_tokens", "requested_max_tokens", - "requires_vision", "has_image", "has_audio", "has_tools", "tool_count", - "response_format", "self_route_only", "prefer_owner", "params", - "request_body_bytes", "retry_after_ms", - "could_have_served", "candidate_count", "capacity_rejections", - "model_too_large_rejections", "vision_rejections", "warm_provider_existed", - "best_ttft_ms", "shortfall_micro_usd", "limit_kind", "over_by", - "created_at", -} - -// writeRejectionCSV streams a header row followed by one row per record to w, -// then flushes and reports any write error. -func writeRejectionCSV(w http.ResponseWriter, records []store.RejectionRecord) error { - cw := csv.NewWriter(w) - if err := cw.Write(rejectionCSVHeader); err != nil { - return err - } - for i := range records { - if err := cw.Write(guardCSVRow(rejectionCSVRow(records[i]))); err != nil { - return err - } - } - cw.Flush() - return cw.Error() -} - -// rejectionCSVRow flattens one record into CSV cells matching -// rejectionCSVHeader. The json.RawMessage Params field is emitted as a string. -func rejectionCSVRow(rec store.RejectionRecord) []string { - return []string{ - rec.RequestID, - rec.Endpoint, - rec.Stage, - rec.ReasonCode, - csvInt(rec.HTTPStatus), - rec.ConsumerKeyHash, - rec.KeyID, - rec.ClientClass, - rec.RequestedModel, - rec.ResolvedModel, - csvBool(rec.Stream), - csvInt(rec.N), - csvInt(rec.EstimatedPromptTokens), - csvInt(rec.RequestedMaxTokens), - csvBool(rec.RequiresVision), - csvBool(rec.HasImage), - csvBool(rec.HasAudio), - csvBool(rec.HasTools), - csvInt(rec.ToolCount), - rec.ResponseFormat, - csvBool(rec.SelfRouteOnly), - csvBool(rec.PreferOwner), - string(rec.Params), - csvInt(rec.RequestBodyBytes), - csvInt(rec.RetryAfterMs), - csvOptionalBool(rec.CouldHaveServed), - csvInt(rec.CandidateCount), - csvInt(rec.CapacityRejections), - csvInt(rec.ModelTooLargeRejections), - csvInt(rec.VisionRejections), - csvBool(rec.WarmProviderExisted), - csvFloat(rec.BestTTFTMs), - csvI64(rec.ShortfallMicroUSD), - rec.LimitKind, - csvI64(rec.OverBy), - csvTime(rec.CreatedAt), - } -} - -// --- scalar formatting ---------------------------------------------------- - -func csvInt(v int) string { return strconv.Itoa(v) } -func csvI64(v int64) string { return strconv.FormatInt(v, 10) } -func csvFloat(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) } -func csvBool(v bool) string { return strconv.FormatBool(v) } - -func csvTime(t time.Time) string { - if t.IsZero() { - return "" - } - return t.Format(time.RFC3339) -} - -// An empty CSV cell, like JSON null and SQL NULL, denotes unknown servability. -func csvOptionalBool(value *bool) string { - if value == nil { - return "" - } - return csvBool(*value) -} diff --git a/coordinator/api/admin_telemetry_route_test.go b/coordinator/api/admin_telemetry_route_test.go deleted file mode 100644 index 98d02dcd13..0000000000 --- a/coordinator/api/admin_telemetry_route_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package api - -import ( - "testing" - - "github.com/eigeninference/d-inference/coordinator/store" -) - -func TestRouteCSVIncludesOutcomeFields(t *testing.T) { - rec := store.InferenceRouteRecord{ - FinalStatus: "partial_success", - ErrorCode: 499, - ErrorClass: "client_gone_after_commit_provider_completed", - ErrorReason: "cancelled", - PromptTokens: 10, - CompletionTokens: 20, - ReasoningTokens: 3, - CostMicroUSD: 1234, - ActualTTFTMs: 11.5, - DispatchToFirstChunkMs: 12.5, - TotalDurationMs: 99, - ParseMs: 1, - ReserveMs: 2, - RouteMs: 3, - EncryptMs: 4, - QueueWaitMs: 5, - DispatchMs: 6, - ActualDecodeTPS: 7, - AdmittedButFailed: true, - UsedBackup: true, - BackupWon: true, - } - row := routeCSVRow(rec) - if len(routeCSVHeader) != len(row) { - t.Fatalf("header cells=%d row cells=%d", len(routeCSVHeader), len(row)) - } - values := map[string]string{} - for i, name := range routeCSVHeader { - values[name] = row[i] - } - for _, name := range []string{"final_status", "error_code", "error_class", "error_reason", "prompt_tokens", "completion_tokens", "reasoning_tokens", "cost_micro_usd", "actual_ttft_ms", "dispatch_to_first_chunk_ms", "total_duration_ms", "parse_ms", "reserve_ms", "route_ms", "encrypt_ms", "queue_wait_ms", "dispatch_ms", "actual_decode_tps", "admitted_but_failed", "used_backup", "backup_won"} { - if _, ok := values[name]; !ok { - t.Fatalf("route CSV missing %q", name) - } - } - if values["final_status"] != "partial_success" || values["error_code"] != "499" || values["error_reason"] != "cancelled" || values["used_backup"] != "true" || values["backup_won"] != "true" { - t.Fatalf("unexpected CSV outcome values: %+v", values) - } -} - -func TestFilterRouteRecordsByFinalStatus(t *testing.T) { - records := []store.InferenceRouteRecord{ - {ProviderID: "p1", Model: "m", Outcome: "selected", FinalStatus: "success"}, - {ProviderID: "p2", Model: "m", Outcome: "selected", FinalStatus: "timeout"}, - } - got := filterRouteRecords(records, "", "", "", "timeout") - if len(got) != 1 || got[0].ProviderID != "p2" { - t.Fatalf("filter by final_status returned %+v", got) - } -} diff --git a/coordinator/api/admin_utilization.go b/coordinator/api/admin_utilization.go deleted file mode 100644 index 578d618655..0000000000 --- a/coordinator/api/admin_utilization.go +++ /dev/null @@ -1,14 +0,0 @@ -package api - -import "net/http" - -// handleAdminUtilization serves GET /v1/admin/utilization: the full -// network-utilization snapshot (demand/capacity across the warm-serving and -// token-budget axes, plus a per-model breakdown and the bottleneck model). -// Admin-gated and read-only. -func (s *Server) handleAdminUtilization(w http.ResponseWriter, r *http.Request) { - if !s.requireAdminKey(w, r) { - return - } - writeJSON(w, http.StatusOK, s.registry.NetworkUtilizationSnapshot()) -} diff --git a/coordinator/api/api_key_cache_generation_test.go b/coordinator/api/api_key_cache_generation_test.go new file mode 100644 index 0000000000..0d920614f6 --- /dev/null +++ b/coordinator/api/api_key_cache_generation_test.go @@ -0,0 +1,160 @@ +package api + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Pause after the real store takes its snapshot, reproducing a slow database +// response that arrives after a concurrent key-management request commits. +type pausedKeyAuthenticationStore struct { + store.Store + token string + entered chan struct{} + release chan struct{} + paused atomic.Bool + reads atomic.Int64 +} + +func (s *pausedKeyAuthenticationStore) AuthenticateKey(raw string) (*store.APIKey, error) { + key, err := s.Store.AuthenticateKey(raw) + if raw == s.token { + s.reads.Add(1) + if s.paused.CompareAndSwap(false, true) { + close(s.entered) + <-s.release + } + } + return key, err +} + +func TestAPIKeyCacheSlowReadCannotOutliveMutation(t *testing.T) { + for _, tc := range []struct { + name string + method string + path string + body string + disabled bool + wantStatus int + wantRPM int64 + wantInitial int + }{ + {name: "disable", method: http.MethodPatch, path: "/v1/keys/%s", body: `{"disabled":true}`, wantStatus: http.StatusUnauthorized, wantInitial: http.StatusOK}, + {name: "delete", method: http.MethodDelete, path: "/v1/keys/%s", wantStatus: http.StatusUnauthorized, wantInitial: http.StatusOK}, + {name: "rotate", method: http.MethodPost, path: "/v1/keys/%s/rotate", wantStatus: http.StatusUnauthorized, wantInitial: http.StatusOK}, + {name: "legacy revoke", method: http.MethodDelete, path: "/v1/auth/keys", body: `{"key":%q}`, wantStatus: http.StatusUnauthorized, wantInitial: http.StatusOK}, + {name: "restrict limit", method: http.MethodPatch, path: "/v1/keys/%s", body: `{"rpm_limit":5}`, wantStatus: http.StatusOK, wantRPM: 5, wantInitial: http.StatusOK}, + {name: "enable", method: http.MethodPatch, path: "/v1/keys/%s", body: `{"disabled":false}`, disabled: true, wantStatus: http.StatusOK, wantRPM: 100, wantInitial: http.StatusUnauthorized}, + } { + t.Run(tc.name, func(t *testing.T) { + srv, base := newKeyTestServer(t) + t.Cleanup(srv.Close) + user := seedUser(t, base, "acct-cache-generation", "cache@example.com") + session := privySession(t, srv, base, user) + rpm := int64(100) + raw, rec, err := base.CreateAPIKey(user.AccountID, store.APIKeyCreate{RPMLimit: &rpm}) + if err != nil { + t.Fatal(err) + } + if tc.disabled { + rec.Disabled = true + if _, err := base.UpdateAPIKey(user.AccountID, rec.ID, *rec); err != nil { + t.Fatal(err) + } + } + paused := &pausedKeyAuthenticationStore{Store: base, token: raw, entered: make(chan struct{}), release: make(chan struct{})} + srv.store = paused + ts := httptest.NewServer(srv.Handler()) + t.Cleanup(ts.Close) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(paused.release) }) } + t.Cleanup(release) + client := ts.Client() + client.Timeout = 5 * time.Second + type result struct { + status int + body []byte + err error + } + call := func(method, path, body, token string) result { + r, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body)) + if err != nil { + return result{err: err} + } + r.Header.Set("Authorization", "Bearer "+token) + r.Header.Set("Content-Type", "application/json") + resp, err := client.Do(r) + if err != nil { + return result{err: err} + } + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + return result{status: resp.StatusCode, body: data, err: err} + } + initial := make(chan result, 1) + go func() { initial <- call(http.MethodGet, "/v1/key", "", raw) }() + select { + case <-paused.entered: + case <-time.After(5 * time.Second): + t.Fatal("authentication never reached its store barrier") + } + + path, body := tc.path, tc.body + if strings.Contains(path, "%s") { + path = fmt.Sprintf(path, rec.ID) + } + if strings.Contains(body, "%q") { + body = fmt.Sprintf(body, raw) + } + mutation := call(tc.method, path, body, session) + if mutation.err != nil || mutation.status != http.StatusOK { + t.Fatalf("mutation = %d %s, err=%v", mutation.status, mutation.body, mutation.err) + } + release() + // The request whose lookup preceded the mutation may finish with its + // original result. It must not cache that result for later requests. + got := <-initial + if got.err != nil || got.status != tc.wantInitial { + t.Fatalf("in-flight result = %d %s, err=%v", got.status, got.body, got.err) + } + for range 2 { + got = call(http.MethodGet, "/v1/key", "", raw) + if got.err != nil || got.status != tc.wantStatus { + t.Fatalf("after mutation = %d %s, err=%v; want %d", got.status, got.body, got.err, tc.wantStatus) + } + if tc.wantRPM > 0 { + var key types.APIKeyResponse + if err := json.Unmarshal(got.body, &key); err != nil { + t.Fatal(err) + } + if key.RPMLimit == nil || *key.RPMLimit != tc.wantRPM { + t.Fatalf("cached RPM = %v, want %d", key.RPMLimit, tc.wantRPM) + } + } + } + if got := paused.reads.Load(); got != 2 { + t.Fatalf("store reads = %d, want the paused read plus one refresh", got) + } + if tc.name == "rotate" { + var rotated types.CreateAPIKeyResponse + if err := json.Unmarshal(mutation.body, &rotated); err != nil { + t.Fatal(err) + } + if got := call(http.MethodGet, "/v1/key", "", rotated.Key); got.err != nil || got.status != http.StatusOK { + t.Fatalf("rotated key = %d %s, err=%v", got.status, got.body, got.err) + } + } + }) + } +} diff --git a/coordinator/api/apikey_handlers.go b/coordinator/api/apikey_handlers.go deleted file mode 100644 index a239e50b21..0000000000 --- a/coordinator/api/apikey_handlers.go +++ /dev/null @@ -1,447 +0,0 @@ -package api - -// apikey_handlers.go holds the consumer-facing API key management endpoints -// (create/list/get/update/rotate/delete) plus their request validation and -// response-shaping helpers. Split out of consumer.go to keep key management -// separate from the inference request path. - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "strings" - "time" - - "github.com/eigeninference/d-inference/coordinator/auth" - "github.com/eigeninference/d-inference/coordinator/store" - - "github.com/eigeninference/d-inference/coordinator/api/types" -) - -// handleCreateKey handles POST /v1/auth/keys — creates a new consumer API key. -// Requires Privy authentication. The key is linked to the user's account so -// requests made with the key are billed to the same account. -func (s *Server) handleCreateKey(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", - "API key creation requires a Privy account — authenticate with a Privy access token")) - return - } - - key, err := s.store.CreateKeyForAccount(user.AccountID) - if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("server_error", "failed to create key")) - return - } - writeJSON(w, http.StatusOK, types.CreateKeyResponse{ - APIKey: key, - AccountID: user.AccountID, - }) -} - -// handleRevokeKey handles DELETE /v1/auth/keys — revokes an API key. -// The caller must own the key (same account). Requires Privy auth so a -// compromised API key cannot revoke legitimate keys. -func (s *Server) handleRevokeKey(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", "authentication required")) - return - } - - var body struct { - Key string `json:"key"` - } - if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Key == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("bad_request", "provide {\"key\": \"sk-db-...\"}")) - return - } - - owner := s.store.GetKeyAccount(body.Key) - if owner != user.AccountID { - writeJSON(w, http.StatusForbidden, errorResponse("forbidden", "you can only revoke your own keys")) - return - } - - if !s.store.RevokeKey(body.Key) { - writeJSON(w, http.StatusNotFound, errorResponse("not_found", "key not found or already revoked")) - return - } - s.invalidateAPIKeyCache(body.Key) - - writeJSON(w, http.StatusOK, types.RevokeKeyResponse{Status: "revoked"}) -} - -// apiKeyToResponse projects a stored key into its masked API representation, -// computing the current-window spend and remaining budget. -func (s *Server) apiKeyToResponse(k *store.APIKey) types.APIKeyResponse { - resp := types.APIKeyResponse{ - ID: k.ID, - Name: k.Name, - Label: k.Label, - Disabled: k.Disabled, - LimitReset: store.NormalizeResetWindow(k.LimitReset), - RPMLimit: k.RPMLimit, - ITPMLimit: k.ITPMLimit, - OTPMLimit: k.OTPMLimit, - AllowedModels: k.AllowedModels, - SelfRouteOnly: k.SelfRouteOnly, - ExpiresAt: k.ExpiresAt, - CreatedAt: k.CreatedAt, - LastUsedAt: k.LastUsedAt, - } - since := store.KeySpendWindowStart(resp.LimitReset, time.Now()) - spent := s.store.KeySpendSince(k.ID, since) - resp.UsageUSD = microToUSD(spent) - if k.LimitMicroUSD != nil { - limitUSD := microToUSD(*k.LimitMicroUSD) - resp.LimitUSD = &limitUSD - remaining := *k.LimitMicroUSD - spent - if remaining < 0 { - remaining = 0 - } - remUSD := microToUSD(remaining) - resp.RemainingUSD = &remUSD - } - return resp -} - -// validateKeyLimitInputs sanity-checks user-supplied limit values. Returns a -// human-readable error string (empty when valid). -func validateKeyLimitInputs(reset string, limitUSD *float64, rpm, itpm, otpm *int64, expiresAt *time.Time) string { - switch reset { - case "", store.KeyResetNone, store.KeyResetDaily, store.KeyResetWeekly, store.KeyResetMonthly: - default: - return "limit_reset must be one of: none, daily, weekly, monthly" - } - if limitUSD != nil && *limitUSD < 0 { - return "limit_usd must be >= 0" - } - if rpm != nil && *rpm < 0 { - return "rpm_limit must be >= 0" - } - if itpm != nil && *itpm < 0 { - return "itpm_limit must be >= 0" - } - if otpm != nil && *otpm < 0 { - return "otpm_limit must be >= 0" - } - if expiresAt != nil && !expiresAt.IsZero() && expiresAt.Before(time.Now()) { - return "expires_at must be in the future" - } - return "" -} - -// keyModelAllowed returns false when the calling key restricts models via an -// allow-list that does not include the requested model. Account-scoped/legacy -// keys (no key in context) and keys without an allow-list always pass. -func (s *Server) keyModelAllowed(ctx context.Context, model string) bool { - k := apiKeyFromContext(ctx) - if k == nil || len(k.AllowedModels) == 0 { - return true - } - for _, m := range k.AllowedModels { - if m == model { - return true - } - } - return false -} - -// checkKeySpendCap reports whether charging additionalMicroUSD to the calling -// key would exceed its per-key spend cap in the current window. It returns -// (message, ok); ok=false means the request must be rejected with 402. The -// per-account balance ledger is still the hard atomic ceiling — this is the -// soft, per-key sub-cap, enforced against settled usage (so concurrent -// in-flight requests are eventually-consistent, never over the account balance). -func (s *Server) checkKeySpendCap(ctx context.Context, additionalMicroUSD int64) (string, bool) { - k := apiKeyFromContext(ctx) - if k == nil || k.ID == "" || k.LimitMicroUSD == nil { - return "", true - } - since := store.KeySpendWindowStart(k.LimitReset, time.Now()) - spent := s.store.KeySpendSince(k.ID, since) - if spent+additionalMicroUSD > *k.LimitMicroUSD { - window := store.NormalizeResetWindow(k.LimitReset) - if window == store.KeyResetNone { - window = "total" - } - return fmt.Sprintf("API key spend limit reached (%s cap $%.2f, used $%.2f) — raise this key's limit or use another key", - window, microToUSD(*k.LimitMicroUSD), microToUSD(spent)), false - } - return "", true -} - -// handleListAPIKeys handles GET /v1/keys — lists the caller's keys (masked). -func (s *Server) handleListAPIKeys(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", "authentication required")) - return - } - keys, err := s.store.ListAPIKeys(user.AccountID) - if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("server_error", "failed to list keys")) - return - } - out := make([]types.APIKeyResponse, 0, len(keys)) - for i := range keys { - out = append(out, s.apiKeyToResponse(&keys[i])) - } - writeJSON(w, http.StatusOK, types.APIKeyListResponse{Object: "list", Data: out}) -} - -// handleCreateAPIKey handles POST /v1/keys — mints a new named, optionally -// limited key. The raw secret is returned exactly once. -func (s *Server) handleCreateAPIKey(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", - "API key creation requires a Privy account — authenticate with a Privy access token")) - return - } - - var req createAPIKeyRequest - if r.Body != nil { - // A missing/empty body is allowed (creates a default unnamed key). - if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) { - writeJSON(w, http.StatusBadRequest, errorResponse("bad_request", "invalid JSON body")) - return - } - } - if msg := validateKeyLimitInputs(req.LimitReset, req.LimitUSD, req.RPMLimit, req.ITPMLimit, req.OTPMLimit, req.ExpiresAt); msg != "" { - writeJSON(w, http.StatusBadRequest, errorResponse("bad_request", msg)) - return - } - - opts := store.APIKeyCreate{ - Name: strings.TrimSpace(req.Name), - LimitReset: store.NormalizeResetWindow(req.LimitReset), - RPMLimit: req.RPMLimit, - ITPMLimit: req.ITPMLimit, - OTPMLimit: req.OTPMLimit, - AllowedModels: req.AllowedModels, - SelfRouteOnly: req.SelfRouteOnly, - ExpiresAt: req.ExpiresAt, - } - if req.LimitUSD != nil { - m := usdToMicro(*req.LimitUSD) - opts.LimitMicroUSD = &m - } - - raw, rec, err := s.store.CreateAPIKey(user.AccountID, opts) - if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("server_error", "failed to create key")) - return - } - writeJSON(w, http.StatusOK, types.CreateAPIKeyResponse{ - Key: raw, - Data: s.apiKeyToResponse(rec), - }) -} - -// handleGetAPIKey handles GET /v1/keys/{id}. -func (s *Server) handleGetAPIKey(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", "authentication required")) - return - } - id := r.PathValue("id") - k, err := s.store.GetAPIKeyByID(user.AccountID, id) - if err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("not_found", "key not found")) - return - } - writeJSON(w, http.StatusOK, s.apiKeyToResponse(k)) -} - -// handleGetCallingKey handles GET /v1/key — returns the metadata for the API -// key used to authenticate the request (OpenRouter parity). -func (s *Server) handleGetCallingKey(w http.ResponseWriter, r *http.Request) { - k := apiKeyFromContext(r.Context()) - if k == nil || k.ID == "" { - writeJSON(w, http.StatusNotFound, errorResponse("not_found", - "no key metadata — this endpoint requires API key authentication")) - return - } - writeJSON(w, http.StatusOK, s.apiKeyToResponse(k)) -} - -// handleUpdateAPIKey handles PATCH /v1/keys/{id} — sparse update of a key's -// name, disabled flag, limits, reset window, expiry, and model allow-list. -func (s *Server) handleUpdateAPIKey(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", "authentication required")) - return - } - id := r.PathValue("id") - existing, err := s.store.GetAPIKeyByID(user.AccountID, id) - if err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("not_found", "key not found")) - return - } - - // Decode into a presence map so we can distinguish "field omitted" (leave - // unchanged) from "field set to null" (clear the limit). - var patch map[string]json.RawMessage - if err := json.NewDecoder(r.Body).Decode(&patch); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("bad_request", "invalid JSON body")) - return - } - if msg := applyKeyPatch(existing, patch); msg != "" { - writeJSON(w, http.StatusBadRequest, errorResponse("bad_request", msg)) - return - } - if msg := validateKeyLimitInputs(existing.LimitReset, nil, existing.RPMLimit, existing.ITPMLimit, existing.OTPMLimit, existing.ExpiresAt); msg != "" { - writeJSON(w, http.StatusBadRequest, errorResponse("bad_request", msg)) - return - } - - // Bump the auth-cache generation before AND after the mutation so a - // concurrent request cannot keep authenticating with a stale (e.g. - // just-disabled) cached record. - s.invalidateAllAPIKeyCache() - updated, err := s.store.UpdateAPIKey(user.AccountID, id, *existing) - if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("server_error", "failed to update key")) - return - } - s.invalidateAllAPIKeyCache() - writeJSON(w, http.StatusOK, s.apiKeyToResponse(updated)) -} - -// applyKeyPatch merges a presence-aware PATCH body into an existing key record. -// Returns a human-readable error string on invalid input (empty when ok). -func applyKeyPatch(k *store.APIKey, patch map[string]json.RawMessage) string { - if raw, ok := patch["name"]; ok { - var name string - if err := json.Unmarshal(raw, &name); err != nil { - return "invalid value for name" - } - k.Name = strings.TrimSpace(name) - } - if raw, ok := patch["disabled"]; ok { - var disabled bool - if err := json.Unmarshal(raw, &disabled); err != nil { - return "invalid value for disabled" - } - k.Disabled = disabled - } - if raw, ok := patch["limit_reset"]; ok { - var reset string - if err := json.Unmarshal(raw, &reset); err != nil { - return "invalid value for limit_reset" - } - k.LimitReset = store.NormalizeResetWindow(reset) - } - if raw, ok := patch["limit_usd"]; ok { - if string(raw) == "null" { - k.LimitMicroUSD = nil - } else { - var usd float64 - if err := json.Unmarshal(raw, &usd); err != nil { - return "invalid value for limit_usd" - } - if usd < 0 { - return "limit_usd must be >= 0" - } - m := usdToMicro(usd) - k.LimitMicroUSD = &m - } - } - if raw, ok := patch["allowed_models"]; ok { - if string(raw) == "null" { - k.AllowedModels = nil - } else { - var models []string - if err := json.Unmarshal(raw, &models); err != nil { - return "invalid value for allowed_models" - } - k.AllowedModels = models - } - } - if raw, ok := patch["self_route_only"]; ok { - var v bool - if err := json.Unmarshal(raw, &v); err != nil { - return "invalid value for self_route_only" - } - k.SelfRouteOnly = v - } - for field, dst := range map[string]**int64{ - "rpm_limit": &k.RPMLimit, - "itpm_limit": &k.ITPMLimit, - "otpm_limit": &k.OTPMLimit, - } { - if raw, ok := patch[field]; ok { - if string(raw) == "null" { - *dst = nil - } else { - var v int64 - if err := json.Unmarshal(raw, &v); err != nil { - return "invalid value for " + field - } - *dst = &v - } - } - } - if raw, ok := patch["expires_at"]; ok { - if string(raw) == "null" { - k.ExpiresAt = nil - } else { - var t time.Time - if err := json.Unmarshal(raw, &t); err != nil { - return "invalid value for expires_at (use RFC 3339)" - } - k.ExpiresAt = &t - } - } - return "" -} - -// handleDeleteAPIKey handles DELETE /v1/keys/{id} — permanently deletes a key. -func (s *Server) handleDeleteAPIKey(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", "authentication required")) - return - } - id := r.PathValue("id") - s.invalidateAllAPIKeyCache() - if err := s.store.RevokeAPIKeyByID(user.AccountID, id); err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("not_found", "key not found")) - return - } - s.invalidateAllAPIKeyCache() - writeJSON(w, http.StatusOK, types.RevokeKeyResponse{Status: "revoked"}) -} - -// handleRotateAPIKey handles POST /v1/keys/{id}/rotate — mints a fresh secret -// carrying the same limits and metadata, then deletes the old key. The new -// secret is returned exactly once. -func (s *Server) handleRotateAPIKey(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", "authentication required")) - return - } - id := r.PathValue("id") - // Bump the auth-cache generation before AND after the mutation so the old - // secret stops authenticating the instant rotation commits. - s.invalidateAllAPIKeyCache() - raw, rec, err := s.store.RotateAPIKey(user.AccountID, id) - if err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("not_found", "key not found")) - return - } - s.invalidateAllAPIKeyCache() - writeJSON(w, http.StatusOK, types.CreateAPIKeyResponse{ - Key: raw, - Data: s.apiKeyToResponse(rec), - }) -} diff --git a/coordinator/api/apikey_handlers_test.go b/coordinator/api/apikey_handlers_test.go deleted file mode 100644 index e75b991087..0000000000 --- a/coordinator/api/apikey_handlers_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "log/slog" - "net/http" - "net/http/httptest" - "os" - "strings" - "testing" - - "github.com/eigeninference/d-inference/coordinator/api/types" - "github.com/eigeninference/d-inference/coordinator/auth" - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" -) - -func newKeyTestServer(t *testing.T) (*Server, *store.MemoryStore) { - t.Helper() - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - st := store.NewMemory(store.Config{}) - srv := NewServer(registry.New(logger), st, ServerConfig{}, logger) - return srv, st -} - -// reqWithUser builds a request whose context carries an authenticated user, -// simulating what requirePrivyAuth installs (so we can unit-test the handlers -// without minting a real Privy JWT). -func reqWithUser(method, target, body, accountID string) *http.Request { - var r *http.Request - if body == "" { - r = httptest.NewRequest(method, target, nil) - } else { - r = httptest.NewRequest(method, target, strings.NewReader(body)) - } - ctx := context.WithValue(r.Context(), auth.CtxKeyUser, &store.User{AccountID: accountID}) - ctx = context.WithValue(ctx, ctxKeyConsumer, accountID) - return r.WithContext(ctx) -} - -func TestHandleCreateAndListAPIKeys(t *testing.T) { - srv, _ := newKeyTestServer(t) - - // Create a key with a $10 monthly cap. - body := `{"name":"prod","limit_usd":10,"limit_reset":"monthly","rpm_limit":120}` - w := httptest.NewRecorder() - srv.handleCreateAPIKey(w, reqWithUser(http.MethodPost, "/v1/keys", body, "acct-1")) - if w.Code != http.StatusOK { - t.Fatalf("create status = %d, body=%s", w.Code, w.Body.String()) - } - var created types.CreateAPIKeyResponse - if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil { - t.Fatalf("decode create: %v", err) - } - if !strings.HasPrefix(created.Key, store.KeyPrefix) { - t.Errorf("returned secret %q missing prefix", created.Key) - } - if created.Data.LimitUSD == nil || *created.Data.LimitUSD != 10 { - t.Errorf("limit_usd = %v, want 10", created.Data.LimitUSD) - } - if created.Data.LimitReset != "monthly" { - t.Errorf("limit_reset = %q", created.Data.LimitReset) - } - if created.Data.RPMLimit == nil || *created.Data.RPMLimit != 120 { - t.Errorf("rpm_limit = %v", created.Data.RPMLimit) - } - if strings.Contains(created.Data.Label, created.Key[10:40]) { - t.Errorf("label leaks secret: %q", created.Data.Label) - } - - // List shows exactly one key (masked, no secret). - w = httptest.NewRecorder() - srv.handleListAPIKeys(w, reqWithUser(http.MethodGet, "/v1/keys", "", "acct-1")) - if w.Code != http.StatusOK { - t.Fatalf("list status = %d", w.Code) - } - var list types.APIKeyListResponse - if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil { - t.Fatalf("decode list: %v", err) - } - if len(list.Data) != 1 { - t.Fatalf("list len = %d, want 1", len(list.Data)) - } - if strings.Contains(w.Body.String(), created.Key) { - t.Error("list response must not contain the raw secret") - } -} - -func TestHandleUpdateAndDisableViaPatch(t *testing.T) { - srv, _ := newKeyTestServer(t) - - w := httptest.NewRecorder() - srv.handleCreateAPIKey(w, reqWithUser(http.MethodPost, "/v1/keys", `{"name":"a","limit_usd":5}`, "acct-1")) - var created types.CreateAPIKeyResponse - json.Unmarshal(w.Body.Bytes(), &created) - id := created.Data.ID - - // PATCH: disable + clear the limit (limit_usd: null) + rename. - patch := `{"name":"renamed","disabled":true,"limit_usd":null}` - r := reqWithUser(http.MethodPatch, "/v1/keys/"+id, patch, "acct-1") - r.SetPathValue("id", id) - w = httptest.NewRecorder() - srv.handleUpdateAPIKey(w, r) - if w.Code != http.StatusOK { - t.Fatalf("patch status = %d, body=%s", w.Code, w.Body.String()) - } - var updated types.APIKeyResponse - json.Unmarshal(w.Body.Bytes(), &updated) - if updated.Name != "renamed" { - t.Errorf("name = %q", updated.Name) - } - if !updated.Disabled { - t.Error("key should be disabled") - } - if updated.LimitUSD != nil { - t.Errorf("limit_usd should be cleared, got %v", *updated.LimitUSD) - } -} - -func TestHandleRotateAPIKey(t *testing.T) { - srv, _ := newKeyTestServer(t) - - w := httptest.NewRecorder() - srv.handleCreateAPIKey(w, reqWithUser(http.MethodPost, "/v1/keys", `{"name":"a","limit_usd":7,"limit_reset":"weekly"}`, "acct-1")) - var created types.CreateAPIKeyResponse - json.Unmarshal(w.Body.Bytes(), &created) - oldID := created.Data.ID - oldSecret := created.Key - - r := reqWithUser(http.MethodPost, "/v1/keys/"+oldID+"/rotate", "", "acct-1") - r.SetPathValue("id", oldID) - w = httptest.NewRecorder() - srv.handleRotateAPIKey(w, r) - if w.Code != http.StatusOK { - t.Fatalf("rotate status = %d, body=%s", w.Code, w.Body.String()) - } - var rotated types.CreateAPIKeyResponse - json.Unmarshal(w.Body.Bytes(), &rotated) - if rotated.Key == oldSecret { - t.Error("rotate must mint a new secret") - } - if rotated.Data.ID == oldID { - t.Error("rotate must produce a new key id") - } - // Limits carried over. - if rotated.Data.LimitUSD == nil || *rotated.Data.LimitUSD != 7 || rotated.Data.LimitReset != "weekly" { - t.Errorf("limits not carried over: %+v", rotated.Data) - } - // Old key gone. - if _, err := srv.store.AuthenticateKey(oldSecret); err == nil { - t.Error("old secret should be revoked after rotate") - } - // New key authenticates. - if _, err := srv.store.AuthenticateKey(rotated.Key); err != nil { - t.Errorf("new secret should authenticate: %v", err) - } -} - -func TestHandleDeleteAPIKeyScoping(t *testing.T) { - srv, _ := newKeyTestServer(t) - - w := httptest.NewRecorder() - srv.handleCreateAPIKey(w, reqWithUser(http.MethodPost, "/v1/keys", `{"name":"a"}`, "acct-1")) - var created types.CreateAPIKeyResponse - json.Unmarshal(w.Body.Bytes(), &created) - id := created.Data.ID - - // Another account cannot delete it. - r := reqWithUser(http.MethodDelete, "/v1/keys/"+id, "", "acct-2") - r.SetPathValue("id", id) - w = httptest.NewRecorder() - srv.handleDeleteAPIKey(w, r) - if w.Code != http.StatusNotFound { - t.Fatalf("cross-account delete status = %d, want 404", w.Code) - } - - // Owner can. - r = reqWithUser(http.MethodDelete, "/v1/keys/"+id, "", "acct-1") - r.SetPathValue("id", id) - w = httptest.NewRecorder() - srv.handleDeleteAPIKey(w, r) - if w.Code != http.StatusOK { - t.Fatalf("owner delete status = %d, want 200", w.Code) - } -} - -func TestHandleCreateAPIKeyRejectsBadInput(t *testing.T) { - srv, _ := newKeyTestServer(t) - w := httptest.NewRecorder() - srv.handleCreateAPIKey(w, reqWithUser(http.MethodPost, "/v1/keys", `{"limit_reset":"hourly"}`, "acct-1")) - if w.Code != http.StatusBadRequest { - t.Fatalf("status = %d, want 400 for bad reset window", w.Code) - } -} diff --git a/coordinator/api/app_attest_shadow_policy.go b/coordinator/api/app_attest_shadow_policy.go index 79c395ec40..0d52b2ed41 100644 --- a/coordinator/api/app_attest_shadow_policy.go +++ b/coordinator/api/app_attest_shadow_policy.go @@ -7,6 +7,7 @@ import ( "github.com/eigeninference/d-inference/coordinator/appattest" "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/providercontrol/releasepolicy" "github.com/eigeninference/d-inference/coordinator/store" ) @@ -20,8 +21,12 @@ func (x *appAttestShadowSession) observeBuildPolicy(status *protocol.AppAttestSt // Enrollment metadata cannot stand in for a current assertion's metadata. evidence.BundleVersion, evidence.ValidationCategory = metadata.BundleVersion, metadata.ValidationCategory } - snapshot := x.s.releaseTrustPolicy.Load() - evidence.CatalogKnown = snapshot != nil && len(snapshot.ByBinaryHash) > 0 + snapshot := x.s.releasePolicyOwner().Snapshot() + var releases map[string][]releasepolicy.Release + if snapshot != nil { + releases = snapshot.Releases() + } + evidence.CatalogKnown = len(releases) > 0 if status != nil { evidence.HardwareKnown, evidence.HardwareMatched = appAttestHardwareComparison(x.protocolVersion, status, x.hardware) evidence.VerificationKeyKnown = x.protocolVersion == 3 && x.attestationKey != "" && status.AttestationPublicKey != "" @@ -30,7 +35,7 @@ func (x *appAttestShadowSession) observeBuildPolicy(status *protocol.AppAttestSt evidence.BuildQualified = qualifiedAppAttestBuild(x.s.appAttestShadow.QualifiedBuildHashes, status.BinaryHash) evidence.CodeMeasurementKnown, evidence.CodeMeasurementMatched = qualifiedAppAttestMeasurement(x.s.appAttestShadow.QualifiedCodeHashes, status.BinaryHash, metadata) if evidence.CatalogKnown { - for _, candidate := range snapshot.ByBinaryHash[status.BinaryHash] { + for _, candidate := range releases[status.BinaryHash] { if candidate.Platform == "macos-arm64" && candidate.Version == status.AppVersion { evidence.BuildMatched = true break diff --git a/coordinator/api/attempt_outcome_metrics.go b/coordinator/api/attempt_outcome_metrics.go index 2eddd72481..cd31bfa10d 100644 --- a/coordinator/api/attempt_outcome_metrics.go +++ b/coordinator/api/attempt_outcome_metrics.go @@ -1,10 +1,10 @@ package api import ( - "math" "strings" - "time" + "github.com/eigeninference/d-inference/coordinator/inference/attempt" + "github.com/eigeninference/d-inference/coordinator/inference/dispatch" "github.com/eigeninference/d-inference/coordinator/store" ) @@ -77,43 +77,25 @@ const ( // persist. A fixed vocabulary: anything else lands in `other`. const ( queueClassClientGone = "client_gone" - queueClassQueueDeadline = rejectionReasonQueueDeadline + queueClassQueueDeadline = dispatch.RejectionReasonQueueDeadline queueClassQueueTimeout = "queue_timeout" queueClassTTFTTooSlow = "ttft_too_slow" queueClassCapabilityUnsupported = "model_capability_unsupported" queueClassOther = "other" ) -// orClassClientGone is the OR-view class for a client that left before the -// first token well inside the upstream budget (an application abort, not our -// slowness) and for post-commit client disconnects. EXCLUDED from the uptime -// formula, like rate_limited / client_error. -const orClassClientGone = "client_gone" - -// deadline_bucket tag values on routing.client_gone: elapsed time at the -// cancel relative to the request's first-content budget (d.deadline, the -// coordinator-side mirror of the upstream first-content deadline). -const ( - deadlineBucketUnderHalf = "under_half" // < 0.5 x budget: application abort - deadlineBucketMid = "mid" // 0.5 .. 0.8 x budget - deadlineBucketNearDeadline = "near_deadline" // >= 0.8 x budget: upstream was about to time out - deadlineBucketOver = "over" // >= budget: upstream already timed out (its 504) - deadlineBucketUnknown = "unknown" // no request clock on this dispatch - deadlineBucketNotApplicable = "not_applicable" // after-commit phase: the budget was met -) - // isCapacityClassErrorReason reports whether a persisted error_reason names a // capacity / admission condition (the provider is healthy but full, the // request cannot fit, or the provider is draining ahead of a restart and // refusing new work — routing counts that as transient capacity too) rather // than a fault. func isCapacityClassErrorReason(reason string) bool { - switch normalizeInferenceErrorReason(reason) { - case errorReasonCapacityBusy, errorReasonCapacityTimeout, errorReasonQueueFull, - errorReasonTokenBudgetExhaust, errorReasonRequestExceedsContext, - errorReasonRequestExceedsNode, errorReasonRequestExceedsNodeBudget, - errorReasonRequestExceedsBatchBudget, errorReasonModelLoad, - errorReasonDraining: + switch attempt.NormalizeInferenceErrorReason(reason) { + case attempt.ErrorReasonCapacityBusy, attempt.ErrorReasonCapacityTimeout, attempt.ErrorReasonQueueFull, + attempt.ErrorReasonTokenBudgetExhaust, attempt.ErrorReasonRequestExceedsContext, + attempt.ErrorReasonRequestExceedsNode, attempt.ErrorReasonRequestExceedsNodeBudget, + attempt.ErrorReasonRequestExceedsBatchBudget, attempt.ErrorReasonModelLoad, + attempt.ErrorReasonDraining: return true default: return false @@ -134,14 +116,14 @@ func attemptOutcomeClass(outcome *store.InferenceRouteOutcome) string { switch status { case "": return "" - case finalStatusSuccess, finalStatusPartialSuccess: + case attempt.FinalStatusSuccess, attempt.FinalStatusPartialSuccess: return attemptClassSuccess - case finalStatusCancelled: + case attempt.FinalStatusCancelled: if class == "speculative_loser" { return attemptClassSpeculativeLoser } return attemptClassClientGone - case finalStatusTimeout: + case attempt.FinalStatusTimeout: // Queue expiries never dispatched to a provider: they are fleet // capacity, not a first-content kill, and must not inflate the // per-model kill rate the alert sketch keys on. @@ -149,7 +131,7 @@ func attemptOutcomeClass(outcome *store.InferenceRouteOutcome) string { return attemptClassCapacity } return attemptClassFirstChunkTimeout - case finalStatusError: + case attempt.FinalStatusError: return attemptErrorOutcomeClass(class, outcome) default: return attemptClassOther @@ -160,20 +142,20 @@ func attemptErrorOutcomeClass(class string, outcome *store.InferenceRouteOutcome switch class { case "first_chunk_timeout": return attemptClassFirstChunkTimeout - case errorClassDeadlineUnreachable: + case attempt.ErrorClassDeadlineUnreachable: return attemptClassDeadlineUnreachable - case errorClassClientError: + case attempt.ErrorClassClientError: return attemptClassClientError case "provider_disconnect_pre_commit", "provider_disconnect_before_response": return attemptClassDisconnect - case "ttft_too_slow", "queue_timeout", errorReasonQueueFull: + case "ttft_too_slow", "queue_timeout", attempt.ErrorReasonQueueFull: return attemptClassCapacity } if isCapacityClassErrorReason(outcome.ErrorReason) { return attemptClassCapacity } switch class { - case errorReasonProviderError: + case attempt.ErrorReasonProviderError: // providerFailedRoutingOutcomeFor stamps AdmittedButFailed on every // provider-executed failure; a bare provider_error row without it is a // coordinator-side dispatch failure ("failed to send request to @@ -225,7 +207,7 @@ func (s *Server) emitAttemptOutcomeMetric(model string, outcome *store.Inference } if s.metrics != nil { s.metrics.IncCounter(metricAttemptOutcomeCounter, - MetricLabel{"model", model}, MetricLabel{"class", class}) + MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: class}) } if s.dd == nil { return @@ -245,7 +227,7 @@ func (s *Server) emitQueueOutcomeMetric(model string, outcome *store.InferenceRo } if s.metrics != nil { s.metrics.IncCounter(metricQueueOutcomeCounter, - MetricLabel{"model", model}, MetricLabel{"class", class}) + MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: class}) } if s.dd == nil { return @@ -262,17 +244,17 @@ func orViewClassForCommittedOutcome(outcome *store.InferenceRouteOutcome) (class return "", false } switch strings.ToLower(strings.TrimSpace(outcome.FinalStatus)) { - case finalStatusSuccess: - return orClassSuccess, true - case finalStatusPartialSuccess: + case attempt.FinalStatusSuccess: + return dispatch.OrClassSuccess, true + case attempt.FinalStatusPartialSuccess: errClass := strings.ToLower(strings.TrimSpace(outcome.ErrorClass)) if strings.HasPrefix(errClass, "client_gone_after_commit") || errClass == "no_terminal_after_cancel" { // The consumer left after content had flowed: the upstream is the // one that hung up, so it is not graded against us. - return orClassClientGone, true + return dispatch.OrClassClientGone, true } // provider_error/disconnect/incomplete_after_commit, stream_timeout_after_commit. - return orClassMidStream, true + return dispatch.OrClassMidStream, true default: return "", false } @@ -302,91 +284,10 @@ func (s *Server) recordRequestOutcomeORView(model, class string) { } if s.metrics != nil { s.metrics.IncCounter(metricRequestOutcomeORViewCounter, - MetricLabel{"model", model}, MetricLabel{"class", class}) + MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: class}) } if s.dd == nil { return } s.ddIncr(metricRequestOutcomeORView, []string{"model:" + model, "class:" + class}) } - -// deadlineBucket buckets a pre-content client cancel by how much of the -// first-content budget had elapsed when the client left. -func deadlineBucket(elapsed, budget time.Duration) string { - if budget <= 0 || elapsed < 0 { - return deadlineBucketUnknown - } - ratio := float64(elapsed) / float64(budget) - switch { - case ratio < 0.5: - return deadlineBucketUnderHalf - case ratio < 0.8: - return deadlineBucketMid - case ratio < 1.0: - return deadlineBucketNearDeadline - default: - return deadlineBucketOver - } -} - -// orViewClassForClientGone maps a pre-content client-gone deadline bucket to -// the OR-view class: at or past ~the upstream budget the upstream timed out on -// us (its 504 → timeout); earlier is an application abort (excluded). -func orViewClassForClientGone(bucket string) string { - switch bucket { - case deadlineBucketNearDeadline, deadlineBucketOver: - return orClassTimeout - default: - return orClassClientGone - } -} - -// clientGoneDeadlineBucket is the deadline bucket for a pre-content cancel on -// this dispatch, measured on the request clock (ReceivedAt + deadline). -func (d *dispatchState) clientGoneDeadlineBucket() string { - if d == nil || d.timing == nil || d.timing.ReceivedAt.IsZero() || d.deadline <= 0 { - return deadlineBucketUnknown - } - return deadlineBucket(time.Since(d.timing.ReceivedAt), d.deadline) -} - -func (d *dispatchState) recordRequestOutcomeORView(class string) { - if d == nil { - return - } - d.s.recordRequestOutcomeORView(d.model, class) -} - -// metricRouteLatency is the per-request scheduler selection latency -// (reserve → routed) sampled at attempt-0 selection time, so routing distress -// is visible while requests are still in flight rather than only at their -// terminal (inference.timing.route_ms). Queued requests are skipped: their -// RoutedAt includes the queue wait, which the request_queue gauges cover. -const metricRouteLatency = "routing.route_latency_ms" - -// emitRouteLatency records the attempt-0 route segment. Called once the -// primary attempt's provider is selected (RoutedAt stamped). -func (d *dispatchState) emitRouteLatency() { - if d == nil || d.s == nil || d.s.dd == nil || d.attempt != 0 || d.timing == nil { - return - } - t := d.timing - if !t.QueuedAt.IsZero() || t.RoutedAt.IsZero() { - return - } - anchor := t.ReservedAt - if !t.MediaFetchedAt.IsZero() { - anchor = t.MediaFetchedAt - } - if anchor.IsZero() || t.RoutedAt.Before(anchor) { - return - } - // Fractional milliseconds: a healthy scan takes well under 1ms, and the - // signal this series exists for is that floor rising toward seconds, so - // sub-millisecond samples must not be truncated to 0 and dropped. - ms := float64(t.RoutedAt.Sub(anchor)) / float64(time.Millisecond) - if ms < 0 || math.IsNaN(ms) || math.IsInf(ms, 0) { - return - } - d.s.ddHistogram(metricRouteLatency, ms, []string{"model:" + d.model}) -} diff --git a/coordinator/api/attempt_outcome_metrics_test.go b/coordinator/api/attempt_outcome_metrics_test.go index de566632dc..7c072546f2 100644 --- a/coordinator/api/attempt_outcome_metrics_test.go +++ b/coordinator/api/attempt_outcome_metrics_test.go @@ -11,6 +11,8 @@ import ( "testing" "time" + "github.com/eigeninference/d-inference/coordinator/inference/attempt" + "github.com/eigeninference/d-inference/coordinator/inference/dispatch" "github.com/eigeninference/d-inference/coordinator/protocol" "github.com/eigeninference/d-inference/coordinator/registry" "github.com/eigeninference/d-inference/coordinator/store" @@ -69,29 +71,29 @@ func TestAttemptOutcomeClass_Mapping(t *testing.T) { want string }{ {"pre-fill (non-terminal) is not counted", store.InferenceRouteOutcome{}, ""}, - {"success", store.InferenceRouteOutcome{FinalStatus: finalStatusSuccess}, attemptClassSuccess}, - {"partial_success is a committed attempt", store.InferenceRouteOutcome{FinalStatus: finalStatusPartialSuccess, ErrorClass: "provider_error_after_commit"}, attemptClassSuccess}, - {"client_gone", store.InferenceRouteOutcome{FinalStatus: finalStatusCancelled, ErrorClass: "client_gone"}, attemptClassClientGone}, - {"speculative loser", store.InferenceRouteOutcome{FinalStatus: finalStatusCancelled, ErrorClass: "speculative_loser"}, attemptClassSpeculativeLoser}, - {"first_chunk_timeout (timeout status)", store.InferenceRouteOutcome{FinalStatus: finalStatusTimeout, ErrorClass: "first_chunk_timeout", ErrorReason: errorReasonProviderError}, attemptClassFirstChunkTimeout}, - {"accepted_timeout", store.InferenceRouteOutcome{FinalStatus: finalStatusTimeout, ErrorClass: "accepted_timeout"}, attemptClassFirstChunkTimeout}, - {"preamble_liveness_timeout", store.InferenceRouteOutcome{FinalStatus: finalStatusTimeout, ErrorClass: "preamble_liveness_timeout"}, attemptClassFirstChunkTimeout}, - {"queue_timeout is capacity", store.InferenceRouteOutcome{FinalStatus: finalStatusTimeout, ErrorClass: "queue_timeout"}, attemptClassCapacity}, - {"queue_deadline is capacity, not a kill", store.InferenceRouteOutcome{FinalStatus: finalStatusTimeout, ErrorClass: "queue_deadline"}, attemptClassCapacity}, - {"first_chunk_timeout via dispatch error class", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: "first_chunk_timeout"}, attemptClassFirstChunkTimeout}, - {"deadline_unreachable", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: errorClassDeadlineUnreachable, ErrorReason: errorReasonDeadlineUnreachable}, attemptClassDeadlineUnreachable}, - {"client_error (jinja)", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: errorClassClientError, ErrorReason: errorReasonJinjaTemplate}, attemptClassClientError}, - {"provider disconnect pre-commit", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: "provider_disconnect_pre_commit", ErrorReason: errorReasonProviderError, AdmittedButFailed: true}, attemptClassDisconnect}, - {"ttft_too_slow is capacity", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: "ttft_too_slow"}, attemptClassCapacity}, - {"provider capacity 503 (token budget)", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: errorReasonProviderError, ErrorReason: errorReasonTokenBudgetExhaust, AdmittedButFailed: true, ErrorCode: 503}, attemptClassCapacity}, - {"provider capacity 503 (busy)", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: errorReasonProviderError, ErrorReason: errorReasonCapacityBusy, AdmittedButFailed: true, ErrorCode: 503}, attemptClassCapacity}, - {"model load failure is capacity", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: errorReasonProviderError, ErrorReason: errorReasonModelLoad, AdmittedButFailed: true}, attemptClassCapacity}, - {"typed draining refusal (chat pre-commit) is capacity, not a fault", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: errorReasonProviderError, ErrorReason: errorReasonDraining, AdmittedButFailed: true, ErrorCode: 503}, attemptClassCapacity}, - {"typed draining refusal (generic endpoint) is capacity, not a fault", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: "provider_error_before_response", ErrorReason: errorReasonDraining, AdmittedButFailed: true, ErrorCode: 503}, attemptClassCapacity}, - {"genuine provider fault", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: errorReasonProviderError, ErrorReason: errorReasonProviderError, AdmittedButFailed: true, ErrorCode: 500}, attemptClassFault}, - {"failed to send (never admitted)", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: errorReasonProviderError, ErrorReason: errorReasonProviderError}, attemptClassSendFailed}, - {"generic endpoint provider error before response", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: "provider_error_before_response", AdmittedButFailed: true}, attemptClassFault}, - {"encryption_missing is other", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: "encryption_missing"}, attemptClassOther}, + {"success", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusSuccess}, attemptClassSuccess}, + {"partial_success is a committed attempt", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusPartialSuccess, ErrorClass: "provider_error_after_commit"}, attemptClassSuccess}, + {"client_gone", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusCancelled, ErrorClass: "client_gone"}, attemptClassClientGone}, + {"speculative loser", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusCancelled, ErrorClass: "speculative_loser"}, attemptClassSpeculativeLoser}, + {"first_chunk_timeout (timeout status)", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusTimeout, ErrorClass: "first_chunk_timeout", ErrorReason: attempt.ErrorReasonProviderError}, attemptClassFirstChunkTimeout}, + {"accepted_timeout", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusTimeout, ErrorClass: "accepted_timeout"}, attemptClassFirstChunkTimeout}, + {"preamble_liveness_timeout", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusTimeout, ErrorClass: "preamble_liveness_timeout"}, attemptClassFirstChunkTimeout}, + {"queue_timeout is capacity", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusTimeout, ErrorClass: "queue_timeout"}, attemptClassCapacity}, + {"queue_deadline is capacity, not a kill", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusTimeout, ErrorClass: "queue_deadline"}, attemptClassCapacity}, + {"first_chunk_timeout via dispatch error class", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: "first_chunk_timeout"}, attemptClassFirstChunkTimeout}, + {"deadline_unreachable", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: attempt.ErrorClassDeadlineUnreachable, ErrorReason: attempt.ErrorReasonDeadlineUnreachable}, attemptClassDeadlineUnreachable}, + {"client_error (jinja)", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: attempt.ErrorClassClientError, ErrorReason: attempt.ErrorReasonJinjaTemplate}, attemptClassClientError}, + {"provider disconnect pre-commit", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: "provider_disconnect_pre_commit", ErrorReason: attempt.ErrorReasonProviderError, AdmittedButFailed: true}, attemptClassDisconnect}, + {"ttft_too_slow is capacity", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: "ttft_too_slow"}, attemptClassCapacity}, + {"provider capacity 503 (token budget)", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: attempt.ErrorReasonProviderError, ErrorReason: attempt.ErrorReasonTokenBudgetExhaust, AdmittedButFailed: true, ErrorCode: 503}, attemptClassCapacity}, + {"provider capacity 503 (busy)", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: attempt.ErrorReasonProviderError, ErrorReason: attempt.ErrorReasonCapacityBusy, AdmittedButFailed: true, ErrorCode: 503}, attemptClassCapacity}, + {"model load failure is capacity", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: attempt.ErrorReasonProviderError, ErrorReason: attempt.ErrorReasonModelLoad, AdmittedButFailed: true}, attemptClassCapacity}, + {"typed draining refusal (chat pre-commit) is capacity, not a fault", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: attempt.ErrorReasonProviderError, ErrorReason: attempt.ErrorReasonDraining, AdmittedButFailed: true, ErrorCode: 503}, attemptClassCapacity}, + {"typed draining refusal (generic endpoint) is capacity, not a fault", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: "provider_error_before_response", ErrorReason: attempt.ErrorReasonDraining, AdmittedButFailed: true, ErrorCode: 503}, attemptClassCapacity}, + {"genuine provider fault", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: attempt.ErrorReasonProviderError, ErrorReason: attempt.ErrorReasonProviderError, AdmittedButFailed: true, ErrorCode: 500}, attemptClassFault}, + {"failed to send (never admitted)", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: attempt.ErrorReasonProviderError, ErrorReason: attempt.ErrorReasonProviderError}, attemptClassSendFailed}, + {"generic endpoint provider error before response", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: "provider_error_before_response", AdmittedButFailed: true}, attemptClassFault}, + {"encryption_missing is other", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: "encryption_missing"}, attemptClassOther}, {"unknown status is other", store.InferenceRouteOutcome{FinalStatus: "weird"}, attemptClassOther}, } for _, tc := range cases { @@ -113,16 +115,16 @@ func TestORViewClassForCommittedOutcome(t *testing.T) { want string wantOK bool }{ - {"success", store.InferenceRouteOutcome{FinalStatus: finalStatusSuccess}, orClassSuccess, true}, - {"provider error after commit is mid_stream", store.InferenceRouteOutcome{FinalStatus: finalStatusPartialSuccess, ErrorClass: "provider_error_after_commit"}, orClassMidStream, true}, - {"provider disconnect after commit is mid_stream", store.InferenceRouteOutcome{FinalStatus: finalStatusPartialSuccess, ErrorClass: "provider_disconnect_after_commit"}, orClassMidStream, true}, - {"stream timeout after commit is mid_stream", store.InferenceRouteOutcome{FinalStatus: finalStatusPartialSuccess, ErrorClass: "stream_timeout_after_commit"}, orClassMidStream, true}, - {"provider incomplete after commit is mid_stream", store.InferenceRouteOutcome{FinalStatus: finalStatusPartialSuccess, ErrorClass: "provider_incomplete_after_commit"}, orClassMidStream, true}, - {"client gone after commit (completed) is excluded", store.InferenceRouteOutcome{FinalStatus: finalStatusPartialSuccess, ErrorClass: errorClassClientGoneAfterCommitCompleted}, orClassClientGone, true}, - {"client gone after commit (error) is excluded", store.InferenceRouteOutcome{FinalStatus: finalStatusPartialSuccess, ErrorClass: "client_gone_after_commit_provider_error"}, orClassClientGone, true}, - {"no terminal after cancel is excluded", store.InferenceRouteOutcome{FinalStatus: finalStatusPartialSuccess, ErrorClass: "no_terminal_after_cancel"}, orClassClientGone, true}, - {"pre-content error is not a committed outcome", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: "provider_error"}, "", false}, - {"pre-content timeout is not a committed outcome", store.InferenceRouteOutcome{FinalStatus: finalStatusTimeout, ErrorClass: "first_chunk_timeout"}, "", false}, + {"success", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusSuccess}, dispatch.OrClassSuccess, true}, + {"provider error after commit is mid_stream", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusPartialSuccess, ErrorClass: "provider_error_after_commit"}, dispatch.OrClassMidStream, true}, + {"provider disconnect after commit is mid_stream", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusPartialSuccess, ErrorClass: "provider_disconnect_after_commit"}, dispatch.OrClassMidStream, true}, + {"stream timeout after commit is mid_stream", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusPartialSuccess, ErrorClass: "stream_timeout_after_commit"}, dispatch.OrClassMidStream, true}, + {"provider incomplete after commit is mid_stream", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusPartialSuccess, ErrorClass: "provider_incomplete_after_commit"}, dispatch.OrClassMidStream, true}, + {"client gone after commit (completed) is excluded", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusPartialSuccess, ErrorClass: attempt.ErrorClassClientGoneAfterCommitCompleted}, dispatch.OrClassClientGone, true}, + {"client gone after commit (error) is excluded", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusPartialSuccess, ErrorClass: "client_gone_after_commit_provider_error"}, dispatch.OrClassClientGone, true}, + {"no terminal after cancel is excluded", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusPartialSuccess, ErrorClass: "no_terminal_after_cancel"}, dispatch.OrClassClientGone, true}, + {"pre-content error is not a committed outcome", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: "provider_error"}, "", false}, + {"pre-content timeout is not a committed outcome", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusTimeout, ErrorClass: "first_chunk_timeout"}, "", false}, {"pre-fill is not counted", store.InferenceRouteOutcome{}, "", false}, } for _, tc := range cases { @@ -135,39 +137,6 @@ func TestORViewClassForCommittedOutcome(t *testing.T) { } } -func TestDeadlineBucket_AndORViewClass(t *testing.T) { - budget := 10 * time.Second - cases := []struct { - elapsed time.Duration - budget time.Duration - want string - wantOR string - }{ - {0, 0, deadlineBucketUnknown, orClassClientGone}, - {time.Second, budget, deadlineBucketUnderHalf, orClassClientGone}, - {4999 * time.Millisecond, budget, deadlineBucketUnderHalf, orClassClientGone}, - {5 * time.Second, budget, deadlineBucketMid, orClassClientGone}, - {7999 * time.Millisecond, budget, deadlineBucketMid, orClassClientGone}, - {8 * time.Second, budget, deadlineBucketNearDeadline, orClassTimeout}, - {9800 * time.Millisecond, budget, deadlineBucketNearDeadline, orClassTimeout}, - {10 * time.Second, budget, deadlineBucketOver, orClassTimeout}, - {30 * time.Second, budget, deadlineBucketOver, orClassTimeout}, - {-time.Second, budget, deadlineBucketUnknown, orClassClientGone}, - } - for _, tc := range cases { - got := deadlineBucket(tc.elapsed, tc.budget) - if got != tc.want { - t.Errorf("deadlineBucket(%s, %s) = %q, want %q", tc.elapsed, tc.budget, got, tc.want) - } - if or := orViewClassForClientGone(got); or != tc.wantOR { - t.Errorf("orViewClassForClientGone(%q) = %q, want %q", got, or, tc.wantOR) - } - } - if got := orViewClassForClientGone(deadlineBucketNotApplicable); got != orClassClientGone { - t.Errorf("not_applicable bucket must be excluded, got %q", got) - } -} - func TestSanitizeVersionTag(t *testing.T) { cases := map[string]string{ "": "unknown", @@ -267,7 +236,7 @@ func TestAttemptOutcome_SilentProviderLadder(t *testing.T) { var total int64 for _, class := range classes { total += snap.Counters[counterKey(metricAttemptOutcomeCounter, - MetricLabel{"model", model}, MetricLabel{"class", class})] + MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: class})] } return total } @@ -279,12 +248,12 @@ func TestAttemptOutcome_SilentProviderLadder(t *testing.T) { got, dispatched, snap.Counters) } kills := snap.Counters[counterKey(metricAttemptOutcomeCounter, - MetricLabel{"model", model}, MetricLabel{"class", attemptClassFirstChunkTimeout})] + MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: attemptClassFirstChunkTimeout})] if kills < 1 { t.Fatalf("attempt_outcome{first_chunk_timeout} = %d, want >= 1; counters=%v", kills, snap.Counters) } if got := snap.Counters[counterKey(metricRequestOutcomeORViewCounter, - MetricLabel{"model", model}, MetricLabel{"class", orClassRateLimited})]; got != 1 { + MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: orClassRateLimited})]; got != 1 { t.Fatalf("request_outcome_or_view{rate_limited} = %d, want 1; counters=%v", got, snap.Counters) } @@ -321,7 +290,7 @@ func TestAttemptOutcome_SilentProviderLadder(t *testing.T) { // instead be recorded as a pre-content client_gone (with a deadline bucket), // refund exactly once, and write nothing. func TestDispatch_ClientGoneBetweenAttempts_RecordsClientGone(t *testing.T) { - srv, _ := testServer(t) + srv, st := testServer(t) collector := newUDPCollector(t) defer collector.Close() dd := newTestDD(t, collector) @@ -341,23 +310,19 @@ func TestDispatch_ClientGoneBetweenAttempts_RecordsClientGone(t *testing.T) { r := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader("{}")).WithContext(ctx) refunds := 0 deadline := 5 * time.Second - d := &dispatchState{ - s: srv, - w: w, - r: r, - model: model, - publicModel: model, - rawBody: []byte(`{"model":"` + model + `"}`), - consumerKey: "test-key", - estimatedPromptTokens: 6, - requestedMaxTokens: 64, - timing: ®istry.RequestTiming{ReceivedAt: time.Now()}, - deadline: deadline, - speculativeAt: deadline / 2, - refundReservation: func() { refunds++ }, - excludeProviders: make(map[string]struct{}), - } - d.run() + request := dispatch.Request{ + Model: model, + PublicModel: model, + RawBody: []byte(`{"model":"` + model + `"}`), + ConsumerKey: "test-key", + EstimatedPromptTokens: 6, + RequestedMaxTokens: 64, + Timing: ®istry.RequestTiming{ReceivedAt: time.Now()}, + Deadline: deadline, + SpeculativeAt: deadline / 2, + RefundReservation: func() { refunds++ }, + } + srv.inferenceDispatch().Run(w, r, request) if refunds != 1 { t.Errorf("reservation refunds = %d, want exactly 1", refunds) @@ -365,17 +330,20 @@ func TestDispatch_ClientGoneBetweenAttempts_RecordsClientGone(t *testing.T) { if w.Body.Len() != 0 { t.Errorf("wrote a response to a dead socket: %s", w.Body.String()) } - if d.attempt != 1 { - t.Errorf("ladder stopped at attempt %d, want the client-gone exit at attempt 1", d.attempt) + // One recorded dispatch followed by client-gone proves the second ladder + // iteration exited before another provider selection. + waitForAdaptiveCondition(t, time.Second, func() bool { return len(st.InferenceRouteRecordsSince(time.Time{})) >= 1 }) + if got := len(st.InferenceRouteRecordsSince(time.Time{})); got != 1 { + t.Errorf("ladder recorded %d attempts, want the client-gone exit after attempt 0", got) } snap := srv.metrics.Snapshot() if got := snap.Counters[counterKey(metricRequestOutcomeORViewCounter, - MetricLabel{"model", model}, MetricLabel{"class", orClassClientGone})]; got != 1 { + MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: dispatch.OrClassClientGone})]; got != 1 { t.Errorf("request_outcome_or_view{client_gone} = %d, want 1; counters=%v", got, snap.Counters) } if got := snap.Counters[counterKey(metricAttemptOutcomeCounter, - MetricLabel{"model", model}, MetricLabel{"class", attemptClassSendFailed})]; got != 1 { + MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: attemptClassSendFailed})]; got != 1 { t.Errorf("attempt_outcome{send_failed} = %d, want 1 (attempt 0's socketless write); counters=%v", got, snap.Counters) } @@ -393,7 +361,7 @@ func TestDispatch_ClientGoneBetweenAttempts_RecordsClientGone(t *testing.T) { if out := findMetrics(packets, metricRequestOutcome+":"); len(out) != 0 { t.Errorf("a client that left mid-ladder must not be counted on request_outcome: %v", out) } - if got := sumMetric(t, packets, metricRequestOutcomeORView, "model:"+model, "class:"+orClassClientGone); got != 1 { + if got := sumMetric(t, packets, metricRequestOutcomeORView, "model:"+model, "class:"+dispatch.OrClassClientGone); got != 1 { t.Errorf("UDP request_outcome_or_view{client_gone} = %v, want 1", got) } } @@ -412,12 +380,12 @@ func TestRecordRejection_MirrorsORView(t *testing.T) { const model = "or-view-mirror-model" srv.recordRejection(rejectionInfo{ - stage: "preflight_capacity", reasonCode: "machine_busy", httpStatus: http.StatusTooManyRequests, - requestedModel: "client-typed-alias", resolvedModel: model, retryAfterMs: 7000, + Stage: "preflight_capacity", ReasonCode: "machine_busy", HttpStatus: http.StatusTooManyRequests, + RequestedModel: "client-typed-alias", ResolvedModel: model, RetryAfterMs: 7000, }) srv.recordRejection(rejectionInfo{ - stage: "validation", reasonCode: "bad_request", httpStatus: http.StatusBadRequest, - requestedModel: "client-typed-alias", resolvedModel: model, + Stage: "validation", ReasonCode: "bad_request", HttpStatus: http.StatusBadRequest, + RequestedModel: "client-typed-alias", ResolvedModel: model, }) _ = dd.Statsd.Flush() @@ -473,7 +441,7 @@ func TestUnknownFrames_CountedByKindAndVersion(t *testing.T) { key := func(kind string) string { return counterKey(metricUnknownFramesCounter, - MetricLabel{"kind", kind}, MetricLabel{"provider_version", "0.6.x"}) + MetricLabel{Name: "kind", Value: kind}, MetricLabel{Name: "provider_version", Value: "0.6.x"}) } snap := waitForCounters(t, srv, 3*time.Second, func(s MetricsSnapshot) bool { return s.Counters[key(unknownFrameKindChunk)] == 1 && @@ -546,12 +514,12 @@ func TestQueueOutcomeClass_Mapping(t *testing.T) { want string }{ {"pre-fill (non-terminal) is not counted", store.InferenceRouteOutcome{}, ""}, - {"client gone while queued", store.InferenceRouteOutcome{FinalStatus: finalStatusCancelled, ErrorClass: "client_gone"}, queueClassClientGone}, - {"queue_deadline", store.InferenceRouteOutcome{FinalStatus: finalStatusTimeout, ErrorClass: rejectionReasonQueueDeadline}, queueClassQueueDeadline}, - {"queue_timeout", store.InferenceRouteOutcome{FinalStatus: finalStatusTimeout, ErrorClass: "queue_timeout"}, queueClassQueueTimeout}, - {"ttft_too_slow", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: "ttft_too_slow"}, queueClassTTFTTooSlow}, - {"tool constraint unavailable", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: "model_capability_unsupported"}, queueClassCapabilityUnsupported}, - {"unknown exit class is other", store.InferenceRouteOutcome{FinalStatus: finalStatusError, ErrorClass: "something_new"}, queueClassOther}, + {"client gone while queued", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusCancelled, ErrorClass: "client_gone"}, queueClassClientGone}, + {"queue_deadline", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusTimeout, ErrorClass: dispatch.RejectionReasonQueueDeadline}, queueClassQueueDeadline}, + {"queue_timeout", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusTimeout, ErrorClass: "queue_timeout"}, queueClassQueueTimeout}, + {"ttft_too_slow", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: "ttft_too_slow"}, queueClassTTFTTooSlow}, + {"tool constraint unavailable", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: "model_capability_unsupported"}, queueClassCapabilityUnsupported}, + {"unknown exit class is other", store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusError, ErrorClass: "something_new"}, queueClassOther}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -589,14 +557,14 @@ func TestEmitAttemptOutcomeMetric_QueueExitIsNotAnAttempt(t *testing.T) { return total } - queued := &store.InferenceRouteOutcome{FinalStatus: finalStatusTimeout, ErrorClass: rejectionReasonQueueDeadline, ErrorCode: http.StatusGatewayTimeout, QueueExit: true} + queued := &store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusTimeout, ErrorClass: dispatch.RejectionReasonQueueDeadline, ErrorCode: http.StatusGatewayTimeout, QueueExit: true} srv.emitAttemptOutcomeMetric(model, queued) snap := srv.metrics.Snapshot() if got := attemptTotal(snap); got != 0 { t.Fatalf("attempt_outcome after a queue exit = %d, want 0; counters=%v", got, snap.Counters) } if got := snap.Counters[counterKey(metricQueueOutcomeCounter, - MetricLabel{"model", model}, MetricLabel{"class", queueClassQueueDeadline})]; got != 1 { + MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: queueClassQueueDeadline})]; got != 1 { t.Fatalf("queue_outcome{queue_deadline} = %d, want 1; counters=%v", got, snap.Counters) } @@ -604,14 +572,14 @@ func TestEmitAttemptOutcomeMetric_QueueExitIsNotAnAttempt(t *testing.T) { srv.emitAttemptOutcomeMetric(model, &store.InferenceRouteOutcome{QueueExit: true}) // The same class from a DISPATCHED attempt still counts as an attempt. - dispatched := &store.InferenceRouteOutcome{FinalStatus: finalStatusTimeout, ErrorClass: rejectionReasonQueueDeadline, ErrorCode: http.StatusGatewayTimeout} + dispatched := &store.InferenceRouteOutcome{FinalStatus: attempt.FinalStatusTimeout, ErrorClass: dispatch.RejectionReasonQueueDeadline, ErrorCode: http.StatusGatewayTimeout} srv.emitAttemptOutcomeMetric(model, dispatched) snap = srv.metrics.Snapshot() if got := attemptTotal(snap); got != 1 { t.Fatalf("attempt_outcome after a dispatched terminal = %d, want 1; counters=%v", got, snap.Counters) } if got := snap.Counters[counterKey(metricAttemptOutcomeCounter, - MetricLabel{"model", model}, MetricLabel{"class", attemptClassCapacity})]; got != 1 { + MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: attemptClassCapacity})]; got != 1 { t.Fatalf("attempt_outcome{capacity} = %d, want 1; counters=%v", got, snap.Counters) } var queueTotal int64 @@ -662,7 +630,7 @@ func TestQueuedExit_LiveQueueDeadline_CountsOnQueueOutcome(t *testing.T) { t.Fatalf("status = %d, want 429; body=%s", res.status, res.body) } - queueKey := counterKey(metricQueueOutcomeCounter, MetricLabel{"model", model}, MetricLabel{"class", queueClassQueueDeadline}) + queueKey := counterKey(metricQueueOutcomeCounter, MetricLabel{Name: "model", Value: model}, MetricLabel{Name: "class", Value: queueClassQueueDeadline}) snap := waitForCounters(t, srv, 3*time.Second, func(s MetricsSnapshot) bool { return s.Counters[queueKey] >= 1 }) diff --git a/coordinator/api/attempt_usage_route_test.go b/coordinator/api/attempt_usage_route_test.go index 6772a48141..d4dbc23cde 100644 --- a/coordinator/api/attempt_usage_route_test.go +++ b/coordinator/api/attempt_usage_route_test.go @@ -1,28 +1,29 @@ package api -// Attempt-usage observability (deadline incident fix): a typed error terminal -// can carry the engine-reconciled partial usage of the failed attempt -// (InferenceErrorMessage.AttemptUsage). The coordinator persists those token -// counts on the route row — the incident's "every strict route had null -// prompt_tokens/completion_tokens" gap — WITHOUT touching billing: refunds, -// reservations, earnings, and cost stay exactly as for a usage-less error. - import ( "testing" "time" + "github.com/eigeninference/d-inference/coordinator/inference/attempt" "github.com/eigeninference/d-inference/coordinator/protocol" "github.com/eigeninference/d-inference/coordinator/registry" "github.com/eigeninference/d-inference/coordinator/store" ) +// Attempt-usage observability (deadline incident fix): a typed error terminal +// can carry the engine-reconciled partial usage of the failed attempt +// (InferenceErrorMessage.AttemptUsage). The coordinator persists those token +// counts on the route row — the incident's "every strict route had null +// prompt_tokens/completion_tokens" gap — WITHOUT touching billing: refunds, +// reservations, earnings, and cost stay exactly as for a usage-less error. + func attemptUsageErrMsg(reqID string, usage *protocol.UsageInfo) protocol.InferenceErrorMessage { return protocol.InferenceErrorMessage{ Type: protocol.TypeInferenceError, RequestID: reqID, Error: "request exceeded safety deadline", StatusCode: 504, - TerminalCause: terminalCauseSafetyDeadline, + TerminalCause: attempt.TerminalCauseSafetyDeadline, AttemptUsage: usage, } } @@ -39,9 +40,9 @@ func TestProviderErrorOutcomesCarryAttemptUsage(t *testing.T) { name string outcome *store.InferenceRouteOutcome }{ - {"post_commit", postCommitProviderErrorOutcome(pr, msg)}, - {"pre_response", preResponseProviderErrorOutcome(pr, msg)}, - {"pre_commit", preCommitProviderErrorOutcome(pr, msg)}, + {"post_commit", attempt.PostCommitProviderErrorOutcome(pr, msg)}, + {"pre_response", attempt.PreResponseProviderErrorOutcome(pr, msg)}, + {"pre_commit", attempt.PreCommitProviderErrorOutcome(pr, msg)}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -64,7 +65,7 @@ func TestProviderErrorOutcomesCarryAttemptUsage(t *testing.T) { clientMsg := attemptUsageErrMsg(pr.RequestID, usage) clientMsg.StatusCode = 400 clientMsg.TerminalCause = "" - if out := preCommitProviderErrorOutcome(pr, clientMsg); out.PromptTokens != 123 || out.CompletionTokens != 456 { + if out := attempt.PreCommitProviderErrorOutcome(pr, clientMsg); out.PromptTokens != 123 || out.CompletionTokens != 456 { t.Errorf("client-error branch tokens = %d/%d, want 123/456", out.PromptTokens, out.CompletionTokens) } } @@ -79,7 +80,7 @@ func TestProviderErrorOutcomesWithoutAttemptUsageUnchanged(t *testing.T) { Error: "boom", StatusCode: 500, } - pre := preCommitProviderErrorOutcome(pr, msg) + pre := attempt.PreCommitProviderErrorOutcome(pr, msg) if pre.PromptTokens != 0 || pre.CompletionTokens != 0 || pre.ReasoningTokens != 0 { t.Errorf("pre-commit legacy tokens = %d/%d/%d, want 0/0/0", pre.PromptTokens, pre.CompletionTokens, pre.ReasoningTokens) @@ -88,7 +89,7 @@ func TestProviderErrorOutcomesWithoutAttemptUsageUnchanged(t *testing.T) { t.Error("error terminal must still force-persist completion_tokens=0 (existing behavior)") } - post := postCommitProviderErrorOutcome(pr, msg) + post := attempt.PostCommitProviderErrorOutcome(pr, msg) if post.CompletionTokensSet { t.Error("partial_success without usage must not force completion_tokens (existing behavior)") } @@ -109,7 +110,7 @@ func TestAttemptUsagePersistsOnErrorRouteRow(t *testing.T) { } msg := attemptUsageErrMsg(pr.RequestID, &protocol.UsageInfo{PromptTokens: 123, CompletionTokens: 456, ReasoningTokens: 7}) - if err := st.UpdateInferenceRouteOutcome(pr.RequestID, pr.Attempt, postCommitProviderErrorOutcome(pr, msg)); err != nil { + if err := st.UpdateInferenceRouteOutcome(pr.RequestID, pr.Attempt, attempt.PostCommitProviderErrorOutcome(pr, msg)); err != nil { t.Fatalf("UpdateInferenceRouteOutcome: %v", err) } @@ -117,7 +118,7 @@ func TestAttemptUsagePersistsOnErrorRouteRow(t *testing.T) { if rec == nil { t.Fatal("route record not found") } - if rec.FinalStatus != finalStatusPartialSuccess { + if rec.FinalStatus != attempt.FinalStatusPartialSuccess { t.Errorf("final_status = %q, want partial_success", rec.FinalStatus) } if rec.PromptTokens != 123 || rec.CompletionTokens != 456 || rec.ReasoningTokens != 7 { diff --git a/coordinator/api/auth_identity.go b/coordinator/api/auth_identity.go new file mode 100644 index 0000000000..1bc590206a --- /dev/null +++ b/coordinator/api/auth_identity.go @@ -0,0 +1,28 @@ +package api + +import ( + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/requestauth" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// resolveAccountID returns the internal account ID for the current request. +// Prefers the Privy user's account ID, falls back to API key. +func (s *Server) resolveAccountID(r *http.Request) string { return requestauth.ResolveAccountID(r) } + +// isAdmin checks if the user has admin privileges (email in admin list). +func (s *Server) isAdmin(user *store.User) bool { + if user == nil || user.Email == "" || len(s.adminEmails) == 0 { + return false + } + return s.adminEmails[strings.ToLower(user.Email)] +} + +// requirePrivyUser requires a linked user installed by authentication middleware. +// Interactive-session-only routes still enforce their own API-key exclusion. +// Returns the user or writes a 401 error and returns nil. +func (s *Server) requirePrivyUser(w http.ResponseWriter, r *http.Request) *store.User { + return requestauth.RequirePrivyUser(w, r) +} diff --git a/coordinator/api/authentication.go b/coordinator/api/authentication.go new file mode 100644 index 0000000000..3fb77dbfee --- /dev/null +++ b/coordinator/api/authentication.go @@ -0,0 +1,49 @@ +package api + +import ( + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/requestauth" + "github.com/eigeninference/d-inference/coordinator/auth" +) + +// authenticationSettings reads current configuration after route registration. +// The shared authenticator owns the key cache; Server retains service wiring and +// the existing request accounting/profiling hooks. +func (s *Server) authenticationSettings() requestauth.Settings { + return requestauth.Settings{ + Store: s.authenticationStore, Logger: s.logger, PrivyAuth: s.privyAuth, AdminKey: s.adminKey, + SetStage: setOutcomeStage, StampAuth: stampAuth, + } +} + +func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc { + return s.requestAuth.RequireAuth(s.authenticationSettings, next) +} + +func (s *Server) requirePrivyAuth(next http.HandlerFunc) http.HandlerFunc { + return s.requestAuth.RequirePrivyAuth(s.authenticationSettings, next) +} + +func extractBearerToken(r *http.Request) string { return requestauth.BearerToken(r) } + +func (s *Server) authenticationStore() requestauth.Store { return s.store } + +// SetAdminKey configures the admin API key for admin-only endpoints. +func (s *Server) SetAdminKey(key string) { + s.adminKey = key +} + +// SetPrivyAuth configures Privy JWT authentication for consumer endpoints. +func (s *Server) SetPrivyAuth(pa *auth.PrivyAuth) { + s.privyAuth = pa +} + +// SetAdminEmails configures which Privy accounts have admin access. +func (s *Server) SetAdminEmails(emails []string) { + s.adminEmails = make(map[string]bool, len(emails)) + for _, e := range emails { + s.adminEmails[strings.ToLower(strings.TrimSpace(e))] = true + } +} diff --git a/coordinator/api/authentication_contract_test.go b/coordinator/api/authentication_contract_test.go new file mode 100644 index 0000000000..4c607685e9 --- /dev/null +++ b/coordinator/api/authentication_contract_test.go @@ -0,0 +1,165 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// A registered route must observe credential replacement. Capturing configuration +// while mounting middleware would silently keep an old admin key or JWT verifier. +func TestAuthenticationUsesCurrentCredentials(t *testing.T) { + srv, st := newKeyTestServer(t) + t.Cleanup(srv.Close) + handler := srv.Handler() + user := &store.User{AccountID: "auth-current-user", PrivyUserID: "did:privy:auth-current"} + if err := st.CreateUser(user); err != nil { + t.Fatal(err) + } + for account, amount := range map[string]int64{"admin": 17, user.AccountID: 29} { + if err := st.Credit(account, amount, store.LedgerAdminCredit, "auth-test"); err != nil { + t.Fatal(err) + } + } + balance := func(token string, want int64) { + t.Helper() + w := authContractRequest(t, handler, http.MethodGet, "/v1/payments/balance", token, "", http.StatusOK) + var got types.BalanceResponse + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got.BalanceMicroUSD != want { + t.Fatalf("balance = %d, want %d for the resolved identity", got.BalanceMicroUSD, want) + } + } + + srv.SetAdminKey("auth-admin-before") + balance("auth-admin-before", 17) + srv.SetAdminKey("auth-admin-after") + authContractRequest(t, handler, http.MethodGet, "/v1/payments/balance", "auth-admin-before", "", http.StatusUnauthorized) + balance("auth-admin-after", 17) + srv.SetAdminKey("") + authContractRequest(t, handler, http.MethodGet, "/v1/payments/balance", "auth-admin-after", "", http.StatusUnauthorized) + + firstSession := privySession(t, srv, st, user) + balance(firstSession, 29) + authContractRequest(t, handler, http.MethodGet, "/v1/keys", firstSession, "", http.StatusOK) + secondSession := privySession(t, srv, st, user) + // JWT-shaped credentials are checked by Privy before considering the admin key. + srv.SetAdminKey(firstSession) + authContractRequest(t, handler, http.MethodGet, "/v1/payments/balance", firstSession, "", http.StatusUnauthorized) + authContractRequest(t, handler, http.MethodGet, "/v1/keys", firstSession, "", http.StatusUnauthorized) + balance(secondSession, 29) + authContractRequest(t, handler, http.MethodGet, "/v1/keys", secondSession, "", http.StatusOK) + srv.SetAdminKey("") + srv.SetPrivyAuth(nil) + authContractRequest(t, handler, http.MethodGet, "/v1/payments/balance", secondSession, "", http.StatusUnauthorized) + authContractRequest(t, handler, http.MethodGet, "/v1/keys", secondSession, "", http.StatusForbidden) + + key, _, err := st.CreateAPIKey(user.AccountID, store.APIKeyCreate{Name: "auth-admin-precedence"}) + if err != nil { + t.Fatal(err) + } + // The admin credential also takes precedence over a valid persisted API key. + srv.SetAdminKey(key) + balance(key, 17) + srv.SetAdminKey("") + balance(key, 29) +} + +type authContractStore struct { + store.Store + keyReads atomic.Int64 +} + +func (s *authContractStore) AuthenticateKey(token string) (*store.APIKey, error) { + s.keyReads.Add(1) + return s.Store.AuthenticateKey(token) +} + +// Mutations use the real registered routes and the same cache as inference auth. +// Provider tokens must remain uncached because they have a separate revoke path. +func TestAuthenticationCacheFollowsCredentialLifecycle(t *testing.T) { + srv, st := newKeyTestServer(t) + t.Cleanup(srv.Close) + counting := &authContractStore{Store: st} + // Install after NewServer: authentication must read the live persistence binding. + srv.store = counting + user := &store.User{AccountID: "auth-lifecycle-user", PrivyUserID: "did:privy:auth-lifecycle"} + if err := st.CreateUser(user); err != nil { + t.Fatal(err) + } + session := privySession(t, srv, st, user) + handler := srv.Handler() + key, record, err := st.CreateAPIKey(user.AccountID, store.APIKeyCreate{Name: "auth-lifecycle"}) + if err != nil { + t.Fatal(err) + } + checkKey := func(token string, status int) { + t.Helper() + authContractRequest(t, handler, http.MethodGet, "/v1/payments/balance", token, "", status) + } + checkKey(key, http.StatusOK) + checkKey(key, http.StatusOK) + if got := counting.keyReads.Load(); got != 1 { + t.Fatalf("repeated key lookup made %d persistence reads, want one cached read", got) + } + + path := "/v1/keys/" + record.ID + authContractRequest(t, handler, http.MethodPatch, path, session, `{"disabled":true}`, http.StatusOK) + checkKey(key, http.StatusUnauthorized) + authContractRequest(t, handler, http.MethodPatch, path, session, `{"disabled":false}`, http.StatusOK) + checkKey(key, http.StatusOK) + w := authContractRequest(t, handler, http.MethodPost, path+"/rotate", session, "", http.StatusOK) + var rotated types.CreateAPIKeyResponse + if err := json.Unmarshal(w.Body.Bytes(), &rotated); err != nil { + t.Fatal(err) + } + checkKey(key, http.StatusUnauthorized) + checkKey(rotated.Key, http.StatusOK) + authContractRequest(t, handler, http.MethodDelete, "/v1/keys/"+rotated.Data.ID, session, "", http.StatusOK) + checkKey(rotated.Key, http.StatusUnauthorized) + + // The legacy raw-token revocation route invalidates the same positive cache. + rawRevokedKey, _, err := st.CreateAPIKey(user.AccountID, store.APIKeyCreate{Name: "auth-raw-revoke"}) + if err != nil { + t.Fatal(err) + } + checkKey(rawRevokedKey, http.StatusOK) + body, err := json.Marshal(map[string]string{"key": rawRevokedKey}) + if err != nil { + t.Fatal(err) + } + authContractRequest(t, handler, http.MethodDelete, "/v1/auth/keys", session, string(body), http.StatusOK) + checkKey(rawRevokedKey, http.StatusUnauthorized) + + const providerToken = "auth-provider-device-token" + if err := st.CreateProviderToken(&store.ProviderToken{ + TokenHash: store.HashKey(providerToken), AccountID: user.AccountID, Active: true, + }); err != nil { + t.Fatal(err) + } + checkKey(providerToken, http.StatusOK) + if err := st.RevokeProviderToken(providerToken); err != nil { + t.Fatal(err) + } + checkKey(providerToken, http.StatusUnauthorized) +} + +func authContractRequest(t *testing.T, handler http.Handler, method, path, token, body string, wantStatus int) *httptest.ResponseRecorder { + t.Helper() + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+token) + w := httptest.NewRecorder() + handler.ServeHTTP(w, r) + if w.Code != wantStatus { + t.Fatalf("%s %s status = %d, want %d: %s", method, path, w.Code, wantStatus, w.Body.String()) + } + return w +} diff --git a/coordinator/api/authorization.go b/coordinator/api/authorization.go new file mode 100644 index 0000000000..3bb6261489 --- /dev/null +++ b/coordinator/api/authorization.go @@ -0,0 +1,27 @@ +package api + +import ( + "crypto/subtle" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/auth" +) + +// requireAdminKey checks that the request is from an admin (either admin key or Privy admin). +// Returns true if authorized, false if it wrote an error response. +func (s *Server) requireAdminKey(w http.ResponseWriter, r *http.Request) bool { + // Check 1: Bearer token matches admin key + token := extractBearerToken(r) + if token != "" && s.adminKey != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.adminKey)) == 1 { + return true + } + + // Check 2: Privy admin + user := auth.UserFromContext(r.Context()) + if user != nil && s.isAdmin(user) { + return true + } + + writeJSON(w, http.StatusForbidden, errorResponse("forbidden", "admin access required")) + return false +} diff --git a/coordinator/api/auto_toolschema_regression_test.go b/coordinator/api/auto_toolschema_regression_test.go index 38af3cee87..09672bf5f4 100644 --- a/coordinator/api/auto_toolschema_regression_test.go +++ b/coordinator/api/auto_toolschema_regression_test.go @@ -1,8 +1,6 @@ package api import ( - "errors" - "fmt" "net/http" "net/http/httptest" "strings" @@ -11,157 +9,6 @@ import ( "github.com/eigeninference/d-inference/coordinator/registry" ) -// autoStandardSchemaCorpus is the set of JSON-Schema constructs #561 started -// rejecting for every model. They are all emitted by mainstream SDKs (pydantic -// and zod hoist definitions into `$defs`/`$ref`; unions become anyOf/oneOf), -// and they are all decidable by the post-generation validator that auto and -// none actually use — so the pre-flight must forward them untouched. The value -// is the property schema placed under a single declared tool; constrained is -// the status the grammar-compiled modes still reject it with. -var autoStandardSchemaCorpus = map[string]struct { - property string - constrained int -}{ - "anyOf string|object": {`{"anyOf":[{"type":"string"}, - {"type":"object","properties":{"source":{"type":"string"}}}]}`, - http.StatusUnprocessableEntity}, - "oneOf string|integer": {`{"oneOf":[{"type":"string"},{"type":"integer"}]}`, - http.StatusUnprocessableEntity}, - "patternProperties": {`{"type":"object","patternProperties":{"^[A-Z_]+$":{"type":"string"}}}`, - http.StatusUnprocessableEntity}, - "pattern": {`{"type":"string","pattern":"^[a-f0-9]{8}$"}`, - http.StatusUnprocessableEntity}, - "if/then": {`{"type":"object","if":{"required":["a"]},"then":{"required":["b"]}}`, - http.StatusUnprocessableEntity}, - "dependentRequired": {`{"type":"object","dependentRequired":{"credit_card":["billing_address"]}}`, - http.StatusUnprocessableEntity}, - "propertyNames": {`{"type":"object","propertyNames":{"pattern":"^[a-z]+$"}}`, - http.StatusUnprocessableEntity}, - "unevaluatedProperties": {`{"type":"object","unevaluatedProperties":false}`, - http.StatusUnprocessableEntity}, - "multi-type": {`{"type":["string","integer"]}`, - http.StatusUnprocessableEntity}, - // A typeless mixed enum reaches the constrained compiler's finite-value - // check rather than its keyword allowlist, so it fails as a malformed - // request (400) instead of an uncompilable one (422). - "typeless mixed enum": {`{"enum":["a",1]}`, http.StatusBadRequest}, -} - -// autoStandardSchemaBody wraps a property schema in a full chat-completions -// request for the given tool_choice. `$defs`/`$ref` needs a sibling on the -// parameters root, so it is spelled separately below. -func autoStandardSchemaBody(model, choice, property string) string { - return fmt.Sprintf(`{"model":%q,"messages":[{"role":"user","content":"x"}], - "tool_choice":%q, - "tools":[{"type":"function","function":{"name":"set_config_value","parameters": - {"type":"object","properties":{"value":%s},"required":["value"]}}}]}`, - model, choice, property) -} - -const autoRefDefsBody = `{"model":%q,"messages":[{"role":"user","content":"x"}], - "tool_choice":%q, - "tools":[{"type":"function","function":{"name":"f","parameters": - {"type":"object","$defs":{"P":{"type":"string"}}, - "properties":{"p":{"$ref":"#/$defs/P"}}}}}]}` - -// #561 regression. `auto` compiles no inference grammar — ToolConstraintFactory -// returns nil for it and the provider validates emitted calls against the full -// JSON Schema afterwards. The coordinator therefore has no grammar-feasibility -// question to answer at admission time, and must forward standard JSON Schema -// for EVERY model. Only the genuinely grammar-compiled modes fail closed. -func TestAutoToolChoiceForwardsStandardJSONSchema(t *testing.T) { - // Model-blind: the pre-flight never saw a model, so a Gemma-class name must - // not be what makes a schema legal. - models := []string{"gpt-oss-20b", "gemma-4-26b", "totally-made-up"} - - t.Run("accepted under auto", func(t *testing.T) { - for name, schema := range autoStandardSchemaCorpus { - for _, model := range models { - body := autoStandardSchemaBody(model, "auto", schema.property) - if _, err := validateToolConstraintRequest([]byte(body)); err != nil { - t.Errorf("%s rejected for model %q: %v", name, model, err) - } - } - } - for _, model := range models { - body := fmt.Sprintf(autoRefDefsBody, model, "auto") - if _, err := validateToolConstraintRequest([]byte(body)); err != nil { - t.Errorf("$defs/$ref rejected for model %q: %v", model, err) - } - } - }) - - // The constrained modes DO compile a grammar, so their allowlist stays - // fail-closed on exactly these constructs. That asymmetry is the point. - t.Run("still rejected under required", func(t *testing.T) { - reject := func(name string, body []byte, want int) { - t.Helper() - _, err := validateToolConstraintRequest(body) - var typed *toolConstraintRequestError - if !errors.As(err, &typed) || typed.status != want { - t.Errorf("%s in constrained mode: %T %v, want status %d", - name, err, err, want) - } - } - for name, schema := range autoStandardSchemaCorpus { - reject(name, - []byte(autoStandardSchemaBody("gpt-oss-20b", "required", schema.property)), - schema.constrained) - } - reject("$defs/$ref", - []byte(fmt.Sprintf(autoRefDefsBody, "gpt-oss-20b", "required")), - http.StatusUnprocessableEntity) - }) - - // The one rejection that survives in the non-grammar modes: the caller - // cannot plant the coordinator's own normalization marker. Validation runs - // on the pre-normalization body, so any occurrence is forged. - t.Run("forged reserved metadata still rejected", func(t *testing.T) { - // The multi-concrete `type` array beside an author combinator is the - // collapse-only normalization path — the guard must still descend the - // author's anyOf and catch a marker planted inside it. - for name, property := range map[string]string{ - "bare marker": `{"type":"string","x-darkbloom-original-boolean-schema":true}`, - "marker inside author anyOf on a type-array node": `{"type":["string","object"], - "anyOf":[{"type":"string","x-darkbloom-original-boolean-schema":true}]}`, - } { - for _, choice := range []string{"auto", "none"} { - body := autoStandardSchemaBody("gpt-oss-20b", choice, property) - _, err := validateToolConstraintRequest([]byte(body)) - var typed *toolConstraintRequestError - if !errors.As(err, &typed) || typed.status != http.StatusBadRequest { - t.Errorf("%s/%s accepted forged reserved metadata: %T %v", - choice, name, err, err) - } - } - } - }) - - // `none` is honored by hiding tools from the prompt and rejecting any call - // the model emits anyway — no sampler grammar, so no Gemma-only fence. - t.Run("none needs no grammar", func(t *testing.T) { - bodies := map[string]string{ - "with tools": `{"model":"gpt-oss-20b","messages":[{"role":"user","content":"x"}], - "tool_choice":"none", - "tools":[{"type":"function","function":{"name":"f","parameters":{"type":"object"}}}]}`, - "without tools": `{"model":"gpt-oss-20b", - "messages":[{"role":"user","content":"x"}],"tool_choice":"none"}`, - } - for name, body := range bodies { - mode, err := validateToolConstraintRequest([]byte(body)) - if err != nil { - t.Fatalf("%s: %v", name, err) - } - if mode != toolChoiceNone { - t.Fatalf("%s: mode = %q, want none", name, mode) - } - if mode.requiresInferenceConstraint() { - t.Errorf("%s: none demanded an inference-enforcing provider", name) - } - } - }) -} - // End-to-end through the real HTTP handler with a non-Gemma model that has no // constraint-capable provider (the production gpt-oss-20b situation). The union // and $ref shapes must clear admission and be answered by the ROUTING @@ -171,9 +18,13 @@ func TestAutoToolSchemaReachesRoutingOverHTTP(t *testing.T) { srv.registry.SetModelCatalog([]registry.CatalogEntry{{ID: "gpt-oss-20b"}}) bodies := map[string]string{ - "anyOf union": autoStandardSchemaBody("gpt-oss-20b", "auto", - autoStandardSchemaCorpus["anyOf string|object"].property), - "$defs/$ref": fmt.Sprintf(autoRefDefsBody, "gpt-oss-20b", "auto"), + "anyOf union": `{"model":"gpt-oss-20b","messages":[{"role":"user","content":"x"}], + "tool_choice":"auto","tools":[{"type":"function","function":{"name":"set_config_value","parameters": + {"type":"object","properties":{"value":{"anyOf":[{"type":"string"}, + {"type":"object","properties":{"source":{"type":"string"}}}]}},"required":["value"]}}}]}`, + "$defs/$ref": `{"model":"gpt-oss-20b","messages":[{"role":"user","content":"x"}], + "tool_choice":"auto","tools":[{"type":"function","function":{"name":"f","parameters": + {"type":"object","$defs":{"P":{"type":"string"}},"properties":{"p":{"$ref":"#/$defs/P"}}}}}]}`, } for name, body := range bodies { t.Run(name, func(t *testing.T) { @@ -190,88 +41,3 @@ func TestAutoToolSchemaReachesRoutingOverHTTP(t *testing.T) { }) } } - -// The capability verdict has to tell a client whether retrying can ever help. -// "This model is served but no build of it EVER enforces tool_choice" is -// permanent (400); a model the fleet does not serve at all, or an enforcing -// provider that is merely trust-lapsed right now, is a retryable condition -// (503). And `none`, which needs no enforcement, must clear both gates. -func TestToolConstraintCapabilityErrorSeparatesPermanentFromTransient(t *testing.T) { - const model = "gpt-oss-20b" - failFast := func( - t *testing.T, - hasTools, requiresConstraint bool, - configure func(*registry.Provider), - ) *httptest.ResponseRecorder { - t.Helper() - srv, _ := testServer(t) - srv.registry.SetModelCatalog([]registry.CatalogEntry{{ID: model}}) - if configure != nil { - configure(registerBuildsProvider(srv, "serving-provider", model)) - } - response := httptest.NewRecorder() - handled := srv.visionToolsFailFast( - response, model, model, false, hasTools, requiresConstraint, - "required", false, selfRoutePolicy{}, nil) - if requiresConstraint && !handled { - t.Fatal("incapable constrained request was allowed into the queue") - } - if !requiresConstraint && handled { - t.Fatalf("unconstrained request was blocked: %d %s", - response.Code, response.Body.String()) - } - return response - } - - // Above the tools floor but advertising no tool-constraint protocol: the - // fleet serves the model, nobody ever enforces on it — permanent. - served := failFast(t, true, true, func(p *registry.Provider) { - p.Mu().Lock() - p.Version = "0.6.5" - p.Mu().Unlock() - }) - if served.Code != http.StatusBadRequest || - !strings.Contains(served.Body.String(), - "inference-enforced tool_choice (required/named) is not supported") { - t.Fatalf("permanent incapability reported as capacity: %d %s", - served.Code, served.Body.String()) - } - - absent := failFast(t, false, true, nil) - if absent.Code != http.StatusServiceUnavailable || - !strings.Contains(absent.Body.String(), - "advertises inference-time tool_choice enforcement") { - t.Fatalf("absent model lost its retryable capacity error: %d %s", - absent.Code, absent.Body.String()) - } - - // A provider that ADVERTISES enforcement (protocol v1 + the concrete - // model) but sits below the registry's trust minimum is transiently - // unroutable — an outage, not an incapability. The verdict must stay - // retryable (503); reporting the permanent 400 would tell clients this - // model can never enforce tool_choice while the fleet is merely - // re-attesting. - lapsed := failFast(t, false, true, func(p *registry.Provider) { - p.Mu().Lock() - p.Version = "0.7.10" - p.ToolConstraintProtocol = registry.ToolConstraintProtocolV1 - p.ToolConstraintModels = map[string]struct{}{model: {}} - p.TrustLevel = registry.TrustSelfSigned - p.Mu().Unlock() - }) - if lapsed.Code != http.StatusServiceUnavailable || - !strings.Contains(lapsed.Body.String(), - "advertises inference-time tool_choice enforcement") { - t.Fatalf("transient trust lapse reported as permanent incapability: %d %s", - lapsed.Code, lapsed.Body.String()) - } - - // tool_choice "none" derives requiresToolConstraint=false, so a model with - // no enforcing provider at all still serves it. - mode, err := validateToolConstraintRequest([]byte( - `{"model":"gpt-oss-20b","messages":[{"role":"user","content":"x"}],"tool_choice":"none"}`)) - if err != nil { - t.Fatal(err) - } - failFast(t, false, mode.requiresInferenceConstraint(), nil) -} diff --git a/coordinator/api/base_rewards_handlers.go b/coordinator/api/base_rewards_handlers.go deleted file mode 100644 index 957aa106a9..0000000000 --- a/coordinator/api/base_rewards_handlers.go +++ /dev/null @@ -1,26 +0,0 @@ -package api - -import "net/http" - -// handleAdminBaseRewards returns the current base-rewards settlement status for -// the most recently closed epoch: the pool budget, how much has been drawn, the -// reduction factor k, and the per-machine draw rows. Admin-only, read-only. -// -// When the feature flag is off (no engine wired) it returns {"enabled": false} -// so the console can render a disabled state without special-casing a 404. -func (s *Server) handleAdminBaseRewards(w http.ResponseWriter, r *http.Request) { - if !s.isAdminAuthorized(w, r) { - return - } - if s.baseRewards == nil { - writeJSON(w, http.StatusOK, map[string]any{"enabled": false}) - return - } - status, err := s.baseRewards.Status(r.Context()) - if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse( - "internal_error", "failed to compute base rewards status")) - return - } - writeJSON(w, http.StatusOK, status) -} diff --git a/coordinator/api/billing/account_policy.go b/coordinator/api/billing/account_policy.go new file mode 100644 index 0000000000..31c557a023 --- /dev/null +++ b/coordinator/api/billing/account_policy.go @@ -0,0 +1,97 @@ +package billing + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// AdminSetUserRole handles PUT /v1/admin/users/role. +// Grants or clears an account role (e.g. RoleService for OpenRouter). Admin only. +func (s *Controller) AdminSetUserRole(w http.ResponseWriter, r *http.Request) { + if !s.authorizeAdmin(w, r) { + return + } + + var req struct { + AccountID string `json:"account_id"` + Role string `json:"role"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.AccountID == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "account_id is required", httpresponse.WithParam("account_id"))) + return + } + // Only known roles are accepted. "" clears the role back to a normal account. + if req.Role != "" && req.Role != store.RoleService { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + fmt.Sprintf("invalid role %q — allowed: %q or \"\"", req.Role, store.RoleService), httpresponse.WithParam("role"))) + return + } + + if err := s.store.SetUserRole(req.AccountID, req.Role); err != nil { + s.logger.Error("admin set role: failed", "account_id", req.AccountID, "error", err) + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "user not found or update failed")) + return + } + + s.logger.Info("admin: user role updated", "account_id", req.AccountID, "role", req.Role) + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "role_updated", + "account_id": req.AccountID, + "role": req.Role, + }) +} + +// AdminSetUserPlatformFee handles PUT /v1/admin/users/platform-fee. +// Sets a per-account platform fee override (0–100). Omit platform_fee_percent +// (or send null) to clear the override and fall back to the global default. +// Admin only. +func (s *Controller) AdminSetUserPlatformFee(w http.ResponseWriter, r *http.Request) { + if !s.authorizeAdmin(w, r) { + return + } + + var req struct { + AccountID string `json:"account_id"` + PlatformFeePercent *int64 `json:"platform_fee_percent"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.AccountID == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "account_id is required", httpresponse.WithParam("account_id"))) + return + } + if req.PlatformFeePercent != nil && (*req.PlatformFeePercent < 0 || *req.PlatformFeePercent > 100) { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "platform_fee_percent must be between 0 and 100", httpresponse.WithParam("platform_fee_percent"))) + return + } + + if err := s.store.SetUserPlatformFeePercent(req.AccountID, req.PlatformFeePercent); err != nil { + s.logger.Error("admin set platform fee: failed", "account_id", req.AccountID, "error", err) + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "user not found or update failed")) + return + } + + resp := map[string]any{ + "status": "platform_fee_updated", + "account_id": req.AccountID, + } + if req.PlatformFeePercent != nil { + resp["platform_fee_percent"] = *req.PlatformFeePercent + } else { + resp["platform_fee_percent"] = nil + resp["note"] = "override cleared — using global default" + } + s.logger.Info("admin: user platform fee updated", "account_id", req.AccountID, "fee", req.PlatformFeePercent) + httpresponse.WriteJSON(w, http.StatusOK, resp) +} diff --git a/coordinator/api/billing/admin_adjustment.go b/coordinator/api/billing/admin_adjustment.go new file mode 100644 index 0000000000..4672c3b74f --- /dev/null +++ b/coordinator/api/billing/admin_adjustment.go @@ -0,0 +1,81 @@ +package billing + +import ( + "encoding/json" + "net/http" + "strconv" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// AdminCredit grants non-withdrawable inference credit. +func (s *Controller) AdminCredit(w http.ResponseWriter, r *http.Request) { + s.handleAdminBalanceAdjustment(w, r, false) +} + +// AdminReward grants withdrawable earnings. +func (s *Controller) AdminReward(w http.ResponseWriter, r *http.Request) { + s.handleAdminBalanceAdjustment(w, r, true) +} + +// Both admin adjustments share authorization, validation and account lookup. +// Their ledger operation and response fields remain explicitly separate. +func (s *Controller) handleAdminBalanceAdjustment(w http.ResponseWriter, r *http.Request, withdrawable bool) { + if !s.authorizeAdmin(w, r) { + return + } + + var req struct { + Email string `json:"email"` + AmountUSD string `json:"amount_usd"` + Note string `json:"note"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.Email == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "email is required")) + return + } + amountFloat, err := strconv.ParseFloat(req.AmountUSD, 64) + if err != nil || amountFloat <= 0 { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "amount_usd must be a positive number")) + return + } + amountMicroUSD := int64(amountFloat * 1_000_000) + + user, err := s.store.GetUserByEmail(req.Email) + if err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "no user found with email: "+req.Email)) + return + } + + action, entryType, credit := "credit", store.LedgerAdminCredit, s.store.Credit + if withdrawable { + action, entryType, credit = "reward", store.LedgerAdminReward, s.store.CreditWithdrawable + } + ref := string(entryType) + if req.Note != "" { + ref += ":" + req.Note + } + if err := credit(user.AccountID, amountMicroUSD, entryType, ref); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to "+action+": "+err.Error())) + return + } + s.logger.Info("admin "+action+" applied", "email", req.Email, "account_id", user.AccountID, + "amount_micro_usd", amountMicroUSD, "note", req.Note) + response := map[string]any{ + "ok": true, "account_id": user.AccountID, "email": user.Email, + "withdrawable": withdrawable, + "balance_after": float64(s.store.GetBalance(user.AccountID)) / 1_000_000, + } + if withdrawable { + response["rewarded_usd"] = amountFloat + response["withdrawable_after"] = float64(s.store.GetWithdrawableBalance(user.AccountID)) / 1_000_000 + } else { + response["credited_usd"] = amountFloat + } + httpresponse.WriteJSON(w, http.StatusOK, response) +} diff --git a/coordinator/api/billing/amounts.go b/coordinator/api/billing/amounts.go new file mode 100644 index 0000000000..a002ecbe01 --- /dev/null +++ b/coordinator/api/billing/amounts.go @@ -0,0 +1,40 @@ +package billing + +import ( + "errors" + "fmt" + "regexp" + "strconv" + "strings" + + "github.com/eigeninference/d-inference/coordinator/billing/globalpayouts" +) + +// microUSDToCents truncates to integer cents (1¢ = 10,000 micro-USD). +func microUSDToCents(microUSD int64) int64 { return microUSD / 10_000 } + +func formatUSD(microUSD int64) string { + return fmt.Sprintf("%.2f", float64(microUSD)/1_000_000) +} + +var payoutUSDPattern = regexp.MustCompile(`^[0-9]{1,7}(\.[0-9]{1,2})?$`) + +func payoutUSDCents(amount string) (int64, error) { + amount = strings.TrimSpace(amount) + if !payoutUSDPattern.MatchString(amount) { + return 0, errors.New("use a USD amount with at most two decimal places") + } + parts := strings.SplitN(amount, ".", 2) + dollars, _ := strconv.ParseInt(parts[0], 10, 64) + cents := int64(0) + if len(parts) == 2 { + cents, _ = strconv.ParseInt((parts[1] + "0")[:2], 10, 64) + } + total := dollars*100 + cents + if total < 100 || total > 100_000_000 { + return 0, errors.New("withdrawal must be between $1 and $1,000,000") + } + return total, nil +} + +func payoutCurrencyExponent(currency string) int { return globalpayouts.CurrencyExponent(currency) } diff --git a/coordinator/api/billing/base_rewards.go b/coordinator/api/billing/base_rewards.go new file mode 100644 index 0000000000..9d5f185c22 --- /dev/null +++ b/coordinator/api/billing/base_rewards.go @@ -0,0 +1,30 @@ +package billing + +import ( + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" +) + +// AdminBaseRewards returns the current base-rewards settlement status for +// the most recently closed epoch: the pool budget, how much has been drawn, the +// reduction factor k, and the per-machine draw rows. Admin-only, read-only. +// +// When the feature flag is off (no engine wired) it returns {"enabled": false} +// so the console can render a disabled state without special-casing a 404. +func (s *Controller) AdminBaseRewards(w http.ResponseWriter, r *http.Request) { + if !s.authorizeAdmin(w, r) { + return + } + if s.baseRewards() == nil { + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"enabled": false}) + return + } + status, err := s.baseRewards().Status(r.Context()) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody( + "internal_error", "failed to compute base rewards status")) + return + } + httpresponse.WriteJSON(w, http.StatusOK, status) +} diff --git a/coordinator/api/billing/checkout.go b/coordinator/api/billing/checkout.go new file mode 100644 index 0000000000..b1f8fd30b1 --- /dev/null +++ b/coordinator/api/billing/checkout.go @@ -0,0 +1,119 @@ +package billing + +import ( + "encoding/json" + "net/http" + "strconv" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/store" + "github.com/google/uuid" +) + +// StripeCreateSession handles POST /v1/billing/stripe/create-session. +func (s *Controller) StripeCreateSession(w http.ResponseWriter, r *http.Request) { + if s.billing() == nil || s.billing().Stripe() == nil { + httpresponse.WriteJSON(w, http.StatusServiceUnavailable, httpresponse.ErrorBody("billing_error", "Stripe payments not configured")) + return + } + + var req struct { + AmountUSD string `json:"amount_usd"` + Email string `json:"email,omitempty"` + ReferralCode string `json:"referral_code,omitempty"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + + amountFloat, err := strconv.ParseFloat(req.AmountUSD, 64) + if err != nil || amountFloat < 0.50 { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "amount_usd must be at least $0.50")) + return + } + + amountCents := int64(amountFloat * 100) + accountID := requestauth.ResolveAccountID(r) + + if req.ReferralCode != "" { + if _, err := s.billing().Store().GetReferrerByCode(req.ReferralCode); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid referral code")) + return + } + } + + sessionID := uuid.New().String() + amountMicroUSD := int64(amountFloat * 1_000_000) + + billingSession := &store.BillingSession{ + ID: sessionID, + AccountID: accountID, + PaymentMethod: "stripe", + AmountMicroUSD: amountMicroUSD, + Status: "pending", + ReferralCode: req.ReferralCode, + CreatedAt: time.Now(), + } + + stripeResp, err := s.billing().Stripe().CreateCheckoutSession(billingservice.CheckoutSessionRequest{ + AmountCents: amountCents, + Currency: "usd", + CustomerEmail: req.Email, + Metadata: map[string]string{ + "app": "darkbloom", + "platform": "eigeninference", + "purchase_type": "inference_credits", + "source": "coordinator", + "coordinator_host": r.Host, + "billing_session_id": sessionID, + "consumer_key": accountID, + "referral_code": req.ReferralCode, + }, + }) + if err != nil { + s.logger.Error("stripe: create checkout session failed", "error", err) + httpresponse.WriteJSON(w, http.StatusBadGateway, httpresponse.ErrorBody("stripe_error", "failed to create checkout session")) + return + } + + billingSession.ExternalID = stripeResp.SessionID + if err := s.billing().Store().CreateBillingSession(billingSession); err != nil { + s.logger.Error("stripe: save billing session failed", "error", err) + } + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "session_id": sessionID, + "stripe_session": stripeResp.SessionID, + "url": stripeResp.URL, + "amount_usd": req.AmountUSD, + "amount_micro_usd": amountMicroUSD, + }) +} + +// StripeSessionStatus handles GET /v1/billing/stripe/session?id=... +func (s *Controller) StripeSessionStatus(w http.ResponseWriter, r *http.Request) { + sessionID := r.URL.Query().Get("id") + if sessionID == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "id query parameter required")) + return + } + + bs, err := s.billing().Store().GetBillingSession(sessionID) + if err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "billing session not found")) + return + } + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "session_id": bs.ID, + "payment_method": bs.PaymentMethod, + "amount_micro_usd": bs.AmountMicroUSD, + "status": bs.Status, + "created_at": bs.CreatedAt, + "completed_at": bs.CompletedAt, + }) +} diff --git a/coordinator/api/billing/checkout_webhook.go b/coordinator/api/billing/checkout_webhook.go new file mode 100644 index 0000000000..6293756d64 --- /dev/null +++ b/coordinator/api/billing/checkout_webhook.go @@ -0,0 +1,94 @@ +package billing + +import ( + "io" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// StripeWebhook handles POST /v1/billing/stripe/webhook. +func (s *Controller) StripeWebhook(w http.ResponseWriter, r *http.Request) { + if s.billing() == nil || s.billing().Stripe() == nil { + http.Error(w, "Stripe not configured", http.StatusServiceUnavailable) + return + } + + payload, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + if err != nil { + http.Error(w, "failed to read body", http.StatusBadRequest) + return + } + + sigHeader := r.Header.Get("Stripe-Signature") + event, err := s.billing().Stripe().VerifyWebhookSignature(payload, sigHeader) + if err != nil { + s.logger.Error("stripe: webhook signature verification failed", "error", err) + http.Error(w, "invalid signature", http.StatusBadRequest) + return + } + + if event.Type != "checkout.session.completed" { + w.WriteHeader(http.StatusOK) + return + } + + session, err := s.billing().Stripe().ParseCheckoutSession(event) + if err != nil { + s.logger.Error("stripe: parse checkout session failed", "error", err) + http.Error(w, "invalid event data", http.StatusBadRequest) + return + } + + billingSessionID := session.Object.Metadata["billing_session_id"] + consumerKey := session.Object.Metadata["consumer_key"] + referralCode := session.Object.Metadata["referral_code"] + + if consumerKey == "" { + s.logger.Error("stripe: webhook missing consumer_key in metadata") + http.Error(w, "missing metadata", http.StatusBadRequest) + return + } + + if billingSessionID != "" { + bs, err := s.billing().Store().GetBillingSession(billingSessionID) + if err == nil && bs.Status == "completed" { + w.WriteHeader(http.StatusOK) + return + } + } + + amountMicroUSD := session.Object.AmountTotal * 10_000 + + if err := s.billing().CreditDeposit(consumerKey, amountMicroUSD, store.LedgerStripeDeposit, + "stripe:"+session.Object.ID); err != nil { + s.logger.Error("stripe: credit balance failed", "error", err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + + if billingSessionID != "" { + // Best-effort: the deposit is already credited above, but a failure here + // leaves the session marked incomplete. The ledger credit is idempotent, + // so redelivery can retry this bookkeeping without adding funds again. + if err := s.billing().Store().CompleteBillingSession(billingSessionID); err != nil { + s.logger.Error("stripe: failed to mark billing session complete", + "billing_session_id", billingSessionID, "error", err) + s.recordMetric("billing.session_complete_failed", nil) + } + } + if referralCode != "" { + // Best-effort: a failure here means the referrer is not credited for this + // deposit; never silently swallow it. + if err := s.billing().Referral().Apply(consumerKey, referralCode); err != nil { + s.logger.Error("stripe: failed to apply referral credit", "error", err) + s.recordMetric("billing.referral_apply_failed", nil) + } + } + + s.logger.Info("stripe: deposit credited", + "consumer_key", consumerKey[:min(8, len(consumerKey))]+"...", + "amount_micro_usd", amountMicroUSD, + ) + w.WriteHeader(http.StatusOK) +} diff --git a/coordinator/api/billing/connect_dashboard.go b/coordinator/api/billing/connect_dashboard.go new file mode 100644 index 0000000000..827a5795fe --- /dev/null +++ b/coordinator/api/billing/connect_dashboard.go @@ -0,0 +1,129 @@ +package billing + +import ( + "errors" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// StripeDashboardLink handles POST /v1/billing/stripe/dashboard. +// +// Mints a single-use Stripe Express Dashboard login link for the caller's +// connected account. That dashboard is where the user changes the bank account +// or debit card their payouts land in, reviews their connected balance, and +// sees Stripe's own payout history — none of which we rebuild ourselves. +// +// It is the only way an already-onboarded Express account can edit its payout +// destination: StripeOnboard's `account_onboarding` link collects +// outstanding requirements only (a ready account has none), and Stripe rejects +// `account_update` links for accounts that have a Stripe-hosted dashboard, +// which every Express account does. +// +// Wired behind requirePrivyAuth for the same reason as unlink, only more so: +// the URL this returns is a bearer credential for a session that can redirect +// the user's earnings to a different bank account. A leaked inference API key +// must not be able to mint one. +func (s *Controller) StripeDashboardLink(w http.ResponseWriter, r *http.Request) { + user := requestauth.RequirePrivyUser(w, r) + if user == nil { + return + } + if s.billing() == nil || s.billing().StripeConnect() == nil { + httpresponse.WriteJSON(w, http.StatusServiceUnavailable, httpresponse.ErrorBody("billing_error", "Stripe Payouts not configured")) + return + } + if user.StripeAccountID == "" || !stripeDashboardAvailable(user.StripeAccountStatus) { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("not_onboarded", + "finish your payout setup first, then you can manage the account in Stripe")) + return + } + + link, err := s.billing().StripeConnect().CreateLoginLink(user.StripeAccountID) + if err != nil { + if billingservice.IsAccountGoneErr(err) { + // Closed on Stripe's side — unlink so the UI falls back to + // onboarding instead of offering a permanently broken button + // (same self-heal as the refresh=1 path in StripeStatus). + s.logger.Warn("stripe connect: stored account gone — unlinking", + "stripe_account_id", user.StripeAccountID, "error", err) + if perr := s.billing().Store().SetUserStripeAccount(user.AccountID, "", "", "", "", "", false); perr != nil { + // Don't claim an unlink we failed to persist — the UI would + // tell the user to set payouts up again while still showing + // the old account. + s.logger.Error("stripe connect: unlink gone account failed", "error", perr) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", + "failed to unlink your closed Stripe account")) + return + } + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("stripe_account_gone", + "your Stripe account no longer exists — set up payouts again")) + return + } + s.logger.Error("stripe connect: create login link failed", + "stripe_account_id", user.StripeAccountID, "error", err) + httpresponse.WriteJSON(w, http.StatusBadGateway, httpresponse.ErrorBody("stripe_error", err.Error())) + return + } + + // Log the issuance, never the link — it is a live credential. + s.logger.Info("stripe connect: express dashboard link issued", + "account", user.AccountID[:min(8, len(user.AccountID))]+"...", + "stripe_account_id", user.StripeAccountID) + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "url": link, + "stripe_account_id": user.StripeAccountID, + }) +} + +// StripeUnlink handles DELETE /v1/billing/stripe/account. +// +// Detaches the stored connected account from the user so the next onboard +// creates a fresh one. This is the self-serve escape hatch for wedged +// accounts (closed on Stripe's side, stuck onboarding, wrong country +// selected, wrong service agreement). It does not touch Stripe — the +// connected account (and any balance still being swept to the user's bank) +// is unaffected, and in-flight withdrawals still reconcile via webhooks +// because the rows carry their own copy of the stripe_account_id. +// +// Idempotent: unlinking with no account on file succeeds. +func (s *Controller) StripeUnlink(w http.ResponseWriter, r *http.Request) { + user := requestauth.RequirePrivyUser(w, r) + if user == nil { + return + } + if repo, ok := s.globalPayoutStore(); ok { + if _, err := repo.GetGlobalRecipient(user.AccountID); err == nil { + if err = repo.RemoveGlobalRecipient(user.AccountID); err != nil { + globalPayoutError(w, err) + return + } + httpresponse.WriteJSON(w, 200, map[string]bool{"unlinked": true}) + return + } else if !errors.Is(err, store.ErrNotFound) { + globalPayoutError(w, err) + return + } + } + if s.billing() == nil { + httpresponse.WriteJSON(w, http.StatusServiceUnavailable, httpresponse.ErrorBody("billing_error", "billing not configured")) + return + } + if user.StripeAccountID == "" { + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"unlinked": false}) + return + } + prev := user.StripeAccountID + if err := s.billing().Store().SetUserStripeAccount(user.AccountID, "", "", "", "", "", false); err != nil { + s.logger.Error("stripe connect: unlink failed", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to unlink Stripe account")) + return + } + s.logger.Info("stripe connect: account unlinked", + "account", user.AccountID[:min(8, len(user.AccountID))]+"...", + "stripe_account_id", prev) + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"unlinked": true}) +} diff --git a/coordinator/api/billing/connect_dashboard_test.go b/coordinator/api/billing/connect_dashboard_test.go new file mode 100644 index 0000000000..6b0282bcf4 --- /dev/null +++ b/coordinator/api/billing/connect_dashboard_test.go @@ -0,0 +1,227 @@ +package billing + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "sync" + "testing" +) + +func TestStripeDashboardLinkRequiresAuth(t *testing.T) { + srv, _ := stripePayoutsTestServer(t, true, nil) + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/dashboard", nil) + w := httptest.NewRecorder() + srv.StripeDashboardLink(w, req) + if w.Code != http.StatusUnauthorized { + t.Errorf("got %d, want 401", w.Code) + } +} + +func TestStripeDashboardLinkRequiresLinkedAccount(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-dash-none", "nobank@example.com") + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/dashboard", nil) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeDashboardLink(w, req) + + if w.Code != http.StatusConflict { + t.Fatalf("got %d, want 409: %s", w.Code, w.Body.String()) + } + if got := errorTypeOf(t, w.Body.Bytes()); got != "not_onboarded" { + t.Errorf("error type = %q", got) + } +} + +// Stripe has no Express Dashboard to log into until the account submits its +// details, so a half-onboarded account must be told to finish setup rather +// than handed a raw Stripe error suggesting a retry that can never work. +// Restricted and rejected accounts DO have a dashboard and must get through. +func TestStripeDashboardLinkStatusGate(t *testing.T) { + cases := []struct { + status string + wantCode int + }{ + {"", http.StatusConflict}, + {stripeStatusPending, http.StatusConflict}, + {stripeStatusReady, http.StatusOK}, + {stripeStatusRestricted, http.StatusOK}, + {stripeStatusRejected, http.StatusOK}, + } + for _, tc := range cases { + name := tc.status + if name == "" { + name = "empty" + } + t.Run(name, func(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-dash-"+name, name+"@example.com") + if err := st.SetUserStripeAccount(user.AccountID, "acct_dash_"+name, tc.status, "US", "bank", "6789", false); err != nil { + t.Fatal(err) + } + user, _ = st.GetUserByAccountID(user.AccountID) + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/dashboard", nil) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeDashboardLink(w, req) + + if w.Code != tc.wantCode { + t.Fatalf("status %q: got %d, want %d: %s", tc.status, w.Code, tc.wantCode, w.Body.String()) + } + if tc.wantCode == http.StatusConflict { + if got := errorTypeOf(t, w.Body.Bytes()); got != "not_onboarded" { + t.Errorf("error type = %q, want not_onboarded", got) + } + } + }) + } +} + +func TestStripeDashboardLinkReturnsLoginURL(t *testing.T) { + var mu sync.Mutex + var gotPath string + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + gotPath = r.URL.Path + mu.Unlock() + _, _ = w.Write([]byte(`{"object":"login_link","url":"https://connect.stripe.com/express/acct_x/tok"}`)) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-dash-ok", "dash@example.com", false) + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/dashboard", nil) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeDashboardLink(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp["url"] != "https://connect.stripe.com/express/acct_x/tok" { + t.Errorf("url = %v", resp["url"]) + } + if resp["stripe_account_id"] != user.StripeAccountID { + t.Errorf("stripe_account_id = %v, want %q", resp["stripe_account_id"], user.StripeAccountID) + } + mu.Lock() + defer mu.Unlock() + if want := "/v1/accounts/" + user.StripeAccountID + "/login_links"; gotPath != want { + t.Errorf("Stripe path = %q, want %q", gotPath, want) + } +} + +// An account the user closed on Stripe's side must be unlinked here too, +// otherwise the UI keeps offering a button that can only ever fail. +func TestStripeDashboardLinkUnlinksGoneAccount(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":{"code":"account_invalid","message":"No such account"}}`)) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-dash-gone", "gone@example.com", false) + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/dashboard", nil) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeDashboardLink(w, req) + + if w.Code != http.StatusConflict { + t.Fatalf("got %d, want 409: %s", w.Code, w.Body.String()) + } + if got := errorTypeOf(t, w.Body.Bytes()); got != "stripe_account_gone" { + t.Errorf("error type = %q", got) + } + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountID != "" { + t.Errorf("StripeAccountID = %q, want cleared", refreshed.StripeAccountID) + } +} + +// A transient Stripe failure must not unlink the account — the user's payout +// destination is still perfectly valid. +func TestStripeDashboardLinkKeepsAccountOnTransientError(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"error":{"type":"api_error","message":"Stripe is down"}}`)) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-dash-5xx", "flaky@example.com", false) + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/dashboard", nil) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeDashboardLink(w, req) + + if w.Code != http.StatusBadGateway { + t.Fatalf("got %d, want 502: %s", w.Code, w.Body.String()) + } + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountID != user.StripeAccountID { + t.Errorf("StripeAccountID = %q, want %q (untouched)", refreshed.StripeAccountID, user.StripeAccountID) + } + if refreshed.StripeAccountStatus != "ready" { + t.Errorf("status = %q, want ready (untouched)", refreshed.StripeAccountStatus) + } +} + +func TestStripeUnlinkClearsAccount(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := readyUser(t, st, "acct-unlink-1", "unlink@example.com", false) + + req := httptest.NewRequest(http.MethodDelete, "/v1/billing/stripe/account", nil) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeUnlink(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp["unlinked"] != true { + t.Errorf("unlinked = %v, want true", resp["unlinked"]) + } + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountID != "" { + t.Errorf("StripeAccountID = %q, want empty", refreshed.StripeAccountID) + } + if refreshed.StripeAccountStatus != "" { + t.Errorf("status = %q, want empty", refreshed.StripeAccountStatus) + } + + // Second unlink is a no-op. + refreshed, _ = st.GetUserByAccountID(user.AccountID) + req2 := httptest.NewRequest(http.MethodDelete, "/v1/billing/stripe/account", nil) + req2 = withPrivyUser(req2, refreshed) + w2 := httptest.NewRecorder() + srv.StripeUnlink(w2, req2) + if w2.Code != http.StatusOK { + t.Fatalf("second unlink got %d", w2.Code) + } + var resp2 map[string]any + _ = json.Unmarshal(w2.Body.Bytes(), &resp2) + if resp2["unlinked"] != false { + t.Errorf("second unlink = %v, want false", resp2["unlinked"]) + } +} + +func TestStripeUnlinkRequiresAuth(t *testing.T) { + srv, _ := stripePayoutsTestServer(t, true, nil) + req := httptest.NewRequest(http.MethodDelete, "/v1/billing/stripe/account", nil) + w := httptest.NewRecorder() + srv.StripeUnlink(w, req) + if w.Code != http.StatusUnauthorized { + t.Errorf("got %d, want 401", w.Code) + } +} diff --git a/coordinator/api/billing/connect_helpers_test.go b/coordinator/api/billing/connect_helpers_test.go new file mode 100644 index 0000000000..91b7b4e355 --- /dev/null +++ b/coordinator/api/billing/connect_helpers_test.go @@ -0,0 +1,154 @@ +package billing + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "os" + "strconv" + "strings" + "sync" + "testing" + "time" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/payments" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// stripePayoutsTestServer wires up a controller fixture with an in-memory store and a +// billing service whose Stripe Connect client points at the supplied fake +// Stripe HTTP server. Pass mockMode=true to bypass Stripe entirely. +func stripePayoutsTestServer(t *testing.T, mockMode bool, fakeStripe *httptest.Server, opts ...billingservice.Config) (*controllerFixture, *store.MemoryStore) { + t.Helper() + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{AdminKey: "test-key"}) + + srv := newControllerFixture(st, logger) + + cfg := billingservice.Config{ + MockMode: mockMode, + StripeConnectReturnURL: "https://app.test/billing?return=1", + StripeConnectRefreshURL: "https://app.test/billing?refresh=1", + StripeConnectPlatformCountry: "US", + } + if !mockMode { + cfg.StripeSecretKey = "sk_test_fake" + cfg.StripeConnectWebhookSecret = "whsec_test" + } + if len(opts) > 0 { + // Allow tests to override individual fields by merging. + o := opts[0] + if o.StripeSecretKey != "" { + cfg.StripeSecretKey = o.StripeSecretKey + } + if o.StripeConnectWebhookSecret != "" { + cfg.StripeConnectWebhookSecret = o.StripeConnectWebhookSecret + } + } + + if fakeStripe != nil { + // Repoint the Stripe API base URL for the duration of the test. + t.Cleanup(setStripeAPIBase(fakeStripe.URL)) + } + + ledger := payments.NewLedger(st) + srv.SetBilling(billingservice.NewService(st, ledger, logger, cfg)) + return srv, st +} + +// setStripeAPIBase swaps billing.stripeAPIBase to point at our fake server, +// returning a cleanup func to restore it. +func setStripeAPIBase(url string) func() { + prev := billingservice.SetStripeAPIBaseForTest(url) + return func() { billingservice.SetStripeAPIBaseForTest(prev) } +} + +// healthyAccountJSON is what a fake Stripe returns for GET /v1/accounts/{id}: +// a fully onboarded account under the given service agreement, on the +// automatic daily payout schedule. instantEligible adds a debit-card +// destination. +func healthyAccountJSON(id, country, agreement string, instantEligible bool) string { + ext := `{"object":"bank_account","last4":"6789","default_for_currency":true}` + if instantEligible { + ext = `{"object":"card","brand":"visa","funding":"debit","last4":"4242","default_for_currency":true}` + } + return `{"id":"` + id + `","country":"` + country + `","default_currency":"usd", + "charges_enabled":true,"payouts_enabled":true,"details_submitted":true, + "tos_acceptance":{"service_agreement":"` + agreement + `"}, + "settings":{"payouts":{"schedule":{"interval":"daily"}}}, + "external_accounts":{"data":[` + ext + `]}}` +} + +// seedUser inserts a Privy-linked user into the store and returns it. +func seedUser(t *testing.T, st *store.MemoryStore, accountID, email string) *store.User { + t.Helper() + u := &store.User{ + AccountID: accountID, + PrivyUserID: "did:privy:" + accountID, + Email: email, + } + if err := st.CreateUser(u); err != nil { + t.Fatalf("create user: %v", err) + } + got, _ := st.GetUserByAccountID(accountID) + return got +} + +// readyUser seeds a user that has finished Stripe onboarding. instantEligible +// controls whether the destination is a debit card (true) or bank (false). +func readyUser(t *testing.T, st *store.MemoryStore, accountID, email string, instantEligible bool) *store.User { + t.Helper() + u := seedUser(t, st, accountID, email) + dest := "bank" + last4 := "6789" + if instantEligible { + dest = "card" + last4 = "4242" + } + if err := st.SetUserStripeAccount(u.AccountID, "acct_"+accountID, "ready", "", dest, last4, instantEligible); err != nil { + t.Fatal(err) + } + got, _ := st.GetUserByAccountID(u.AccountID) + return got +} + +// signedConnectRequest builds an HTTP request with a valid Stripe-Signature +// header for the given payload + secret. +func signedConnectRequest(t *testing.T, payload []byte, secret string) *http.Request { + t.Helper() + ts := strconv.FormatInt(time.Now().Unix(), 10) + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(ts + "." + string(payload))) + sig := hex.EncodeToString(mac.Sum(nil)) + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/connect/webhook", + strings.NewReader(string(payload))) + req.Header.Set("Stripe-Signature", "t="+ts+",v1="+sig) + req.Header.Set("Content-Type", "application/json") + return req +} + +// silence unused-import linter when tests are pruned during iteration. +var ( + _ = io.Discard + _ = url.QueryEscape + _ = sync.Mutex{} +) + +// errorTypeOf pulls error.type out of a coordinator error envelope. +func errorTypeOf(t *testing.T, body []byte) string { + t.Helper() + var resp map[string]any + if err := json.Unmarshal(body, &resp); err != nil { + t.Fatalf("unmarshal error body %q: %v", body, err) + } + errObj, _ := resp["error"].(map[string]any) + s, _ := errObj["type"].(string) + return s +} diff --git a/coordinator/api/billing/connect_onboarding.go b/coordinator/api/billing/connect_onboarding.go new file mode 100644 index 0000000000..ade069fb66 --- /dev/null +++ b/coordinator/api/billing/connect_onboarding.go @@ -0,0 +1,191 @@ +package billing + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" + billingservice "github.com/eigeninference/d-inference/coordinator/billing" +) + +// StripeOnboard handles POST /v1/billing/stripe/onboard. +// Creates a Stripe Express connected account on first call (or reuses the one +// on file) and returns a hosted onboarding URL. +func (s *Controller) StripeOnboard(w http.ResponseWriter, r *http.Request) { + user := requestauth.RequirePrivyUser(w, r) + if user == nil { + return + } + if s.billing() == nil || s.billing().StripeConnect() == nil { + httpresponse.WriteJSON(w, http.StatusServiceUnavailable, httpresponse.ErrorBody("billing_error", "Stripe Payouts not configured")) + return + } + + // Allow the frontend to override the return URL (handy for staged envs) + // but fall back to the coordinator-configured default. + var req struct { + ReturnURL string `json:"return_url,omitempty"` + RefreshURL string `json:"refresh_url,omitempty"` + Country string `json:"country,omitempty"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + + returnURL := strings.TrimSpace(req.ReturnURL) + if returnURL == "" { + returnURL = s.billing().StripeConnectReturnURL() + } + refreshURL := strings.TrimSpace(req.RefreshURL) + if refreshURL == "" { + refreshURL = s.billing().StripeConnectRefreshURL() + } + if refreshURL == "" { + // Sensible fallback so the link doesn't 500 if only return_url is set. + refreshURL = returnURL + } + if returnURL == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "return_url is required (configure EIGENINFERENCE_STRIPE_CONNECT_RETURN_URL or pass it in the request)")) + return + } + + // Validate the return/refresh URLs against the configured default's + // origin to prevent open-redirect: a phisher could otherwise hand the + // user a /stripe/onboard link with their own domain as return_url and + // hijack the post-KYC flow. The allowlist is the host of the configured + // default; localhost is also allowed for dev. + if err := validateRedirectURL(returnURL, s.billing().StripeConnectReturnURL()); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "return_url is not allowed: "+err.Error())) + return + } + if err := validateRedirectURL(refreshURL, s.billing().StripeConnectReturnURL()); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "refresh_url is not allowed: "+err.Error())) + return + } + + // Normalize the requested country up front. Stripe Express country is + // immutable once the account is created, so we treat the user's selection + // as the source of truth. + requestedCountry := strings.ToUpper(strings.TrimSpace(req.Country)) + if s.maybeGlobalOnboard(w, r, user, requestedCountry, returnURL, refreshURL) { + return + } + if requestedCountry == "" && user.StripeAccountID == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "country is required before creating a Stripe payout account")) + return + } + + // Decide whether the existing account (if any) is reusable. Stripe locks + // both the country and the service agreement when the Express account is + // created (https://docs.stripe.com/connect/accounts, + // https://docs.stripe.com/connect/service-agreement-types), so we must + // create a NEW account when: + // - the user picked a different country than their existing account, + // - the account no longer exists on Stripe (user closed it), or + // - the account is under the wrong service agreement for its country + // (e.g. AU/NZ/JP accounts created under `full` before we set + // `recipient` — those can never receive platform transfers). + stripeAcctID := user.StripeAccountID + needNewAccount := stripeAcctID == "" + existingCountry := user.StripeAccountCountry + + if stripeAcctID != "" { + countryChanged := requestedCountry != "" && + (user.StripeAccountCountry == "" || requestedCountry != user.StripeAccountCountry) + + acct, err := s.billing().StripeConnect().GetAccount(stripeAcctID) + switch { + case err != nil && billingservice.IsAccountGoneErr(err): + s.logger.Warn("stripe connect: stored account gone — recreating", + "stripe_account_id", stripeAcctID, "error", err) + needNewAccount = true + case err != nil: + // Transient Stripe error — only force a new account if the user + // explicitly changed country; otherwise proceed with the existing + // one and let CreateAccountLink surface any real problem. + s.logger.Warn("stripe connect: onboard account fetch failed", "error", err) + needNewAccount = countryChanged + default: + if acct.Country != "" { + existingCountry = acct.Country + } + required := billingservice.RequiredServiceAgreement( + s.billing().StripeConnect().PlatformCountry(), acct.Country) + have := billingservice.NormalizeServiceAgreement(acct.ServiceAgreement) + agreementMismatch := have != required + if agreementMismatch { + s.logger.Warn("stripe connect: service agreement mismatch — recreating account", + "stripe_account_id", stripeAcctID, "country", acct.Country, + "have", have, "want", required) + } + needNewAccount = countryChanged || agreementMismatch + if !needNewAccount && acct.PayoutInterval == "manual" { + // Self-heal accounts created by older code with a manual + // payout schedule (they strand transferred funds). + if err := s.billing().StripeConnect().UpdateAccountPayoutScheduleAuto(stripeAcctID, acct.Country); err != nil { + s.logger.Warn("stripe connect: payout schedule self-heal failed", + "stripe_account_id", stripeAcctID, "error", err) + } else { + s.logger.Info("stripe connect: payout schedule healed to automatic", + "stripe_account_id", stripeAcctID) + } + } + } + } + + if needNewAccount { + country := requestedCountry + if country == "" { + country = existingCountry + } + if country == "" { + country = s.billing().StripeConnect().PlatformCountry() + } + acct, err := s.billing().StripeConnect().CreateExpressAccount(billingservice.CreateExpressAccountParams{ + Email: user.Email, + Country: country, + }) + if err != nil { + s.logger.Error("stripe connect: create account failed", "error", err) + httpresponse.WriteJSON(w, http.StatusBadGateway, httpresponse.ErrorBody("stripe_error", err.Error())) + return + } + stripeAcctID = acct.ID + if err := s.billing().Store().SetUserStripeAccount(user.AccountID, stripeAcctID, stripeStatusPending, country, "", "", false); err != nil { + s.logger.Error("stripe connect: persist account id failed", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to persist Stripe account")) + return + } + } + + link, err := s.billing().StripeConnect().CreateAccountLink(stripeAcctID, returnURL, refreshURL) + if err != nil { + s.logger.Error("stripe connect: create account link failed", "error", err) + httpresponse.WriteJSON(w, http.StatusBadGateway, httpresponse.ErrorBody("stripe_error", err.Error())) + return + } + + if repo, ok := s.globalPayoutStore(); ok { + if err := repo.RemoveGlobalRecipient(user.AccountID); err != nil { + globalPayoutError(w, err) + return + } + } + + // Re-read the user — the SetUserStripeAccount above may have updated the + // status from "" to "pending"; we want the response to reflect that. + refreshed, err := s.billing().Store().GetUserByAccountID(user.AccountID) + if err == nil { + user = refreshed + } + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "url": link, + "stripe_account_id": stripeAcctID, + "status": user.StripeAccountStatus, + }) +} diff --git a/coordinator/api/billing/connect_onboarding_recovery_test.go b/coordinator/api/billing/connect_onboarding_recovery_test.go new file mode 100644 index 0000000000..69b4504a70 --- /dev/null +++ b/coordinator/api/billing/connect_onboarding_recovery_test.go @@ -0,0 +1,176 @@ +package billing + +import ( + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" +) + +// TestStripeOnboardRecreatesAccountOnServiceAgreementMismatch pins the +// migration path for AU/NZ/JP users whose accounts were created under the +// `full` agreement before we set `recipient`: re-running onboarding must +// create a NEW account under the recipient agreement (transfers-only). +func TestStripeOnboardRecreatesAccountOnServiceAgreementMismatch(t *testing.T) { + var mu sync.Mutex + var createBody url.Values + + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet: + // Existing AU account wrongly under the full agreement. + _, _ = w.Write([]byte(healthyAccountJSON("acct_au_full", "AU", "full", false))) + case r.URL.Path == "/v1/accounts" && r.Method == http.MethodPost: + body, _ := io.ReadAll(r.Body) + parsed, _ := url.ParseQuery(string(body)) + mu.Lock() + createBody = parsed + mu.Unlock() + _, _ = w.Write([]byte(`{"id":"acct_au_recipient","country":"AU","tos_acceptance":{"service_agreement":"recipient"}}`)) + case strings.HasPrefix(r.URL.Path, "/v1/account_links"): + _, _ = w.Write([]byte(`{"url":"https://connect.stripe.com/setup/e/au_new"}`)) + default: + t.Errorf("unexpected Stripe call: %s %s", r.Method, r.URL.Path) + } + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := seedUser(t, st, "acct-au-mig", "au@example.com") + _ = st.SetUserStripeAccount(user.AccountID, "acct_au_full", "ready", "AU", "bank", "6789", false) + user, _ = st.GetUserByAccountID(user.AccountID) + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", strings.NewReader(`{}`)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountID != "acct_au_recipient" { + t.Errorf("StripeAccountID = %q, want acct_au_recipient", refreshed.StripeAccountID) + } + if refreshed.StripeAccountCountry != "AU" { + t.Errorf("country = %q, want AU", refreshed.StripeAccountCountry) + } + + mu.Lock() + defer mu.Unlock() + if createBody == nil { + t.Fatal("no account creation request was made") + } + if got := createBody.Get("tos_acceptance[service_agreement]"); got != "recipient" { + t.Errorf("service_agreement = %q, want recipient", got) + } + if got := createBody.Get("capabilities[card_payments][requested]"); got != "" { + t.Errorf("card_payments must not be requested for recipient accounts, got %q", got) + } + if got := createBody.Get("capabilities[transfers][requested]"); got != "true" { + t.Errorf("transfers capability = %q, want true", got) + } + if got := createBody.Get("settings[payouts][schedule][interval]"); got != "daily" { + t.Errorf("payout schedule = %q, want daily", got) + } + if got := createBody.Get("country"); got != "AU" { + t.Errorf("country = %q, want AU", got) + } +} + +// TestStripeOnboardRecreatesAccountWhenGone pins recovery for users who +// closed their Stripe account: onboarding must create a fresh account +// instead of failing on the stale acct_… forever. +func TestStripeOnboardRecreatesAccountWhenGone(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet: + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"error":{"code":"account_invalid","message":"The provided key does not have access to account 'acct_gone'"}}`)) + case r.URL.Path == "/v1/accounts" && r.Method == http.MethodPost: + _, _ = w.Write([]byte(`{"id":"acct_fresh","country":"NZ","tos_acceptance":{"service_agreement":"recipient"}}`)) + case strings.HasPrefix(r.URL.Path, "/v1/account_links"): + _, _ = w.Write([]byte(`{"url":"https://connect.stripe.com/setup/e/fresh"}`)) + default: + t.Errorf("unexpected Stripe call: %s %s", r.Method, r.URL.Path) + } + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := seedUser(t, st, "acct-gone-1", "nz@example.com") + _ = st.SetUserStripeAccount(user.AccountID, "acct_gone", "ready", "NZ", "bank", "6789", false) + user, _ = st.GetUserByAccountID(user.AccountID) + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", strings.NewReader(`{}`)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountID != "acct_fresh" { + t.Errorf("StripeAccountID = %q, want acct_fresh", refreshed.StripeAccountID) + } +} + +// TestStripeOnboardHealsManualPayoutSchedule pins the self-heal: reusing a +// healthy account that still has the legacy manual payout schedule must flip +// it to daily so parked funds drain to the user's bank. +func TestStripeOnboardHealsManualPayoutSchedule(t *testing.T) { + var mu sync.Mutex + var scheduleUpdate url.Values + + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet: + acct := strings.Replace(healthyAccountJSON("acct_manual_1", "US", "full", false), + `"interval":"daily"`, `"interval":"manual"`, 1) + _, _ = w.Write([]byte(acct)) + case strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodPost: + body, _ := io.ReadAll(r.Body) + parsed, _ := url.ParseQuery(string(body)) + mu.Lock() + scheduleUpdate = parsed + mu.Unlock() + _, _ = w.Write([]byte(healthyAccountJSON("acct_manual_1", "US", "full", false))) + case strings.HasPrefix(r.URL.Path, "/v1/account_links"): + _, _ = w.Write([]byte(`{"url":"https://connect.stripe.com/setup/e/manual"}`)) + default: + t.Errorf("unexpected Stripe call: %s %s", r.Method, r.URL.Path) + } + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := seedUser(t, st, "acct-manual-heal", "heal@example.com") + _ = st.SetUserStripeAccount(user.AccountID, "acct_manual_1", "ready", "US", "bank", "6789", false) + user, _ = st.GetUserByAccountID(user.AccountID) + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", strings.NewReader(`{"country":"US"}`)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountID != "acct_manual_1" { + t.Errorf("account should be reused, got %q", refreshed.StripeAccountID) + } + + mu.Lock() + defer mu.Unlock() + if scheduleUpdate == nil { + t.Fatal("expected a POST /v1/accounts/{id} schedule heal") + } + if got := scheduleUpdate.Get("settings[payouts][schedule][interval]"); got != "daily" { + t.Errorf("healed interval = %q, want daily", got) + } +} diff --git a/coordinator/api/billing/connect_onboarding_test.go b/coordinator/api/billing/connect_onboarding_test.go new file mode 100644 index 0000000000..ceb4ec0abd --- /dev/null +++ b/coordinator/api/billing/connect_onboarding_test.go @@ -0,0 +1,225 @@ +package billing + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" +) + +func TestStripeOnboardRequiresAuth(t *testing.T) { + srv, _ := stripePayoutsTestServer(t, true, nil) + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", strings.NewReader(`{"country":"US"}`)) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + if w.Code != http.StatusUnauthorized { + t.Errorf("got %d, want 401", w.Code) + } +} + +func TestStripeOnboardCreatesAccountAndPersistsID(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-onboard-1", "alice@example.com") + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", strings.NewReader(`{"country":"US"}`)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp["url"] == nil || !strings.Contains(resp["url"].(string), "/setup/mock/") { + t.Errorf("expected mock setup URL, got %v", resp["url"]) + } + + // Confirm the user was persisted with an account ID + pending status. + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountID == "" { + t.Error("StripeAccountID was not persisted") + } + if refreshed.StripeAccountStatus != "pending" { + t.Errorf("status = %q, want pending", refreshed.StripeAccountStatus) + } +} + +func TestStripeOnboardPassesCountryToStripe(t *testing.T) { + var mu sync.Mutex + var accountCreateBody url.Values + + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + parsed, _ := url.ParseQuery(string(body)) + + switch { + case r.URL.Path == "/v1/accounts" && r.Method == http.MethodPost: + mu.Lock() + accountCreateBody = parsed + mu.Unlock() + w.WriteHeader(200) + _, _ = w.Write([]byte(`{"id":"acct_gb_test","type":"express","charges_enabled":false,"payouts_enabled":false,"details_submitted":false}`)) + case strings.HasPrefix(r.URL.Path, "/v1/account_links"): + w.WriteHeader(200) + _, _ = w.Write([]byte(`{"url":"https://connect.stripe.com/setup/e/gb_test"}`)) + default: + w.WriteHeader(404) + } + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := seedUser(t, st, "acct-country-1", "alice@example.com") + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", + strings.NewReader(`{"country":"GB"}`)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + mu.Lock() + got := accountCreateBody.Get("country") + mu.Unlock() + if got != "GB" { + t.Errorf("country sent to Stripe = %q, want GB", got) + } +} + +func TestStripeOnboardRequiresCountryForNewAccount(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-country-2", "bob@example.com") + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", + strings.NewReader(`{}`)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("got %d, want 400: %s", w.Code, w.Body.String()) + } + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountID != "" { + t.Errorf("StripeAccountID = %q, want empty", refreshed.StripeAccountID) + } +} + +func TestStripeOnboardReusesExistingAccount(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-reuse-1", "bob@example.com") + + // Pre-seed an existing Stripe account ID locked to the US. + _ = st.SetUserStripeAccount(user.AccountID, "acct_existing_123", "ready", "US", "bank", "1234", false) + user, _ = st.GetUserByAccountID(user.AccountID) + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", strings.NewReader(`{"country":"US"}`)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp["stripe_account_id"] != "acct_existing_123" { + t.Errorf("expected reuse of acct_existing_123, got %v", resp["stripe_account_id"]) + } +} + +func TestStripeOnboardCreatesNewAccountWhenCountryChanges(t *testing.T) { + var mu sync.Mutex + var createdCountries []string + + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/v1/accounts" && r.Method == http.MethodPost: + body, _ := io.ReadAll(r.Body) + parsed, _ := url.ParseQuery(string(body)) + mu.Lock() + createdCountries = append(createdCountries, parsed.Get("country")) + mu.Unlock() + w.WriteHeader(200) + id := "acct_" + strings.ToLower(parsed.Get("country")) + "_new" + _, _ = w.Write([]byte(`{"id":"` + id + `","type":"express","charges_enabled":false,"payouts_enabled":false,"details_submitted":false}`)) + case strings.HasPrefix(r.URL.Path, "/v1/account_links"): + w.WriteHeader(200) + _, _ = w.Write([]byte(`{"url":"https://connect.stripe.com/setup/e/new"}`)) + default: + w.WriteHeader(404) + } + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := seedUser(t, st, "acct-country-change-1", "alice@example.com") + + // Pre-seed an existing Stripe account ID locked to the US. + _ = st.SetUserStripeAccount(user.AccountID, "acct_us_old", "pending", "US", "", "", false) + user, _ = st.GetUserByAccountID(user.AccountID) + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", + strings.NewReader(`{"country":"GB"}`)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp["stripe_account_id"] != "acct_gb_new" { + t.Errorf("expected new GB account, got %v", resp["stripe_account_id"]) + } + + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountCountry != "GB" { + t.Errorf("StripeAccountCountry = %q, want GB", refreshed.StripeAccountCountry) + } + if refreshed.StripeAccountStatus != "pending" { + t.Errorf("status = %q, want pending", refreshed.StripeAccountStatus) + } + + mu.Lock() + countries := append([]string(nil), createdCountries...) + mu.Unlock() + if len(countries) != 1 || countries[0] != "GB" { + t.Errorf("Stripe create account countries = %v, want [GB]", countries) + } +} + +func TestStripeOnboardCreatesNewAccountWhenExistingCountryUnknown(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-country-unknown-1", "carol@example.com") + + // Simulates users created before stripe_account_country existed. If they + // explicitly select a country, don't reuse the unknown-country account. + _ = st.SetUserStripeAccount(user.AccountID, "acct_old_unknown", "pending", "", "", "", false) + user, _ = st.GetUserByAccountID(user.AccountID) + + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", + strings.NewReader(`{"country":"GB"}`)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountID == "acct_old_unknown" { + t.Fatal("expected a new Stripe account for explicit country selection") + } + if refreshed.StripeAccountCountry != "GB" { + t.Errorf("StripeAccountCountry = %q, want GB", refreshed.StripeAccountCountry) + } +} diff --git a/coordinator/api/billing/connect_payout_bounce_race_test.go b/coordinator/api/billing/connect_payout_bounce_race_test.go new file mode 100644 index 0000000000..5e11d499d1 --- /dev/null +++ b/coordinator/api/billing/connect_payout_bounce_race_test.go @@ -0,0 +1,64 @@ +package billing + +import ( + "net/http" + "testing" + "time" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/payments" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Return an instant payout snapshot after another delivery has detached it +// and a later automatic sweep has completed the same withdrawal. +type replacedPayoutStore struct { + *store.MemoryStore + t *testing.T +} + +func (s *replacedPayoutStore) GetStripeWithdrawalByPayoutID(id string) (*store.StripeWithdrawal, error) { + row, err := s.MemoryStore.GetStripeWithdrawalByPayoutID(id) + if err != nil { + return row, err + } + stale := *row + row.Status, row.PayoutID = "transferred", "" + if err := s.MemoryStore.UpdateStripeWithdrawal(row); err != nil { + s.t.Fatal(err) + } + if applied, err := s.MemoryStore.MarkStripeWithdrawalPaid(row.ID, "", "po_new"); err != nil || !applied { + s.t.Fatalf("new sweep completion: applied=%v err=%v", applied, err) + } + return &stale, nil +} + +func TestConnectWebhookOldInstantBouncePreservesNewSweepCompletion(t *testing.T) { + fakeStripe := accountServingStripe("full") + defer fakeStripe.Close() + srv, mem := stripePayoutsTestServer(t, false, fakeStripe) + st := &replacedPayoutStore{MemoryStore: mem, t: t} + srv.SetBilling(billingservice.NewService(st, payments.NewLedger(st), srv.logger, billingservice.Config{ + StripeSecretKey: "sk_test_fake", StripeConnectWebhookSecret: "whsec_test", + StripeConnectReturnURL: "https://app.test/billing", StripeConnectRefreshURL: "https://app.test/billing", + StripeConnectPlatformCountry: "US", + })) + user := readyUser(t, mem, "acct-sweep-race", "alice@example.com", false) + mkWithdrawal(t, mem, store.StripeWithdrawal{ + ID: "wd-sweep-race", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "instant", Status: "paid", TransferID: "tr_sweep_race", PayoutID: "po_old", + }) + before := mem.GetBalance(user.AccountID) + response := deliverConnectWebhook(t, srv, payoutEventPayload("po_old", user.StripeAccountID, "failed", false, time.Now().Unix())) + if response.Code != http.StatusOK { + t.Fatalf("webhook returned %d: %s", response.Code, response.Body.String()) + } + wd, err := mem.GetStripeWithdrawal("wd-sweep-race") + if err != nil { + t.Fatal(err) + } + if wd.Status != "paid" || wd.SweepPayoutID != "po_new" || mem.GetBalance(user.AccountID) != before { + t.Fatalf("new sweep completion overwritten: status=%s sweep=%q balance=%d want=%d", wd.Status, wd.SweepPayoutID, mem.GetBalance(user.AccountID), before) + } +} diff --git a/coordinator/api/billing/connect_payout_events.go b/coordinator/api/billing/connect_payout_events.go new file mode 100644 index 0000000000..0f7af1e3f0 --- /dev/null +++ b/coordinator/api/billing/connect_payout_events.go @@ -0,0 +1,154 @@ +package billing + +import ( + "errors" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// handlePayoutTerminal handles payout.paid / payout.failed / payout.canceled. +// +// Success: the row (matched by payout ID, or by connected account for +// automatic sweep payouts we never created) is marked "paid". +// +// Failure: the funds return to the connected account's Stripe balance and the +// automatic daily payout schedule retries delivery — so we do NOT re-credit +// the ledger (that would double-pay: once from the ledger refund and again +// when the sweep eventually reaches the user's bank). The instant fee IS +// refunded (once, keyed on FeeRefunded): the user paid for instant delivery +// and is getting the standard rail instead. The dead payout ID is detached +// from the row so the sweep matcher can complete it when the daily sweep +// delivers. Ledger principal refunds only happen on transfer.reversed, where +// the money actually returns to the platform. +// +// A failure can arrive after payout.paid (banks bounce payouts days later); +// in that case the row is reopened to "transferred" so the retrying sweep +// stays observable — see the inline comment on the failure branch. +// +// Returns a non-nil error only for transient store failures, so the webhook +// responds non-2xx and Stripe redelivers. +func (s *Controller) handlePayoutTerminal(event *billingservice.WebhookEvent, connectedAcct string, success bool) error { + pe, err := s.billing().StripeConnect().PayoutFromEvent(event, connectedAcct) + if err != nil { + s.logger.Warn("stripe connect webhook: payout parse failed", "error", err) + return nil + } + + wd, err := s.billing().Store().GetStripeWithdrawalByPayoutID(pe.ID) + if err != nil { + if !errors.Is(err, store.ErrNotFound) { + // Transient store failure — do NOT fall through to account-wide + // reconciliation (that could claim unrelated rows for this + // payout). Redeliver instead. + s.logger.Error("stripe connect webhook: payout lookup failed", + "payout_id", pe.ID, "error", err) + return err + } + // Not a payout we created — either Stripe's automatic sweep (the + // normal delivery path for standard withdrawals) or a payout made + // directly in the dashboard. Reconcile it against this connected + // account's outstanding "transferred" rows. + return s.reconcileUnmatchedPayout(pe, success) + } + + if success { + // Idempotent redelivery of payout.paid on a completed row. + if wd.Status == "paid" { + return nil + } + // The flip is guarded INSIDE the store (only pending/transferred + + // !Refunded rows flip): a concurrent payout.failed/transfer.reversed + // delivery that persisted Refunded after our read above can't be + // overwritten by this stale copy. + applied, err := s.billing().Store().MarkStripeWithdrawalPaid(wd.ID, pe.ID, "") + if err != nil { + s.logger.Error("stripe connect webhook: mark paid failed", "error", err) + return err + } + if !applied { + // Refunded or already terminal — e.g. the ledger was refunded + // (transfer.reversed) AND the payout delivered; the user may + // hold both. Never overwrite; escalate for manual review. + s.logger.Error("stripe connect webhook: payout.paid on a refunded/terminal withdrawal — possible double payment, manual review required", + "withdrawal_id", wd.ID, "payout_id", pe.ID, "status", wd.Status, + "stripe_account_id", wd.StripeAccountID) + } + return nil + } + + // Matched payout failed. Funds are back in the connected account balance; + // the daily sweep will retry via the standard rail. + // + // This applies to "paid" rows too: Stripe documents payout.failed arriving + // AFTER payout.paid for the same payout when the bank later bounces it. + // Because this row was looked up BY the event's payout ID, the failure is + // about the observed in-flight payout. The store rechecks that ownership + // before applying the transition: a concurrent failure may detach it and a + // newer sweep may complete the row after this lookup. For a match, we + // reopen the row for the sweep to retry. Later failures from an older + // payout can never reach this path: processing a failure detaches the + // payout ID from the row (below), so a redelivered or out-of-order event + // for that payout misses the lookup and falls into + // reconcileUnmatchedPayout, which ignores non-automatic payouts. + if wd.Refunded { + if wd.Status == "paid" { + // Refunded AND paid — the ledger was already made whole under + // the old semantics while the bank payout completed. Ambiguous + // clawback state; never touch it automatically. + s.logger.Error("stripe connect webhook: payout failed on a paid+refunded withdrawal — manual review required", + "withdrawal_id", wd.ID, "payout_id", pe.ID) + return nil + } + // Legacy row already refunded under the old semantics — leave it + // terminal so we never double-account. + if wd.Status != "failed" { + next := *wd + next.Status = "failed" + if _, err := s.billing().Store().CompareAndSwapStripeWithdrawal(wd, &next); err != nil { + s.logger.Error("stripe connect webhook: status flip failed", "error", err) + return err + } + } + return nil + } + + // The user paid for instant delivery and is getting the standard sweep + // instead — refund the fee. The credit is idempotent on its ledger + // reference, so any crash/redelivery interleaving converges: a retried + // event skips the credit and re-attempts only the row persist. + if wd.FeeMicroUSD > 0 && !wd.FeeRefunded { + if _, err := s.billing().Store().CreditWithdrawableOnce(wd.AccountID, wd.FeeMicroUSD, + store.LedgerRefund, "stripe_withdraw_fee:"+wd.ID); err != nil { + s.logger.Error("stripe connect webhook: instant fee refund failed", + "error", err, "withdrawal_id", wd.ID) + return err + } + wd.FeeRefunded = true + } + + // Reopen for the sweep to retry: status back to "transferred" with the + // dead payout ID detached (the sweep matcher only completes rows with + // no in-flight payout of their own). The transition is guarded INSIDE + // the store: if a concurrent transfer.reversed terminalized the row + // (Refunded/failed) after our read above, this stale copy cannot + // overwrite the refund back to a sweep-eligible state. + reason := "payout_failed " + pe.FailureCode + ": " + pe.FailureReason + + " (payout " + pe.ID + "; auto-payout will retry)" + applied, err := s.billing().Store().ReopenStripeWithdrawalAfterPayoutFailure(wd.ID, pe.ID, reason, wd.FeeRefunded) + if err != nil { + s.logger.Error("stripe connect webhook: persist payout failure failed", + "error", err, "withdrawal_id", wd.ID) + return err + } + if !applied { + s.logger.Warn("stripe connect webhook: payout failure not applied — row terminalized or payout ownership changed concurrently", + "withdrawal_id", wd.ID, "payout_id", pe.ID) + return nil + } + s.logger.Warn("stripe connect webhook: payout failed — funds returned to connected balance, sweep will retry", + "withdrawal_id", wd.ID, "payout_id", pe.ID, + "failure_code", pe.FailureCode, "failure_reason", pe.FailureReason, + "fee_refunded", wd.FeeRefunded) + return nil +} diff --git a/coordinator/api/billing/connect_payout_events_test.go b/coordinator/api/billing/connect_payout_events_test.go new file mode 100644 index 0000000000..549a96a526 --- /dev/null +++ b/coordinator/api/billing/connect_payout_events_test.go @@ -0,0 +1,248 @@ +package billing + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// TestConnectWebhookPayoutBounceAfterPaidReopens: Stripe documents +// payout.failed arriving AFTER payout.paid for the same payout (the bank +// bounces it days later — funds return to the connected balance). Because the +// row is looked up by the event's payout ID, the failure is provably about +// the row's own payout: the row must reopen to "transferred" (so the sweep +// retries and the 48h stuck detector can see it), the instant fee must be +// refunded once, and the dead payout ID detached. +func TestConnectWebhookPayoutBounceAfterPaidReopens(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-paid-bounce", "alice@example.com", true) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-paid-bounce", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, FeeMicroUSD: 500_000, NetMicroUSD: 4_500_000, + Method: "instant", Status: "paid", TransferID: "tr_pb", PayoutID: "po_pb", + }) + balBefore := st.GetBalance(user.AccountID) + + payload := payoutEventPayload("po_pb", user.StripeAccountID, "failed", false, time.Now().Unix()) + if w := deliverConnectWebhook(t, srv, payload); w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + + wd, _ := st.GetStripeWithdrawal("wd-paid-bounce") + if wd.Status != "transferred" { + t.Errorf("status = %q, want transferred (bounced payout reopens for the sweep)", wd.Status) + } + if !wd.FeeRefunded { + t.Error("instant fee should be refunded — the user is getting the standard rail") + } + if wd.PayoutID != "" { + t.Errorf("dead payout ID should be detached, got %q", wd.PayoutID) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore+500_000 { + t.Errorf("balance = %d, want %d (fee refunded exactly once)", bal, balBefore+500_000) + } + + // Redelivery: the payout ID no longer matches a row and the payout is + // not automatic — no-op, no double credit. + if w := deliverConnectWebhook(t, srv, payload); w.Code != http.StatusOK { + t.Fatalf("redelivery got %d", w.Code) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore+500_000 { + t.Errorf("redelivery double-credited: balance = %d", bal) + } + wd, _ = st.GetStripeWithdrawal("wd-paid-bounce") + if wd.Status != "transferred" { + t.Errorf("redelivery changed status to %q", wd.Status) + } +} + +// TestConnectWebhookStalePayoutFailureLeavesPaidRow: a payout.failed whose +// payout ID matches no row (e.g. an older payout that was already detached, +// or a payout that isn't ours) must not touch rows that were completed by a +// sweep — unmatched non-automatic payouts are ignored. +func TestConnectWebhookStalePayoutFailureLeavesPaidRow(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-stale-fail", "alice@example.com", false) + + // Paid via sweep: no payout ID of its own. + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-stale-fail", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "paid", TransferID: "tr_sf", + }) + balBefore := st.GetBalance(user.AccountID) + + w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_stale_detached", user.StripeAccountID, "failed", false, time.Now().Unix())) + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + wd, _ := st.GetStripeWithdrawal("wd-stale-fail") + if wd.Status != "paid" { + t.Errorf("status = %q, want paid (stale failures never touch completed rows)", wd.Status) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore { + t.Errorf("balance moved: %d -> %d", balBefore, bal) + } +} + +// TestConnectWebhookPayoutBounceOnPaidRefundedRowUntouched: paid AND refunded +// is the ambiguous legacy double-state — a matched payout failure must not +// reopen or re-credit it, only surface it for manual review. +func TestConnectWebhookPayoutBounceOnPaidRefundedRowUntouched(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-paid-refunded", "alice@example.com", true) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-paid-refunded", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, FeeMicroUSD: 500_000, NetMicroUSD: 4_500_000, + Method: "instant", Status: "paid", TransferID: "tr_pr", PayoutID: "po_pr", + Refunded: true, + }) + balBefore := st.GetBalance(user.AccountID) + + if w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_pr", user.StripeAccountID, "failed", false, time.Now().Unix())); w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + wd, _ := st.GetStripeWithdrawal("wd-paid-refunded") + if wd.Status != "paid" || !wd.Refunded { + t.Errorf("row = status %q refunded=%v, want paid/true (untouched)", wd.Status, wd.Refunded) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore { + t.Errorf("balance moved on paid+refunded row: %d -> %d", balBefore, bal) + } +} + +// TestConnectWebhookInstantPayoutFailedRefundsFeeAndDetaches: when an instant +// payout fails after creation, the user gets standard delivery via the sweep +// — so the instant fee is refunded (exactly once) and the dead payout ID is +// detached so the sweep matcher can complete the row. +func TestConnectWebhookInstantPayoutFailedRefundsFeeAndDetaches(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-async-fee", "alice@example.com", true) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-async-fee", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, FeeMicroUSD: 500_000, NetMicroUSD: 4_500_000, + Method: "instant", Status: "transferred", TransferID: "tr_af", PayoutID: "po_af", + }) + balBefore := st.GetBalance(user.AccountID) + + payload := payoutEventPayload("po_af", user.StripeAccountID, "failed", false, time.Now().Unix()) + if w := deliverConnectWebhook(t, srv, payload); w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + + wd, _ := st.GetStripeWithdrawal("wd-async-fee") + if wd.Status != "transferred" { + t.Errorf("status = %q, want transferred (sweep delivers)", wd.Status) + } + if !wd.FeeRefunded { + t.Error("FeeRefunded should be set") + } + if wd.PayoutID != "" { + t.Errorf("payout ID should be detached, got %q", wd.PayoutID) + } + if !strings.Contains(wd.FailureReason, "po_af") { + t.Errorf("failure reason should record the failed payout id, got %q", wd.FailureReason) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore+500_000 { + t.Errorf("balance = %d, want %d (fee refunded once)", bal, balBefore+500_000) + } + + // Redelivery of the same event must not double-credit: the payout ID no + // longer matches a row, and the payout is not automatic, so it's a no-op. + if w := deliverConnectWebhook(t, srv, payload); w.Code != http.StatusOK { + t.Fatalf("redelivery got %d", w.Code) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore+500_000 { + t.Errorf("redelivery double-credited: balance = %d", bal) + } +} + +// TestConnectWebhookTransientLookupErrorReturns500: a transient store failure +// on the payout lookup must NOT fall through to account-wide sweep +// reconciliation (which could claim unrelated rows) — it responds non-2xx so +// Stripe redelivers. +func TestConnectWebhookTransientLookupErrorReturns500(t *testing.T) { + fakeStripe := accountServingStripe("full") + defer fakeStripe.Close() + srv, flaky := newFlakyPayoutServer(t, fakeStripe) + flaky.failLookups = true + mem := flaky.MemoryStore + user := readyUser(t, mem, "acct-flaky", "alice@example.com", false) + + // An unrelated transferred row that blanket reconciliation would claim. + mkWithdrawal(t, mem, store.StripeWithdrawal{ + ID: "wd-flaky-unrelated", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_fl", + }) + + w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_known", user.StripeAccountID, "paid", true, time.Now().Add(time.Hour).Unix())) + if w.Code != http.StatusInternalServerError { + t.Fatalf("got %d, want 500 (Stripe must redeliver)", w.Code) + } + wd, _ := mem.GetStripeWithdrawal("wd-flaky-unrelated") + if wd.Status != "transferred" { + t.Errorf("unrelated row = %q, want transferred (no blanket reconcile on transient error)", wd.Status) + } + + // Once the store recovers, redelivery reconciles normally. + flaky.failLookups = false + w = deliverConnectWebhook(t, srv, + payoutEventPayload("po_known", user.StripeAccountID, "paid", true, time.Now().Add(time.Hour).Unix())) + if w.Code != http.StatusOK { + t.Fatalf("recovery delivery got %d", w.Code) + } + wd, _ = mem.GetStripeWithdrawal("wd-flaky-unrelated") + if wd.Status != "paid" { + t.Errorf("after recovery = %q, want paid", wd.Status) + } +} + +// TestConnectWebhookPayoutPaidOnRefundedRowStaysFailed: if transfer.reversed +// already refunded the ledger and the row still carries its instant payout +// ID, a late/redelivered payout.paid must not overwrite the refunded row to +// "paid" — that would hide a possible double payment. +func TestConnectWebhookPayoutPaidOnRefundedRowStaysFailed(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-paid-on-ref", "alice@example.com", true) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-paid-on-ref", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, FeeMicroUSD: 500_000, NetMicroUSD: 4_500_000, + Method: "instant", Status: "failed", TransferID: "tr_por", PayoutID: "po_por", + Refunded: true, FailureReason: "transfer_reversed", + }) + balBefore := st.GetBalance(user.AccountID) + + if w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_por", user.StripeAccountID, "paid", false, time.Now().Unix())); w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + wd, _ := st.GetStripeWithdrawal("wd-paid-on-ref") + if wd.Status != "failed" || !wd.Refunded { + t.Errorf("row = status %q refunded=%v, want failed/true (manual review, never paid)", wd.Status, wd.Refunded) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore { + t.Errorf("balance moved: %d -> %d", balBefore, bal) + } +} diff --git a/coordinator/api/billing/connect_reconcile.go b/coordinator/api/billing/connect_reconcile.go new file mode 100644 index 0000000000..9efe6a8a3c --- /dev/null +++ b/coordinator/api/billing/connect_reconcile.go @@ -0,0 +1,128 @@ +package billing + +import ( + "context" + "time" + + "github.com/eigeninference/d-inference/coordinator/saferun" +) + +const ( + // stripeReconcileInterval is how often the reconciler sweeps. + stripeReconcileInterval = 1 * time.Hour + + // stripeStuckThreshold is how long a withdrawal may sit in "transferred" + // before it is considered stuck. The normal happy path is: transfer → + // (up to 24h availability delay on recipient accounts) → daily sweep → + // bank rail. 48h covers all of that with margin. + stripeStuckThreshold = 48 * time.Hour + + // stripeReconcileBatch bounds how many stuck rows one sweep inspects. + stripeReconcileBatch = 200 +) + +// StartStripePayoutReconciler launches the hourly stuck-withdrawal sweep: it +// heals legacy "manual" payout schedules (which strand transferred funds in +// the connected balance forever) and alerts on rows that stay non-terminal +// past the threshold. It never touches the ledger — money movement stays in +// the withdraw handler and the webhook state machine. No-op when Stripe +// Connect isn't configured. +func (s *Controller) StartStripePayoutReconciler(ctx context.Context) { + if s.billing() == nil || s.billing().StripeConnect() == nil { + return + } + s.logger.Info("stripe payout reconciler started", + "interval", stripeReconcileInterval.String(), + "stuck_threshold", stripeStuckThreshold.String()) + saferun.Go(s.logger, "api.stripePayoutReconciler", func() { + // First sweep shortly after boot so a deploy heals stuck accounts + // without waiting an hour. + timer := time.NewTimer(1 * time.Minute) + defer timer.Stop() + select { + case <-ctx.Done(): + return + case <-timer.C: + s.sweepStuckStripeWithdrawals() + } + ticker := time.NewTicker(stripeReconcileInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + s.sweepStuckStripeWithdrawals() + } + } + }) +} + +// sweepStuckStripeWithdrawals runs one reconciler pass. +func (s *Controller) sweepStuckStripeWithdrawals() { + cutoff := time.Now().Add(-stripeStuckThreshold) + + // Rows stuck in "pending" mean the transfer-create either never ran + // (crash mid-request) or ran and the row update failed after retries — + // in the latter case money moved without a local trace. No safe + // automatic action exists (can't tell the two apart locally), so alert + // for a manual check against the Stripe dashboard. + if pending, err := s.billing().Store().ListStripeWithdrawalsByStatus("pending", cutoff, stripeReconcileBatch); err != nil { + s.logger.Error("stripe reconciler: list stale pending withdrawals failed", "error", err) + } else if len(pending) > 0 { + for _, wd := range pending { + s.logger.Error("stripe reconciler: withdrawal stuck in pending — verify against Stripe dashboard (idempotency key wd-tr-)", + "withdrawal_id", wd.ID, "account_id", wd.AccountID, + "stripe_account_id", wd.StripeAccountID, + "amount_micro_usd", wd.AmountMicroUSD, "created_at", wd.CreatedAt) + } + } + + stuck, err := s.billing().Store().ListStripeWithdrawalsByStatus("transferred", cutoff, stripeReconcileBatch) + if err != nil { + s.logger.Error("stripe reconciler: list stuck withdrawals failed", "error", err) + return + } + if len(stuck) == 0 { + return + } + + // Group by connected account — one Stripe lookup (and at most one + // schedule heal) per account, not per withdrawal. + byAcct := map[string]int{} + for _, wd := range stuck { + byAcct[wd.StripeAccountID]++ + } + s.logger.Warn("stripe reconciler: withdrawals stuck in transferred", + "withdrawals", len(stuck), "accounts", len(byAcct), "stuck_threshold", stripeStuckThreshold.String()) + + for acctID, count := range byAcct { + if acctID == "" { + continue + } + acct, err := s.billing().StripeConnect().GetAccount(acctID) + if err != nil { + s.logger.Warn("stripe reconciler: account fetch failed", + "stripe_account_id", acctID, "stuck_withdrawals", count, "error", err) + continue + } + if acct.PayoutInterval == "manual" { + if err := s.billing().StripeConnect().UpdateAccountPayoutScheduleAuto(acctID, acct.Country); err != nil { + s.logger.Error("stripe reconciler: payout schedule heal failed", + "stripe_account_id", acctID, "stuck_withdrawals", count, "error", err) + continue + } + s.logger.Info("stripe reconciler: healed manual payout schedule to automatic", + "stripe_account_id", acctID, "stuck_withdrawals", count) + continue + } + // Schedule is already automatic — the sweep should be moving these. + // Loud log for ops: likely payouts_enabled=false (user needs to fix + // bank details) or a failed sweep that keeps retrying. + s.logger.Warn("stripe reconciler: stuck withdrawals on auto-schedule account", + "stripe_account_id", acctID, "stuck_withdrawals", count, + "payouts_enabled", acct.PayoutsEnabled, + "disabled_reason", acct.DisabledReason, + "payout_interval", acct.PayoutInterval) + } +} diff --git a/coordinator/api/billing/connect_reconcile_test.go b/coordinator/api/billing/connect_reconcile_test.go new file mode 100644 index 0000000000..138873c6a4 --- /dev/null +++ b/coordinator/api/billing/connect_reconcile_test.go @@ -0,0 +1,61 @@ +package billing + +import ( + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// TestStripeReconcilerHealsManualScheduleForStuckWithdrawals pins the +// background unstick path: withdrawals stuck in "transferred" on an account +// with the legacy manual payout schedule cause the reconciler to flip the +// schedule to daily. +func TestStripeReconcilerHealsManualScheduleForStuckWithdrawals(t *testing.T) { + var mu sync.Mutex + var scheduleUpdates []string + + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet: + acct := strings.Replace(healthyAccountJSON("acct_stuck_1", "FR", "full", false), + `"interval":"daily"`, `"interval":"manual"`, 1) + _, _ = w.Write([]byte(acct)) + case strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodPost: + mu.Lock() + scheduleUpdates = append(scheduleUpdates, strings.TrimPrefix(r.URL.Path, "/v1/accounts/")) + mu.Unlock() + _, _ = w.Write([]byte(healthyAccountJSON("acct_stuck_1", "FR", "full", false))) + default: + t.Errorf("unexpected Stripe call: %s %s", r.Method, r.URL.Path) + } + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-stuck-user", "stuck@example.com", false) + // Stuck for 3 days — like the €10.57 sitting in a manual-schedule account. + _ = st.CreateStripeWithdrawal(&store.StripeWithdrawal{ + ID: "wd-stuck-1", AccountID: user.AccountID, StripeAccountID: "acct_stuck_1", + TransferID: "tr_stuck_1", AmountMicroUSD: 10_570_000, NetMicroUSD: 10_570_000, + Method: "standard", Status: "transferred", CreatedAt: time.Now().Add(-72 * time.Hour), + }) + // A fresh transferred row must NOT trigger reconciliation. + _ = st.CreateStripeWithdrawal(&store.StripeWithdrawal{ + ID: "wd-fresh-1", AccountID: user.AccountID, StripeAccountID: "acct_fresh_ok", + TransferID: "tr_fresh_1", AmountMicroUSD: 1_000_000, NetMicroUSD: 1_000_000, + Method: "standard", Status: "transferred", CreatedAt: time.Now().Add(-1 * time.Hour), + }) + + srv.sweepStuckStripeWithdrawals() + + mu.Lock() + defer mu.Unlock() + if len(scheduleUpdates) != 1 || scheduleUpdates[0] != "acct_stuck_1" { + t.Errorf("schedule updates = %v, want [acct_stuck_1]", scheduleUpdates) + } +} diff --git a/coordinator/api/billing/connect_redirect.go b/coordinator/api/billing/connect_redirect.go new file mode 100644 index 0000000000..e025032ef0 --- /dev/null +++ b/coordinator/api/billing/connect_redirect.go @@ -0,0 +1,40 @@ +package billing + +import ( + "errors" + "fmt" + "net/url" + "strings" +) + +// validateRedirectURL ensures the user-supplied URL is on the same host as +// the operator-configured default. localhost is always allowed (dev). If no +// default is configured, the URL must be https and the call rejects http. +func validateRedirectURL(candidate, defaultURL string) error { + cu, err := url.Parse(candidate) + if err != nil { + return errors.New("invalid URL") + } + if cu.Scheme != "https" && cu.Scheme != "http" { + return errors.New("scheme must be http or https") + } + host := strings.ToLower(cu.Hostname()) + if host == "localhost" || host == "127.0.0.1" || host == "::1" { + return nil + } + if defaultURL == "" { + // No allowlist configured → require https + non-empty host. + if cu.Scheme != "https" || host == "" { + return errors.New("must be https with a hostname when no default is configured") + } + return nil + } + du, err := url.Parse(defaultURL) + if err != nil { + return nil // defaults are operator-configured; if malformed, fall back to allow https + } + if !strings.EqualFold(cu.Hostname(), du.Hostname()) { + return fmt.Errorf("host %q does not match allowed host %q", cu.Hostname(), du.Hostname()) + } + return nil +} diff --git a/coordinator/api/billing/connect_redirect_test.go b/coordinator/api/billing/connect_redirect_test.go new file mode 100644 index 0000000000..3338564b81 --- /dev/null +++ b/coordinator/api/billing/connect_redirect_test.go @@ -0,0 +1,55 @@ +package billing + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestStripeOnboardRejectsForeignReturnURL(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-onboard-redir", "alice@example.com") + + // Default return URL is https://app.test/...; passing attacker.example + // must be rejected before any Stripe call is made. + body := `{"return_url":"https://attacker.example/billing"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("got %d, want 400 on foreign host: %s", w.Code, w.Body.String()) + } +} + +func TestStripeOnboardAllowsLocalhostForDev(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-onboard-local", "alice@example.com") + + body := `{"return_url":"http://localhost:3000/billing","country":"US"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d, want 200 for localhost: %s", w.Code, w.Body.String()) + } +} + +func TestStripeOnboardRejectsJavascriptScheme(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-onboard-js", "alice@example.com") + + body := `{"return_url":"javascript:alert(1)"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/onboard", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeOnboard(w, req) + + if w.Code != http.StatusBadRequest { + t.Errorf("got %d, want 400 on non-http scheme", w.Code) + } +} diff --git a/coordinator/api/billing/connect_retry.go b/coordinator/api/billing/connect_retry.go new file mode 100644 index 0000000000..75b45b7c84 --- /dev/null +++ b/coordinator/api/billing/connect_retry.go @@ -0,0 +1,88 @@ +package billing + +import ( + "errors" + "net/http" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// retryAmbiguousStripe retries fn while it fails with a non-definitive error +// (transport timeout, connection drop, lost response) — outcomes where an +// idempotency-keyed Stripe request may have been accepted. Replaying with the +// same key returns the original result instead of moving money twice, so the +// retry either recovers the lost response or surfaces Stripe's definitive +// rejection. Definitive API errors return immediately. Bounded at 3 attempts +// (0/200/400ms backoff), same budget as the other in-request retries. +func retryAmbiguousStripe[T any](fn func() (T, error)) (T, error) { + out, err := fn() + for attempt := 1; attempt <= 2 && err != nil && !billingservice.IsDefinitiveAPIErr(err); attempt++ { + time.Sleep(time.Duration(attempt) * 200 * time.Millisecond) + out, err = fn() + } + return out, err +} + +// creditRefundOnceWithRetry credits a reference-idempotent refund, riding out +// transient store blips with short retries (safe: duplicates are deduped on +// the ledger reference). Returns whether the credit is durably applied. +// +// The retries deliberately ignore the request context and run to completion: +// they only execute AFTER money has moved (or a debit landed), and a client +// disconnect must not abandon the user's refund. Worst case is bounded at +// 600ms of backoff (3 attempts × 0/200/400ms). +func (s *Controller) creditRefundOnceWithRetry(accountID string, amountMicroUSD int64, ref, withdrawalID string) bool { + for attempt := 0; attempt < 3; attempt++ { + if attempt > 0 { + time.Sleep(time.Duration(attempt) * 200 * time.Millisecond) + } + _, err := s.billing().Store().CreditWithdrawableOnce(accountID, amountMicroUSD, store.LedgerRefund, ref) + if err == nil { + return true + } + s.logger.Warn("stripe payout: refund credit attempt failed", + "attempt", attempt+1, "error", err, "withdrawal_id", withdrawalID, "ledger_ref", ref) + } + s.logger.Error("stripe payout: refund credit failed after retries — MANUAL CREDIT REQUIRED", + "withdrawal_id", withdrawalID, "ledger_ref", ref, "amount_micro_usd", amountMicroUSD) + return false +} + +// persistWithdrawalUpdate retries transient errors with the same expected state. +// A changed row returns immediately; retrying it must not overwrite a webhook. +// Used after money has moved (transfer/payout created): losing the update +// strands the row in a state the webhook matcher and sweep reconciler don't +// look at, so it's worth riding out a transient store blip in-request. Like +// creditRefundOnceWithRetry, it deliberately ignores request-context +// cancellation (bounded at 600ms total backoff) — abandoning the persist on +// client disconnect is exactly how rows get orphaned. +func (s *Controller) persistWithdrawalUpdate(previous, wd *store.StripeWithdrawal, stage string) error { + var err error + for attempt := 0; attempt < 3; attempt++ { + if attempt > 0 { + time.Sleep(time.Duration(attempt) * 200 * time.Millisecond) + } + var applied bool + applied, err = s.billing().Store().CompareAndSwapStripeWithdrawal(previous, wd) + if err == nil { + if !applied { + return errWithdrawalStateChanged + } + return nil + } + s.logger.Warn("stripe payout: persist "+stage+" attempt failed", + "attempt", attempt+1, "error", err, "withdrawal_id", wd.ID) + } + return err +} + +var errWithdrawalStateChanged = errors.New("withdrawal state changed during submission") + +func (s *Controller) writeWithdrawalStateChanged(w http.ResponseWriter, withdrawalID string) { + s.logger.Warn("stripe payout: submission state changed; preserving webhook state", "withdrawal_id", withdrawalID) + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("withdrawal_state_changed", + "your withdrawal was updated while it was being submitted — check its status before retrying")) +} diff --git a/coordinator/api/billing/connect_reversal_race_test.go b/coordinator/api/billing/connect_reversal_race_test.go new file mode 100644 index 0000000000..d080b09b71 --- /dev/null +++ b/coordinator/api/billing/connect_reversal_race_test.go @@ -0,0 +1,59 @@ +package billing + +import ( + "net/http" + "net/http/httptest" + "testing" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/payments" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// paidDuringReversalStore makes payout.paid win after reversal reads the row. +// Returning that old copy models the two independent webhook requests without +// relying on scheduler timing. +type paidDuringReversalStore struct { + *store.MemoryStore + t *testing.T +} + +func (s *paidDuringReversalStore) GetStripeWithdrawalByTransferID(id string) (*store.StripeWithdrawal, error) { + wd, err := s.MemoryStore.GetStripeWithdrawalByTransferID(id) + if err == nil { + applied, markErr := s.MarkStripeWithdrawalPaid(wd.ID, wd.PayoutID, "") + if markErr != nil || !applied { + s.t.Fatalf("concurrent payout completion: applied=%v err=%v", applied, markErr) + } + } + return wd, err +} + +func TestConnectWebhookReversalDoesNotRefundConcurrentlyPaidWithdrawal(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, mem := stripePayoutsTestServer(t, false, fakeStripe) + st := &paidDuringReversalStore{MemoryStore: mem, t: t} + srv.SetBilling(billingservice.NewService(st, payments.NewLedger(st), srv.logger, billingservice.Config{ + StripeSecretKey: "sk_test_fake", StripeConnectWebhookSecret: "whsec_test", + StripeConnectReturnURL: "https://app.test/billing", StripeConnectRefreshURL: "https://app.test/billing", + StripeConnectPlatformCountry: "US", + })) + user := readyUser(t, mem, "acct-reversal-race", "alice@example.com", false) + mkWithdrawal(t, mem, store.StripeWithdrawal{ + ID: "wd-reversal-race", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_reversal_race", PayoutID: "po_reversal_race", + }) + before := mem.GetBalance(user.AccountID) + if response := deliverConnectWebhook(t, srv, transferReversedPayload("tr_reversal_race")); response.Code != http.StatusOK { + t.Fatalf("webhook returned %d: %s", response.Code, response.Body.String()) + } + wd, err := mem.GetStripeWithdrawal("wd-reversal-race") + if err != nil { + t.Fatal(err) + } + if wd.Status != "paid" || wd.Refunded || mem.GetBalance(user.AccountID) != before { + t.Fatalf("concurrently paid withdrawal must stay unchanged for manual review: status=%s refunded=%v balance=%d want=%d", wd.Status, wd.Refunded, mem.GetBalance(user.AccountID), before) + } +} diff --git a/coordinator/api/billing/connect_status.go b/coordinator/api/billing/connect_status.go new file mode 100644 index 0000000000..bc1424b12e --- /dev/null +++ b/coordinator/api/billing/connect_status.go @@ -0,0 +1,135 @@ +package billing + +import ( + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" + billingservice "github.com/eigeninference/d-inference/coordinator/billing" +) + +// stripeStatusReady is the value of User.StripeAccountStatus when payouts are +// enabled on the Stripe side. The set of statuses tracks the StripeAccount +// lifecycle: "" (not onboarded) → "pending" (link created, not finished) → +// "ready" | "restricted" | "rejected". +const ( + stripeStatusPending = "pending" + stripeStatusReady = "ready" + stripeStatusRestricted = "restricted" + stripeStatusRejected = "rejected" +) + +// StripeStatus handles GET /v1/billing/stripe/status. +// Returns the full readiness/destination snapshot used by the billing UI to +// render the Withdraw → Bank panel. +func (s *Controller) StripeStatus(w http.ResponseWriter, r *http.Request) { + user := requestauth.RequirePrivyUser(w, r) + if user == nil { + return + } + if s.billing() == nil || s.billing().StripeConnect() == nil { + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"has_account": false, "configured": false}) + return + } + + if s.maybeGlobalStatus(w, r, user) { + return + } + resp := map[string]any{ + "account_id": user.AccountID, + "payout_rail": "connect", + "countries": s.payoutCountries(), + "has_account": user.StripeAccountID != "", + "configured": true, + "stripe_account_id": user.StripeAccountID, + "status": user.StripeAccountStatus, + "stripe_account_country": user.StripeAccountCountry, + "destination_type": user.StripeDestinationType, + "destination_last4": user.StripeDestinationLast4, + "instant_eligible": user.StripeInstantEligible, + "min_withdraw_micro_usd": billingservice.MinWithdrawMicroUSD, + "instant_fee_bps": billingservice.InstantFeeBps, + "instant_fee_min_usd": float64(billingservice.InstantFeeMinMicroUSD) / 1_000_000, + } + + // Optional refresh=1 query param fetches the latest snapshot from Stripe + // and rewrites our local state. The frontend hits this on return from the + // onboarding flow so the UI doesn't lag behind the webhook. + if user.StripeAccountID != "" && r.URL.Query().Get("refresh") == "1" { + acct, err := s.billing().StripeConnect().GetAccount(user.StripeAccountID) + switch { + case err != nil && billingservice.IsAccountGoneErr(err): + // The user closed their Stripe account — unlink it so the UI + // offers a fresh onboarding instead of a permanently broken state. + s.logger.Warn("stripe connect: stored account gone — unlinking", + "stripe_account_id", user.StripeAccountID, "error", err) + if perr := s.billing().Store().SetUserStripeAccount(user.AccountID, "", "", "", "", "", false); perr != nil { + s.logger.Error("stripe connect: unlink gone account failed", "error", perr) + } else { + resp["has_account"] = false + resp["stripe_account_id"] = "" + resp["status"] = "" + } + case err != nil: + s.logger.Warn("stripe connect: status refresh failed", "error", err) + default: + // Self-heal accounts created by older code with a manual payout + // schedule — a manual schedule strands transferred funds in the + // connected account ("Contact Eigen Labs, Inc. to get paid out"). + if acct.PayoutInterval == "manual" { + if herr := s.billing().StripeConnect().UpdateAccountPayoutScheduleAuto(user.StripeAccountID, acct.Country); herr != nil { + s.logger.Warn("stripe connect: payout schedule self-heal failed", + "stripe_account_id", user.StripeAccountID, "error", herr) + } else { + s.logger.Info("stripe connect: payout schedule healed to automatic", + "stripe_account_id", user.StripeAccountID) + } + } + status := stripeStatusForAccount(acct) + if err := s.billing().Store().SetUserStripeAccount(user.AccountID, user.StripeAccountID, + status, acct.Country, acct.DestinationType, acct.DestinationLast4, acct.InstantEligible); err != nil { + s.logger.Warn("stripe connect: status persist failed", "error", err) + } else { + resp["status"] = status + resp["stripe_account_country"] = acct.Country + resp["destination_type"] = acct.DestinationType + resp["destination_last4"] = acct.DestinationLast4 + resp["instant_eligible"] = acct.InstantEligible + resp["currently_due"] = acct.CurrentlyDue + } + } + } + + httpresponse.WriteJSON(w, http.StatusOK, resp) +} + +// stripeDashboardAvailable reports whether an account in the given local +// status has an Express Dashboard to log in to. Stripe only issues login +// links once the account has submitted its details, so the pre-submission +// states ("" and pending) have nothing to log in to. Restricted and rejected +// accounts DO have one — that's where Stripe explains what went wrong and +// lets them fix it. +func stripeDashboardAvailable(status string) bool { + switch status { + case stripeStatusReady, stripeStatusRestricted, stripeStatusRejected: + return true + default: + return false + } +} + +// stripeStatusForAccount maps a fresh Stripe account snapshot onto our local +// status enum. +func stripeStatusForAccount(acct *billingservice.ExpressAccount) string { + switch { + case acct.DisabledReason != "" && strings.HasPrefix(acct.DisabledReason, "rejected"): + return stripeStatusRejected + case acct.PayoutsEnabled: + return stripeStatusReady + case acct.DetailsSubmitted && len(acct.CurrentlyDue) > 0: + return stripeStatusRestricted + default: + return stripeStatusPending + } +} diff --git a/coordinator/api/billing/connect_status_test.go b/coordinator/api/billing/connect_status_test.go new file mode 100644 index 0000000000..590fa0edff --- /dev/null +++ b/coordinator/api/billing/connect_status_test.go @@ -0,0 +1,38 @@ +package billing + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +func TestStripeStatusReportsCurrentState(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-status-1", "alice@example.com") + _ = st.SetUserStripeAccount(user.AccountID, "acct_x", "ready", "", "card", "4242", true) + user, _ = st.GetUserByAccountID(user.AccountID) + + req := httptest.NewRequest(http.MethodGet, "/v1/billing/stripe/status", nil) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeStatus(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp["status"] != "ready" { + t.Errorf("status = %v", resp["status"]) + } + if resp["destination_type"] != "card" { + t.Errorf("destination_type = %v", resp["destination_type"]) + } + if resp["destination_last4"] != "4242" { + t.Errorf("destination_last4 = %v", resp["destination_last4"]) + } + if resp["instant_eligible"] != true { + t.Errorf("instant_eligible = %v", resp["instant_eligible"]) + } +} diff --git a/coordinator/api/billing/connect_sweep.go b/coordinator/api/billing/connect_sweep.go new file mode 100644 index 0000000000..af7938d6cf --- /dev/null +++ b/coordinator/api/billing/connect_sweep.go @@ -0,0 +1,235 @@ +package billing + +import ( + "time" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// stripeRecipientTransferDelay is how long a platform transfer takes to +// become available in a recipient-agreement connected account's balance +// (documented Stripe behavior: +24h). The sweep matcher uses it as the +// settlement-safe cutoff when attributing automatic payouts to rows. +const stripeRecipientTransferDelay = 24 * time.Hour + +// reconcileUnmatchedPayout maps an automatic sweep payout (created by Stripe's +// daily payout schedule, so its ID is unknown to us) back onto local +// withdrawal rows for the same connected account. +// +// Only automatic payouts reconcile: a dashboard/API payout we didn't create +// has no attributable rows, and blanket-claiming them would mark withdrawals +// paid that the payout may not cover. Rows with an in-flight instant payout +// of their own (PayoutID set) are skipped — their own payout.paid/failed +// drives them. +// +// We deliberately do NOT match on amount: a sweep payout is denominated in +// the connected account's settlement currency (EUR, AUD, …) after Stripe's +// FX conversion, so it is not comparable to our USD row amounts. A sweep +// covers the balance AVAILABLE at its creation time, so on payout.paid we +// mark every "transferred" row whose funds had become available by then as +// "paid". Transfers to recipient-agreement accounts take +24h to become +// available, so rows younger than that cannot be in this sweep — claiming +// them early would hide a row from the 48h stuck detector if the NEXT sweep +// then failed. Full-agreement transfers are available immediately, and their +// rows must be claimed by the same-day sweep (a later sweep may never come +// if the balance is empty). The availability delay is derived from the +// account's service agreement. +func (s *Controller) reconcileUnmatchedPayout(pe *billingservice.PayoutEvent, success bool) error { + if pe.ConnectedAcct == "" { + s.logger.Debug("stripe connect webhook: unknown payout without account", "payout_id", pe.ID) + return nil + } + if !pe.Automatic { + s.logger.Info("stripe connect webhook: ignoring non-automatic payout we didn't create", + "stripe_account_id", pe.ConnectedAcct, "payout_id", pe.ID, "success", success) + return nil + } + if !success { + // Sweep failed — funds stay in the connected balance and Stripe + // retries on the next scheduled payout (typically after the user + // fixes their bank details; account.updated flips them to + // "restricted" when Stripe requires action). No ledger movement, + // but rows this same sweep previously marked "paid" (its paid event + // can precede a bank bounce) must reopen so they stay observable. + return s.reopenSweepBouncedRows(pe) + } + + rows, err := s.billing().Store().ListStripeWithdrawalsForStripeAccount(pe.ConnectedAcct, "transferred") + if err != nil { + s.logger.Error("stripe connect webhook: sweep reconcile list failed", + "error", err, "stripe_account_id", pe.ConnectedAcct) + return err + } + if len(rows) == 0 { + return nil + } + + // Webhook delivery order is not guaranteed: a stale payout.paid can be + // delivered AFTER the same payout already failed (whose failure event, + // finding nothing stamped yet, was necessarily a no-op). Confirm the + // payout is still live-"paid" before attributing rows to it. + livePayout, perr := s.billing().StripeConnect().GetPayout(pe.ConnectedAcct, pe.ID) + if perr != nil { + if billingservice.IsAccountGoneErr(perr) { + s.logger.Warn("stripe connect webhook: sweep reconcile skipped — account gone", + "stripe_account_id", pe.ConnectedAcct, "payout_id", pe.ID) + return nil + } + s.logger.Error("stripe connect webhook: sweep payout live-status check failed", + "error", perr, "payout_id", pe.ID) + return perr // redeliver + } + if livePayout.Status != "paid" { + s.logger.Warn("stripe connect webhook: stale sweep payout.paid — payout is no longer paid, not claiming rows", + "payout_id", pe.ID, "live_status", livePayout.Status, + "stripe_account_id", pe.ConnectedAcct) + return nil + } + + // Settlement-safe cutoff: recipient-agreement transfers become available + // +24h after creation, so this sweep cannot contain them until then. + availabilityDelay := time.Duration(0) + acct, aerr := s.billing().StripeConnect().GetAccount(pe.ConnectedAcct) + if aerr != nil { + if billingservice.IsAccountGoneErr(aerr) { + // Account deleted after the sweep fired — nothing left to claim + // safely; the 48h reconciler surfaces any stragglers. + s.logger.Warn("stripe connect webhook: sweep reconcile skipped — account gone", + "stripe_account_id", pe.ConnectedAcct, "payout_id", pe.ID) + return nil + } + // Transient — redeliver rather than guess the wrong cutoff in + // either direction. + s.logger.Error("stripe connect webhook: sweep reconcile account fetch failed", + "error", aerr, "stripe_account_id", pe.ConnectedAcct) + return aerr + } + if billingservice.NormalizeServiceAgreement(acct.ServiceAgreement) == billingservice.ServiceAgreementRecipient { + availabilityDelay = stripeRecipientTransferDelay + } + + payoutCreated := time.Unix(pe.Created, 0) + settledBefore := payoutCreated.Add(-availabilityDelay) + + // The account list is capped (MaxStripeWithdrawalsByStatusLimit) and + // Stripe never redelivers an acked payout.paid — so keep claiming pages + // until a page comes back short or makes no progress. Claimed rows + // leave the "transferred" filter, so each iteration sees the remainder. + totalMarked := 0 + var firstErr error + for page := 0; page < 50; page++ { + if page > 0 { + rows, err = s.billing().Store().ListStripeWithdrawalsForStripeAccount(pe.ConnectedAcct, "transferred") + if err != nil { + s.logger.Error("stripe connect webhook: sweep reconcile list failed", + "error", err, "stripe_account_id", pe.ConnectedAcct) + firstErr = err + break + } + } + marked := 0 + for i := range rows { + wd := &rows[i] + if wd.PayoutID != "" { + continue // in-flight instant payout — its own webhook drives it + } + if wd.Refunded { + continue // ledger already refunded (legacy state) — never mark paid + } + // The row must have REACHED its current "transferred" state + // (UpdatedAt ≈ when the transfer completed) at least the + // availability delay before the sweep was cut — a row that was + // still pending, mid-transfer, or inside the recipient +24h + // window when the sweep was created cannot have its funds in + // that sweep. Anchoring on UpdatedAt rather than CreatedAt also + // covers rows that sat parked/pending long after creation, and + // rows reopened by a sweep bounce (fresh UpdatedAt), so a + // redelivered payout.paid from the OLD (bounced) sweep can't + // re-claim them — only a sweep cut after the funds actually + // (re-)settled completes the row. + if pe.Created > 0 && wd.UpdatedAt.After(settledBefore) { + continue + } + // Guarded flip (store-side): a concurrent refund/failure + // delivery can't be overwritten by this loop's stale copy, and + // the payout_id='' condition rejects rows that acquired an + // in-flight payout since our read. The sweep payout ID is + // stamped so a later bounce (payout.failed after paid) can + // reopen exactly these rows via reopenSweepBouncedRows. + applied, merr := s.billing().Store().MarkStripeWithdrawalPaid(wd.ID, "", pe.ID) + if merr != nil { + s.logger.Error("stripe connect webhook: sweep mark paid failed", + "error", merr, "withdrawal_id", wd.ID) + if firstErr == nil { + firstErr = merr + } + continue + } + if applied { + marked++ + } + } + totalMarked += marked + if firstErr != nil || marked == 0 || len(rows) < store.MaxStripeWithdrawalsByStatusLimit { + break + } + } + if totalMarked > 0 { + s.logger.Info("stripe connect webhook: sweep payout reconciled", + "stripe_account_id", pe.ConnectedAcct, "payout_id", pe.ID, "withdrawals_paid", totalMarked) + } + // A partial failure redelivers; rows already marked "paid" drop out of + // the "transferred" list, so the retry only touches the stragglers. + return firstErr +} + +// reopenSweepBouncedRows handles payout.failed / payout.canceled for an +// automatic sweep payout. Funds are back in the connected balance and the +// next scheduled sweep retries, so there is no ledger movement — but rows +// this same sweep already marked "paid" (its paid event can precede a bank +// bounce by days) must reopen to "transferred": left "paid" they would hide +// funds that are actually parked in the connected balance from both the +// sweep matcher and the 48h stuck detector. Rows are found via the +// SweepPayoutID stamped when the sweep claimed them; rows claimed by other +// sweeps are untouched. +func (s *Controller) reopenSweepBouncedRows(pe *billingservice.PayoutEvent) error { + // Looked up by the sweep stamp directly (not by scanning the account's + // paid rows): exact, and immune to any per-account list bound. + paid, err := s.billing().Store().ListStripeWithdrawalsBySweepPayoutID(pe.ID) + if err != nil { + s.logger.Error("stripe connect webhook: sweep bounce list failed", + "error", err, "stripe_account_id", pe.ConnectedAcct) + return err // redeliver + } + reopened := 0 + var firstErr error + for i := range paid { + wd := &paid[i] + if wd.Status != "paid" || wd.Refunded { + continue + } + reason := "sweep_payout_failed " + pe.FailureCode + ": " + pe.FailureReason + + " (payout " + pe.ID + "; next sweep will retry)" + // The snapshot can outlive another bounce and a newer paid sweep. + // Recheck ownership and terminal state atomically inside the store. + applied, err := s.billing().Store().ReopenStripeWithdrawalAfterSweepFailure(wd.ID, pe.ID, reason) + if err != nil { + s.logger.Error("stripe connect webhook: sweep bounce reopen failed", + "error", err, "withdrawal_id", wd.ID) + if firstErr == nil { + firstErr = err + } + continue + } + if applied { + reopened++ + } + } + s.logger.Warn("stripe connect webhook: sweep payout failed — will retry on next schedule", + "stripe_account_id", pe.ConnectedAcct, "payout_id", pe.ID, + "failure_code", pe.FailureCode, "reopened_withdrawals", reopened) + // Partial persist failures redeliver; reopened rows drop out of the + // "paid" list, so the retry only touches the stragglers. + return firstErr +} diff --git a/coordinator/api/billing/connect_sweep_bounce_race_test.go b/coordinator/api/billing/connect_sweep_bounce_race_test.go new file mode 100644 index 0000000000..cb2a6239bf --- /dev/null +++ b/coordinator/api/billing/connect_sweep_bounce_race_test.go @@ -0,0 +1,62 @@ +package billing + +import ( + "net/http" + "testing" + "time" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/payments" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Return the old sweep's snapshot after a concurrent bounce delivery has +// reopened the row and a newer sweep has completed it. +type replacedSweepStore struct { + *store.MemoryStore + t *testing.T +} + +func (s *replacedSweepStore) ListStripeWithdrawalsBySweepPayoutID(id string) ([]store.StripeWithdrawal, error) { + rows, err := s.MemoryStore.ListStripeWithdrawalsBySweepPayoutID(id) + for _, row := range rows { + row.Status, row.SweepPayoutID = "transferred", "" + if err := s.MemoryStore.UpdateStripeWithdrawal(&row); err != nil { + s.t.Fatal(err) + } + if applied, err := s.MemoryStore.MarkStripeWithdrawalPaid(row.ID, "", "po_new"); err != nil || !applied { + s.t.Fatalf("new sweep completion: applied=%v err=%v", applied, err) + } + } + return rows, err +} + +func TestConnectWebhookOldSweepBouncePreservesNewSweepCompletion(t *testing.T) { + fakeStripe := accountServingStripe("full") + defer fakeStripe.Close() + srv, mem := stripePayoutsTestServer(t, false, fakeStripe) + st := &replacedSweepStore{MemoryStore: mem, t: t} + srv.SetBilling(billingservice.NewService(st, payments.NewLedger(st), srv.logger, billingservice.Config{ + StripeSecretKey: "sk_test_fake", StripeConnectWebhookSecret: "whsec_test", + StripeConnectReturnURL: "https://app.test/billing", StripeConnectRefreshURL: "https://app.test/billing", + StripeConnectPlatformCountry: "US", + })) + user := readyUser(t, mem, "acct-sweep-race", "alice@example.com", false) + mkWithdrawal(t, mem, store.StripeWithdrawal{ + ID: "wd-sweep-race", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "paid", TransferID: "tr_sweep_race", SweepPayoutID: "po_old", + }) + before := mem.GetBalance(user.AccountID) + response := deliverConnectWebhook(t, srv, payoutEventPayload("po_old", user.StripeAccountID, "failed", true, time.Now().Unix())) + if response.Code != http.StatusOK { + t.Fatalf("webhook returned %d: %s", response.Code, response.Body.String()) + } + wd, err := mem.GetStripeWithdrawal("wd-sweep-race") + if err != nil { + t.Fatal(err) + } + if wd.Status != "paid" || wd.SweepPayoutID != "po_new" || mem.GetBalance(user.AccountID) != before { + t.Fatalf("new sweep completion overwritten: status=%s sweep=%q balance=%d want=%d", wd.Status, wd.SweepPayoutID, mem.GetBalance(user.AccountID), before) + } +} diff --git a/coordinator/api/billing/connect_sweep_legacy_test.go b/coordinator/api/billing/connect_sweep_legacy_test.go new file mode 100644 index 0000000000..1f015c2eb2 --- /dev/null +++ b/coordinator/api/billing/connect_sweep_legacy_test.go @@ -0,0 +1,99 @@ +package billing + +import ( + "net/http" + "net/http/httptest" + "strconv" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestConnectWebhookSweepPayoutPaidMarksTransferredRows(t *testing.T) { + // Standard withdrawals have no payout ID — Stripe's automatic daily sweep + // delivers them. When the sweep's payout.paid arrives (an ID we never + // recorded), every "transferred" row for that connected account whose + // funds had settled by the sweep's creation must flip to "paid". This + // account is under the full agreement, so transfers settle immediately. + fakeStripe := accountServingStripe("full") + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-wh-sweep", "alice@example.com", false) + + sweepTime := time.Now() + mk := func(id string, createdAt time.Time, status string) { + t.Helper() + if err := st.CreateStripeWithdrawal(&store.StripeWithdrawal{ + ID: id, AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: status, CreatedAt: createdAt, + }); err != nil { + t.Fatalf("create withdrawal %s: %v", id, err) + } + } + mk("wd-sw-old-1", sweepTime.Add(-48*time.Hour), "transferred") + mk("wd-sw-old-2", sweepTime.Add(-1*time.Hour), "transferred") + mk("wd-sw-after", sweepTime.Add(2*time.Hour), "transferred") // transferred after the sweep was cut + mk("wd-sw-paid", sweepTime.Add(-3*time.Hour), "paid") // already terminal + + payload := []byte(`{ + "type":"payout.paid","account":"` + user.StripeAccountID + `", + "data":{"object":{"id":"po_sweep_unknown","status":"paid","amount":1000,"method":"standard", + "automatic":true,"created":` + strconv.FormatInt(sweepTime.Unix(), 10) + `}} + }`) + req := signedConnectRequest(t, payload, "whsec_test") + w := httptest.NewRecorder() + srv.StripeConnectWebhook(w, req) + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + + want := map[string]string{ + "wd-sw-old-1": "paid", + "wd-sw-old-2": "paid", + "wd-sw-after": "transferred", + "wd-sw-paid": "paid", + } + for id, wantStatus := range want { + wd, _ := st.GetStripeWithdrawal(id) + if wd.Status != wantStatus { + t.Errorf("%s: status = %q, want %q", id, wd.Status, wantStatus) + } + } +} + +func TestConnectWebhookSweepPayoutFailedLeavesRowsAlone(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-wh-sweepfail", "alice@example.com", false) + _ = st.CreateStripeWithdrawal(&store.StripeWithdrawal{ + ID: "wd-swf-1", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", CreatedAt: time.Now().Add(-2 * time.Hour), + }) + + payload := []byte(`{ + "type":"payout.failed","account":"` + user.StripeAccountID + `", + "data":{"object":{"id":"po_sweep_fail","status":"failed","amount":500,"method":"standard", + "automatic":true,"created":` + strconv.FormatInt(time.Now().Unix(), 10) + `, + "failure_code":"account_closed","failure_message":"closed"}} + }`) + req := signedConnectRequest(t, payload, "whsec_test") + w := httptest.NewRecorder() + srv.StripeConnectWebhook(w, req) + if w.Code != http.StatusOK { + t.Fatalf("got %d", w.Code) + } + + wd, _ := st.GetStripeWithdrawal("wd-swf-1") + if wd.Status != "transferred" { + t.Errorf("status = %q, want transferred (sweep retries on next schedule)", wd.Status) + } + if wd.Refunded { + t.Error("no ledger refund on sweep failure") + } +} diff --git a/coordinator/api/billing/connect_sweep_test.go b/coordinator/api/billing/connect_sweep_test.go new file mode 100644 index 0000000000..78d72f9961 --- /dev/null +++ b/coordinator/api/billing/connect_sweep_test.go @@ -0,0 +1,255 @@ +package billing + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// TestConnectWebhookSweepSkipsRowsWithInFlightPayout: the sweep matcher must +// not claim withdrawals that have their own instant payout still in flight — +// that payout may yet fail. +func TestConnectWebhookSweepSkipsRowsWithInFlightPayout(t *testing.T) { + fakeStripe := accountServingStripe("full") + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-sweep-skip", "alice@example.com", true) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-standard", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_std", + }) + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-instant-inflight", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, FeeMicroUSD: 500_000, NetMicroUSD: 4_500_000, + Method: "instant", Status: "transferred", TransferID: "tr_inf", PayoutID: "po_inflight", + }) + + w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_sweep_x", user.StripeAccountID, "paid", true, time.Now().Add(time.Hour).Unix())) + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + + std, _ := st.GetStripeWithdrawal("wd-standard") + if std.Status != "paid" { + t.Errorf("standard row = %q, want paid", std.Status) + } + inflight, _ := st.GetStripeWithdrawal("wd-instant-inflight") + if inflight.Status != "transferred" { + t.Errorf("in-flight instant row = %q, want transferred (its own webhook drives it)", inflight.Status) + } +} + +// TestConnectWebhookSweepRecipientCutoffSkipsUnsettledRows: transfers to +// recipient-agreement accounts take +24h to become available, so a sweep +// cannot contain a transfer younger than that — claiming it early would hide +// the row from the 48h stuck detector if the next sweep failed. Rows past +// the availability delay are claimed; younger rows wait for the next sweep. +func TestConnectWebhookSweepRecipientCutoffSkipsUnsettledRows(t *testing.T) { + fakeStripe := accountServingStripe("recipient") + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-sweep-recipient", "alice@example.com", false) + + sweepTime := time.Now() + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-rec-settled", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_rs", + CreatedAt: sweepTime.Add(-30 * time.Hour), // past the +24h availability delay + }) + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-rec-unsettled", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_ru", + CreatedAt: sweepTime.Add(-2 * time.Hour), // still inside the delay window + }) + + w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_sweep_rec", user.StripeAccountID, "paid", true, sweepTime.Unix())) + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + + settled, _ := st.GetStripeWithdrawal("wd-rec-settled") + if settled.Status != "paid" { + t.Errorf("settled row = %q, want paid", settled.Status) + } + unsettled, _ := st.GetStripeWithdrawal("wd-rec-unsettled") + if unsettled.Status != "transferred" { + t.Errorf("unsettled row = %q, want transferred (funds could not be in this sweep)", unsettled.Status) + } +} + +// TestConnectWebhookNonAutomaticPayoutDoesNotReconcile: a dashboard/API +// payout we didn't create must not blanket-mark rows paid — only Stripe's +// automatic sweep payouts reconcile by account. +func TestConnectWebhookNonAutomaticPayoutDoesNotReconcile(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-manual-po", "alice@example.com", false) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-manual-po", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_mp", + }) + + w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_dashboard", user.StripeAccountID, "paid", false, time.Now().Add(time.Hour).Unix())) + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + wd, _ := st.GetStripeWithdrawal("wd-manual-po") + if wd.Status != "transferred" { + t.Errorf("status = %q, want transferred (non-automatic payouts don't reconcile)", wd.Status) + } +} + +// TestConnectWebhookSweepBounceReopensClaimedRows: when an automatic sweep's +// payout.failed arrives after its payout.paid (bank bounce), the rows that +// sweep claimed must reopen to "transferred" — otherwise money parked back +// in the connected balance hides behind terminal "paid" rows. Rows claimed +// by OTHER sweeps stay paid. +func TestConnectWebhookSweepBounceReopensClaimedRows(t *testing.T) { + fakeStripe := accountServingStripe("full") + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-sweep-bounce", "alice@example.com", false) + + sweepTime := time.Now() + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-sb-1", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_sb1", + CreatedAt: sweepTime.Add(-3 * time.Hour), + }) + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-sb-2", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 3_000_000, NetMicroUSD: 3_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_sb2", + CreatedAt: sweepTime.Add(-4 * time.Hour), + }) + // Claimed by an OLDER sweep — must stay paid. + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-sb-old", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 2_000_000, NetMicroUSD: 2_000_000, + Method: "standard", Status: "paid", TransferID: "tr_sb0", SweepPayoutID: "po_sweep_old", + CreatedAt: sweepTime.Add(-48 * time.Hour), + }) + balBefore := st.GetBalance(user.AccountID) + + // The sweep pays: both transferred rows are claimed and stamped. + if w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_sweep_b", user.StripeAccountID, "paid", true, sweepTime.Unix())); w.Code != http.StatusOK { + t.Fatalf("sweep paid got %d: %s", w.Code, w.Body.String()) + } + for _, id := range []string{"wd-sb-1", "wd-sb-2"} { + wd, _ := st.GetStripeWithdrawal(id) + if wd.Status != "paid" || wd.SweepPayoutID != "po_sweep_b" { + t.Fatalf("%s = status %q sweep %q, want paid/po_sweep_b", id, wd.Status, wd.SweepPayoutID) + } + } + + // The same sweep bounces: its rows reopen; the older sweep's row stays. + if w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_sweep_b", user.StripeAccountID, "failed", true, sweepTime.Unix())); w.Code != http.StatusOK { + t.Fatalf("sweep failed got %d: %s", w.Code, w.Body.String()) + } + for _, id := range []string{"wd-sb-1", "wd-sb-2"} { + wd, _ := st.GetStripeWithdrawal(id) + if wd.Status != "transferred" || wd.SweepPayoutID != "" { + t.Errorf("%s = status %q sweep %q, want transferred/empty (reopened)", id, wd.Status, wd.SweepPayoutID) + } + if !strings.Contains(wd.FailureReason, "sweep_payout_failed") { + t.Errorf("%s failure reason = %q", id, wd.FailureReason) + } + } + old, _ := st.GetStripeWithdrawal("wd-sb-old") + if old.Status != "paid" || old.SweepPayoutID != "po_sweep_old" { + t.Errorf("older sweep's row = status %q sweep %q, want paid/po_sweep_old (untouched)", old.Status, old.SweepPayoutID) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore { + t.Errorf("sweep bounce moved the ledger: %d -> %d", balBefore, bal) + } + + // A redelivered payout.paid from the BOUNCED sweep must not re-claim the + // reopened rows: their reopen bumped UpdatedAt past the old sweep's + // creation time, so only a sweep cut AFTER the reopen (one that can + // actually contain the re-parked funds) may complete them. + if w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_sweep_b", user.StripeAccountID, "paid", true, sweepTime.Unix())); w.Code != http.StatusOK { + t.Fatalf("stale sweep paid redelivery got %d: %s", w.Code, w.Body.String()) + } + for _, id := range []string{"wd-sb-1", "wd-sb-2"} { + wd, _ := st.GetStripeWithdrawal(id) + if wd.Status != "transferred" { + t.Errorf("%s re-claimed by the bounced sweep's stale paid event: status %q", id, wd.Status) + } + } + + // A NEW sweep cut after the reopen delivers and completes them. + if w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_sweep_b2", user.StripeAccountID, "paid", true, time.Now().Add(time.Hour).Unix())); w.Code != http.StatusOK { + t.Fatalf("retry sweep paid got %d: %s", w.Code, w.Body.String()) + } + for _, id := range []string{"wd-sb-1", "wd-sb-2"} { + wd, _ := st.GetStripeWithdrawal(id) + if wd.Status != "paid" || wd.SweepPayoutID != "po_sweep_b2" { + t.Errorf("%s = status %q sweep %q, want paid/po_sweep_b2 (claimed by the retry sweep)", id, wd.Status, wd.SweepPayoutID) + } + } +} + +// TestConnectWebhookStaleSweepPaidForFailedPayoutNoClaim: webhook delivery +// order isn't guaranteed — a payout.failed can be DELIVERED before the same +// sweep's payout.paid. The paid handler verifies the payout's live status +// with Stripe before claiming rows; a payout that already failed claims +// nothing (the funds are back in the balance and the next sweep delivers). +func TestConnectWebhookStaleSweepPaidForFailedPayoutNoClaim(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/accounts/") { + id := strings.TrimPrefix(r.URL.Path, "/v1/accounts/") + _, _ = w.Write([]byte(healthyAccountJSON(id, "US", "full", false))) + return + } + if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/payouts/") { + id := strings.TrimPrefix(r.URL.Path, "/v1/payouts/") + _, _ = w.Write([]byte(`{"id":"` + id + `","status":"failed","amount":450,"method":"standard","failure_code":"could_not_process"}`)) + return + } + })) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-stale-sweep", "alice@example.com", false) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-stale-sweep", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_ss", + CreatedAt: time.Now().Add(-3 * time.Hour), + }) + + // The failure was delivered first: no rows were stamped, so it was a + // no-op. The stale paid event arrives afterwards. + if w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_stale_sweep", user.StripeAccountID, "failed", true, time.Now().Unix())); w.Code != http.StatusOK { + t.Fatalf("failed delivery got %d", w.Code) + } + if w := deliverConnectWebhook(t, srv, + payoutEventPayload("po_stale_sweep", user.StripeAccountID, "paid", true, time.Now().Unix())); w.Code != http.StatusOK { + t.Fatalf("stale paid delivery got %d", w.Code) + } + + wd, _ := st.GetStripeWithdrawal("wd-stale-sweep") + if wd.Status != "transferred" { + t.Errorf("status = %q, want transferred (live payout status is failed — nothing claimed)", wd.Status) + } +} diff --git a/coordinator/api/billing/connect_transfer_reversal.go b/coordinator/api/billing/connect_transfer_reversal.go new file mode 100644 index 0000000000..c1887b815c --- /dev/null +++ b/coordinator/api/billing/connect_transfer_reversal.go @@ -0,0 +1,91 @@ +package billing + +import ( + "errors" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// handleTransferFailed handles the rare case where Stripe rolls back a transfer +// after we've considered it successful. This is the only event that re-credits +// the ledger principal: the money is actually back at the platform. +// +// Only FULL reversals (reversed=true, i.e. amount_reversed == amount) refund +// automatically and terminalize the row; partial reversals are ops-initiated +// and alert for manual review instead (see the inline comment). +// +// The refund is split into two reference-idempotent credits — principal-net +// (gross − fee) and the fee — so it composes with the instant-fee refund +// path: whichever path credited the fee first wins, and no interleaving of +// crashes and redeliveries can pay either part twice. +func (s *Controller) handleTransferFailed(event *billingservice.WebhookEvent) error { + te, err := s.billing().StripeConnect().TransferFromEvent(event) + if err != nil { + s.logger.Warn("stripe connect webhook: transfer parse failed", "error", err) + return nil + } + wd, err := s.billing().Store().GetStripeWithdrawalByTransferID(te.ID) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + return nil // not a transfer we created + } + s.logger.Error("stripe connect webhook: transfer lookup failed", + "transfer_id", te.ID, "error", err) + return err + } + if wd.Status == "paid" { + // The user's bank payout completed AND the transfer reversed — an + // ambiguous clawback state. Never auto-refund a paid row; surface it + // for a human decision. + s.logger.Error("stripe connect webhook: transfer reversed on an already-paid withdrawal — manual review required", + "withdrawal_id", wd.ID, "transfer_id", te.ID, "stripe_account_id", wd.StripeAccountID) + return nil + } + if wd.Refunded { + // Terminal (covers legacy rows refunded under the old semantics). + // This status flip is what keeps the already-refunded row out of + // sweep reconciliation — if it fails, return the error so Stripe + // redelivers rather than leaving a refunded row claimable. + if wd.Status != "failed" { + next := *wd + next.Status = "failed" + if _, err := s.billing().Store().CompareAndSwapStripeWithdrawal(wd, &next); err != nil { + s.logger.Error("stripe connect webhook: refunded-row status flip failed", + "error", err, "withdrawal_id", wd.ID) + return err + } + } + return nil + } + if !te.Reversed { + // PARTIAL reversal: Stripe only sets reversed=true once + // amount_reversed == amount. Our code never creates reversals, so a + // partial one is always a deliberate ops action in the dashboard — + // often precisely because the ledger was already adjusted by hand + // (e.g. clawing back a historical double-refund). Auto-crediting the + // full net here would over-pay, and auto-crediting the partial + // amount can double-pay against the manual adjustment the reversal + // is compensating for. No automatic ledger movement: surface for + // the human who initiated it. The row stays non-terminal so the + // sweep/reconciler keep watching the remaining funds. + s.logger.Error("stripe connect webhook: PARTIAL transfer reversal — no automatic refund, manual ledger review required", + "withdrawal_id", wd.ID, "transfer_id", te.ID, + "amount_cents", te.AmountCents, "amount_reversed_cents", te.AmountReversedCents, + "stripe_account_id", wd.StripeAccountID) + return nil + } + // Recheck the current row while locking it for the whole refund. A + // payout.paid that won after the lookup must not receive an automatic + // refund, and a credit cannot become visible before the terminal state. + applied, err := s.billing().Store().RefundStripeWithdrawalAfterReversal(wd.ID, te.ID) + if err != nil { + s.logger.Error("stripe connect webhook: reversal settlement failed", "error", err, "withdrawal_id", wd.ID) + return err + } + if !applied { + s.logger.Warn("stripe connect webhook: reversal not applied — withdrawal changed concurrently, review current state", + "withdrawal_id", wd.ID, "transfer_id", te.ID) + } + return nil +} diff --git a/coordinator/api/billing/connect_transfer_reversal_test.go b/coordinator/api/billing/connect_transfer_reversal_test.go new file mode 100644 index 0000000000..ece0b7be93 --- /dev/null +++ b/coordinator/api/billing/connect_transfer_reversal_test.go @@ -0,0 +1,267 @@ +package billing + +import ( + "net/http" + "net/http/httptest" + "strconv" + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func transferReversedPayload(transferID string) []byte { + return []byte(`{ + "type":"transfer.reversed","account":"", + "data":{"object":{"id":"` + transferID + `","amount":450,"amount_reversed":450,"reversed":true}} + }`) +} + +// partialTransferReversedPayload models a partial reversal: amount_reversed < +// amount, and Stripe keeps reversed=false until the transfer is fully undone. +func partialTransferReversedPayload(transferID string, amountReversed int) []byte { + return []byte(`{ + "type":"transfer.reversed","account":"", + "data":{"object":{"id":"` + transferID + `","amount":450,"amount_reversed":` + + strconv.Itoa(amountReversed) + `,"reversed":false}} + }`) +} + +// TestConnectWebhookPartialTransferReversalNoAutoRefund: partial reversals +// (always ops-initiated — our code never creates them) must not auto-credit +// the ledger or terminalize the row: crediting the full net would over-pay, +// and even the partial amount may be compensating a manual ledger adjustment. +// A later FULL reversal still makes the user whole exactly once. +func TestConnectWebhookPartialTransferReversalNoAutoRefund(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-rev-partial", "alice@example.com", false) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-rev-partial", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_partial", + }) + balBefore := st.GetBalance(user.AccountID) + + // Partial reversal: no ledger movement, row stays non-terminal. + if w := deliverConnectWebhook(t, srv, partialTransferReversedPayload("tr_partial", 200)); w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + wd, _ := st.GetStripeWithdrawal("wd-rev-partial") + if wd.Status != "transferred" || wd.Refunded { + t.Errorf("row = status %q refunded=%v, want transferred/false (manual review only)", wd.Status, wd.Refunded) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore { + t.Errorf("partial reversal moved the ledger: %d -> %d", balBefore, bal) + } + + // The reversal is later completed: normal full-reversal semantics. + if w := deliverConnectWebhook(t, srv, transferReversedPayload("tr_partial")); w.Code != http.StatusOK { + t.Fatalf("full reversal got %d", w.Code) + } + wd, _ = st.GetStripeWithdrawal("wd-rev-partial") + if wd.Status != "failed" || !wd.Refunded { + t.Errorf("row = status %q refunded=%v, want failed/true", wd.Status, wd.Refunded) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore+5_000_000 { + t.Errorf("balance = %d, want %d (refunded exactly once, on full reversal)", bal, balBefore+5_000_000) + } +} + +// TestConnectWebhookTransferReversedNetsOutRefundedFee: if the instant fee +// was already credited back (instant payout fell through), a later +// transfer.reversed must refund gross − fee, not gross — otherwise the user +// is paid the fee twice. The fee credit is deduped on its ledger reference. +func TestConnectWebhookTransferReversedNetsOutRefundedFee(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-rev-fee", "alice@example.com", true) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-rev-fee", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, FeeMicroUSD: 500_000, NetMicroUSD: 4_500_000, + Method: "instant", Status: "transferred", TransferID: "tr_rev", + FeeRefunded: true, // fee credited when the instant payout fell through… + }) + // …which in production wrote this ledger entry — the dedup key. + if err := st.CreditWithdrawable(user.AccountID, 500_000, store.LedgerRefund, + "stripe_withdraw_fee:wd-rev-fee"); err != nil { + t.Fatal(err) + } + balBefore := st.GetBalance(user.AccountID) + + if w := deliverConnectWebhook(t, srv, transferReversedPayload("tr_rev")); w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + + wd, _ := st.GetStripeWithdrawal("wd-rev-fee") + if wd.Status != "failed" || !wd.Refunded { + t.Errorf("row = status %q refunded=%v, want failed/true", wd.Status, wd.Refunded) + } + // Refund is gross − fee = 4_500_000, NOT the full 5_000_000. + if bal := st.GetBalance(user.AccountID); bal != balBefore+4_500_000 { + t.Errorf("balance = %d, want %d (gross minus already-refunded fee)", bal, balBefore+4_500_000) + } +} + +// TestConnectWebhookTransferReversedDedupesFeeByLedgerRef: the fee dedupe +// must hold even when the FeeRefunded FLAG was lost (persist failure after +// the fee credit landed) — the ledger reference, not the flag, is the source +// of truth. +func TestConnectWebhookTransferReversedDedupesFeeByLedgerRef(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-rev-flagless", "alice@example.com", true) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-rev-flagless", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, FeeMicroUSD: 500_000, NetMicroUSD: 4_500_000, + Method: "instant", Status: "transferred", TransferID: "tr_rev_fl", + FeeRefunded: false, // flag lost… + }) + // …but the fee credit itself landed under its ledger reference. + if err := st.CreditWithdrawable(user.AccountID, 500_000, store.LedgerRefund, + "stripe_withdraw_fee:wd-rev-flagless"); err != nil { + t.Fatal(err) + } + balBefore := st.GetBalance(user.AccountID) + + if w := deliverConnectWebhook(t, srv, transferReversedPayload("tr_rev_fl")); w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + // Only the net part credits; the fee ref already exists. + if bal := st.GetBalance(user.AccountID); bal != balBefore+4_500_000 { + t.Errorf("balance = %d, want %d (fee deduped by ledger ref despite lost flag)", bal, balBefore+4_500_000) + } +} + +// TestConnectWebhookTransferReversedRefundsGrossWhenFeeNotRefunded: with no +// prior fee refund, a reversal refunds the full gross (net + fee parts). +func TestConnectWebhookTransferReversedRefundsGrossWhenFeeNotRefunded(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-rev-gross", "alice@example.com", true) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-rev-gross", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, FeeMicroUSD: 500_000, NetMicroUSD: 4_500_000, + Method: "instant", Status: "transferred", TransferID: "tr_rev_g", + }) + balBefore := st.GetBalance(user.AccountID) + + if w := deliverConnectWebhook(t, srv, transferReversedPayload("tr_rev_g")); w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore+5_000_000 { + t.Errorf("balance = %d, want %d (full gross)", bal, balBefore+5_000_000) + } + + // Redelivery is a no-op: row is Refunded, credits are reference-deduped. + if w := deliverConnectWebhook(t, srv, transferReversedPayload("tr_rev_g")); w.Code != http.StatusOK { + t.Fatalf("redelivery got %d", w.Code) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore+5_000_000 { + t.Errorf("redelivery double-credited: balance = %d", bal) + } +} + +// TestConnectWebhookTransferReversedOnPaidRowNeedsHuman: a reversal landing +// on an already-paid withdrawal (bank payout completed, then clawback) is +// ambiguous — never auto-refund, leave the row paid for manual review. +func TestConnectWebhookTransferReversedOnPaidRowNeedsHuman(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-rev-paid", "alice@example.com", false) + + mkWithdrawal(t, st, store.StripeWithdrawal{ + ID: "wd-rev-paid", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "paid", TransferID: "tr_rev_p", + }) + balBefore := st.GetBalance(user.AccountID) + + if w := deliverConnectWebhook(t, srv, transferReversedPayload("tr_rev_p")); w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + wd, _ := st.GetStripeWithdrawal("wd-rev-paid") + if wd.Status != "paid" || wd.Refunded { + t.Errorf("row = status %q refunded=%v, want paid/false (manual review)", wd.Status, wd.Refunded) + } + if bal := st.GetBalance(user.AccountID); bal != balBefore { + t.Errorf("balance moved on a paid row: %d -> %d", balBefore, bal) + } +} + +// A failed reversal transaction returns 500 without changing the balance; +// webhook redelivery settles it once with both the refund and terminal state. +func TestConnectWebhookTransferReversedConvergesAcrossPersistFailure(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, flaky := newFlakyPayoutServer(t, fakeStripe) + user := readyUser(t, flaky.MemoryStore, "acct-rev-conv", "alice@example.com", false) + + mkWithdrawal(t, flaky.MemoryStore, store.StripeWithdrawal{ + ID: "wd-rev-conv", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_conv", + }) + balBefore := flaky.GetBalance(user.AccountID) + + flaky.failReversals = true + if w := deliverConnectWebhook(t, srv, transferReversedPayload("tr_conv")); w.Code != http.StatusInternalServerError { + t.Fatalf("got %d, want 500 (persist failed — Stripe must redeliver)", w.Code) + } + if bal := flaky.GetBalance(user.AccountID); bal != balBefore { + t.Fatalf("failed reversal moved balance: %d, want %d", bal, balBefore) + } + + flaky.failReversals = false + if w := deliverConnectWebhook(t, srv, transferReversedPayload("tr_conv")); w.Code != http.StatusOK { + t.Fatalf("redelivery got %d", w.Code) + } + if bal := flaky.GetBalance(user.AccountID); bal != balBefore+5_000_000 { + t.Errorf("redelivery double-credited: balance = %d", bal) + } + wd, _ := flaky.GetStripeWithdrawal("wd-rev-conv") + if wd.Status != "failed" || !wd.Refunded { + t.Errorf("row = status %q refunded=%v, want failed/true", wd.Status, wd.Refunded) + } +} + +// TestConnectWebhookTransientLookupErrorReturns500: a transient store failure +// on the payout lookup must NOT fall through to account-wide sweep +// reconciliation (which could claim unrelated rows) — it responds non-2xx so +// Stripe redelivers. +func TestConnectWebhookRefundedRowFlipRedelivers(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, flaky := newFlakyPayoutServer(t, fakeStripe) + user := readyUser(t, flaky.MemoryStore, "acct-ref-flip", "alice@example.com", false) + + // Legacy shape: ledger refunded but row never flipped to failed. + mkWithdrawal(t, flaky.MemoryStore, store.StripeWithdrawal{ + ID: "wd-ref-flip", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", TransferID: "tr_rf_flip", + Refunded: true, + }) + + flaky.failUpdates = true + if w := deliverConnectWebhook(t, srv, transferReversedPayload("tr_rf_flip")); w.Code != http.StatusInternalServerError { + t.Fatalf("got %d, want 500 (persist failed — Stripe must redeliver)", w.Code) + } + + flaky.failUpdates = false + if w := deliverConnectWebhook(t, srv, transferReversedPayload("tr_rf_flip")); w.Code != http.StatusOK { + t.Fatalf("redelivery got %d", w.Code) + } + wd, _ := flaky.GetStripeWithdrawal("wd-ref-flip") + if wd.Status != "failed" { + t.Errorf("status = %q, want failed (terminal, out of sweep reconciliation)", wd.Status) + } +} diff --git a/coordinator/api/billing/connect_webhook.go b/coordinator/api/billing/connect_webhook.go new file mode 100644 index 0000000000..f912e62e3f --- /dev/null +++ b/coordinator/api/billing/connect_webhook.go @@ -0,0 +1,88 @@ +package billing + +import ( + "encoding/json" + "io" + "net/http" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" +) + +// StripeConnectWebhook handles POST /v1/billing/stripe/connect/webhook. +// Drives the local withdrawal state machine for Connect events. This is a +// separate endpoint from the Checkout webhook because Stripe lets you +// configure per-endpoint signing secrets. +// +// Transient store failures return a non-2xx so Stripe redelivers the event; +// malformed payloads and business no-ops are acked with 200 (redelivery +// cannot fix those). +func (s *Controller) StripeConnectWebhook(w http.ResponseWriter, r *http.Request) { + if s.billing() == nil || s.billing().StripeConnect() == nil { + http.Error(w, "Stripe Connect not configured", http.StatusServiceUnavailable) + return + } + + payload, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + if err != nil { + http.Error(w, "read body", http.StatusBadRequest) + return + } + sig := r.Header.Get("Stripe-Signature") + event, err := s.billing().StripeConnect().VerifyConnectWebhookSignature(payload, sig) + if err != nil { + s.logger.Warn("stripe connect webhook: signature verification failed", "error", err) + http.Error(w, "invalid signature", http.StatusBadRequest) + return + } + + // Connect webhooks include the connected account ID at the top level + // (event.account in Stripe's payload). We re-parse the raw payload to + // pull it out; the WebhookEvent struct only exposes Type + Data. + var envelope struct { + Account string `json:"account"` + } + _ = json.Unmarshal(payload, &envelope) + + var handleErr error + switch event.Type { + case "account.updated": + // Best-effort mirror: account.updated recurs on every account change + // and the status endpoint re-syncs on page load, so a dropped event + // self-heals without redelivery. + s.handleAccountUpdated(event) + case "payout.paid": + handleErr = s.handlePayoutTerminal(event, envelope.Account, true) + case "payout.failed", "payout.canceled": + handleErr = s.handlePayoutTerminal(event, envelope.Account, false) + case "transfer.reversed": + handleErr = s.handleTransferFailed(event) + default: + // Ignore everything else — we just ack. + } + if handleErr != nil { + http.Error(w, "transient failure — retry", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +// handleAccountUpdated mirrors Stripe's view of the connected account into our +// User row. This is what flips a user from "pending" → "ready". +func (s *Controller) handleAccountUpdated(event *billingservice.WebhookEvent) { + acct, err := s.billing().StripeConnect().AccountUpdatedFromEvent(event) + if err != nil { + s.logger.Warn("stripe connect webhook: account.updated parse failed", "error", err) + return + } + user, err := s.billing().Store().GetUserByStripeAccount(acct.ID) + if err != nil { + s.logger.Warn("stripe connect webhook: account.updated user lookup failed", + "stripe_account_id", acct.ID, "error", err) + return + } + status := stripeStatusForAccount(acct) + if err := s.billing().Store().SetUserStripeAccount(user.AccountID, acct.ID, + status, acct.Country, acct.DestinationType, acct.DestinationLast4, acct.InstantEligible); err != nil { + s.logger.Error("stripe connect webhook: persist account state failed", "error", err) + } +} diff --git a/coordinator/api/billing/connect_webhook_helpers_test.go b/coordinator/api/billing/connect_webhook_helpers_test.go new file mode 100644 index 0000000000..e564d85d70 --- /dev/null +++ b/coordinator/api/billing/connect_webhook_helpers_test.go @@ -0,0 +1,126 @@ +package billing + +import ( + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strconv" + "strings" + "testing" + "time" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/payments" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// mkWithdrawal seeds a withdrawal row directly in the store. +func mkWithdrawal(t *testing.T, st *store.MemoryStore, wd store.StripeWithdrawal) { + t.Helper() + if wd.CreatedAt.IsZero() { + wd.CreatedAt = time.Now().Add(-2 * time.Hour) + } + if err := st.CreateStripeWithdrawal(&wd); err != nil { + t.Fatalf("create withdrawal %s: %v", wd.ID, err) + } +} + +func payoutEventPayload(payoutID, account, status string, automatic bool, created int64) []byte { + eventType := "payout.paid" + if status != "paid" { + eventType = "payout.failed" + } + return []byte(`{ + "type":"` + eventType + `","account":"` + account + `", + "data":{"object":{"id":"` + payoutID + `","status":"` + status + `","amount":450,"method":"standard", + "automatic":` + strconv.FormatBool(automatic) + `,"created":` + strconv.FormatInt(created, 10) + `, + "failure_code":"could_not_process","failure_message":"bank rejected"}} + }`) +} + +func deliverConnectWebhook(t *testing.T, srv *controllerFixture, payload []byte) *httptest.ResponseRecorder { + t.Helper() + req := signedConnectRequest(t, payload, "whsec_test") + w := httptest.NewRecorder() + srv.StripeConnectWebhook(w, req) + return w +} + +// accountServingStripe returns a fake Stripe that answers GET +// /v1/accounts/{id} with a healthy account under the given service agreement +// (echoing the requested ID), GET /v1/payouts/{id} with a live-"paid" payout +// (the sweep matcher verifies payout status before claiming rows), and +// 200-empty for everything else. +func accountServingStripe(agreement string) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/accounts/") { + id := strings.TrimPrefix(r.URL.Path, "/v1/accounts/") + _, _ = w.Write([]byte(healthyAccountJSON(id, "US", agreement, false))) + return + } + if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/payouts/") { + id := strings.TrimPrefix(r.URL.Path, "/v1/payouts/") + _, _ = w.Write([]byte(`{"id":"` + id + `","status":"paid","amount":450,"method":"standard"}`)) + return + } + })) +} + +// flakyPayoutStore wraps MemoryStore and injects transient (non-ErrNotFound) +// failures into specific operations. +type flakyPayoutStore struct { + *store.MemoryStore + failLookups bool + failUpdates bool + failReversals bool +} + +func (f *flakyPayoutStore) GetStripeWithdrawalByPayoutID(payoutID string) (*store.StripeWithdrawal, error) { + if f.failLookups { + return nil, errors.New("connection reset by peer") + } + return f.MemoryStore.GetStripeWithdrawalByPayoutID(payoutID) +} + +func (f *flakyPayoutStore) UpdateStripeWithdrawal(wd *store.StripeWithdrawal) error { + if f.failUpdates { + return errors.New("connection reset by peer") + } + return f.MemoryStore.UpdateStripeWithdrawal(wd) +} + +// newFlakyPayoutServer wires a Server + billing around a flakyPayoutStore. +func newFlakyPayoutServer(t *testing.T, fakeStripe *httptest.Server) (*controllerFixture, *flakyPayoutStore) { + t.Helper() + mem := store.NewMemory(store.Config{AdminKey: "test-key"}) + flaky := &flakyPayoutStore{MemoryStore: mem} + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + + srv := newControllerFixture(flaky, logger) + t.Cleanup(setStripeAPIBase(fakeStripe.URL)) + ledger := payments.NewLedger(flaky) + srv.SetBilling(billingservice.NewService(flaky, ledger, logger, billingservice.Config{ + StripeSecretKey: "sk_test_fake", + StripeConnectWebhookSecret: "whsec_test", + StripeConnectReturnURL: "https://app.test/billing", + StripeConnectRefreshURL: "https://app.test/billing", + StripeConnectPlatformCountry: "US", + })) + return srv, flaky +} + +func (f *flakyPayoutStore) RefundStripeWithdrawalAfterReversal(id, transferID string) (bool, error) { + if f.failReversals { + return false, errors.New("connection reset by peer") + } + return f.MemoryStore.RefundStripeWithdrawalAfterReversal(id, transferID) +} + +func (f *flakyPayoutStore) CompareAndSwapStripeWithdrawal(previous, next *store.StripeWithdrawal) (bool, error) { + if f.failUpdates { + return false, errors.New("connection reset by peer") + } + return f.MemoryStore.CompareAndSwapStripeWithdrawal(previous, next) +} diff --git a/coordinator/api/billing/connect_webhook_test.go b/coordinator/api/billing/connect_webhook_test.go new file mode 100644 index 0000000000..df2c3576be --- /dev/null +++ b/coordinator/api/billing/connect_webhook_test.go @@ -0,0 +1,241 @@ +package billing + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestConnectWebhookAccountUpdatedFlipsStatusToReady(t *testing.T) { + // Use a fake Stripe server because account.updated calls don't actually + // hit the API — Stripe sends us the object — but we still want the + // signature verifier to be enabled. + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + t.Errorf("unexpected Stripe call: %s", r.URL.Path) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := seedUser(t, st, "acct-wh-1", "alice@example.com") + _ = st.SetUserStripeAccount(user.AccountID, "acct_x_wh", "pending", "", "", "", false) + + payload := []byte(`{ + "type": "account.updated", + "account": "acct_x_wh", + "data": {"object": { + "id": "acct_x_wh", + "payouts_enabled": true, + "details_submitted": true, + "external_accounts": {"data":[ + {"object":"bank_account","last4":"6789","default_for_currency":true} + ]} + }} + }`) + req := signedConnectRequest(t, payload, "whsec_test") + w := httptest.NewRecorder() + srv.StripeConnectWebhook(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountStatus != "ready" { + t.Errorf("status = %q, want ready", refreshed.StripeAccountStatus) + } + if refreshed.StripeDestinationType != "bank" { + t.Errorf("destination_type = %q, want bank", refreshed.StripeDestinationType) + } + if refreshed.StripeDestinationLast4 != "6789" { + t.Errorf("last4 = %q", refreshed.StripeDestinationLast4) + } +} + +func TestConnectWebhookPayoutFailedKeepsFundsAndDoesNotRefund(t *testing.T) { + // payout.failed means the funds returned to the CONNECTED account's + // balance, where Stripe's daily auto-payout retries delivery. Refunding + // the ledger here would double-pay the user (ledger credit + eventual + // bank payout), so the row stays "transferred" with the failure recorded. + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-wh-fail", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + // Manually create a withdrawal row mimicking what the handler would have + // persisted, then debit the ledger to put us in the post-withdraw state. + withdrawalID := "wd-test-1" + _ = st.Debit(user.AccountID, 5_000_000, store.LedgerCharge, "stripe_withdraw:"+withdrawalID) + _ = st.CreateStripeWithdrawal(&store.StripeWithdrawal{ + ID: withdrawalID, + AccountID: user.AccountID, + StripeAccountID: user.StripeAccountID, + PayoutID: "po_failtest", + AmountMicroUSD: 5_000_000, + FeeMicroUSD: 0, + NetMicroUSD: 5_000_000, + Method: "standard", + Status: "transferred", + }) + + payload := []byte(`{ + "type": "payout.failed", + "account": "` + user.StripeAccountID + `", + "data": {"object": { + "id": "po_failtest", + "status": "failed", + "amount": 500, + "method": "standard", + "failure_code": "account_closed", + "failure_message": "Bank account closed" + }} + }`) + req := signedConnectRequest(t, payload, "whsec_test") + w := httptest.NewRecorder() + srv.StripeConnectWebhook(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + + if bal := st.GetBalance(user.AccountID); bal != 5_000_000 { + t.Errorf("balance = %d, want 5_000_000 (no refund — funds retry via sweep)", bal) + } + wd, _ := st.GetStripeWithdrawal(withdrawalID) + if wd.Status != "transferred" { + t.Errorf("status = %q, want transferred (sweep will retry)", wd.Status) + } + if wd.Refunded { + t.Error("refunded flag should NOT be set") + } + if !strings.Contains(wd.FailureReason, "account_closed") { + t.Errorf("failure_reason = %q", wd.FailureReason) + } +} + +func TestConnectWebhookPayoutFailedNeverRefundsOnRedelivery(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-wh-idem", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + withdrawalID := "wd-idem-1" + _ = st.Debit(user.AccountID, 5_000_000, store.LedgerCharge, "stripe_withdraw:"+withdrawalID) + _ = st.CreateStripeWithdrawal(&store.StripeWithdrawal{ + ID: withdrawalID, AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + PayoutID: "po_idem", AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", + }) + + payload := []byte(`{ + "type":"payout.failed","account":"` + user.StripeAccountID + `", + "data":{"object":{"id":"po_idem","status":"failed","amount":500,"method":"standard","failure_code":"x","failure_message":"y"}} + }`) + + for i := range 3 { + req := signedConnectRequest(t, payload, "whsec_test") + w := httptest.NewRecorder() + srv.StripeConnectWebhook(w, req) + if w.Code != http.StatusOK { + t.Fatalf("delivery %d: got %d", i, w.Code) + } + } + if bal := st.GetBalance(user.AccountID); bal != 5_000_000 { + t.Errorf("balance after 3x payout.failed = %d, want 5_000_000 (no refunds)", bal) + } + wd, _ := st.GetStripeWithdrawal(withdrawalID) + if wd.Status != "transferred" { + t.Errorf("status = %q, want transferred", wd.Status) + } +} + +func TestConnectWebhookLegacyRefundedRowStaysTerminal(t *testing.T) { + // Rows refunded under the pre-fix semantics must never flip back to + // "transferred" (the sweep matcher could otherwise double-pay them). + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-wh-legacy", "alice@example.com", false) + _ = st.CreateStripeWithdrawal(&store.StripeWithdrawal{ + ID: "wd-legacy-1", AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + PayoutID: "po_legacy", AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", Refunded: true, + }) + + payload := []byte(`{ + "type":"payout.failed","account":"` + user.StripeAccountID + `", + "data":{"object":{"id":"po_legacy","status":"failed","amount":500,"method":"standard","failure_code":"x","failure_message":"y"}} + }`) + req := signedConnectRequest(t, payload, "whsec_test") + w := httptest.NewRecorder() + srv.StripeConnectWebhook(w, req) + if w.Code != http.StatusOK { + t.Fatalf("got %d", w.Code) + } + + wd, _ := st.GetStripeWithdrawal("wd-legacy-1") + if wd.Status != "failed" { + t.Errorf("status = %q, want failed (terminal for already-refunded rows)", wd.Status) + } +} + +func TestConnectWebhookPayoutPaidIsIdempotent(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-wh-paid", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + withdrawalID := "wd-paid-1" + _ = st.Debit(user.AccountID, 5_000_000, store.LedgerCharge, "stripe_withdraw:"+withdrawalID) + _ = st.CreateStripeWithdrawal(&store.StripeWithdrawal{ + ID: withdrawalID, AccountID: user.AccountID, StripeAccountID: user.StripeAccountID, + PayoutID: "po_paid", AmountMicroUSD: 5_000_000, NetMicroUSD: 5_000_000, + Method: "standard", Status: "transferred", + }) + + payload := []byte(`{ + "type":"payout.paid","account":"` + user.StripeAccountID + `", + "data":{"object":{"id":"po_paid","status":"paid","amount":500,"method":"standard"}} + }`) + for i := range 3 { + req := signedConnectRequest(t, payload, "whsec_test") + w := httptest.NewRecorder() + srv.StripeConnectWebhook(w, req) + if w.Code != http.StatusOK { + t.Fatalf("delivery %d: got %d", i, w.Code) + } + } + if bal := st.GetBalance(user.AccountID); bal != 5_000_000 { + t.Errorf("balance shouldn't change on payout.paid; got %d, want 5_000_000", bal) + } + wd, _ := st.GetStripeWithdrawal(withdrawalID) + if wd.Status != "paid" { + t.Errorf("status = %q", wd.Status) + } +} + +func TestConnectWebhookRejectsBadSignature(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer fakeStripe.Close() + srv, _ := stripePayoutsTestServer(t, false, fakeStripe) + + payload := []byte(`{"type":"account.updated","data":{"object":{"id":"x"}}}`) + req := httptest.NewRequest(http.MethodPost, "/v1/billing/stripe/connect/webhook", strings.NewReader(string(payload))) + req.Header.Set("Stripe-Signature", "t=1,v1=deadbeef") + w := httptest.NewRecorder() + srv.StripeConnectWebhook(w, req) + + if w.Code != http.StatusBadRequest { + t.Errorf("got %d, want 400 on bad signature", w.Code) + } +} diff --git a/coordinator/api/billing/connect_withdraw.go b/coordinator/api/billing/connect_withdraw.go new file mode 100644 index 0000000000..10f09ae2da --- /dev/null +++ b/coordinator/api/billing/connect_withdraw.go @@ -0,0 +1,495 @@ +package billing + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/store" + "github.com/google/uuid" +) + +// StripeWithdraw handles POST /v1/billing/withdraw/stripe. +// +// Body: { amount_usd: "10.00", method: "standard"|"instant" } +// +// Behavior: +// 1. Validate method + amount, then pre-validate the connected account +// against Stripe: closed accounts are unlinked, wrong-service-agreement +// accounts (AU/NZ/JP created under `full`) get an actionable +// "recreate" error, and legacy manual payout schedules are healed. +// 2. Compute fee (Instant: 1.5%, $0.50 min; Standard: free). +// 3. Debit the ledger by the GROSS amount. +// 4. transfers.create — on failure the ledger is re-credited. +// Standard: done; Stripe's automatic daily payout sweeps the connected +// balance to the user's bank in their local currency. +// Instant: payouts.create to the debit card; if it fails, the instant +// fee is refunded and the daily sweep delivers via the standard rail. +// 5. Persist a stripe_withdrawals row; webhooks drive it to a terminal +// state (payout.paid → "paid", including automatic sweep payouts). +func (s *Controller) StripeWithdraw(w http.ResponseWriter, r *http.Request) { + user := requestauth.RequirePrivyUser(w, r) + if user == nil { + return + } + if s.billing() == nil || s.billing().StripeConnect() == nil { + httpresponse.WriteJSON(w, http.StatusServiceUnavailable, httpresponse.ErrorBody("billing_error", "Stripe Payouts not configured")) + return + } + if s.maybeGlobalWithdraw(w, r, user) { + return + } + if user.StripeAccountID == "" || user.StripeAccountStatus != stripeStatusReady { + httpresponse.WriteJSON(w, http.StatusForbidden, httpresponse.ErrorBody("not_onboarded", + "link your bank or debit card via Stripe before withdrawing")) + return + } + + var req struct { + AmountUSD string `json:"amount_usd"` + Method string `json:"method"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + + method := strings.ToLower(strings.TrimSpace(req.Method)) + if method == "" { + method = "standard" + } + if method != "standard" && method != "instant" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "method must be 'standard' or 'instant'")) + return + } + + // Pre-validate the connected account against Stripe BEFORE debiting the + // ledger. This catches accounts that are doomed to fail the transfer — + // closed accounts and wrong-service-agreement accounts (AU/NZ/JP created + // under `full`) — and turns them into actionable errors instead of a + // debit/refund cycle with a cryptic Stripe message. + acct, err := s.billing().StripeConnect().GetAccount(user.StripeAccountID) + if err != nil { + if billingservice.IsAccountGoneErr(err) { + s.logger.Warn("stripe payout: stored account gone — unlinking", + "stripe_account_id", user.StripeAccountID, "error", err) + if perr := s.billing().Store().SetUserStripeAccount(user.AccountID, "", "", "", "", "", false); perr != nil { + s.logger.Error("stripe payout: unlink gone account failed", "error", perr) + } + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("stripe_account_gone", + "your Stripe payout account no longer exists — set up payouts again from the billing page")) + return + } + s.logger.Error("stripe payout: account pre-check failed", "error", err) + httpresponse.WriteJSON(w, http.StatusBadGateway, httpresponse.ErrorBody("stripe_error", + "could not verify your payout account with Stripe — try again shortly")) + return + } + requiredAgreement := billingservice.RequiredServiceAgreement( + s.billing().StripeConnect().PlatformCountry(), acct.Country) + if billingservice.NormalizeServiceAgreement(acct.ServiceAgreement) != requiredAgreement { + // The agreement is immutable — this account can never receive + // transfers. Flip the local status so the UI prompts the user to + // re-run payout setup, which recreates the account correctly. + if perr := s.billing().Store().SetUserStripeAccount(user.AccountID, user.StripeAccountID, + stripeStatusRestricted, acct.Country, acct.DestinationType, acct.DestinationLast4, + acct.InstantEligible); perr != nil { + s.logger.Error("stripe payout: persist restricted status failed", "error", perr) + } + s.logger.Warn("stripe payout: service agreement mismatch — user must re-onboard", + "stripe_account_id", user.StripeAccountID, "country", acct.Country, + "have", billingservice.NormalizeServiceAgreement(acct.ServiceAgreement), "want", requiredAgreement) + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("stripe_account_recreate_required", + "your payout account can't receive transfers in your country — re-run payout setup from the billing page to recreate it")) + return + } + if !acct.PayoutsEnabled { + // Persist the fresh (non-ready) snapshot so the UI's status refresh + // reflects reality — otherwise the card keeps showing "Ready" while + // withdrawals 403, with no visible path to fix the account. + if perr := s.billing().Store().SetUserStripeAccount(user.AccountID, user.StripeAccountID, + stripeStatusForAccount(acct), acct.Country, acct.DestinationType, acct.DestinationLast4, + acct.InstantEligible); perr != nil { + s.logger.Error("stripe payout: persist disabled status failed", "error", perr) + } + httpresponse.WriteJSON(w, http.StatusForbidden, httpresponse.ErrorBody("not_onboarded", + "your Stripe account can't receive payouts yet — finish onboarding from the billing page")) + return + } + if acct.PayoutInterval == "manual" { + // Self-heal accounts created by older code: a manual schedule strands + // transferred funds in the connected account balance forever. Delivery + // depends entirely on the daily sweep (the instant path falls back to + // it too), so if the heal fails we abort BEFORE the ledger debit + // rather than park the user's money behind a schedule that never pays + // out — the exact bug this path exists to fix. + if herr := s.billing().StripeConnect().UpdateAccountPayoutScheduleAuto(user.StripeAccountID, acct.Country); herr != nil { + s.logger.Error("stripe payout: payout schedule self-heal failed — refusing withdrawal", + "stripe_account_id", user.StripeAccountID, "error", herr) + httpresponse.WriteJSON(w, http.StatusBadGateway, httpresponse.ErrorBody("stripe_error", + "could not enable automatic payouts on your account — try again shortly")) + return + } + s.logger.Info("stripe payout: payout schedule healed to automatic", + "stripe_account_id", user.StripeAccountID) + } + // Instant requires a debit-card destination. Trust either the fresh + // snapshot or the webhook-maintained flag — if both are stale and Stripe + // rejects the instant payout, the fallback path refunds the instant fee + // and delivers via the standard daily sweep. + if method == "instant" && !acct.InstantEligible && !user.StripeInstantEligible { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("instant_unavailable", + "instant payouts require a debit card destination — link one in Stripe to enable")) + return + } + + amountFloat, err := strconv.ParseFloat(req.AmountUSD, 64) + if err != nil || amountFloat <= 0 { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "amount_usd must be a positive number")) + return + } + grossMicroUSD := int64(amountFloat * 1_000_000) + if grossMicroUSD < billingservice.MinWithdrawMicroUSD { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + fmt.Sprintf("minimum withdrawal is $%.2f", float64(billingservice.MinWithdrawMicroUSD)/1_000_000))) + return + } + + feeMicroUSD := billingservice.FeeForMethodMicroUSD(method, grossMicroUSD) + netMicroUSD := grossMicroUSD - feeMicroUSD + if netMicroUSD <= 0 { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + fmt.Sprintf("amount after fees must be > $0 (fee is $%.2f)", float64(feeMicroUSD)/1_000_000))) + return + } + + // Cents-rounded amounts crossing the Stripe boundary. We never refund + // sub-cent dust to the user — the gross debit absorbs any rounding so + // the platform's books stay balanced. + netCents := microUSDToCents(netMicroUSD) + if netCents <= 0 { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "net amount rounds to less than 1 cent")) + return + } + + // State machine: + // + // pending → row persisted, ledger debited, no Stripe call yet. + // transferred → transfer succeeded; payout may or may not be created. + // paid → payout.paid webhook delivered. + // failed → terminal failure; ledger refunded if Refunded=true. + // + // We persist the row BEFORE any Stripe call so a DB write failure can + // never coexist with a successful money movement (no double-spend window). + withdrawalID := uuid.New().String() + debitRef := "stripe_withdraw:" + withdrawalID + + wd := &store.StripeWithdrawal{ + ID: withdrawalID, + AccountID: user.AccountID, + StripeAccountID: user.StripeAccountID, + AmountMicroUSD: grossMicroUSD, + FeeMicroUSD: feeMicroUSD, + NetMicroUSD: netMicroUSD, + Method: method, + Status: "pending", + } + // One store transaction debits both balance columns (preventing the + // inflation bug where a plain Debit eats non-withdrawable credits and a + // refund restores them as withdrawable) AND inserts the withdrawal row — + // either both happen or neither. A crash here can no longer leave a + // debited balance with no withdrawal row. + if err := s.billing().Store().CreateStripeWithdrawalWithDebit(wd, store.LedgerStripePayout, debitRef); err != nil { + if errors.Is(err, store.ErrInsufficientBalance) { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("insufficient_withdrawable", + "insufficient withdrawable balance — only earned funds can be withdrawn")) + return + } + s.logger.Error("stripe payout: debit+persist withdrawal failed", "error", err, "withdrawal_id", withdrawalID) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", + "could not start the withdrawal — nothing was debited; try again shortly")) + return + } + + // Keep the last acknowledged state across external Stripe calls so a + // webhook transition cannot be overwritten by our older local copy. + persisted := *wd + persistUpdate := func(stage string) error { + err := s.persistWithdrawalUpdate(&persisted, wd, stage) + if err == nil { + persisted = *wd + } + return err + } + + // markFailedRefund refunds the ledger and marks the row failed + // (best-effort — neither store call has rollback). Returns whether the + // refund credit is durably applied; the Refunded flag prevents webhook + // replay from double-crediting. + markFailedRefund := func(reason string) bool { + refunded := s.creditRefundOnceWithRetry(user.AccountID, grossMicroUSD, debitRef, withdrawalID) + if refunded { + wd.Refunded = true + } + wd.Status = "failed" + wd.FailureReason = reason + if uerr := persistUpdate("failure"); uerr != nil { + s.logger.Error("stripe payout: mark failed failed", "error", uerr, "withdrawal_id", withdrawalID) + } + return refunded + } + + // Step 2: transfer USD from platform balance to the connected account. + // Retried through retryAmbiguousStripe: the idempotency key makes a + // replay after a transport blip return the original transfer instead of + // creating a second one. + transfer, err := retryAmbiguousStripe(func() (*billingservice.Transfer, error) { + return s.billing().StripeConnect().CreateTransfer(billingservice.CreateTransferParams{ + DestinationAccountID: user.StripeAccountID, + AmountCents: netCents, + IdempotencyKey: "wd-tr-" + withdrawalID, + Description: "Darkbloom credit withdrawal", + }) + }) + if err != nil && !billingservice.IsDefinitiveAPIErr(err) { + // AMBIGUOUS outcome: Stripe never answered, so the idempotent + // request may have been accepted with the response lost. If it was, + // the daily sweep will still deliver the money — refunding here + // would pay the user twice. Park the row in "pending" (no refund): + // if the transfer landed, ops sees the stuck-pending reconciler + // alert and completes the row from the Stripe dashboard via the + // idempotency key; if it didn't, the same alert drives the refund. + wd.FailureReason = "transfer_create_unconfirmed: " + err.Error() + if uerr := persistUpdate("ambiguous transfer"); uerr != nil { + if errors.Is(uerr, errWithdrawalStateChanged) { + s.writeWithdrawalStateChanged(w, withdrawalID) + return + } + + s.logger.Error("stripe payout: persist ambiguous-transfer state failed", + "error", uerr, "withdrawal_id", withdrawalID) + } + s.logger.Error("stripe payout: transfer outcome UNCONFIRMED — no refund issued, verify against Stripe dashboard", + "error", err, "withdrawal_id", withdrawalID, "idempotency_key", "wd-tr-"+withdrawalID) + httpresponse.WriteJSON(w, http.StatusBadGateway, httpresponse.ErrorBody("stripe_error", + "we couldn't confirm the transfer with Stripe — your withdrawal is on hold and nothing was refunded; it will complete or be resolved automatically, contact support if it doesn't update within 24 hours")) + return + } + if err != nil { + refunded := markFailedRefund("transfer_create_failed: " + err.Error()) + s.logger.Error("stripe payout: transfer failed", "error", err, "withdrawal_id", withdrawalID) + refundNote := "your balance was refunded" + if !refunded { + refundNote = "the refund to your balance is pending — contact support if it doesn't appear shortly" + } + + // Classify permanent account problems (races with the pre-check) so + // the user gets an actionable error instead of a raw Stripe message. + switch { + case billingservice.IsAccountGoneErr(err): + if perr := s.billing().Store().SetUserStripeAccount(user.AccountID, "", "", "", "", "", false); perr != nil { + s.logger.Error("stripe payout: unlink gone account failed", "error", perr) + } + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("stripe_account_gone", + "your Stripe payout account no longer exists — "+refundNote+"; set up payouts again from the billing page")) + case billingservice.IsServiceAgreementErr(err): + if perr := s.billing().Store().SetUserStripeAccount(user.AccountID, user.StripeAccountID, + stripeStatusRestricted, "", "", "", false); perr != nil { + s.logger.Error("stripe payout: persist restricted status failed", "error", perr) + } + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("stripe_account_recreate_required", + "your payout account can't receive transfers in your country — "+refundNote+"; re-run payout setup from the billing page to recreate it")) + default: + httpresponse.WriteJSON(w, http.StatusBadGateway, httpresponse.ErrorBody("stripe_error", + "failed to transfer funds ("+refundNote+"): "+err.Error())) + } + return + } + wd.TransferID = transfer.ID + wd.Status = "transferred" + if err := persistUpdate("transfer_id"); err != nil { + if errors.Is(err, errWithdrawalStateChanged) { + s.writeWithdrawalStateChanged(w, withdrawalID) + return + } + + // Transfer succeeded but we lost track of it: the row is stuck + // "pending" with no transfer_id, invisible to the webhook matcher and + // sweep reconciler. Money is in the connected account and the daily + // auto-payout still delivers it — don't refund (double-credit). The + // reconciler's stale-pending alert surfaces the row for ops. + s.logger.Error("stripe payout: persist transfer_id failed after retries — row stuck pending, funds deliver via sweep", + "error", err, "withdrawal_id", withdrawalID, "transfer_id", transfer.ID) + } + + // Step 3 (standard): nothing to do. The connected account is on Stripe's + // automatic daily payout schedule, which sweeps the balance to the user's + // bank in their local currency. We deliberately do NOT create a manual + // payout here: manual payouts require the balance to already be available + // (transfers to `recipient` accounts take +24h) and must be denominated in + // the connected account's settlement currency — Stripe converts cross- + // border transfers, so a hardcoded USD payout fails for any non-USD + // account. The sweep handles both; the payout.paid webhook marks the row. + if method == "standard" { + s.logger.Info("stripe payout: transferred (auto-payout will deliver)", + "withdrawal_id", withdrawalID, + "account", user.AccountID[:min(8, len(user.AccountID))]+"...", + "gross_micro_usd", grossMicroUSD, + "net_micro_usd", netMicroUSD, + ) + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "transferred", + "withdrawal_id": withdrawalID, + "transfer_id": transfer.ID, + "amount_usd": formatUSD(grossMicroUSD), + "fee_usd": formatUSD(feeMicroUSD), + "net_usd": formatUSD(netMicroUSD), + "method": method, + "eta": etaForMethod(method, acct.Country), + "message": sweepDeliveryMessage(acct.Country), + "balance_micro_usd": s.billing().Ledger().Balance(user.AccountID), + }) + return + } + + // Step 3 (instant): create the Stripe Instant Payout from the connected + // account to the user's debit card. Instant payouts are USD/debit-card + // only, which the InstantEligible gate above guarantees. Idempotent — + // ambiguous transport failures are retried with the same key. + payout, err := retryAmbiguousStripe(func() (*billingservice.Payout, error) { + return s.billing().StripeConnect().CreatePayout(billingservice.CreatePayoutParams{ + OnBehalfOfAccountID: user.StripeAccountID, + AmountCents: netCents, + Method: method, + IdempotencyKey: "wd-po-" + withdrawalID, + Description: "Darkbloom credit withdrawal", + }) + }) + if err != nil && !billingservice.IsDefinitiveAPIErr(err) { + // AMBIGUOUS outcome: the payout may exist with its ID lost in + // flight. If it does, the user IS getting instant delivery — so do + // NOT refund the instant fee, and don't guess a terminal state. The + // row keeps its transfer and no payout ID; if the payout landed, + // its paid webhook won't match (unmatched non-automatic payouts are + // ignored) and no sweep will fire on the emptied balance, so the + // 48h reconciler alert surfaces the row for ops to settle via the + // idempotency key. If it didn't land, the daily sweep delivers and + // completes the row; ops refunds the fee from the same alert trail. + wd.FailureReason = "instant_payout_unconfirmed: " + err.Error() + if uerr := persistUpdate("ambiguous payout"); uerr != nil { + if errors.Is(uerr, errWithdrawalStateChanged) { + s.writeWithdrawalStateChanged(w, withdrawalID) + return + } + + s.logger.Error("stripe payout: persist ambiguous-payout state failed", + "error", uerr, "withdrawal_id", withdrawalID) + } + s.logger.Error("stripe payout: instant payout outcome UNCONFIRMED — fee NOT refunded, verify against Stripe dashboard", + "error", err, "withdrawal_id", withdrawalID, "transfer_id", transfer.ID, + "idempotency_key", "wd-po-"+withdrawalID) + httpresponse.WriteJSON(w, http.StatusAccepted, map[string]any{ + "status": "transferred", + "withdrawal_id": withdrawalID, + "transfer_id": transfer.ID, + "amount_usd": formatUSD(grossMicroUSD), + "fee_usd": formatUSD(feeMicroUSD), + "net_usd": formatUSD(netMicroUSD), + "method": method, + "message": "we couldn't confirm your instant payout with Stripe — if it went through, funds reach your card in ~30 minutes; otherwise the daily payout delivers them and support will refund the instant fee, contact support if nothing arrives within 24 hours", + "balance_micro_usd": s.billing().Ledger().Balance(user.AccountID), + }) + return + } + if err != nil { + // Transfer succeeded — funds are in the connected account and the + // daily auto-payout will deliver them via the standard rail. We do + // NOT refund the principal (that would double-credit), but we DO + // refund the instant fee: the user isn't getting instant delivery. + wd.FailureReason = "instant_payout_create_failed: " + err.Error() + // Reference-idempotent: shares its ledger ref with the webhook + // fee-refund path, so no interleaving pays the fee twice — a later + // transfer.reversed re-checks the same reference. + feeRefunded := feeMicroUSD == 0 + if feeMicroUSD > 0 && + s.creditRefundOnceWithRetry(user.AccountID, feeMicroUSD, "stripe_withdraw_fee:"+withdrawalID, withdrawalID) { + feeRefunded = true + wd.FeeRefunded = true + wd.FailureReason += " (instant fee refunded)" + } + if uerr := persistUpdate("payout failure"); uerr != nil { + if errors.Is(uerr, errWithdrawalStateChanged) { + s.writeWithdrawalStateChanged(w, withdrawalID) + return + } + + s.logger.Error("stripe payout: persist payout failure failed", + "error", uerr, "withdrawal_id", withdrawalID) + } + s.logger.Error("stripe payout: create instant payout failed", "error", err, + "withdrawal_id", withdrawalID, "transfer_id", transfer.ID) + msg := "instant payout unavailable — the fee was refunded and funds will arrive via the standard daily payout" + if !feeRefunded { + msg = "instant payout unavailable — funds will arrive via the standard daily payout; the instant-fee refund is pending, contact support if it doesn't appear shortly" + } + httpresponse.WriteJSON(w, http.StatusAccepted, map[string]any{ + "status": "transferred", + "withdrawal_id": withdrawalID, + "transfer_id": transfer.ID, + "amount_usd": formatUSD(grossMicroUSD), + "fee_usd": formatUSD(feeMicroUSD), + "net_usd": formatUSD(netMicroUSD), + "method": method, + "message": msg, + "balance_micro_usd": s.billing().Ledger().Balance(user.AccountID), + }) + return + } + wd.PayoutID = payout.ID + if err := persistUpdate("payout_id"); err != nil { + if errors.Is(err, errWithdrawalStateChanged) { + s.writeWithdrawalStateChanged(w, withdrawalID) + return + } + + // Payout succeeded but we couldn't persist the ID. Webhook will + // arrive with the payout ID — without the index entry the sweep + // matcher will still reconcile it by connected account. Log loudly + // so ops can double-check via the Stripe dashboard. + s.logger.Error("stripe payout: persist payout_id failed after retries", + "error", err, "withdrawal_id", withdrawalID, + "transfer_id", transfer.ID, "payout_id", payout.ID) + } + + s.logger.Info("stripe payout: created", + "withdrawal_id", withdrawalID, + "account", user.AccountID[:min(8, len(user.AccountID))]+"...", + "method", method, + "gross_micro_usd", grossMicroUSD, + "fee_micro_usd", feeMicroUSD, + "net_micro_usd", netMicroUSD, + ) + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "submitted", + "withdrawal_id": withdrawalID, + "transfer_id": transfer.ID, + "payout_id": payout.ID, + "amount_usd": formatUSD(grossMicroUSD), + "fee_usd": formatUSD(feeMicroUSD), + "net_usd": formatUSD(netMicroUSD), + "method": method, + "eta": etaForMethod(method, acct.Country), + "arrival_unix": payout.ArrivalDate, + "balance_micro_usd": s.billing().Ledger().Balance(user.AccountID), + }) +} diff --git a/coordinator/api/billing/connect_withdraw_account_test.go b/coordinator/api/billing/connect_withdraw_account_test.go new file mode 100644 index 0000000000..8b87a59a2e --- /dev/null +++ b/coordinator/api/billing/connect_withdraw_account_test.go @@ -0,0 +1,157 @@ +package billing + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// TestStripeWithdrawAccountGonePreCheckUnlinksWithoutDebit pins that a +// withdrawal against a closed Stripe account fails BEFORE the ledger debit +// and unlinks the dead account. +func TestStripeWithdrawAccountGonePreCheckUnlinksWithoutDebit(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":{"message":"No such account: 'acct_acct-w-gone'","type":"invalid_request_error"}}`)) + return + } + t.Errorf("unexpected Stripe call: %s %s", r.Method, r.URL.Path) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-w-gone", "gone@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusConflict { + t.Fatalf("got %d, want 409: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + errObj, _ := resp["error"].(map[string]any) + if errObj["type"] != "stripe_account_gone" { + t.Errorf("error type = %v", errObj["type"]) + } + // No debit happened. + if bal := st.GetBalance(user.AccountID); bal != 10_000_000 { + t.Errorf("balance = %d, want 10_000_000 (untouched)", bal) + } + // Dead account unlinked so the user can re-onboard. + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountID != "" { + t.Errorf("StripeAccountID = %q, want empty after unlink", refreshed.StripeAccountID) + } + // No withdrawal row persisted. + wds, _ := st.ListStripeWithdrawals(user.AccountID, 0) + if len(wds) != 0 { + t.Errorf("expected no withdrawal rows, got %d", len(wds)) + } +} + +// TestStripeWithdrawServiceAgreementMismatchPreCheck pins the AU/NZ/JP +// experience: withdrawing against a full-agreement account outside the +// transfer region returns an actionable "recreate" error before any debit +// and flips the local status to restricted. +func TestStripeWithdrawServiceAgreementMismatchPreCheck(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet { + _, _ = w.Write([]byte(healthyAccountJSON("acct_acct-w-au", "AU", "full", false))) + return + } + t.Errorf("unexpected Stripe call: %s %s", r.Method, r.URL.Path) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-w-au", "au@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusConflict { + t.Fatalf("got %d, want 409: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + errObj, _ := resp["error"].(map[string]any) + if errObj["type"] != "stripe_account_recreate_required" { + t.Errorf("error type = %v", errObj["type"]) + } + if bal := st.GetBalance(user.AccountID); bal != 10_000_000 { + t.Errorf("balance = %d, want 10_000_000 (untouched)", bal) + } + refreshed, _ := st.GetUserByAccountID(user.AccountID) + if refreshed.StripeAccountStatus != "restricted" { + t.Errorf("status = %q, want restricted (prompts re-onboarding)", refreshed.StripeAccountStatus) + } +} + +// TestStripeWithdrawAgreementMismatchWithOmittedField pins the REAL Stripe +// API shape, verified against the live platform: accounts under the full +// agreement OMIT tos_acceptance.service_agreement entirely (only date/ip are +// present). The mismatch detection must normalize the absent field to "full" +// — treating it as unknown silently skipped every broken AU/NZ/JP account. +func TestStripeWithdrawAgreementMismatchWithOmittedField(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet { + // Verbatim shape of a live AU full-agreement Express account. + _, _ = w.Write([]byte(`{ + "id": "acct_acct-w-au-real", + "country": "AU", + "default_currency": "aud", + "payouts_enabled": true, + "details_submitted": true, + "tos_acceptance": {"date": 1782738707}, + "capabilities": {"card_payments": "active", "transfers": "active"}, + "settings": {"payouts": {"schedule": {"delay_days": 2, "interval": "manual"}}}, + "external_accounts": {"data": [{"object":"bank_account","last4":"6789","default_for_currency":true}]} + }`)) + return + } + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodPost { + // Schedule self-heal fires for the manual interval — accept it. + _, _ = w.Write([]byte(`{"id":"acct_acct-w-au-real"}`)) + return + } + t.Errorf("unexpected Stripe call: %s %s", r.Method, r.URL.Path) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-w-au-real", "au-real@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusConflict { + t.Fatalf("got %d, want 409 (absent service_agreement must normalize to full): %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + errObj, _ := resp["error"].(map[string]any) + if errObj["type"] != "stripe_account_recreate_required" { + t.Errorf("error type = %v", errObj["type"]) + } + if bal := st.GetBalance(user.AccountID); bal != 10_000_000 { + t.Errorf("balance = %d, want untouched", bal) + } +} diff --git a/coordinator/api/billing/connect_withdraw_fallback_test.go b/coordinator/api/billing/connect_withdraw_fallback_test.go new file mode 100644 index 0000000000..e4b12ef197 --- /dev/null +++ b/coordinator/api/billing/connect_withdraw_fallback_test.go @@ -0,0 +1,121 @@ +package billing + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestStripeWithdrawTransferOkInstantPayoutFailRefundsFeeOnly(t *testing.T) { + // Instant withdrawal: transfer succeeds, payouts.create fails. The funds + // stay in the connected account (Stripe's daily auto-payout delivers via + // the standard rail), so the principal is NOT refunded — but the instant + // fee IS, because the user isn't getting instant delivery. Row stays at + // "transferred" with FailureReason set. + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet { + _, _ = w.Write([]byte(healthyAccountJSON("acct_acct-tr-only", "US", "full", true))) + return + } + switch r.URL.Path { + case "/v1/transfers": + _, _ = w.Write([]byte(`{"id":"tr_ok","amount":450,"destination":"acct_x","created":1700000000}`)) + case "/v1/payouts": + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":{"message":"insufficient connected balance"}}`)) + default: + t.Errorf("unexpected: %s", r.URL.Path) + } + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-tr-only", "alice@example.com", true) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + // $5 instant → fee floor $0.50 → net $4.50 transferred. + body := `{"amount_usd":"5.00","method":"instant"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusAccepted { + t.Fatalf("got %d, want 202: %s", w.Code, w.Body.String()) + } + // Seed $10 − gross $5 + fee refund $0.50 = $5.50. The $4.50 principal is + // in the connected account, en route via the daily sweep. + if bal := st.GetBalance(user.AccountID); bal != 5_500_000 { + t.Errorf("balance = %d, want 5_500_000 (fee refunded, principal in connected acct)", bal) + } + wds, _ := st.ListStripeWithdrawals(user.AccountID, 0) + if wds[0].Status != "transferred" { + t.Errorf("status = %q, want transferred", wds[0].Status) + } + if wds[0].Refunded { + t.Error("refunded flag should NOT be set (principal not refunded)") + } + if wds[0].TransferID != "tr_ok" { + t.Errorf("transfer_id = %q", wds[0].TransferID) + } + if !strings.Contains(wds[0].FailureReason, "instant_payout_create_failed") { + t.Errorf("failure_reason = %q", wds[0].FailureReason) + } + if !strings.Contains(wds[0].FailureReason, "fee refunded") { + t.Errorf("failure_reason should note the fee refund, got %q", wds[0].FailureReason) + } +} + +// TestStripeWithdrawNoInflationOnFailedPayout verifies that a failed payout +// followed by a refund does not inflate the withdrawable balance beyond its +// original value. This was the core accounting bug: Debit ate non-withdrawable +// credits, but CreditWithdrawable restored the amount as withdrawable earnings. +func TestStripeWithdrawNoInflationOnFailedPayout(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/v1/transfers" && r.Method == http.MethodPost: + w.WriteHeader(400) + _, _ = w.Write([]byte(`{"error":{"message":"boom","type":"invalid_request_error"}}`)) + default: + w.WriteHeader(404) + } + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-inflate-1", "inflate@example.com", false) + + // Seed: $100 total, $50 withdrawable (earned), $50 non-withdrawable (credits). + st.Credit(user.AccountID, 50_000_000, store.LedgerStripeDeposit, "deposit") + st.CreditWithdrawable(user.AccountID, 50_000_000, store.LedgerPayout, "earnings") + + beforeBalance := st.GetBalance(user.AccountID) + beforeWithdrawable := st.GetWithdrawableBalance(user.AccountID) + if beforeBalance != 100_000_000 { + t.Fatalf("initial balance = %d, want 100_000_000", beforeBalance) + } + if beforeWithdrawable != 50_000_000 { + t.Fatalf("initial withdrawable = %d, want 50_000_000", beforeWithdrawable) + } + + // Attempt a $10 withdrawal — transfer will fail, triggering refund. + body := `{"amount_usd":"10.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + // Transfer fails → refund should restore original balances exactly. + afterBalance := st.GetBalance(user.AccountID) + afterWithdrawable := st.GetWithdrawableBalance(user.AccountID) + + if afterBalance != beforeBalance { + t.Errorf("balance after failed withdrawal = %d, want %d (unchanged)", afterBalance, beforeBalance) + } + if afterWithdrawable != beforeWithdrawable { + t.Errorf("withdrawable after failed withdrawal = %d, want %d (unchanged) — inflation bug!", afterWithdrawable, beforeWithdrawable) + } +} diff --git a/coordinator/api/billing/connect_withdraw_recovery_test.go b/coordinator/api/billing/connect_withdraw_recovery_test.go new file mode 100644 index 0000000000..8d036fcf9c --- /dev/null +++ b/coordinator/api/billing/connect_withdraw_recovery_test.go @@ -0,0 +1,245 @@ +package billing + +import ( + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// TestStripeWithdrawAbortsWhenScheduleHealFails: a legacy manual-schedule +// account whose heal-to-daily update fails must abort BEFORE the ledger +// debit — standard delivery depends entirely on the daily sweep. +func TestStripeWithdrawAbortsWhenScheduleHealFails(t *testing.T) { + manualAccountJSON := strings.Replace( + healthyAccountJSON("acct_acct-heal-fail", "US", "full", false), + `"interval":"daily"`, `"interval":"manual"`, 1) + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") { + if r.Method == http.MethodGet { + _, _ = w.Write([]byte(manualAccountJSON)) + return + } + // The heal (POST /v1/accounts/{id}) fails. + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"error":{"message":"api unavailable"}}`)) + return + } + t.Errorf("unexpected Stripe call after failed heal: %s %s", r.Method, r.URL.Path) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-heal-fail", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusBadGateway { + t.Fatalf("got %d, want 502: %s", w.Code, w.Body.String()) + } + if bal := st.GetBalance(user.AccountID); bal != 10_000_000 { + t.Errorf("balance = %d, want 10_000_000 (no debit before abort)", bal) + } + if wds, _ := st.ListStripeWithdrawals(user.AccountID, 0); len(wds) != 0 { + t.Errorf("no withdrawal row should exist, got %d", len(wds)) + } +} + +// droppingStripe builds a fake Stripe that serves a healthy account on GET +// /v1/accounts/*, drops the connection (transport error, outcome unknown) for +// the first failN requests to dropPath, and delegates the rest to next. +func droppingStripe(t *testing.T, dropPath string, failN int, next http.HandlerFunc) *httptest.Server { + t.Helper() + var calls int32 + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet { + id := strings.TrimPrefix(r.URL.Path, "/v1/accounts/") + _, _ = w.Write([]byte(healthyAccountJSON(id, "US", "full", true))) + return + } + if r.URL.Path == dropPath && atomic.AddInt32(&calls, 1) <= int32(failN) { + hj, ok := w.(http.Hijacker) + if !ok { + t.Fatal("recorder not hijackable") + } + conn, _, err := hj.Hijack() + if err != nil { + t.Fatalf("hijack: %v", err) + } + _ = conn.Close() // response lost in flight — ambiguous outcome + return + } + if next != nil { + next(w, r) + return + } + t.Errorf("unexpected Stripe call: %s %s", r.Method, r.URL.Path) + })) +} + +// TestStripeWithdrawAmbiguousTransferParksRowWithoutRefund: when Stripe never +// answers transfers.create (idempotent request possibly accepted), refunding +// would double-pay if the sweep later delivers the accepted transfer. The row +// must park in "pending" with NO refund, surfaced by the reconciler. +func TestStripeWithdrawAmbiguousTransferParksRowWithoutRefund(t *testing.T) { + fakeStripe := droppingStripe(t, "/v1/transfers", 99, nil) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-ambig-tr", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusBadGateway { + t.Fatalf("got %d, want 502: %s", w.Code, w.Body.String()) + } + // Debited, NOT refunded — the transfer may have been accepted. + if bal := st.GetBalance(user.AccountID); bal != 5_000_000 { + t.Errorf("balance = %d, want 5_000_000 (debit stands, no refund on ambiguity)", bal) + } + wds, _ := st.ListStripeWithdrawals(user.AccountID, 0) + if len(wds) != 1 { + t.Fatalf("want 1 withdrawal row, got %d", len(wds)) + } + if wds[0].Status != "pending" || wds[0].Refunded { + t.Errorf("row = status %q refunded=%v, want pending/false (parked for reconciliation)", wds[0].Status, wds[0].Refunded) + } + if !strings.Contains(wds[0].FailureReason, "transfer_create_unconfirmed") { + t.Errorf("failure reason = %q, want transfer_create_unconfirmed", wds[0].FailureReason) + } +} + +// TestStripeWithdrawAmbiguousTransferRetryRecovers: a single dropped response +// followed by a successful idempotent replay completes the withdrawal +// normally — one debit, no refund, row transferred. +func TestStripeWithdrawAmbiguousTransferRetryRecovers(t *testing.T) { + fakeStripe := droppingStripe(t, "/v1/transfers", 1, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/transfers" && r.Method == http.MethodPost { + _, _ = w.Write([]byte(`{"id":"tr_recovered","amount":500,"destination":"acct_x","created":1}`)) + return + } + }) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-ambig-rec", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + if bal := st.GetBalance(user.AccountID); bal != 5_000_000 { + t.Errorf("balance = %d, want 5_000_000 (exactly one debit)", bal) + } + wds, _ := st.ListStripeWithdrawals(user.AccountID, 0) + if len(wds) != 1 || wds[0].Status != "transferred" || wds[0].TransferID != "tr_recovered" { + t.Errorf("row = %+v, want transferred with tr_recovered", wds[0]) + } +} + +// TestStripeWithdrawAmbiguousInstantPayoutKeepsFee: when payouts.create times +// out, the payout may exist (user gets instant delivery) — the fee must NOT +// be refunded and the row must stay observable (transferred, no payout ID). +func TestStripeWithdrawAmbiguousInstantPayoutKeepsFee(t *testing.T) { + fakeStripe := droppingStripe(t, "/v1/payouts", 99, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/transfers" && r.Method == http.MethodPost { + _, _ = w.Write([]byte(`{"id":"tr_ambig_po","amount":450,"destination":"acct_x","created":1}`)) + return + } + }) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-ambig-po", "alice@example.com", true) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"instant"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusAccepted { + t.Fatalf("got %d, want 202: %s", w.Code, w.Body.String()) + } + // Gross debited, fee NOT refunded (payout may have delivered). + if bal := st.GetBalance(user.AccountID); bal != 5_000_000 { + t.Errorf("balance = %d, want 5_000_000 (fee kept until outcome is known)", bal) + } + wds, _ := st.ListStripeWithdrawals(user.AccountID, 0) + if len(wds) != 1 { + t.Fatalf("want 1 withdrawal row, got %d", len(wds)) + } + wd := wds[0] + if wd.Status != "transferred" || wd.PayoutID != "" || wd.FeeRefunded { + t.Errorf("row = status %q payout %q feeRefunded=%v, want transferred/empty/false", wd.Status, wd.PayoutID, wd.FeeRefunded) + } + if !strings.Contains(wd.FailureReason, "instant_payout_unconfirmed") { + t.Errorf("failure reason = %q, want instant_payout_unconfirmed", wd.FailureReason) + } +} + +// TestStripeWithdraw500TransferParksRowWithoutRefund: Stripe documents 5xx +// on POST mutations as indeterminate and possibly side-effecting — a 500 +// from transfers.create must take the unconfirmed path (idempotent replays, +// then park without refund), never the definitive refund path. +func TestStripeWithdraw500TransferParksRowWithoutRefund(t *testing.T) { + var transferCalls int32 + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet { + id := strings.TrimPrefix(r.URL.Path, "/v1/accounts/") + _, _ = w.Write([]byte(healthyAccountJSON(id, "US", "full", false))) + return + } + if r.URL.Path == "/v1/transfers" { + atomic.AddInt32(&transferCalls, 1) + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"error":{"message":"An unknown error occurred","type":"api_error"}}`)) + return + } + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-500-tr", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusBadGateway { + t.Fatalf("got %d, want 502: %s", w.Code, w.Body.String()) + } + if n := atomic.LoadInt32(&transferCalls); n != 3 { + t.Errorf("transfer attempts = %d, want 3 (idempotent replays before parking)", n) + } + if bal := st.GetBalance(user.AccountID); bal != 5_000_000 { + t.Errorf("balance = %d, want 5_000_000 (500 is indeterminate — no refund)", bal) + } + wds, _ := st.ListStripeWithdrawals(user.AccountID, 0) + if len(wds) != 1 || wds[0].Status != "pending" || wds[0].Refunded { + t.Errorf("row = %+v, want pending/unrefunded (parked for reconciliation)", wds[0]) + } +} diff --git a/coordinator/api/billing/connect_withdraw_success_test.go b/coordinator/api/billing/connect_withdraw_success_test.go new file mode 100644 index 0000000000..e27ef6a29b --- /dev/null +++ b/coordinator/api/billing/connect_withdraw_success_test.go @@ -0,0 +1,115 @@ +package billing + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestStripeWithdrawStandardSuccess(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := readyUser(t, st, "acct-w-std", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp["fee_usd"] != "0.00" { + t.Errorf("standard fee should be 0, got %v", resp["fee_usd"]) + } + if resp["net_usd"] != "5.00" { + t.Errorf("net should equal gross for standard, got %v", resp["net_usd"]) + } + if resp["amount_usd"] != "5.00" { + t.Errorf("amount = %v", resp["amount_usd"]) + } + if balance, _ := resp["balance_micro_usd"].(float64); int64(balance) != 5_000_000 { + t.Errorf("balance = %v, want 5_000_000", resp["balance_micro_usd"]) + } + + // Confirm a withdrawal row was persisted. + wds, _ := st.ListStripeWithdrawals(user.AccountID, 0) + if len(wds) != 1 { + t.Fatalf("expected 1 withdrawal row, got %d", len(wds)) + } + if wds[0].Method != "standard" { + t.Errorf("method = %q", wds[0].Method) + } + if wds[0].FeeMicroUSD != 0 { + t.Errorf("persisted fee = %d", wds[0].FeeMicroUSD) + } + if wds[0].NetMicroUSD != 5_000_000 { + t.Errorf("persisted net = %d", wds[0].NetMicroUSD) + } +} + +func TestStripeWithdrawInstantAppliesFee(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := readyUser(t, st, "acct-w-inst", "alice@example.com", true) + st.CreditWithdrawable(user.AccountID, 100_000_000, store.LedgerDeposit, "seed") + + // $50 instant → 1.5% fee = $0.75 → net $49.25 → balance after = $50 + body := `{"amount_usd":"50.00","method":"instant"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp["fee_usd"] != "0.75" { + t.Errorf("fee_usd = %v, want 0.75", resp["fee_usd"]) + } + if resp["net_usd"] != "49.25" { + t.Errorf("net_usd = %v, want 49.25", resp["net_usd"]) + } + if resp["amount_usd"] != "50.00" { + t.Errorf("amount_usd = %v", resp["amount_usd"]) + } + if resp["eta"] != "~30 minutes" { + t.Errorf("eta = %v", resp["eta"]) + } + if balance, _ := resp["balance_micro_usd"].(float64); int64(balance) != 50_000_000 { + t.Errorf("balance = %v, want 50_000_000", resp["balance_micro_usd"]) + } +} + +func TestStripeWithdrawSmallInstantHitsFloor(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := readyUser(t, st, "acct-w-small", "alice@example.com", true) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + // $5 instant → 1.5% = $0.075 < $0.50 → fee snaps to $0.50 → net $4.50 + body := `{"amount_usd":"5.00","method":"instant"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp["fee_usd"] != "0.50" { + t.Errorf("fee_usd = %v, want 0.50 (floor)", resp["fee_usd"]) + } + if resp["net_usd"] != "4.50" { + t.Errorf("net_usd = %v", resp["net_usd"]) + } +} diff --git a/coordinator/api/billing/connect_withdraw_transfer_test.go b/coordinator/api/billing/connect_withdraw_transfer_test.go new file mode 100644 index 0000000000..c5f3949324 --- /dev/null +++ b/coordinator/api/billing/connect_withdraw_transfer_test.go @@ -0,0 +1,178 @@ +package billing + +import ( + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/payments" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// TestStripeWithdrawTransferFailureRefunds exercises the ledger-refund branch +// when Stripe rejects transfers.create. We use a real-HTTP Stripe Connect +// client backed by a fake Stripe server that returns 400 on /v1/transfers. +func TestStripeWithdrawTransferFailureRefunds(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet { + _, _ = w.Write([]byte(healthyAccountJSON("acct_acct-w-fail", "US", "full", false))) + return + } + if r.URL.Path == "/v1/transfers" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":{"message":"insufficient platform funds","type":"invalid_request_error"}}`)) + return + } + t.Errorf("unexpected Stripe call: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusInternalServerError) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-w-fail", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusBadGateway { + t.Fatalf("got %d, want 502: %s", w.Code, w.Body.String()) + } + if bal := st.GetBalance(user.AccountID); bal != 10_000_000 { + t.Errorf("balance after refund = %d, want 10_000_000 (full original)", bal) + } + // Ledger should now have: deposit (+10), charge (-5), refund (+5). + entries := st.LedgerHistory(user.AccountID) + if len(entries) != 3 { + t.Fatalf("expected 3 ledger entries, got %d", len(entries)) + } + // Newest first: refund, charge, deposit. + if entries[0].Type != store.LedgerRefund { + t.Errorf("entries[0].Type = %q, want refund", entries[0].Type) + } +} + +func TestStripeWithdrawPersistsRowAsPendingFirst(t *testing.T) { + // Verify the row exists before any Stripe call returns. We use a fake + // Stripe that records when CreateTransfer is called and the test then + // asserts that the DB had a "pending" row at that moment. + var rowSeenAtTransferTime *store.StripeWithdrawal + st := store.NewMemory(store.Config{AdminKey: "test-key"}) + + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet { + _, _ = w.Write([]byte(healthyAccountJSON("acct_acct-pers-1", "US", "full", false))) + return + } + if r.URL.Path == "/v1/transfers" { + // Snapshot the only withdrawal in the store at the moment of the + // transfer call; should already be persisted with status=pending. + wds, _ := st.ListStripeWithdrawals("acct-pers-1", 0) + if len(wds) == 1 { + cp := wds[0] + rowSeenAtTransferTime = &cp + } + _, _ = w.Write([]byte(`{"id":"tr_pers","amount":500,"destination":"acct_x","created":1700000000}`)) + return + } + // Standard withdrawals must NOT create manual payouts — Stripe's + // automatic daily schedule delivers the funds. + t.Errorf("unexpected Stripe call: %s", r.URL.Path) + })) + defer fakeStripe.Close() + + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + + srv := newControllerFixture(st, logger) + t.Cleanup(setStripeAPIBase(fakeStripe.URL)) + ledger := payments.NewLedger(st) + srv.SetBilling(billingservice.NewService(st, ledger, logger, billingservice.Config{ + StripeSecretKey: "sk_test_fake", + StripeConnectWebhookSecret: "whsec_test", + StripeConnectReturnURL: "https://app.test/billing", + StripeConnectRefreshURL: "https://app.test/billing", + StripeConnectPlatformCountry: "US", + })) + + user := readyUser(t, st, "acct-pers-1", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("got %d: %s", w.Code, w.Body.String()) + } + if rowSeenAtTransferTime == nil { + t.Fatal("withdrawal row should have been persisted before the transfer call") + } + if rowSeenAtTransferTime.Status != "pending" { + t.Errorf("at transfer-time status was %q, want pending", rowSeenAtTransferTime.Status) + } + + // Final state: transferred, no payout ID — delivery is Stripe's + // automatic daily sweep, whose payout.paid webhook completes the row. + wds, _ := st.ListStripeWithdrawals(user.AccountID, 0) + if len(wds) != 1 { + t.Fatalf("expected 1 withdrawal row, got %d", len(wds)) + } + if wds[0].Status != "transferred" { + t.Errorf("final status = %q, want transferred", wds[0].Status) + } + if wds[0].TransferID != "tr_pers" { + t.Errorf("transfer id not persisted: %+v", wds[0]) + } + if wds[0].PayoutID != "" { + t.Errorf("standard withdrawal should have no payout id, got %q", wds[0].PayoutID) + } +} + +func TestStripeWithdrawTransferFailureMarksRowFailedAndRefunded(t *testing.T) { + fakeStripe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/accounts/") && r.Method == http.MethodGet { + _, _ = w.Write([]byte(healthyAccountJSON("acct_acct-w-marked", "US", "full", false))) + return + } + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":{"message":"boom","type":"invalid_request_error"}}`)) + })) + defer fakeStripe.Close() + + srv, st := stripePayoutsTestServer(t, false, fakeStripe) + user := readyUser(t, st, "acct-w-marked", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusBadGateway { + t.Fatalf("got %d, want 502", w.Code) + } + wds, _ := st.ListStripeWithdrawals(user.AccountID, 0) + if len(wds) != 1 { + t.Fatalf("expected 1 withdrawal row, got %d", len(wds)) + } + if wds[0].Status != "failed" { + t.Errorf("status = %q, want failed", wds[0].Status) + } + if !wds[0].Refunded { + t.Error("refunded flag should be set") + } + if !strings.Contains(wds[0].FailureReason, "transfer_create_failed") { + t.Errorf("failure_reason = %q", wds[0].FailureReason) + } +} diff --git a/coordinator/api/billing/connect_withdraw_validation_test.go b/coordinator/api/billing/connect_withdraw_validation_test.go new file mode 100644 index 0000000000..ff31d96f60 --- /dev/null +++ b/coordinator/api/billing/connect_withdraw_validation_test.go @@ -0,0 +1,118 @@ +package billing + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestStripeWithdrawRejectsWithoutOnboarding(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := seedUser(t, st, "acct-w-1", "alice@example.com") + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusForbidden { + t.Errorf("got %d, want 403", w.Code) + } +} + +func TestStripeWithdrawRejectsBelowMinimum(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := readyUser(t, st, "acct-w-min", "alice@example.com", false) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"0.50","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusBadRequest { + t.Errorf("got %d, want 400", w.Code) + } +} + +func TestStripeWithdrawRejectsInstantWithoutDebitCard(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := readyUser(t, st, "acct-w-inst-1", "alice@example.com", false /* instant_eligible */) + st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerDeposit, "seed") + + body := `{"amount_usd":"5.00","method":"instant"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("got %d, want 400: %s", w.Code, w.Body.String()) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + errObj, _ := resp["error"].(map[string]any) + if errObj["type"] != "instant_unavailable" { + t.Errorf("error type = %v", errObj["type"]) + } +} + +func TestStripeWithdrawInsufficientBalance(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := readyUser(t, st, "acct-w-poor", "alice@example.com", false) + // No credit seeded. + + body := `{"amount_usd":"5.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusBadRequest { + t.Errorf("got %d, want 400", w.Code) + } + var resp map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &resp) + errObj, _ := resp["error"].(map[string]any) + if errObj["type"] != "insufficient_withdrawable" { + t.Errorf("error type = %v", errObj["type"]) + } +} + +// TestStripeWithdrawRejectsExceedingWithdrawableViaDebit verifies that the +// DebitWithdrawable path rejects a withdrawal that exceeds the withdrawable +// balance even when total balance is sufficient. +func TestStripeWithdrawRejectsExceedingWithdrawableViaDebit(t *testing.T) { + srv, st := stripePayoutsTestServer(t, true, nil) + user := readyUser(t, st, "acct-debit-guard", "guard@example.com", false) + + // $100 total but only $20 withdrawable. + st.Credit(user.AccountID, 80_000_000, store.LedgerStripeDeposit, "deposit") + st.CreditWithdrawable(user.AccountID, 20_000_000, store.LedgerPayout, "earnings") + + // Try to withdraw $30 — total balance is $100 but withdrawable is only $20. + body := `{"amount_usd":"30.00","method":"standard"}` + req := httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(body)) + req = withPrivyUser(req, user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("got %d, want 400; body: %s", w.Code, w.Body.String()) + } + + // Balances should be untouched. + if bal := st.GetBalance(user.AccountID); bal != 100_000_000 { + t.Errorf("balance = %d, want 100_000_000 (unchanged)", bal) + } + if wd := st.GetWithdrawableBalance(user.AccountID); wd != 20_000_000 { + t.Errorf("withdrawable = %d, want 20_000_000 (unchanged)", wd) + } +} diff --git a/coordinator/api/billing/connect_withdrawal_progress_test.go b/coordinator/api/billing/connect_withdrawal_progress_test.go new file mode 100644 index 0000000000..a7568dee55 --- /dev/null +++ b/coordinator/api/billing/connect_withdrawal_progress_test.go @@ -0,0 +1,92 @@ +package billing + +import ( + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// A webhook can settle or refund the transfer while the HTTP withdrawal +// handler is still awaiting payouts.create. Its later progress write must not +// overwrite that newer terminal state with the handler's old transferred row. +func TestStripeWithdrawalProgressPreservesConcurrentTerminal(t *testing.T) { + for _, terminal := range []string{"paid", "refunded"} { + t.Run(terminal, func(t *testing.T) { + var srv *controllerFixture + var st *store.MemoryStore + snapshots := make(chan store.StripeWithdrawal, 1) + callbackErrors := make(chan error, 1) + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/accounts/"): + _, _ = w.Write([]byte(healthyAccountJSON(strings.TrimPrefix(r.URL.Path, "/v1/accounts/"), "US", "full", true))) + case r.Method == http.MethodPost && r.URL.Path == "/v1/transfers": + _, _ = w.Write([]byte(`{"id":"tr_progress","amount":450,"currency":"usd"}`)) + case r.Method == http.MethodPost && r.URL.Path == "/v1/payouts": + row, err := st.GetStripeWithdrawalByTransferID("tr_progress") + if err == nil { + if terminal == "paid" { + var applied bool + applied, err = st.MarkStripeWithdrawalPaid(row.ID, "", "po_sweep") + if err == nil && !applied { + err = fmt.Errorf("paid transition not applied") + } + } else { + result := deliverConnectWebhook(t, srv, transferReversedPayload("tr_progress")) + if result.Code != http.StatusOK { + err = fmt.Errorf("reversal status%d: %s", result.Code, result.Body.String()) + } + } + } + if err == nil { + row, err = st.GetStripeWithdrawal(row.ID) + } + if err != nil { + callbackErrors <- err + http.Error(w, "fixture failed", 500) + return + } + snapshots <- *row + _, _ = w.Write([]byte(`{"id":"po_progress","amount":450,"status":"pending","method":"instant"}`)) + default: + http.Error(w, "unexpected path "+r.URL.Path, 500) + } + })) + defer fake.Close() + srv, st = stripePayoutsTestServer(t, false, fake) + user := readyUser(t, st, "progress-user", "progress@example.com", true) + if err := st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerPayout, "progress-funding"); err != nil { + t.Fatal(err) + } + req := withPrivyUser(httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(`{"amount_usd":"5.00","method":"instant"}`)), user) + w := httptest.NewRecorder() + srv.StripeWithdraw(w, req) + select { + case err := <-callbackErrors: + t.Fatal(err) + default: + } + var want store.StripeWithdrawal + select { + case want = <-snapshots: + default: + t.Fatalf("payout callback did not run: status%d %s", w.Code, w.Body.String()) + } + got, err := st.GetStripeWithdrawal(want.ID) + if err != nil { + t.Fatal(err) + } + if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "withdrawal_state_changed") { + t.Fatalf("concurrent update response=%d %s", w.Code, w.Body.String()) + } + if !reflect.DeepEqual(*got, want) { + t.Fatalf("late progress replaced terminal row: got%+v want%+v", *got, want) + } + }) + } +} diff --git a/coordinator/api/billing/controller.go b/coordinator/api/billing/controller.go new file mode 100644 index 0000000000..015c8d9390 --- /dev/null +++ b/coordinator/api/billing/controller.go @@ -0,0 +1,67 @@ +// Package billing owns billing, referral, pricing, earnings and payout HTTP +// controllers. Financial services and durable ledger transitions remain in +// coordinator/billing, payments and store. +package billing + +import ( + "log/slog" + "net/http" + "time" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/payments/baserewards" +) + +// ByteCache is the shared cache of serialized read responses. +// Implementations own synchronization and expiry; controllers retain no cache state. +type ByteCache interface { + Get(string) ([]byte, bool) + Set(string, []byte, time.Duration) +} + +// Metrics records the existing billing failure counters. +type Metrics interface { + Incr(string, []string) +} + +// Dependencies connects the HTTP controller to existing services. Service and +// BaseRewards are getters because configuration can be installed or replaced +// after routes are registered. They must be supplied even when they return nil. +// AuthorizeAdmin uses the router's current authentication policy and writes its +// rejection response. Store, Logger and Cache are shared with the router. +type Dependencies struct { + Store Store + Service func() *billingservice.Service + BaseRewards func() *baserewards.Engine + Logger *slog.Logger + Cache ByteCache + Metrics Metrics + AuthorizeAdmin func(http.ResponseWriter, *http.Request) bool +} + +// Controller holds endpoint dependencies without owning a second billing +// service, ledger, auth configuration or reconciliation store. +type Controller struct { + store Store + billing func() *billingservice.Service + baseRewards func() *baserewards.Engine + logger *slog.Logger + readCache ByteCache + metrics Metrics + authorizeAdmin func(http.ResponseWriter, *http.Request) bool +} + +// New binds endpoint dependencies without copying mutable service configuration. +func New(deps Dependencies) *Controller { + return &Controller{ + store: deps.Store, billing: deps.Service, baseRewards: deps.BaseRewards, + logger: deps.Logger, readCache: deps.Cache, metrics: deps.Metrics, + authorizeAdmin: deps.AuthorizeAdmin, + } +} + +func (s *Controller) recordMetric(name string, tags []string) { + if s.metrics != nil { + s.metrics.Incr(name, tags) + } +} diff --git a/coordinator/api/billing/controller_helpers_test.go b/coordinator/api/billing/controller_helpers_test.go new file mode 100644 index 0000000000..35b089e446 --- /dev/null +++ b/coordinator/api/billing/controller_helpers_test.go @@ -0,0 +1,43 @@ +package billing + +import ( + "context" + "log/slog" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" + "github.com/eigeninference/d-inference/coordinator/auth" + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/payments/baserewards" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// controllerFixture supplies the mutable service lifecycle used by the former +// Server fixtures. Endpoint bodies run against the real services and memory +// store; middleware and authenticated mux tests remain in the parent API package. +type controllerFixture struct { + *Controller + configuredService *billingservice.Service +} + +func newControllerFixture(st store.Store, logger *slog.Logger) *controllerFixture { + fixture := &controllerFixture{} + fixture.Controller = New(Dependencies{ + Store: st, Logger: logger, + Service: func() *billingservice.Service { return fixture.configuredService }, + BaseRewards: func() *baserewards.Engine { return nil }, + }) + return fixture +} + +func (f *controllerFixture) SetBilling(service *billingservice.Service) { + f.configuredService = service +} + +// withPrivyUser attaches exactly the user and account context values used by +// the existing direct-handler fixtures; it does not replace endpoint auth policy. +func withPrivyUser(r *http.Request, user *store.User) *http.Request { + ctx := requestcontext.WithAccountID(r.Context(), user.AccountID) + ctx = context.WithValue(ctx, auth.CtxKeyUser, user) + return r.WithContext(ctx) +} diff --git a/coordinator/api/billing/delivery.go b/coordinator/api/billing/delivery.go new file mode 100644 index 0000000000..83d56ec02d --- /dev/null +++ b/coordinator/api/billing/delivery.go @@ -0,0 +1,30 @@ +package billing + +import ( + "strings" +) + +func etaForMethod(method, accountCountry string) string { + if method == "instant" { + return "~30 minutes" + } + // Japan has no daily automatic payouts — accounts there sweep weekly + // (see billing.setAutoPayoutSchedule), so the honest ETA is up to a + // week to the sweep plus the bank rail. + if strings.EqualFold(strings.TrimSpace(accountCountry), "JP") { + return "up to 7-10 business days (weekly payout schedule)" + } + // Standard: Stripe's automatic daily payout sweeps the connected balance, + // then the bank rail (ACH/SEPA/local) takes 1-2 business days. Recipient- + // agreement accounts add +24h of transfer availability delay. + return "1-3 business days" +} + +// sweepDeliveryMessage is the human copy for a standard withdrawal's success +// response, honest about the country's actual sweep cadence. +func sweepDeliveryMessage(accountCountry string) string { + if strings.EqualFold(strings.TrimSpace(accountCountry), "JP") { + return "funds are on the way — Stripe pays out to your bank on a weekly schedule in Japan" + } + return "funds are on the way — Stripe pays out to your bank on a daily schedule" +} diff --git a/coordinator/api/billing/earnings.go b/coordinator/api/billing/earnings.go new file mode 100644 index 0000000000..f91d99f9c4 --- /dev/null +++ b/coordinator/api/billing/earnings.go @@ -0,0 +1,72 @@ +package billing + +import ( + "encoding/json" + "fmt" + "net/http" + "strconv" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" +) + +// AccountEarnings handles GET /v1/provider/account-earnings?limit=50. +// Returns recent earnings history, lifetime aggregates, and current account balance +// for the authenticated provider account. +// Cached for 20s per account — dashboard polls this frequently. +func (s *Controller) AccountEarnings(w http.ResponseWriter, r *http.Request) { + accountID := requestauth.ResolveAccountID(r) + + limit := 50 + if v := r.URL.Query().Get("limit"); v != "" { + if parsed, err := strconv.Atoi(v); err == nil && parsed > 0 { + limit = parsed + } + } + if limit > 1000 { + limit = 1000 + } + + cacheKey := "account-earnings:" + accountID + ":" + strconv.Itoa(limit) + if cached, ok := s.readCache.Get(cacheKey); ok { + httpresponse.WriteCachedJSON(w, cached) + return + } + + earnings, err := s.store.GetAccountEarnings(accountID, limit) + if err != nil { + s.logger.Error("get account earnings failed", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to fetch earnings")) + return + } + + summary, err := s.store.GetAccountEarningsSummary(accountID) + if err != nil { + s.logger.Error("get account earnings summary failed", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to fetch earnings summary")) + return + } + + availableBalance, withdrawableBalance := s.store.GetBalanceWithWithdrawable(accountID) + + body, err := json.Marshal(map[string]any{ + "account_id": accountID, + "earnings": earnings, + "total_micro_usd": summary.TotalMicroUSD, + "total_usd": fmt.Sprintf("%.6f", float64(summary.TotalMicroUSD)/1_000_000), + "count": summary.Count, + "recent_count": len(earnings), + "history_limit": limit, + "available_balance_micro_usd": availableBalance, + "available_balance_usd": fmt.Sprintf("%.6f", float64(availableBalance)/1_000_000), + "withdrawable_balance_micro_usd": withdrawableBalance, + "withdrawable_balance_usd": fmt.Sprintf("%.6f", float64(withdrawableBalance)/1_000_000), + }) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to marshal earnings")) + return + } + s.readCache.Set(cacheKey, body, 20*time.Second) + httpresponse.WriteCachedJSON(w, body) +} diff --git a/coordinator/api/billing/global_config_change_test.go b/coordinator/api/billing/global_config_change_test.go new file mode 100644 index 0000000000..b629fd27f4 --- /dev/null +++ b/coordinator/api/billing/global_config_change_test.go @@ -0,0 +1,107 @@ +package billing + +import ( + "context" + "encoding/json" + "net/http" + "testing" + "time" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func newConfigChangeQuote(t *testing.T, failFirst bool) (*controllerFixture, *store.MemoryStore, *store.User, *fakeGlobalStripe, string) { + t.Helper() + s, st, u, f := globalPayoutAPIFixture(t, failFirst) + w := globalAPIRequest(t, s, u, "/onboard", `{"country":"IN"}`, s.StripeOnboard) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + w = globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"10"}`, s.GlobalPayoutQuote) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + var q struct { + ID string `json:"id"` + } + if err := json.Unmarshal(w.Body.Bytes(), &q); err != nil { + t.Fatal(err) + } + return s, st, u, f, q.ID +} + +func TestGlobalPayoutFundingChangeReconcilesKnownReturn(t *testing.T) { + s, st, u, f, id := newConfigChangeQuote(t, false) + globalAPIRequest(t, s, u, "/withdraw", `{"amount_usd":"10","quote_id":"`+id+`"}`, s.StripeWithdraw) + s.billing().GlobalPayouts().FinancialAccount = "fa_new" + f.mu.Lock() + f.state = "returned" + f.mu.Unlock() + for range 2 { + if err := s.syncGlobalPayout(context.Background(), id); err != nil { + t.Fatal(err) + } + } + p, _ := st.GetGlobalPayout(id) + if !p.Refunded || f.creates != 1 || st.GetWithdrawableBalance(u.AccountID) != 20_000_000 { + t.Fatalf("old funding account return stranded: %+v", p) + } +} + +func TestGlobalPayoutFundingChangeRejectsUndebitedQuote(t *testing.T) { + s, st, u, f, id := newConfigChangeQuote(t, false) + s.billing().GlobalPayouts().FinancialAccount = "fa_new" + w := globalAPIRequest(t, s, u, "/withdraw", `{"amount_usd":"10","quote_id":"`+id+`"}`, s.StripeWithdraw) + p, _ := st.GetGlobalPayout(id) + if w.Code != 409 || !p.QuoteInvalidated || f.creates != 0 || st.GetWithdrawableBalance(u.AccountID) != 20_000_000 { + t.Fatalf("changed quote debited: %d %+v", w.Code, p) + } +} + +func TestGlobalPayoutFundingChangeRefundsOnlyFirstUnsentAttempt(t *testing.T) { + for _, ambiguous := range []bool{false, true} { + t.Run(map[bool]string{false: "never-sent", true: "ambiguous"}[ambiguous], func(t *testing.T) { + s, st, u, f, id := newConfigChangeQuote(t, ambiguous) + if ambiguous { + globalAPIRequest(t, s, u, "/withdraw", `{"amount_usd":"10","quote_id":"`+id+`"}`, s.StripeWithdraw) + } else { + if _, err := st.BeginGlobalPayout(u.AccountID, id, time.Now()); err != nil { + t.Fatal(err) + } + } + s.billing().GlobalPayouts().FinancialAccount = "fa_new" + if err := s.syncGlobalPayout(context.Background(), id); err != nil { + t.Fatal(err) + } + p, _ := st.GetGlobalPayout(id) + if ambiguous { + if p.Refunded || f.creates != 1 || st.GetWithdrawableBalance(u.AccountID) != 10_000_000 { + t.Fatalf("unknown payment refunded: %+v", p) + } + } else { + if !p.Refunded || f.creates != 0 || st.GetWithdrawableBalance(u.AccountID) != 20_000_000 { + t.Fatalf("unsent payment stranded: %+v", p) + } + } + }) + } +} + +func TestGlobalPayoutPauseExpiresUnsubmittedConfirmation(t *testing.T) { + s, st, u, f, id := newConfigChangeQuote(t, false) + base := s.billing().GlobalPayouts().BaseURL + s.SetBilling(billingservice.NewService(st, s.billing().Ledger(), s.logger, billingservice.Config{MockMode: true, StripeGlobalPayoutsFinancialAccount: "fa_gp", StripeGlobalPayoutsSecretKey: "rk_test_gp"})) + s.billing().GlobalPayouts().BaseURL = base + w := globalAPIRequest(t, s, u, "/withdraw", `{"amount_usd":"10","quote_id":"`+id+`"}`, s.StripeWithdraw) + var result struct { + Error struct { + Code string `json:"code"` + } `json:"error"` + } + _ = json.Unmarshal(w.Body.Bytes(), &result) + p, _ := st.GetGlobalPayout(id) + if w.Code != http.StatusConflict || result.Error.Code != "quote_paused" || !p.QuoteInvalidated || f.creates != 0 || st.GetWithdrawableBalance(u.AccountID) != 20_000_000 { + t.Fatalf("paused confirmation stranded: %d %s", w.Code, w.Body.String()) + } +} diff --git a/coordinator/api/billing/global_errors.go b/coordinator/api/billing/global_errors.go new file mode 100644 index 0000000000..8e51d5745e --- /dev/null +++ b/coordinator/api/billing/global_errors.go @@ -0,0 +1,41 @@ +package billing + +import ( + "errors" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/billing/globalpayouts" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func globalPayoutError(w http.ResponseWriter, err error) { + code, message, status := "payout_unavailable", "Bank withdrawals are temporarily unavailable. Please try again shortly.", http.StatusBadGateway + var stripeErr *globalpayouts.Error + if errors.As(err, &stripeErr) { + switch stripeErr.Code { + case "amount_too_small_for_payout_method", "amount_too_small_for_selected_delivery_option": + code, message, status = "invalid_request_error", "This bank transfer requires a larger withdrawal amount.", http.StatusBadRequest + case "amount_too_large_for_payout_method", "amount_too_large_for_selected_delivery_option": + code, message, status = "invalid_request_error", "This bank transfer exceeds the withdrawal limit. Try a smaller amount.", http.StatusBadRequest + case "fx_quote_expired": + code, message, status = "quote_expired", "The exchange quote expired. Review your withdrawal again.", http.StatusConflict + case "outbound_flow_unsupported_country", "recipient_feature_not_active", "payout_method_disabled", "payout_method_archived": + code, message, status = "not_onboarded", "Your bank account needs attention. Update your payout details in Stripe.", http.StatusConflict + } + } + if errors.Is(err, store.ErrInsufficientBalance) { + code, message, status = "insufficient_withdrawable", "Only available earned funds can be withdrawn.", http.StatusBadRequest + } + if errors.Is(err, store.ErrPayoutQuoteExpired) { + code, message, status = "quote_expired", "The exchange quote expired. Review your withdrawal again.", http.StatusConflict + } + if errors.Is(err, store.ErrPayoutConflict) { + code, message, status = "payout_changed", "Your payout details changed. Review your withdrawal again.", http.StatusConflict + } + var limitErr *globalpayouts.RecipientLimitError + if errors.As(err, &limitErr) { + code, message, status = "recipient_amount_limit", limitErr.Error(), http.StatusBadRequest + } + httpresponse.WriteJSON(w, status, httpresponse.ErrorBody(code, message)) +} diff --git a/coordinator/api/billing/global_history.go b/coordinator/api/billing/global_history.go new file mode 100644 index 0000000000..03976991fe --- /dev/null +++ b/coordinator/api/billing/global_history.go @@ -0,0 +1,42 @@ +package billing + +import ( + "fmt" + "sort" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func globalWithdrawalView(p store.GlobalPayout) map[string]any { + return map[string]any{"id": p.ID, "account_id": p.AccountID, "stripe_account_id": p.RecipientID, "payout_id": p.ExternalID, "amount_micro_usd": p.AmountMicroUSD, "net_micro_usd": p.AmountMicroUSD, "fee_micro_usd": int64(0), "method": "standard", "status": p.Status, "payout_rail": "global", "destination_amount": p.DestinationAmount, "payout_currency": p.Currency, "currency_exponent": payoutCurrencyExponent(p.Currency), "failure_reason": p.FailureCode, "refunded": p.Refunded, "created_at": p.SubmittedAt, "updated_at": p.CheckedAt} +} + +func (s *Controller) appendGlobalWithdrawals(accountID string, connect []store.StripeWithdrawal, limit int) ([]any, error) { + type entry struct { + at time.Time + value any + } + entries := make([]entry, 0, len(connect)) + for _, p := range connect { + entries = append(entries, entry{p.CreatedAt, p}) + } + if repo, ok := s.globalPayoutStore(); ok { + payouts, err := repo.ListGlobalPayouts(accountID, limit) + if err != nil { + return nil, fmt.Errorf("list Global Payouts: %w", err) + } + for _, p := range payouts { + entries = append(entries, entry{p.SubmittedAt, globalWithdrawalView(p)}) + } + } + sort.Slice(entries, func(i, j int) bool { return entries[i].at.After(entries[j].at) }) + if len(entries) > limit { + entries = entries[:limit] + } + out := make([]any, 0, len(entries)) + for _, e := range entries { + out = append(out, e.value) + } + return out, nil +} diff --git a/coordinator/api/billing/global_lifecycle_test.go b/coordinator/api/billing/global_lifecycle_test.go new file mode 100644 index 0000000000..27d548c5c2 --- /dev/null +++ b/coordinator/api/billing/global_lifecycle_test.go @@ -0,0 +1,312 @@ +package billing + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/billing/globalpayouts" + "github.com/eigeninference/d-inference/coordinator/store" +) + +type fakeGlobalStripe struct { + mu sync.Mutex + payments map[string]globalpayouts.Payment + creates int + failFirst bool + state string + rejectRequests bool + bankStatus int + emptyBanks bool + country, currency, quoteError string + rate int64 + quoteCalls int +} + +func (f *fakeGlobalStripe) serve(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + switch { + case r.URL.Path == "/v2/core/accounts" || strings.HasPrefix(r.URL.Path, "/v2/core/accounts/"): + _ = json.NewEncoder(w).Encode(map[string]any{"id": "acct_gp", "identity": map[string]string{"country": f.country}, "defaults": map[string]any{"payout_methods": map[string]string{f.currency: "pm_gp"}}, "configuration": map[string]any{"recipient": map[string]any{"capabilities": map[string]any{"bank_accounts": map[string]any{"local": map[string]string{"status": "active"}, "wire": map[string]string{"status": "active"}}}}}}) + case r.URL.Path == "/v2/core/account_links": + _, _ = w.Write([]byte(`{"url":"https://accounts.stripe.com/test-onboarding"}`)) + case r.URL.Path == "/v2/money_management/payout_methods": + if f.bankStatus != 0 { + w.WriteHeader(f.bankStatus) + _, _ = w.Write([]byte(`{"error":{"code":"api_error"}}`)) + return + } + if f.emptyBanks { + _, _ = w.Write([]byte(`{"data":[]}`)) + return + } + m := globalpayouts.BankMethod{ID: "pm_gp", Type: "bank_account"} + m.BankAccount.Country = strings.ToUpper(f.country) + m.BankAccount.Last4 = "1234" + m.BankAccount.SupportedCurrencies = []string{f.currency} + m.BankAccount.EnabledDeliveryOptions = []string{"local", "wire"} + m.UsageStatus.Payments = "eligible" + _ = json.NewEncoder(w).Encode(map[string]any{"data": []globalpayouts.BankMethod{m}}) + case r.URL.Path == "/v2/money_management/outbound_payment_quotes": + f.quoteCalls++ + if f.quoteError != "" { + w.WriteHeader(400) + _ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": f.quoteError}}) + return + } + var req globalpayouts.PaymentRequest + _ = json.NewDecoder(r.Body).Decode(&req) + q := globalpayouts.Quote{EstimatedFees: []globalpayouts.EstimatedFee{{Type: "standard_payout_fee", Amount: globalpayouts.EstimatedFeeAmount{Currency: "usd", Value: json.Number("150")}}}, ID: "obpq_gp", Amount: req.Amount, From: globalpayouts.Source{FinancialAccount: req.From["financial_account"], Debited: req.Amount}, To: globalpayouts.Destination{Recipient: req.To["recipient"], PayoutMethod: req.To["payout_method"], Credited: globalpayouts.Amount{Value: req.Amount.Value * f.rate, Currency: f.currency}}} + _ = json.NewEncoder(w).Encode(q) + case r.URL.Path == "/v2/money_management/outbound_payments": + if f.rejectRequests { + w.WriteHeader(403) + _, _ = w.Write([]byte(`{"error":{"code":"forbidden"}}`)) + return + } + key := r.Header.Get("Idempotency-Key") + p, ok := f.payments[key] + if !ok { + var req globalpayouts.PaymentRequest + _ = json.NewDecoder(r.Body).Decode(&req) + p = globalpayouts.Payment{ID: "obp_gp", Amount: req.Amount, From: globalpayouts.Source{FinancialAccount: req.From["financial_account"], Debited: req.Amount}, To: globalpayouts.Destination{Recipient: req.To["recipient"], PayoutMethod: req.To["payout_method"], Credited: globalpayouts.Amount{Value: req.Amount.Value * f.rate, Currency: f.currency}}, Status: "processing"} + f.payments[key] = p + f.creates++ + if f.failFirst { + w.WriteHeader(503) + _, _ = w.Write([]byte(`{"error":{"code":"response_lost"}}`)) + return + } + } + _ = json.NewEncoder(w).Encode(p) + case strings.HasPrefix(r.URL.Path, "/v2/money_management/outbound_payments/"): + for _, p := range f.payments { + p.Status = f.state + _ = json.NewEncoder(w).Encode(p) + return + } + w.WriteHeader(404) + default: + w.WriteHeader(404) + } +} + +func globalPayoutAPIFixture(t *testing.T, failFirst bool) (*controllerFixture, *store.MemoryStore, *store.User, *fakeGlobalStripe) { + t.Helper() + srv, st := stripePayoutsTestServer(t, true, nil) + srv.SetBilling(billingservice.NewService(st, srv.billing().Ledger(), srv.logger, billingservice.Config{MockMode: true, StripeConnectReturnURL: "https://app.test/billing", StripeGlobalPayoutsEnabled: true, StripeGlobalPayoutsFinancialAccount: "fa_gp", StripeGlobalPayoutsSecretKey: "rk_test_gp", StripeGlobalPayoutsWebhookSecret: "whsec_test"})) + f := &fakeGlobalStripe{payments: map[string]globalpayouts.Payment{}, failFirst: failFirst, state: "posted", country: "in", currency: "inr", rate: 80} + remote := httptest.NewServer(http.HandlerFunc(f.serve)) + t.Cleanup(remote.Close) + srv.billing().GlobalPayouts().BaseURL = remote.URL + u := seedUser(t, st, "gp-account", "provider@example.com") + if err := st.CreditWithdrawable(u.AccountID, 20_000_000, store.LedgerPayout, "earned"); err != nil { + t.Fatal(err) + } + return srv, st, u, f +} + +func globalAPIRequest(t *testing.T, s *controllerFixture, u *store.User, path, body string, handler http.HandlerFunc) *httptest.ResponseRecorder { + t.Helper() + req := withPrivyUser(httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)), u) + w := httptest.NewRecorder() + handler(w, req) + return w +} + +func TestGlobalPayoutOnboardQuoteConfirmAndReturn(t *testing.T) { + s, st, u, f := globalPayoutAPIFixture(t, true) + w := globalAPIRequest(t, s, u, "/onboard", `{"country":"IN"}`, s.StripeOnboard) + if w.Code != 200 { + t.Fatalf("onboard %d %s", w.Code, w.Body.String()) + } + local, _ := st.GetGlobalRecipient(u.AccountID) + if local.RecipientID != "acct_gp" { + t.Fatalf("recipient: %+v", local) + } + w = globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"10.00"}`, s.GlobalPayoutQuote) + if w.Code != 200 { + t.Fatalf("quote %d %s", w.Code, w.Body.String()) + } + var quote struct { + ID string `json:"id"` + DestinationAmount int64 `json:"destination_amount"` + } + _ = json.Unmarshal(w.Body.Bytes(), "e) + if quote.DestinationAmount != 80000 || st.GetWithdrawableBalance(u.AccountID) != 20_000_000 { + t.Fatal("quote moved funds or returned wrong currency amount") + } + body := `{"amount_usd":"10.00","method":"standard","quote_id":"` + quote.ID + `"}` + w = globalAPIRequest(t, s, u, "/withdraw", body, s.StripeWithdraw) + if w.Code != 202 { + t.Fatalf("confirm %d %s", w.Code, w.Body.String()) + } + p, _ := st.GetGlobalPayout(quote.ID) + if p.Status != "pending" || p.Refunded { + t.Fatalf("ambiguous send was refunded: %+v", p) + } + // Retry even after unlink must remain a Global Payouts confirmation. + if err := st.RemoveGlobalRecipient(u.AccountID); err != nil { + t.Fatal(err) + } + w = globalAPIRequest(t, s, u, "/withdraw", body, s.StripeWithdraw) + if w.Code != 202 { + t.Fatalf("retry %d %s", w.Code, w.Body.String()) + } + if f.creates != 1 || st.GetWithdrawableBalance(u.AccountID) != 10_000_000 { + t.Fatal("retry duplicated money movement") + } + p, _ = st.GetGlobalPayout(quote.ID) + if p.ExternalID != "obp_gp" { + t.Fatal("retry lost payout ID") + } + if err := s.syncGlobalPayout(httptest.NewRequest("GET", "/", nil).Context(), p.ID); err != nil { + t.Fatal(err) + } + p, _ = st.GetGlobalPayout(quote.ID) + if p.Status != "posted" { + t.Fatalf("status %s", p.Status) + } + f.state = "returned" + for range 2 { + if err := s.syncGlobalPayout(httptest.NewRequest("GET", "/", nil).Context(), p.ID); err != nil { + t.Fatal(err) + } + } + if st.GetWithdrawableBalance(u.AccountID) != 20_000_000 { + t.Fatal("bank return failed to refund exactly once") + } +} + +func TestGlobalPayoutRejectsInvalidQuotesAndCountries(t *testing.T) { + s, st, u, _ := globalPayoutAPIFixture(t, false) + for _, country := range []string{"CN", "KH", "GI"} { + w := globalAPIRequest(t, s, u, "/onboard", `{"country":"`+country+`"}`, s.StripeOnboard) + if w.Code != 400 { + t.Fatalf("unverified country %s accepted", country) + } + } + for _, value := range []string{"NaN", "Inf", "1e4", "1.001", "-5", "0.99", "1000001"} { + if _, err := payoutUSDCents(value); err == nil { + t.Fatalf("invalid amount accepted %q", value) + } + } + if st.GetWithdrawableBalance(u.AccountID) != 20_000_000 { + t.Fatal("invalid requests moved funds") + } +} + +func TestGlobalPayoutUnknownOutcomeStopsResubmitting(t *testing.T) { + s, st, u, f := globalPayoutAPIFixture(t, false) + r := store.GlobalRecipient{ID: "old", AccountID: u.AccountID, Country: "IN", RecipientID: "acct_gp", PayoutMethodID: "pm_gp", Ready: true} + _, _ = st.PrepareGlobalRecipient(r) + request := globalpayouts.NewRequest("fa_gp", "acct_gp", "pm_gp", "inr", 1000) + data, _ := json.Marshal(request) + p := store.GlobalPayout{ID: "old-quote", AccountID: u.AccountID, RecipientGeneration: r.ID, RecipientID: r.RecipientID, PayoutMethodID: r.PayoutMethodID, AmountMicroUSD: 10_000_000, Request: data, Status: "quoted", ExpiresAt: time.Now().Add(time.Minute)} + if err := st.CreateGlobalPayoutQuote(p); err != nil { + t.Fatal(err) + } + if _, err := st.BeginGlobalPayout(u.AccountID, p.ID, time.Now().Add(-13*time.Hour)); err != nil { + t.Fatal(err) + } + if err := s.syncGlobalPayout(httptest.NewRequest("GET", "/", nil).Context(), p.ID); err != nil { + t.Fatal(err) + } + if f.creates != 0 || st.GetWithdrawableBalance(u.AccountID) != 10_000_000 { + t.Fatal("old unknown outcome was resent or refunded") + } + parked, err := st.GetGlobalPayout(p.ID) + if err != nil || !parked.RequiresManualReconciliation() { + t.Fatalf("old unknown outcome was not parked: %+v %v", parked, err) + } + if err := s.syncGlobalPayout(httptest.NewRequest("GET", "/", nil).Context(), p.ID); err != nil { + t.Fatal(err) + } + after, _ := st.GetGlobalPayout(p.ID) + if after.DispatchAttempts != parked.DispatchAttempts || !after.CheckedAt.Equal(parked.CheckedAt) { + t.Fatal("manual reconciliation retry wrote or claimed the row again") + } + rows, err := st.ListGlobalPayoutsToReconcile(time.Now().Add(24*time.Hour), 200) + if err != nil || len(rows) != 0 { + t.Fatalf("manual payout returned to automatic scan: %+v %v", rows, err) + } +} + +func TestGlobalPayoutAmbiguousSendThenPermissionLossDoesNotRefund(t *testing.T) { + s, st, u, f := globalPayoutAPIFixture(t, true) + globalAPIRequest(t, s, u, "/onboard", `{"country":"IN"}`, s.StripeOnboard) + w := globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"10"}`, s.GlobalPayoutQuote) + var q struct { + ID string `json:"id"` + } + _ = json.Unmarshal(w.Body.Bytes(), &q) + body := `{"amount_usd":"10","quote_id":"` + q.ID + `"}` + globalAPIRequest(t, s, u, "/withdraw", body, s.StripeWithdraw) + f.mu.Lock() + f.rejectRequests = true + f.mu.Unlock() + globalAPIRequest(t, s, u, "/withdraw", body, s.StripeWithdraw) + p, _ := st.GetGlobalPayout(q.ID) + if p.Refunded || p.Status != "pending" || st.GetWithdrawableBalance(u.AccountID) != 10_000_000 { + t.Fatalf("permission loss refunded an already accepted payout: %+v", p) + } +} + +func TestGlobalPayoutPausePreservesReconciliation(t *testing.T) { + s, st, u, _ := globalPayoutAPIFixture(t, false) + globalAPIRequest(t, s, u, "/onboard", `{"country":"IN"}`, s.StripeOnboard) + w := globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"10"}`, s.GlobalPayoutQuote) + var q struct { + ID string `json:"id"` + } + _ = json.Unmarshal(w.Body.Bytes(), &q) + if _, err := st.BeginGlobalPayout(u.AccountID, q.ID, time.Now()); err != nil { + t.Fatal(err) + } + baseURL := s.billing().GlobalPayouts().BaseURL + s.SetBilling(billingservice.NewService(st, s.billing().Ledger(), s.logger, billingservice.Config{MockMode: true, StripeGlobalPayoutsFinancialAccount: "fa_gp", StripeGlobalPayoutsSecretKey: "rk_test_gp", StripeGlobalPayoutsWebhookSecret: "whsec_test"})) + s.billing().GlobalPayouts().BaseURL = baseURL + w = globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"10"}`, s.GlobalPayoutQuote) + if w.Code != http.StatusBadGateway { + t.Fatalf("new quote accepted while paused: %d", w.Code) + } + if err := s.syncGlobalPayout(httptest.NewRequest("GET", "/", nil).Context(), q.ID); err != nil { + t.Fatal(err) + } + p, _ := st.GetGlobalPayout(q.ID) + if p.ExternalID == "" || p.Status != "processing" { + t.Fatalf("paused confirmed payment was stranded: %+v", p) + } +} + +func TestGlobalPayoutWebhookUsesCurrentStateAndSignature(t *testing.T) { + s, st, u, _ := globalPayoutAPIFixture(t, false) + globalAPIRequest(t, s, u, "/onboard", `{"country":"IN"}`, s.StripeOnboard) + w := globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"10"}`, s.GlobalPayoutQuote) + var q struct { + ID string `json:"id"` + } + _ = json.Unmarshal(w.Body.Bytes(), &q) + globalAPIRequest(t, s, u, "/withdraw", `{"amount_usd":"10","quote_id":"`+q.ID+`"}`, s.StripeWithdraw) + payload := []byte(`{"type":"v2.money_management.outbound_payment.returned","related_object":{"id":"obp_gp"}}`) + unsigned := httptest.NewRecorder() + s.GlobalPayoutWebhook(unsigned, httptest.NewRequest("POST", "/", strings.NewReader(string(payload)))) + if unsigned.Code != 400 { + t.Fatalf("unsigned event accepted: %d", unsigned.Code) + } + signed := httptest.NewRecorder() + s.GlobalPayoutWebhook(signed, signedConnectRequest(t, payload, "whsec_test")) + if signed.Code != 200 { + t.Fatalf("signed event %d %s", signed.Code, signed.Body.String()) + } + p, _ := st.GetGlobalPayout(q.ID) + if p.Refunded || p.Status != "posted" { + t.Fatalf("webhook state was trusted instead of current Stripe state: %+v", p) + } +} diff --git a/coordinator/api/billing/global_limits_test.go b/coordinator/api/billing/global_limits_test.go new file mode 100644 index 0000000000..628831ebd7 --- /dev/null +++ b/coordinator/api/billing/global_limits_test.go @@ -0,0 +1,58 @@ +package billing + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/billing/globalpayouts" +) + +func TestGlobalPayoutRecipientLimits(t *testing.T) { + cases := []struct { + name, country, amount, quoteError, want string + rate int64 + calls int + }{ + {"usd-floor-before-stripe", "PA", "5", "", "50.00 USD", 1, 0}, + {"usd-other-floor", "SV", "5", "", "30.00 USD", 1, 0}, + {"fx-floor-from-quote", "TW", "5", "", "800.00 TWD", 30, 1}, + {"fx-floor-stripe-rejection", "TW", "5", "amount_too_small_for_payout_method", "800.00 TWD", 30, 1}, + {"fx-ceiling", "PE", "90000", "", "310000.00 PEN", 4, 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s, st, u, f := globalPayoutAPIFixture(t, false) + policy, _ := globalpayouts.Lookup(tc.country) + f.country = strings.ToLower(tc.country) + f.currency = policy.Currency + f.rate = tc.rate + f.quoteError = tc.quoteError + w := globalAPIRequest(t, s, u, "/onboard", `{"country":"`+tc.country+`"}`, s.StripeOnboard) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + w = globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"`+tc.amount+`"}`, s.GlobalPayoutQuote) + if w.Code != 400 || !strings.Contains(w.Body.String(), tc.want) || f.quoteCalls != tc.calls || st.GetWithdrawableBalance(u.AccountID) != 20_000_000 { + t.Fatalf("limit not actionable or moved funds: %d %s calls=%d", w.Code, w.Body.String(), f.quoteCalls) + } + w = globalAPIRequest(t, s, u, "/status", ``, s.StripeStatus) + if !strings.Contains(w.Body.String(), "recipient_limits") { + t.Fatal("limits missing before review") + } + }) + } +} + +func TestGlobalPayoutQuoteRetainsStripeFeeEstimate(t *testing.T) { + s, st, u, _, id := newConfigChangeQuote(t, false) + p, _ := st.GetGlobalPayout(id) + var fees []globalpayouts.EstimatedFee + if err := json.Unmarshal(p.EstimatedStripeFees, &fees); err != nil || len(fees) != 1 || fees[0].Amount.Value.String() != "150" { + t.Fatalf("fee estimate lost: %s %v", p.EstimatedStripeFees, err) + } + w := globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"10"}`, s.GlobalPayoutQuote) + if !strings.Contains(w.Body.String(), `"fee_usd":"0.00"`) { + t.Fatal("platform fee was charged to provider") + } +} diff --git a/coordinator/api/billing/global_onboarding.go b/coordinator/api/billing/global_onboarding.go new file mode 100644 index 0000000000..32a801303d --- /dev/null +++ b/coordinator/api/billing/global_onboarding.go @@ -0,0 +1,161 @@ +package billing + +import ( + "context" + "errors" + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/billing/globalpayouts" + "github.com/eigeninference/d-inference/coordinator/store" + "github.com/google/uuid" +) + +func (s *Controller) globalPayoutStore() (store.GlobalPayoutStore, bool) { + if s.billing() == nil { + return nil, false + } + return store.As[store.GlobalPayoutStore](s.billing().Store()) +} + +func (s *Controller) payoutCountries() []globalpayouts.Country { + if s.billing() == nil || !s.billing().GlobalPayoutsEnabled() { + return nil + } + return append([]globalpayouts.Country(nil), globalpayouts.Countries...) +} + +// maybeGlobalOnboard is called after validating redirects, before any Express +// account is created. Existing ready Connect destinations remain usable. +func (s *Controller) maybeGlobalOnboard(w http.ResponseWriter, r *http.Request, user *store.User, country, returnURL, refreshURL string) bool { + repo, ok := s.globalPayoutStore() + if !ok { + return false + } + active, err := repo.GetGlobalRecipient(user.AccountID) + if err != nil && !errors.Is(err, store.ErrNotFound) { + globalPayoutError(w, err) + return true + } + if !s.billing().GlobalPayoutsEnabled() && errors.Is(err, store.ErrNotFound) { + return false + } + if country == "" && err == nil { + country = active.Country + } + if country == "" { + return false + } // existing Connect onboarding handles default/required country + policy, known := globalpayouts.Lookup(country) + legacyReady := user.StripeAccountID != "" && user.StripeAccountStatus == stripeStatusReady && user.StripeAccountCountry == country && errors.Is(err, store.ErrNotFound) + if legacyReady || (known && policy.Rail == "connect") { + return false + } + if !known || !s.billing().GlobalPayoutsEnabled() { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("country_unavailable", "Bank withdrawals are not available in this country yet. Your earnings remain in your account.")) + return true + } + if user.Email == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("email_required", "Add an email address to your account before setting up bank withdrawals.")) + return true + } + local, err := repo.PrepareGlobalRecipient(store.GlobalRecipient{ID: uuid.NewString(), AccountID: user.AccountID, Country: country}) + if err != nil { + globalPayoutError(w, err) + return true + } + client := s.billing().GlobalPayouts() + if local.RecipientID == "" { + remote, e := client.CreateRecipient(r.Context(), user.Email, country, policy.Capability, "gp-recipient-"+local.ID) + if e != nil { + s.logger.Warn("global payout recipient create failed", "error", e) + globalPayoutError(w, e) + return true + } + if remote.ID == "" || !strings.EqualFold(remote.Identity.Country, country) { + globalPayoutError(w, store.ErrPayoutConflict) + return true + } + local.RecipientID = remote.ID + if e = repo.SaveGlobalRecipient(*local); e != nil { + globalPayoutError(w, e) + return true + } + } + link, err := client.OnboardingLink(r.Context(), local.RecipientID, returnURL, refreshURL) + if err != nil { + s.logger.Warn("global payout onboarding link failed", "error", err) + globalPayoutError(w, err) + return true + } + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"url": link, "stripe_account_id": local.RecipientID, "status": "pending", "payout_rail": "global"}) + return true +} + +func (s *Controller) refreshGlobalRecipient(ctx context.Context, local *store.GlobalRecipient) error { + client := s.billing().GlobalPayouts() + if client == nil { + return errors.New("Global Payouts is disabled") + } + policy, ok := globalpayouts.Lookup(local.Country) + if !ok || policy.Capability == "" { + return store.ErrPayoutConflict + } + remote, err := client.Recipient(ctx, local.RecipientID) + if err != nil { + return err + } + updated := *local + updated.Ready = false + updated.PayoutMethodID = "" + updated.Last4 = "" + if remote.Ready(local.Country, policy.Capability) { + method, e := client.BankMethod(ctx, remote, local.Country, policy.Currency, policy.Capability) + if e != nil && !errors.Is(e, globalpayouts.ErrNoEligibleBankMethod) { + return e + } + if e == nil { + updated.Ready = true + updated.PayoutMethodID = method.ID + updated.Last4 = method.BankAccount.Last4 + } + } + repo, _ := s.globalPayoutStore() + if err := repo.SaveGlobalRecipient(updated); err != nil { + return err + } + *local = updated + return nil +} + +func (s *Controller) maybeGlobalStatus(w http.ResponseWriter, r *http.Request, user *store.User) bool { + repo, ok := s.globalPayoutStore() + if !ok { + return false + } + local, err := repo.GetGlobalRecipient(user.AccountID) + if errors.Is(err, store.ErrNotFound) { + return false + } + if err != nil { + globalPayoutError(w, err) + return true + } + configured := s.billing().GlobalPayoutsEnabled() + if configured && local.RecipientID != "" && r.URL.Query().Get("refresh") == "1" { + if err = s.refreshGlobalRecipient(r.Context(), local); err != nil { + s.logger.Warn("global payout recipient refresh failed", "error", err) + globalPayoutError(w, err) + return true + } + } + status := "pending" + if local.Ready && configured { + status = "ready" + } + policy, _ := globalpayouts.Lookup(local.Country) + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"account_id": user.AccountID, "configured": true, "has_account": true, "stripe_account_id": local.RecipientID, "stripe_account_country": local.Country, "status": status, "destination_type": "bank", "destination_last4": local.Last4, "instant_eligible": false, "min_withdraw_micro_usd": billingservice.MinWithdrawMicroUSD, "payout_rail": "global", "payout_currency": policy.Currency, "recipient_limits": policy.Limits(), "countries": s.payoutCountries(), "payouts_available": configured}) + return true +} diff --git a/coordinator/api/billing/global_persistence.go b/coordinator/api/billing/global_persistence.go new file mode 100644 index 0000000000..e0f68ad8ca --- /dev/null +++ b/coordinator/api/billing/global_persistence.go @@ -0,0 +1,32 @@ +package billing + +import ( + "context" + "errors" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Preserve the first definitive response before attempting the ledger refund. +// A disconnected browser must not cancel this write. A stored rejection fences +// subsequent dispatches, so even a later refund failure is safe to retry. +func recordGlobalPayoutRejection(ctx context.Context, repo store.GlobalPayoutStore, id string, attempt int, code string) error { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second) + defer cancel() + var err error + for retry := 0; retry < 3; retry++ { + err = repo.RecordGlobalPayoutRejection(id, attempt, code) + if err == nil || errors.Is(err, store.ErrPayoutConflict) || errors.Is(err, store.ErrNotFound) { + return err + } + timer := time.NewTimer(time.Duration(retry+1) * 100 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } + return err +} diff --git a/coordinator/api/billing/global_quote.go b/coordinator/api/billing/global_quote.go new file mode 100644 index 0000000000..3960817541 --- /dev/null +++ b/coordinator/api/billing/global_quote.go @@ -0,0 +1,117 @@ +package billing + +import ( + "encoding/json" + "errors" + "net/http" + "strings" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" + "github.com/eigeninference/d-inference/coordinator/billing/globalpayouts" + "github.com/eigeninference/d-inference/coordinator/store" + "github.com/google/uuid" +) + +func (s *Controller) GlobalPayoutQuote(w http.ResponseWriter, r *http.Request) { + user := requestauth.RequirePrivyUser(w, r) + if user == nil { + return + } + repo, ok := s.globalPayoutStore() + if !ok || !s.billing().GlobalPayoutsEnabled() { + globalPayoutError(w, errors.New("Global Payouts unavailable")) + return + } + var req struct { + Amount string `json:"amount_usd"` + } + if json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req) != nil { + httpresponse.WriteJSON(w, 400, httpresponse.ErrorBody("invalid_request_error", "Enter a valid withdrawal amount.")) + return + } + cents, err := payoutUSDCents(req.Amount) + if err != nil { + httpresponse.WriteJSON(w, 400, httpresponse.ErrorBody("invalid_request_error", err.Error())) + return + } + local, err := repo.GetGlobalRecipient(user.AccountID) + if err != nil { + globalPayoutError(w, err) + return + } + if err = s.refreshGlobalRecipient(r.Context(), local); err != nil { + globalPayoutError(w, err) + return + } + if !local.Ready { + httpresponse.WriteJSON(w, 409, httpresponse.ErrorBody("not_onboarded", "Complete your bank details in Stripe before withdrawing.")) + return + } + policy, _ := globalpayouts.Lookup(local.Country) + // The input is USD. Only USD destination bounds can be compared before FX. + if policy.Currency == "usd" { + if err := policy.ValidateRecipientAmount(globalpayouts.Amount{Value: cents, Currency: "usd"}); err != nil { + globalPayoutError(w, err) + return + } + } + request := globalpayouts.NewRequest(s.billing().GlobalPayouts().FinancialAccount, local.RecipientID, local.PayoutMethodID, policy.Currency, cents) + quote, err := s.billing().GlobalPayouts().Quote(r.Context(), request) + if err != nil { + s.logger.Warn("global payout quote failed", "error", err) + var stripeErr *globalpayouts.Error + if errors.As(err, &stripeErr) { + var limitErr error + if strings.HasPrefix(stripeErr.Code, "amount_too_small") { + limitErr = policy.LimitError(true) + } + if strings.HasPrefix(stripeErr.Code, "amount_too_large") { + limitErr = policy.LimitError(false) + } + if limitErr != nil { + err = limitErr + } + } + globalPayoutError(w, err) + return + } + if err = quote.Validate(request); err != nil { + globalPayoutError(w, err) + return + } + if err := policy.ValidateRecipientAmount(quote.To.Credited); err != nil { + globalPayoutError(w, err) + return + } + now := time.Now() + expires := now.Add(2 * time.Minute) + if quote.FXQuote != nil && !quote.FXQuote.LockExpiresAt.IsZero() && quote.FXQuote.LockExpiresAt.Before(expires) { + expires = quote.FXQuote.LockExpiresAt + } + if !expires.After(now.Add(5 * time.Second)) { + globalPayoutError(w, store.ErrPayoutQuoteExpired) + return + } + id := uuid.NewString() + request.QuoteID = quote.ID + request.Description = "Darkbloom earnings" + request.Metadata = map[string]string{"darkbloom_withdrawal_id": id} + payload, err := json.Marshal(request) + if err != nil { + globalPayoutError(w, err) + return + } + fees, err := json.Marshal(quote.EstimatedFees) + if err != nil { + globalPayoutError(w, err) + return + } + p := store.GlobalPayout{EstimatedStripeFees: fees, ID: id, AccountID: user.AccountID, RecipientID: local.RecipientID, RecipientGeneration: local.ID, PayoutMethodID: local.PayoutMethodID, Country: local.Country, AmountMicroUSD: cents * 10_000, DestinationAmount: quote.To.Credited.Value, Currency: quote.To.Credited.Currency, Request: payload, Status: "quoted", ExpiresAt: expires, CreatedAt: now} + if err = repo.CreateGlobalPayoutQuote(p); err != nil { + globalPayoutError(w, err) + return + } + httpresponse.WriteJSON(w, 200, map[string]any{"id": id, "amount_usd": formatUSD(p.AmountMicroUSD), "fee_usd": "0.00", "destination_amount": p.DestinationAmount, "currency": p.Currency, "currency_exponent": payoutCurrencyExponent(p.Currency), "expires_at": expires, "destination_last4": local.Last4, "eta": "Typically 1–7 business days"}) +} diff --git a/coordinator/api/billing/global_reconcile.go b/coordinator/api/billing/global_reconcile.go new file mode 100644 index 0000000000..78ca2fc470 --- /dev/null +++ b/coordinator/api/billing/global_reconcile.go @@ -0,0 +1,129 @@ +package billing + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/eigeninference/d-inference/coordinator/billing/globalpayouts" + "github.com/eigeninference/d-inference/coordinator/saferun" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// syncGlobalPayout always reads Stripe's current state rather than applying +// potentially duplicated/out-of-order webhook state directly to the ledger. +func (s *Controller) syncGlobalPayout(ctx context.Context, id string) error { + repo, ok := s.globalPayoutStore() + if !ok || s.billing().GlobalPayouts() == nil { + return errors.New("Global Payouts unavailable") + } + claimed, err := repo.ClaimGlobalPayout(id, time.Now()) + if err != nil { + return err + } + if !claimed { + p, e := repo.GetGlobalPayout(id) + if e != nil { + return e + } + if p.Refunded || p.RequiresManualReconciliation() { + return nil + } + return errors.New("payout reconciliation is already in progress") + } + p, err := repo.GetGlobalPayout(id) + if err != nil { + return err + } + if p.Rejection != nil { + return repo.ApplyGlobalPayout(id, store.GlobalPayoutResult{Status: "failed", FailureCode: p.Rejection.Code}, time.Now()) + } + // Stop automatic work before the idempotency retention horizon, including + // old ambiguous requests whose original funding configuration has changed. + if p.ExternalID == "" && time.Since(p.SubmittedAt) > 12*time.Hour { + if err := repo.ApplyGlobalPayout(id, store.GlobalPayoutResult{FailureCode: store.GlobalPayoutManualReview}, time.Now()); err != nil { + return err + } + s.logger.Error("global payout outcome requires manual reconciliation", "withdrawal_id", p.ID) + return nil + } + var request globalpayouts.PaymentRequest + if err = json.Unmarshal(p.Request, &request); err != nil { + return err + } + if p.ExternalID == "" && request.From["financial_account"] != s.billing().GlobalPayouts().FinancialAccount { + // This claim reserved the first attempt; no Send has run yet. Persist + // that rejection before refunding. Prior ambiguous attempts stay held. + if p.DispatchAttempts == 1 { + if err := recordGlobalPayoutRejection(ctx, repo, p.ID, p.DispatchAttempts, "funding_account_changed"); err != nil { + return err + } + return repo.ApplyGlobalPayout(id, store.GlobalPayoutResult{Status: "failed", FailureCode: "funding_account_changed"}, time.Now()) + } + return repo.ApplyGlobalPayout(id, store.GlobalPayoutResult{FailureCode: "funding_account_changed"}, time.Now()) + } + var remote *globalpayouts.Payment + client := s.billing().GlobalPayouts() + if p.ExternalID != "" { + remote, err = client.Payment(ctx, p.ExternalID) + } else { + remote, err = client.Send(ctx, p.Request, "gp-withdraw-"+p.ID) + } + if err != nil { + result := store.GlobalPayoutResult{FailureCode: "confirmation_pending"} + var apiErr *globalpayouts.Error + if p.ExternalID == "" && p.DispatchAttempts == 1 && errors.As(err, &apiErr) && apiErr.Definitive() { + if persistErr := recordGlobalPayoutRejection(ctx, repo, p.ID, p.DispatchAttempts, apiErr.Code); persistErr != nil { + return persistErr + } + result.Status = "failed" + result.FailureCode = apiErr.Code + } + if persistErr := repo.ApplyGlobalPayout(id, result, time.Now()); persistErr != nil { + return persistErr + } + return err + } + if err = remote.Validate(request); err != nil { + return err + } + return repo.ApplyGlobalPayout(id, store.GlobalPayoutResult{ExternalID: remote.ID, Status: remote.Status, FailureCode: remote.StatusDetails[remote.Status].Reason, DestinationAmount: remote.To.Credited.Value, Currency: remote.To.Credited.Currency, Arrival: remote.ExpectedArrivalDate}, time.Now()) +} + +func (s *Controller) StartGlobalPayoutReconciler(ctx context.Context) { + repo, ok := s.globalPayoutStore() + if !ok { + return + } + saferun.Go(s.logger, "api.globalPayoutReconciler", func() { + ticker := time.NewTicker(time.Minute) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + if _, err := repo.PruneExpiredGlobalPayoutQuotes(time.Now(), 1000); err != nil { + s.logger.Warn("expired payout quote cleanup failed", "error", err) + } + if s.billing().GlobalPayouts() == nil { + continue + } + rows, err := repo.ListGlobalPayoutsToReconcile(time.Now(), 200) + if err != nil { + s.logger.Error("global payout reconciliation scan failed", "error", err) + continue + } + for _, p := range rows { + if ctx.Err() != nil { + return + } + if err = s.syncGlobalPayout(ctx, p.ID); err != nil { + s.logger.Warn("global payout reconciliation failed", "withdrawal_id", p.ID, "error", err) + } + } + } + }) +} diff --git a/coordinator/api/billing/global_recovery_test.go b/coordinator/api/billing/global_recovery_test.go new file mode 100644 index 0000000000..b530ff1b86 --- /dev/null +++ b/coordinator/api/billing/global_recovery_test.go @@ -0,0 +1,144 @@ +package billing + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "testing" + "time" + + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestGlobalPayoutDisabledPreservesLegacyConnect(t *testing.T) { + for _, country := range []string{"AU", "IN", "JP", "BR", "GH", "NG"} { + t.Run(country, func(t *testing.T) { + s, st, u, _ := globalPayoutAPIFixture(t, false) + s.SetBilling(billingservice.NewService(st, s.billing().Ledger(), s.logger, billingservice.Config{MockMode: true, StripeConnectReturnURL: "https://app.test/billing", StripeGlobalPayoutsFinancialAccount: "fa_gp", StripeGlobalPayoutsSecretKey: "rk_test_gp"})) + if s.billing().GlobalPayouts() == nil { + t.Fatal("test must configure the disabled client") + } + if s.payoutCountries() != nil { + t.Fatal("disabled flag replaced the legacy country menu") + } + w := globalAPIRequest(t, s, u, "/onboard", `{"country":"`+country+`"}`, s.StripeOnboard) + if w.Code != 200 { + t.Fatalf("legacy onboarding rejected: %d %s", w.Code, w.Body.String()) + } + if _, err := st.GetGlobalRecipient(u.AccountID); !errors.Is(err, store.ErrNotFound) { + t.Fatal("disabled global route created a recipient") + } + updated, _ := st.GetUserByAccountID(u.AccountID) + if updated.StripeAccountCountry != country { + t.Fatalf("Connect country lost: %+v", updated) + } + }) + } +} + +func TestGlobalPayoutBankLookupFailurePreservesReadyDestination(t *testing.T) { + s, st, u, f := globalPayoutAPIFixture(t, false) + globalAPIRequest(t, s, u, "/onboard", `{"country":"IN"}`, s.StripeOnboard) + w := globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"10"}`, s.GlobalPayoutQuote) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + original, _ := st.GetGlobalRecipient(u.AccountID) + for _, code := range []int{429, 500} { + f.mu.Lock() + f.bankStatus = code + f.mu.Unlock() + for _, handler := range []http.HandlerFunc{s.StripeStatus, s.GlobalPayoutQuote} { + w = globalAPIRequest(t, s, u, "/?refresh=1", `{"amount_usd":"10"}`, handler) + if w.Code != 502 { + t.Fatalf("transient Stripe failure became onboarding failure: %d %s", w.Code, w.Body.String()) + } + after, _ := st.GetGlobalRecipient(u.AccountID) + if *after != *original { + t.Fatalf("transient failure changed destination: %+v", after) + } + } + } + f.mu.Lock() + f.bankStatus = 0 + f.emptyBanks = true + f.mu.Unlock() + w = globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"10"}`, s.GlobalPayoutQuote) + after, _ := st.GetGlobalRecipient(u.AccountID) + if w.Code != 409 || after.Ready { + t.Fatalf("successful empty lookup should require bank setup: %d %+v", w.Code, after) + } +} + +type failingGlobalPayoutPersistence struct { + *store.MemoryStore + recordFailures, refundFailures, recordCalls, refundCalls int + claimOffset time.Duration +} + +func (f *failingGlobalPayoutPersistence) RecordGlobalPayoutRejection(id string, attempt int, code string) error { + f.recordCalls++ + if f.recordFailures > 0 { + f.recordFailures-- + return errors.New("temporary rejection write failure") + } + return f.MemoryStore.RecordGlobalPayoutRejection(id, attempt, code) +} + +func (f *failingGlobalPayoutPersistence) ApplyGlobalPayout(id string, result store.GlobalPayoutResult, now time.Time) error { + f.refundCalls++ + if f.refundFailures > 0 { + f.refundFailures-- + return errors.New("temporary refund transaction failure") + } + return f.MemoryStore.ApplyGlobalPayout(id, result, now) +} + +func (f *failingGlobalPayoutPersistence) ClaimGlobalPayout(id string, now time.Time) (bool, error) { + return f.MemoryStore.ClaimGlobalPayout(id, now.Add(f.claimOffset)) +} + +func TestGlobalPayoutDefinitiveRejectionSurvivesRefundFailure(t *testing.T) { + s, st, u, f := globalPayoutAPIFixture(t, false) + globalAPIRequest(t, s, u, "/onboard", `{"country":"IN"}`, s.StripeOnboard) + w := globalAPIRequest(t, s, u, "/quote", `{"amount_usd":"10"}`, s.GlobalPayoutQuote) + var q struct { + ID string `json:"id"` + } + _ = json.Unmarshal(w.Body.Bytes(), &q) + wrapper := &failingGlobalPayoutPersistence{MemoryStore: st, recordFailures: 1, refundFailures: 1} + cfg := billingservice.Config{MockMode: true, StripeGlobalPayoutsEnabled: true, StripeGlobalPayoutsFinancialAccount: "fa_gp", StripeGlobalPayoutsSecretKey: "rk_test_gp"} + baseURL := s.billing().GlobalPayouts().BaseURL + s.SetBilling(billingservice.NewService(wrapper, s.billing().Ledger(), s.logger, cfg)) + s.billing().GlobalPayouts().BaseURL = baseURL + f.mu.Lock() + f.rejectRequests = true + f.mu.Unlock() + w = globalAPIRequest(t, s, u, "/withdraw", `{"amount_usd":"10","quote_id":"`+q.ID+`"}`, s.StripeWithdraw) + if w.Code != 202 { + t.Fatal(w.Body.String()) + } + p, _ := st.GetGlobalPayout(q.ID) + if p.Rejection == nil || p.Refunded || wrapper.recordCalls != 2 { + t.Fatalf("rejection not durable before failed refund: %+v", p) + } + // Permissions recover before the next worker. A second Send would now move money. + f.mu.Lock() + f.rejectRequests = false + f.mu.Unlock() + wrapper.claimOffset = 2 * time.Minute + s.SetBilling(billingservice.NewService(wrapper, s.billing().Ledger(), s.logger, cfg)) + s.billing().GlobalPayouts().BaseURL = baseURL + if err := s.syncGlobalPayout(context.Background(), q.ID); err != nil { + t.Fatal(err) + } + if err := s.syncGlobalPayout(context.Background(), q.ID); err != nil { + t.Fatal(err) + } + p, _ = st.GetGlobalPayout(q.ID) + if !p.Refunded || p.DispatchAttempts != 1 || f.creates != 0 || st.GetWithdrawableBalance(u.AccountID) != 20_000_000 { + t.Fatalf("failed refund led to redispatch or stranded earnings: %+v, creates=%d", p, f.creates) + } +} diff --git a/coordinator/api/billing/global_webhook.go b/coordinator/api/billing/global_webhook.go new file mode 100644 index 0000000000..56ea1aef7c --- /dev/null +++ b/coordinator/api/billing/global_webhook.go @@ -0,0 +1,81 @@ +package billing + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + billingservice "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func (s *Controller) GlobalPayoutWebhook(w http.ResponseWriter, r *http.Request) { + if s.billing() == nil || s.billing().GlobalPayouts() == nil || s.billing().GlobalPayoutsWebhookSecret() == "" { + httpresponse.WriteJSON(w, 503, httpresponse.ErrorBody("not_configured", "Payout event processing is unavailable.")) + return + } + payload, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) + if err != nil { + httpresponse.WriteJSON(w, 400, httpresponse.ErrorBody("invalid_request_error", "Invalid event.")) + return + } + verifier := billingservice.NewStripeConnect("", s.billing().GlobalPayoutsWebhookSecret(), "US", false, s.logger) + if _, err = verifier.VerifyConnectWebhookSignature(payload, r.Header.Get("Stripe-Signature")); err != nil { + httpresponse.WriteJSON(w, 400, httpresponse.ErrorBody("invalid_signature", "Invalid event signature.")) + return + } + var event struct { + Type string `json:"type"` + RelatedObject struct { + ID string `json:"id"` + } `json:"related_object"` + Data struct { + Object struct { + ID string `json:"id"` + } `json:"object"` + RelatedObject struct { + ID string `json:"id"` + } `json:"related_object"` + } `json:"data"` + } + if json.Unmarshal(payload, &event) != nil { + httpresponse.WriteJSON(w, 400, httpresponse.ErrorBody("invalid_request_error", "Invalid event.")) + return + } + if !strings.Contains(event.Type, "outbound_payment.") { + httpresponse.WriteJSON(w, 200, map[string]bool{"received": true}) + return + } + id := event.Data.Object.ID + if id == "" { + id = event.RelatedObject.ID + } + if id == "" { + id = event.Data.RelatedObject.ID + } + if !strings.HasPrefix(id, "obp_") { + httpresponse.WriteJSON(w, 200, map[string]bool{"received": true}) + return + } + repo, ok := s.globalPayoutStore() + if !ok { + httpresponse.WriteJSON(w, 503, httpresponse.ErrorBody("not_configured", "Payout storage unavailable.")) + return + } + p, err := repo.GetGlobalPayoutByExternalID(id) + if errors.Is(err, store.ErrNotFound) { // A webhook can precede the create response. The persisted pending row is retried by the reconciler. + httpresponse.WriteJSON(w, 200, map[string]bool{"received": true}) + return + } + if err == nil { + err = s.syncGlobalPayout(r.Context(), p.ID) + } + if err != nil { + httpresponse.WriteJSON(w, 500, httpresponse.ErrorBody("reconcile_error", "Retry event delivery.")) + return + } + httpresponse.WriteJSON(w, 200, map[string]bool{"received": true}) +} diff --git a/coordinator/api/billing/global_withdraw.go b/coordinator/api/billing/global_withdraw.go new file mode 100644 index 0000000000..9f006a7b38 --- /dev/null +++ b/coordinator/api/billing/global_withdraw.go @@ -0,0 +1,113 @@ +package billing + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/billing/globalpayouts" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func (s *Controller) maybeGlobalWithdraw(w http.ResponseWriter, r *http.Request, user *store.User) bool { + repo, ok := s.globalPayoutStore() + if !ok { + return false + } + // Inspect once and restore the body for the Connect handler. A Global + // confirmation must remain on its original rail even after unlink/country changes. + body, readErr := io.ReadAll(http.MaxBytesReader(w, r.Body, 4096)) + if readErr != nil { + httpresponse.WriteJSON(w, 400, httpresponse.ErrorBody("invalid_request_error", "Invalid withdrawal request.")) + return true + } + r.Body = io.NopCloser(bytes.NewReader(body)) + var req struct { + Amount string `json:"amount_usd"` + Method string `json:"method"` + QuoteID string `json:"quote_id"` + } + decodeErr := json.Unmarshal(body, &req) + local, err := repo.GetGlobalRecipient(user.AccountID) + if errors.Is(err, store.ErrNotFound) && req.QuoteID == "" { + return false + } + if err != nil && !errors.Is(err, store.ErrNotFound) { + globalPayoutError(w, err) + return true + } + if s.billing().GlobalPayouts() == nil { + globalPayoutError(w, errors.New("Global Payouts unavailable")) + return true + } + if decodeErr != nil { + httpresponse.WriteJSON(w, 400, httpresponse.ErrorBody("invalid_request_error", "Invalid withdrawal request.")) + return true + } + cents, err := payoutUSDCents(req.Amount) + if err != nil || req.QuoteID == "" || (req.Method != "" && req.Method != "standard") { + httpresponse.WriteJSON(w, 400, httpresponse.ErrorBody("quote_required", "Review your bank withdrawal before confirming.")) + return true + } + p, err := repo.GetGlobalPayout(req.QuoteID) + if err != nil || p.AccountID != user.AccountID || p.AmountMicroUSD != cents*10_000 { + httpresponse.WriteJSON(w, 409, httpresponse.ErrorBody("quote_required", "Review your bank withdrawal again.")) + return true + } + if p.Status == "quoted" { + var original globalpayouts.PaymentRequest + if err := json.Unmarshal(p.Request, &original); err != nil { + globalPayoutError(w, err) + return true + } + paused := !s.billing().GlobalPayoutsEnabled() + changed := original.From["financial_account"] != s.billing().GlobalPayouts().FinancialAccount + if paused || changed { + // Serialize invalidation with Begin: never clear a saved client + // identity based on a stale "quoted" snapshot after another debit. + p, err = repo.ExpireGlobalPayoutQuote(user.AccountID, p.ID, time.Now()) + if err != nil { + globalPayoutError(w, err) + return true + } + if p.Status == "quoted" { + code, message := "payout_changed", "Payout settings changed. Review a new withdrawal." + if paused { + code, message = "quote_paused", "New bank withdrawals are paused. Your unsubmitted confirmation has been released." + } + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody(code, message)) + return true + } + } + } + if p.Status == "quoted" { + if local == nil { + globalPayoutError(w, store.ErrPayoutConflict) + return true + } + if err = s.refreshGlobalRecipient(r.Context(), local); err != nil { + globalPayoutError(w, err) + return true + } + p, err = repo.BeginGlobalPayout(user.AccountID, p.ID, time.Now()) + if err != nil { + globalPayoutError(w, err) + return true + } + } + // A lost HTTP response can be retried using the same quote ID without a + // second ledger debit or a new Stripe idempotency key. + if err = s.syncGlobalPayout(r.Context(), p.ID); err != nil { + s.logger.Error("global payout reconciliation pending", "withdrawal_id", p.ID, "error", err) + } + latest, err := repo.GetGlobalPayout(p.ID) + if err == nil { + p = latest + } + httpresponse.WriteJSON(w, http.StatusAccepted, map[string]any{"status": p.Status, "withdrawal_id": p.ID, "payout_id": p.ExternalID, "amount_usd": formatUSD(p.AmountMicroUSD), "fee_usd": "0.00", "net_usd": formatUSD(p.AmountMicroUSD), "method": "standard", "payout_rail": "global", "destination_amount": p.DestinationAmount, "payout_currency": p.Currency, "refunded": p.Refunded, "eta": "Typically 1–7 business days", "balance_micro_usd": s.billing().Ledger().Balance(user.AccountID)}) + return true +} diff --git a/coordinator/api/billing/methods.go b/coordinator/api/billing/methods.go new file mode 100644 index 0000000000..b144ed5357 --- /dev/null +++ b/coordinator/api/billing/methods.go @@ -0,0 +1,23 @@ +package billing + +import ( + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" +) + +func (s *Controller) BillingMethods(w http.ResponseWriter, r *http.Request) { + if s.billing() == nil { + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"methods": []any{}}) + return + } + methods := s.billing().SupportedMethods() + resp := map[string]any{"methods": methods} + if s.billing().Referral() != nil { + resp["referral"] = map[string]any{ + "enabled": true, + "share_percent": s.billing().Referral().SharePercent(), + } + } + httpresponse.WriteJSON(w, http.StatusOK, resp) +} diff --git a/coordinator/api/billing/pricing.go b/coordinator/api/billing/pricing.go new file mode 100644 index 0000000000..75326123e2 --- /dev/null +++ b/coordinator/api/billing/pricing.go @@ -0,0 +1,165 @@ +package billing + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" + "github.com/eigeninference/d-inference/coordinator/payments" +) + +// GetPricing handles GET /v1/pricing. +// Public endpoint — returns platform default prices. Also overlays platform +// DB overrides (set via admin endpoint). +func (s *Controller) GetPricing(w http.ResponseWriter, r *http.Request) { + type priceEntry struct { + Model string `json:"model"` + InputPrice int64 `json:"input_price"` // micro-USD per 1M tokens + OutputPrice int64 `json:"output_price"` // micro-USD per 1M tokens + InputUSD string `json:"input_usd"` + OutputUSD string `json:"output_usd"` + } + + // All model prices come from the database (set via PUT /v1/admin/pricing). + platformPrices := s.store.ListModelPrices("platform") + prices := make([]priceEntry, 0, len(platformPrices)) + for _, mp := range platformPrices { + prices = append(prices, priceEntry{ + Model: mp.Model, + InputPrice: mp.InputPrice, + OutputPrice: mp.OutputPrice, + InputUSD: fmt.Sprintf("$%.4f", float64(mp.InputPrice)/1_000_000), + OutputUSD: fmt.Sprintf("$%.4f", float64(mp.OutputPrice)/1_000_000), + }) + } + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "prices": prices, + "fallback_input_price": payments.DefaultInputPricePerMillion, + "fallback_output_price": payments.DefaultOutputPricePerMillion, + "fallback_input_usd": fmt.Sprintf("$%.4f", float64(payments.DefaultInputPricePerMillion)/1_000_000), + "fallback_output_usd": fmt.Sprintf("$%.4f", float64(payments.DefaultOutputPricePerMillion)/1_000_000), + }) +} + +// AdminPricing handles PUT /v1/admin/pricing. +// Sets platform default prices for a model. Requires a Privy account with +// an admin email. These defaults apply to all users who haven't set custom prices. +func (s *Controller) AdminPricing(w http.ResponseWriter, r *http.Request) { + if !s.authorizeAdmin(w, r) { + return + } + + var req struct { + Model string `json:"model"` + InputPrice int64 `json:"input_price"` + OutputPrice int64 `json:"output_price"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.Model == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "model is required", httpresponse.WithParam("model"))) + return + } + if req.InputPrice <= 0 || req.OutputPrice <= 0 { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "input_price and output_price must be positive")) + return + } + + // Store under the special "platform" account. + if err := s.store.SetModelPrice("platform", req.Model, req.InputPrice, req.OutputPrice); err != nil { + s.logger.Error("admin pricing: set failed", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to set price")) + return + } + + s.logger.Info("admin: platform price updated", + "model", req.Model, + "input_price", req.InputPrice, + "output_price", req.OutputPrice, + ) + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "platform_default_updated", + "model": req.Model, + "input_price": req.InputPrice, + "output_price": req.OutputPrice, + "input_usd": fmt.Sprintf("$%.4f per 1M tokens", float64(req.InputPrice)/1_000_000), + "output_usd": fmt.Sprintf("$%.4f per 1M tokens", float64(req.OutputPrice)/1_000_000), + }) +} + +// SetPricing handles PUT /v1/pricing. +// Providers set custom prices for models they serve. Requires Privy auth. +func (s *Controller) SetPricing(w http.ResponseWriter, r *http.Request) { + if requestauth.RequirePrivyUser(w, r) == nil { + return + } + var req struct { + Model string `json:"model"` + InputPrice int64 `json:"input_price"` + OutputPrice int64 `json:"output_price"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.Model == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "model is required", httpresponse.WithParam("model"))) + return + } + if req.InputPrice <= 0 || req.OutputPrice <= 0 { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "input_price and output_price must be positive (micro-USD per 1M tokens)")) + return + } + + accountID := requestauth.ResolveAccountID(r) + if err := s.store.SetModelPrice(accountID, req.Model, req.InputPrice, req.OutputPrice); err != nil { + s.logger.Error("pricing: set failed", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to set price")) + return + } + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "updated", + "model": req.Model, + "input_price": req.InputPrice, + "output_price": req.OutputPrice, + "input_usd": fmt.Sprintf("$%.4f per 1M tokens", float64(req.InputPrice)/1_000_000), + "output_usd": fmt.Sprintf("$%.4f per 1M tokens", float64(req.OutputPrice)/1_000_000), + }) +} + +// DeletePricing handles DELETE /v1/pricing. +// Removes a custom price override, reverting to platform defaults. +func (s *Controller) DeletePricing(w http.ResponseWriter, r *http.Request) { + if requestauth.RequirePrivyUser(w, r) == nil { + return + } + var req struct { + Model string `json:"model"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.Model == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "model is required", httpresponse.WithParam("model"))) + return + } + + accountID := requestauth.ResolveAccountID(r) + if err := s.store.DeleteModelPrice(accountID, req.Model); err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", err.Error())) + return + } + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "deleted", + "model": req.Model, + }) +} diff --git a/coordinator/api/billing/referrals.go b/coordinator/api/billing/referrals.go new file mode 100644 index 0000000000..f11ffae4fd --- /dev/null +++ b/coordinator/api/billing/referrals.go @@ -0,0 +1,108 @@ +package billing + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" +) + +func (s *Controller) ReferralRegister(w http.ResponseWriter, r *http.Request) { + if s.billing() == nil || s.billing().Referral() == nil { + httpresponse.WriteJSON(w, http.StatusServiceUnavailable, httpresponse.ErrorBody("billing_error", "referral system not available")) + return + } + if requestauth.RequirePrivyUser(w, r) == nil { + return + } + + var req struct { + Code string `json:"code"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.Code == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "code is required — choose your own referral code (3-20 chars, alphanumeric)")) + return + } + + accountID := requestauth.ResolveAccountID(r) + referrer, err := s.billing().Referral().Register(accountID, req.Code) + if err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("referral_error", err.Error())) + return + } + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "code": referrer.Code, + "share_percent": s.billing().Referral().SharePercent(), + "message": fmt.Sprintf("Share your code %s — you earn %d%% of the platform fee on every inference by referred users.", referrer.Code, s.billing().Referral().SharePercent()), + }) +} + +func (s *Controller) ReferralApply(w http.ResponseWriter, r *http.Request) { + if s.billing() == nil || s.billing().Referral() == nil { + httpresponse.WriteJSON(w, http.StatusServiceUnavailable, httpresponse.ErrorBody("billing_error", "referral system not available")) + return + } + if requestauth.RequirePrivyUser(w, r) == nil { + return + } + var req struct { + Code string `json:"code"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.Code == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "code is required")) + return + } + accountID := requestauth.ResolveAccountID(r) + if err := s.billing().Referral().Apply(accountID, req.Code); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("referral_error", err.Error())) + return + } + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "applied", + "code": req.Code, + "message": "Referral code applied successfully.", + }) +} + +func (s *Controller) ReferralStats(w http.ResponseWriter, r *http.Request) { + if s.billing() == nil || s.billing().Referral() == nil { + httpresponse.WriteJSON(w, http.StatusServiceUnavailable, httpresponse.ErrorBody("billing_error", "referral system not available")) + return + } + accountID := requestauth.ResolveAccountID(r) + stats, err := s.billing().Referral().Stats(accountID) + if err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("referral_error", err.Error())) + return + } + httpresponse.WriteJSON(w, http.StatusOK, stats) +} + +func (s *Controller) ReferralInfo(w http.ResponseWriter, r *http.Request) { + if s.billing() == nil || s.billing().Referral() == nil { + httpresponse.WriteJSON(w, http.StatusServiceUnavailable, httpresponse.ErrorBody("billing_error", "referral system not available")) + return + } + accountID := requestauth.ResolveAccountID(r) + referrer, err := s.billing().Store().GetReferrerByAccount(accountID) + if err != nil { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("referral_error", "not a registered referrer — use POST /v1/referral/register")) + return + } + referredBy, _ := s.billing().Store().GetReferrerForAccount(accountID) + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "code": referrer.Code, + "share_percent": s.billing().Referral().SharePercent(), + "referred_by": referredBy, + }) +} diff --git a/coordinator/api/billing/store.go b/coordinator/api/billing/store.go new file mode 100644 index 0000000000..b01cd62363 --- /dev/null +++ b/coordinator/api/billing/store.go @@ -0,0 +1,23 @@ +package billing + +import "github.com/eigeninference/d-inference/coordinator/store" + +// Store is the account/pricing/earnings view used directly by these endpoints. +// Checkout and payout transitions use the current billing service's store, so +// its existing transaction, locking and optional Global Payouts contracts stay +// with that service rather than being reimplemented by the HTTP controller. +type Store interface { + ListModelPrices(accountID string) []store.ModelPrice + SetModelPrice(accountID, model string, inputPrice, outputPrice int64) error + DeleteModelPrice(accountID, model string) error + SetUserRole(accountID, role string) error + SetUserPlatformFeePercent(accountID string, feePercent *int64) error + GetUserByEmail(email string) (*store.User, error) + Credit(accountID string, amountMicroUSD int64, entryType store.LedgerEntryType, reference string) error + CreditWithdrawable(accountID string, amountMicroUSD int64, entryType store.LedgerEntryType, reference string) error + GetBalance(accountID string) int64 + GetWithdrawableBalance(accountID string) int64 + GetBalanceWithWithdrawable(accountID string) (balance int64, withdrawable int64) + GetAccountEarnings(accountID string, limit int) ([]store.ProviderEarning, error) + GetAccountEarningsSummary(accountID string) (store.ProviderEarningsSummary, error) +} diff --git a/coordinator/api/billing/wallet.go b/coordinator/api/billing/wallet.go new file mode 100644 index 0000000000..dc24fb60f7 --- /dev/null +++ b/coordinator/api/billing/wallet.go @@ -0,0 +1,19 @@ +package billing + +import ( + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" +) + +// WalletBalance handles GET /v1/billing/wallet/balance. +func (s *Controller) WalletBalance(w http.ResponseWriter, r *http.Request) { + accountID := requestauth.ResolveAccountID(r) + + resp := map[string]any{ + "credit_balance_micro_usd": s.billing().Ledger().Balance(accountID), + } + + httpresponse.WriteJSON(w, http.StatusOK, resp) +} diff --git a/coordinator/api/billing/withdrawal_history.go b/coordinator/api/billing/withdrawal_history.go new file mode 100644 index 0000000000..2a37d1f248 --- /dev/null +++ b/coordinator/api/billing/withdrawal_history.go @@ -0,0 +1,35 @@ +package billing + +import ( + "net/http" + "strconv" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestauth" +) + +// StripeWithdrawals handles GET /v1/billing/stripe/withdrawals. +// Returns the user's recent Stripe withdrawals for display in the UI. +func (s *Controller) StripeWithdrawals(w http.ResponseWriter, r *http.Request) { + user := requestauth.RequirePrivyUser(w, r) + if user == nil { + return + } + limit := 50 + if l := r.URL.Query().Get("limit"); l != "" { + if v, err := strconv.Atoi(l); err == nil && v > 0 && v <= 200 { + limit = v + } + } + withdrawals, err := s.billing().Store().ListStripeWithdrawals(user.AccountID, limit) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", err.Error())) + return + } + combined, err := s.appendGlobalWithdrawals(user.AccountID, withdrawals, limit) + if err != nil { + globalPayoutError(w, err) + return + } + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"withdrawals": combined}) +} diff --git a/coordinator/api/billing_controller.go b/coordinator/api/billing_controller.go new file mode 100644 index 0000000000..8354dc03a1 --- /dev/null +++ b/coordinator/api/billing_controller.go @@ -0,0 +1,54 @@ +package api + +import ( + "context" + + billingapi "github.com/eigeninference/d-inference/coordinator/api/billing" + "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/payments/baserewards" +) + +// billingController binds endpoint policy to the router's existing service +// lifecycle. The getters retain SetBilling/SetBaseRewards updates made after +// NewServer registered routes; inference and HTTP billing use the same services. +func (s *Server) billingController() *billingapi.Controller { + return billingapi.New(billingapi.Dependencies{ + Store: s.store, Service: s.Billing, BaseRewards: s.BaseRewards, + Logger: s.logger, Cache: s.readCache, Metrics: billingMetrics{s}, + AuthorizeAdmin: s.isAdminAuthorized, + }) +} + +type billingMetrics struct{ server *Server } + +func (m billingMetrics) Incr(name string, tags []string) { m.server.ddIncr(name, tags) } + +// StartStripePayoutReconciler launches the existing stuck-withdrawal worker. +func (s *Server) StartStripePayoutReconciler(ctx context.Context) { + s.billingController().StartStripePayoutReconciler(ctx) +} + +// StartGlobalPayoutReconciler launches the existing quote cleanup and payout worker. +func (s *Server) StartGlobalPayoutReconciler(ctx context.Context) { + s.billingController().StartGlobalPayoutReconciler(ctx) +} + +// SetBilling configures the billing service for multi-chain payments and referrals. +func (s *Server) SetBilling(svc *billing.Service) { + s.billing = svc +} + +func (s *Server) Billing() *billing.Service { + return s.billing +} + +// SetBaseRewards configures the provider base-rewards engine (off unless the +// EIGENINFERENCE_BASE_REWARDS flag is set; nil = disabled). +func (s *Server) SetBaseRewards(e *baserewards.Engine) { + s.baseRewards = e +} + +// BaseRewards returns the base-rewards engine, or nil when disabled. +func (s *Server) BaseRewards() *baserewards.Engine { + return s.baseRewards +} diff --git a/coordinator/api/billing_controller_test.go b/coordinator/api/billing_controller_test.go new file mode 100644 index 0000000000..a4617f8d14 --- /dev/null +++ b/coordinator/api/billing_controller_test.go @@ -0,0 +1,126 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" + "github.com/eigeninference/d-inference/coordinator/auth" + "github.com/eigeninference/d-inference/coordinator/billing" + "github.com/eigeninference/d-inference/coordinator/payments/baserewards" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Routes are registered before configuration. These real HTTP requests retain +// the published handler while replacing the services it must observe. +func TestBillingControllerUsesCurrentServices(t *testing.T) { + srv, st := testServerWithConfig(t, ServerConfig{AdminKey: "billing-admin"}) + t.Cleanup(srv.Close) + server := httptest.NewServer(srv.Handler()) + t.Cleanup(server.Close) + client := server.Client() + client.Timeout = 5 * time.Second + read := func(path, token string, wantStatus int) map[string]any { + t.Helper() + req, err := http.NewRequest(http.MethodGet, server.URL+path, nil) + if err != nil { + t.Fatal(err) + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var body map[string]any + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + t.Fatal(err) + } + if resp.StatusCode != wantStatus { + t.Fatalf("GET %s: %d, want %d: %+v", path, resp.StatusCode, wantStatus, body) + } + return body + } + + methodsPath := "/v1/billing/methods" + if body := read(methodsPath, "", http.StatusOK); body["referral"] != nil { + t.Fatalf("unconfigured service advertises referral: %+v", body) + } + for _, share := range []int64{17, 37} { + service := billing.NewService(st, srv.ledger, srv.logger, billing.Config{MockMode: true, ReferralSharePercent: share}) + srv.SetBilling(service) + if srv.Billing() != service { + t.Fatal("router and inference must retain the same billing service") + } + body := read(methodsPath, "", http.StatusOK) + referral, ok := body["referral"].(map[string]any) + if !ok || referral["share_percent"] != float64(share) || referral["enabled"] != true { + t.Fatalf("route retained an earlier service: %+v", body) + } + } + srv.SetBilling(nil) + if body := read(methodsPath, "", http.StatusOK); body["referral"] != nil { + t.Fatalf("route retained cleared service: %+v", body) + } + + rewardsPath := "/v1/admin/base-rewards" + read(rewardsPath, "", http.StatusForbidden) + if body := read(rewardsPath, "billing-admin", http.StatusOK); body["enabled"] != false { + t.Fatalf("unconfigured engine is enabled: %+v", body) + } + for _, budget := range []int64{17_000_000, 37_000_000} { + cfg := baserewards.DefaultConfig() + cfg.Enabled, cfg.PoolBudgetMicroUSD = true, budget + engine := baserewards.NewEngine(st, srv.registry, cfg, srv.logger) + srv.SetBaseRewards(engine) + if srv.BaseRewards() != engine { + t.Fatal("router must retain the configured rewards engine") + } + body := read(rewardsPath, "billing-admin", http.StatusOK) + if body["enabled"] != true || body["monthly_pool_budget"] != float64(budget) { + t.Fatalf("route retained an earlier rewards engine: %+v", body) + } + } + srv.SetBaseRewards(nil) + if body := read(rewardsPath, "billing-admin", http.StatusOK); body["enabled"] != false { + t.Fatalf("route retained cleared rewards engine: %+v", body) + } +} + +// Both API adapters and extracted endpoints use this shared policy: linked +// user identity wins over the account carrier, and a carrier alone does not +// satisfy an endpoint's linked-user requirement. +func TestBillingRequestIdentityContract(t *testing.T) { + srv := &Server{} + req := httptest.NewRequest(http.MethodGet, "/", nil) + if got := srv.resolveAccountID(req); got != "" { + t.Fatalf("absent identity = %q", got) + } + req = req.WithContext(requestcontext.WithAccountID(req.Context(), "key-account")) + if got := srv.resolveAccountID(req); got != "key-account" { + t.Fatalf("key identity = %q", got) + } + w := httptest.NewRecorder() + if user := srv.requirePrivyUser(w, req); user != nil { + t.Fatal("account context alone supplied a linked user") + } + const want = "{\"error\":{\"code\":\"auth_error\",\"message\":\"this endpoint requires a Privy account — authenticate with a Privy access token\",\"type\":\"auth_error\"}}\n" + if w.Code != http.StatusUnauthorized || w.Header().Get("Content-Type") != "application/json" || w.Body.String() != want { + t.Fatalf("linked-user rejection changed: %d %q", w.Code, w.Body.String()) + } + user := &store.User{AccountID: "linked-account"} + req = req.WithContext(context.WithValue(req.Context(), auth.CtxKeyUser, user)) + if got := srv.resolveAccountID(req); got != user.AccountID { + t.Fatalf("linked identity lost precedence: %q", got) + } + w = httptest.NewRecorder() + if got := srv.requirePrivyUser(w, req); got != user || w.Body.Len() != 0 { + t.Fatal("linked-user adapter must return the original user without writing a response") + } +} diff --git a/coordinator/api/billing_earnings_test.go b/coordinator/api/billing_earnings_test.go index ff85a82792..91b9ba89d1 100644 --- a/coordinator/api/billing_earnings_test.go +++ b/coordinator/api/billing_earnings_test.go @@ -1,13 +1,13 @@ package api import ( - "context" "encoding/json" "net/http" "net/http/httptest" "testing" "time" + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" "github.com/eigeninference/d-inference/coordinator/store" ) @@ -58,10 +58,10 @@ func TestAccountEarningsUsesLifetimeTotalsAndCurrentBalance(t *testing.T) { } req := httptest.NewRequest(http.MethodGet, "/v1/provider/account-earnings?limit=1", nil) - req = req.WithContext(context.WithValue(req.Context(), ctxKeyConsumer, accountID)) + req = req.WithContext(requestcontext.WithAccountID(req.Context(), accountID)) w := httptest.NewRecorder() - srv.handleAccountEarnings(w, req) + srv.billingController().AccountEarnings(w, req) if w.Code != http.StatusOK { t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String()) diff --git a/coordinator/api/billing_handlers.go b/coordinator/api/billing_handlers.go deleted file mode 100644 index 3cd928a402..0000000000 --- a/coordinator/api/billing_handlers.go +++ /dev/null @@ -1,738 +0,0 @@ -package api - -// Billing API handlers for Stripe payments and referral system. -// -// Consumer payment flow (Stripe Checkout): -// 1. User authenticates via Privy JWT -// 2. User creates a Stripe Checkout session -// 3. Stripe webhook confirms payment and credits internal balance -// -// Provider payouts use Stripe Connect Express (bank/card withdrawals). -// -// Endpoints that modify account state (referral, pricing, deposits) require -// Privy authentication to prevent spam. API key auth is accepted for -// read-only endpoints and inference. - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "strconv" - "strings" - "time" - - "github.com/eigeninference/d-inference/coordinator/auth" - "github.com/eigeninference/d-inference/coordinator/billing" - "github.com/eigeninference/d-inference/coordinator/payments" - "github.com/eigeninference/d-inference/coordinator/store" - "github.com/google/uuid" -) - -// --- Stripe Handlers --- - -// handleStripeCreateSession handles POST /v1/billing/stripe/create-session. -func (s *Server) handleStripeCreateSession(w http.ResponseWriter, r *http.Request) { - if s.billing == nil || s.billing.Stripe() == nil { - writeJSON(w, http.StatusServiceUnavailable, errorResponse("billing_error", "Stripe payments not configured")) - return - } - - var req struct { - AmountUSD string `json:"amount_usd"` - Email string `json:"email,omitempty"` - ReferralCode string `json:"referral_code,omitempty"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "invalid JSON: "+err.Error())) - return - } - - amountFloat, err := strconv.ParseFloat(req.AmountUSD, 64) - if err != nil || amountFloat < 0.50 { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "amount_usd must be at least $0.50")) - return - } - - amountCents := int64(amountFloat * 100) - accountID := s.resolveAccountID(r) - - if req.ReferralCode != "" { - if _, err := s.billing.Store().GetReferrerByCode(req.ReferralCode); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "invalid referral code")) - return - } - } - - sessionID := uuid.New().String() - amountMicroUSD := int64(amountFloat * 1_000_000) - - billingSession := &store.BillingSession{ - ID: sessionID, - AccountID: accountID, - PaymentMethod: "stripe", - AmountMicroUSD: amountMicroUSD, - Status: "pending", - ReferralCode: req.ReferralCode, - CreatedAt: time.Now(), - } - - stripeResp, err := s.billing.Stripe().CreateCheckoutSession(billing.CheckoutSessionRequest{ - AmountCents: amountCents, - Currency: "usd", - CustomerEmail: req.Email, - Metadata: map[string]string{ - "app": "darkbloom", - "platform": "eigeninference", - "purchase_type": "inference_credits", - "source": "coordinator", - "coordinator_host": r.Host, - "billing_session_id": sessionID, - "consumer_key": accountID, - "referral_code": req.ReferralCode, - }, - }) - if err != nil { - s.logger.Error("stripe: create checkout session failed", "error", err) - writeJSON(w, http.StatusBadGateway, errorResponse("stripe_error", "failed to create checkout session")) - return - } - - billingSession.ExternalID = stripeResp.SessionID - if err := s.billing.Store().CreateBillingSession(billingSession); err != nil { - s.logger.Error("stripe: save billing session failed", "error", err) - } - - writeJSON(w, http.StatusOK, map[string]any{ - "session_id": sessionID, - "stripe_session": stripeResp.SessionID, - "url": stripeResp.URL, - "amount_usd": req.AmountUSD, - "amount_micro_usd": amountMicroUSD, - }) -} - -// handleStripeWebhook handles POST /v1/billing/stripe/webhook. -func (s *Server) handleStripeWebhook(w http.ResponseWriter, r *http.Request) { - if s.billing == nil || s.billing.Stripe() == nil { - http.Error(w, "Stripe not configured", http.StatusServiceUnavailable) - return - } - - payload, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) - if err != nil { - http.Error(w, "failed to read body", http.StatusBadRequest) - return - } - - sigHeader := r.Header.Get("Stripe-Signature") - event, err := s.billing.Stripe().VerifyWebhookSignature(payload, sigHeader) - if err != nil { - s.logger.Error("stripe: webhook signature verification failed", "error", err) - http.Error(w, "invalid signature", http.StatusBadRequest) - return - } - - if event.Type != "checkout.session.completed" { - w.WriteHeader(http.StatusOK) - return - } - - session, err := s.billing.Stripe().ParseCheckoutSession(event) - if err != nil { - s.logger.Error("stripe: parse checkout session failed", "error", err) - http.Error(w, "invalid event data", http.StatusBadRequest) - return - } - - billingSessionID := session.Object.Metadata["billing_session_id"] - consumerKey := session.Object.Metadata["consumer_key"] - referralCode := session.Object.Metadata["referral_code"] - - if consumerKey == "" { - s.logger.Error("stripe: webhook missing consumer_key in metadata") - http.Error(w, "missing metadata", http.StatusBadRequest) - return - } - - if billingSessionID != "" { - bs, err := s.billing.Store().GetBillingSession(billingSessionID) - if err == nil && bs.Status == "completed" { - w.WriteHeader(http.StatusOK) - return - } - } - - amountMicroUSD := session.Object.AmountTotal * 10_000 - - if err := s.billing.CreditDeposit(consumerKey, amountMicroUSD, store.LedgerStripeDeposit, - "stripe:"+session.Object.ID); err != nil { - s.logger.Error("stripe: credit balance failed", "error", err) - http.Error(w, "internal error", http.StatusInternalServerError) - return - } - - if billingSessionID != "" { - // Best-effort: the deposit is already credited above, but a failure here - // leaves the session marked incomplete (and replayable). Surface it. - if err := s.billing.Store().CompleteBillingSession(billingSessionID); err != nil { - s.logger.Error("stripe: failed to mark billing session complete", - "billing_session_id", billingSessionID, "error", err) - s.ddIncr("billing.session_complete_failed", nil) - } - } - if referralCode != "" { - // Best-effort: a failure here means the referrer is not credited for this - // deposit; never silently swallow it. - if err := s.billing.Referral().Apply(consumerKey, referralCode); err != nil { - s.logger.Error("stripe: failed to apply referral credit", "error", err) - s.ddIncr("billing.referral_apply_failed", nil) - } - } - - s.logger.Info("stripe: deposit credited", - "consumer_key", consumerKey[:min(8, len(consumerKey))]+"...", - "amount_micro_usd", amountMicroUSD, - ) - w.WriteHeader(http.StatusOK) -} - -// handleStripeSessionStatus handles GET /v1/billing/stripe/session?id=... -func (s *Server) handleStripeSessionStatus(w http.ResponseWriter, r *http.Request) { - sessionID := r.URL.Query().Get("id") - if sessionID == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "id query parameter required")) - return - } - - bs, err := s.billing.Store().GetBillingSession(sessionID) - if err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("not_found", "billing session not found")) - return - } - - writeJSON(w, http.StatusOK, map[string]any{ - "session_id": bs.ID, - "payment_method": bs.PaymentMethod, - "amount_micro_usd": bs.AmountMicroUSD, - "status": bs.Status, - "created_at": bs.CreatedAt, - "completed_at": bs.CompletedAt, - }) -} - -// handleWalletBalance handles GET /v1/billing/wallet/balance. -func (s *Server) handleWalletBalance(w http.ResponseWriter, r *http.Request) { - accountID := s.resolveAccountID(r) - - resp := map[string]any{ - "credit_balance_micro_usd": s.billing.Ledger().Balance(accountID), - } - - writeJSON(w, http.StatusOK, resp) -} - -// --- Referral Handlers --- - -func (s *Server) handleReferralRegister(w http.ResponseWriter, r *http.Request) { - if s.billing == nil || s.billing.Referral() == nil { - writeJSON(w, http.StatusServiceUnavailable, errorResponse("billing_error", "referral system not available")) - return - } - if s.requirePrivyUser(w, r) == nil { - return - } - - var req struct { - Code string `json:"code"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "invalid JSON: "+err.Error())) - return - } - if req.Code == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "code is required — choose your own referral code (3-20 chars, alphanumeric)")) - return - } - - accountID := s.resolveAccountID(r) - referrer, err := s.billing.Referral().Register(accountID, req.Code) - if err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("referral_error", err.Error())) - return - } - writeJSON(w, http.StatusOK, map[string]any{ - "code": referrer.Code, - "share_percent": s.billing.Referral().SharePercent(), - "message": fmt.Sprintf("Share your code %s — you earn %d%% of the platform fee on every inference by referred users.", referrer.Code, s.billing.Referral().SharePercent()), - }) -} - -func (s *Server) handleReferralApply(w http.ResponseWriter, r *http.Request) { - if s.billing == nil || s.billing.Referral() == nil { - writeJSON(w, http.StatusServiceUnavailable, errorResponse("billing_error", "referral system not available")) - return - } - if s.requirePrivyUser(w, r) == nil { - return - } - var req struct { - Code string `json:"code"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "invalid JSON: "+err.Error())) - return - } - if req.Code == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "code is required")) - return - } - accountID := s.resolveAccountID(r) - if err := s.billing.Referral().Apply(accountID, req.Code); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("referral_error", err.Error())) - return - } - writeJSON(w, http.StatusOK, map[string]any{ - "status": "applied", - "code": req.Code, - "message": "Referral code applied successfully.", - }) -} - -func (s *Server) handleReferralStats(w http.ResponseWriter, r *http.Request) { - if s.billing == nil || s.billing.Referral() == nil { - writeJSON(w, http.StatusServiceUnavailable, errorResponse("billing_error", "referral system not available")) - return - } - accountID := s.resolveAccountID(r) - stats, err := s.billing.Referral().Stats(accountID) - if err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("referral_error", err.Error())) - return - } - writeJSON(w, http.StatusOK, stats) -} - -func (s *Server) handleReferralInfo(w http.ResponseWriter, r *http.Request) { - if s.billing == nil || s.billing.Referral() == nil { - writeJSON(w, http.StatusServiceUnavailable, errorResponse("billing_error", "referral system not available")) - return - } - accountID := s.resolveAccountID(r) - referrer, err := s.billing.Store().GetReferrerByAccount(accountID) - if err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("referral_error", "not a registered referrer — use POST /v1/referral/register")) - return - } - referredBy, _ := s.billing.Store().GetReferrerForAccount(accountID) - writeJSON(w, http.StatusOK, map[string]any{ - "code": referrer.Code, - "share_percent": s.billing.Referral().SharePercent(), - "referred_by": referredBy, - }) -} - -// --- Pricing --- - -// handleGetPricing handles GET /v1/pricing. -// Public endpoint — returns platform default prices. Also overlays platform -// DB overrides (set via admin endpoint). -func (s *Server) handleGetPricing(w http.ResponseWriter, r *http.Request) { - type priceEntry struct { - Model string `json:"model"` - InputPrice int64 `json:"input_price"` // micro-USD per 1M tokens - OutputPrice int64 `json:"output_price"` // micro-USD per 1M tokens - InputUSD string `json:"input_usd"` - OutputUSD string `json:"output_usd"` - } - - // All model prices come from the database (set via PUT /v1/admin/pricing). - platformPrices := s.store.ListModelPrices("platform") - prices := make([]priceEntry, 0, len(platformPrices)) - for _, mp := range platformPrices { - prices = append(prices, priceEntry{ - Model: mp.Model, - InputPrice: mp.InputPrice, - OutputPrice: mp.OutputPrice, - InputUSD: fmt.Sprintf("$%.4f", float64(mp.InputPrice)/1_000_000), - OutputUSD: fmt.Sprintf("$%.4f", float64(mp.OutputPrice)/1_000_000), - }) - } - - writeJSON(w, http.StatusOK, map[string]any{ - "prices": prices, - "fallback_input_price": payments.DefaultInputPricePerMillion, - "fallback_output_price": payments.DefaultOutputPricePerMillion, - "fallback_input_usd": fmt.Sprintf("$%.4f", float64(payments.DefaultInputPricePerMillion)/1_000_000), - "fallback_output_usd": fmt.Sprintf("$%.4f", float64(payments.DefaultOutputPricePerMillion)/1_000_000), - }) -} - -// handleAdminPricing handles PUT /v1/admin/pricing. -// Sets platform default prices for a model. Requires a Privy account with -// an admin email. These defaults apply to all users who haven't set custom prices. -func (s *Server) handleAdminPricing(w http.ResponseWriter, r *http.Request) { - if !s.isAdminAuthorized(w, r) { - return - } - - var req struct { - Model string `json:"model"` - InputPrice int64 `json:"input_price"` - OutputPrice int64 `json:"output_price"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "invalid JSON: "+err.Error())) - return - } - if req.Model == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "model is required", withParam("model"))) - return - } - if req.InputPrice <= 0 || req.OutputPrice <= 0 { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "input_price and output_price must be positive")) - return - } - - // Store under the special "platform" account. - if err := s.store.SetModelPrice("platform", req.Model, req.InputPrice, req.OutputPrice); err != nil { - s.logger.Error("admin pricing: set failed", "error", err) - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to set price")) - return - } - - s.logger.Info("admin: platform price updated", - "model", req.Model, - "input_price", req.InputPrice, - "output_price", req.OutputPrice, - ) - - writeJSON(w, http.StatusOK, map[string]any{ - "status": "platform_default_updated", - "model": req.Model, - "input_price": req.InputPrice, - "output_price": req.OutputPrice, - "input_usd": fmt.Sprintf("$%.4f per 1M tokens", float64(req.InputPrice)/1_000_000), - "output_usd": fmt.Sprintf("$%.4f per 1M tokens", float64(req.OutputPrice)/1_000_000), - }) -} - -// handleAdminSetUserRole handles PUT /v1/admin/users/role. -// Grants or clears an account role (e.g. RoleService for OpenRouter). Admin only. -func (s *Server) handleAdminSetUserRole(w http.ResponseWriter, r *http.Request) { - if !s.isAdminAuthorized(w, r) { - return - } - - var req struct { - AccountID string `json:"account_id"` - Role string `json:"role"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "invalid JSON: "+err.Error())) - return - } - if req.AccountID == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "account_id is required", withParam("account_id"))) - return - } - // Only known roles are accepted. "" clears the role back to a normal account. - if req.Role != "" && req.Role != store.RoleService { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", - fmt.Sprintf("invalid role %q — allowed: %q or \"\"", req.Role, store.RoleService), withParam("role"))) - return - } - - if err := s.store.SetUserRole(req.AccountID, req.Role); err != nil { - s.logger.Error("admin set role: failed", "account_id", req.AccountID, "error", err) - writeJSON(w, http.StatusNotFound, errorResponse("not_found", "user not found or update failed")) - return - } - - s.logger.Info("admin: user role updated", "account_id", req.AccountID, "role", req.Role) - writeJSON(w, http.StatusOK, map[string]any{ - "status": "role_updated", - "account_id": req.AccountID, - "role": req.Role, - }) -} - -// handleAdminSetUserPlatformFee handles PUT /v1/admin/users/platform-fee. -// Sets a per-account platform fee override (0–100). Omit platform_fee_percent -// (or send null) to clear the override and fall back to the global default. -// Admin only. -func (s *Server) handleAdminSetUserPlatformFee(w http.ResponseWriter, r *http.Request) { - if !s.isAdminAuthorized(w, r) { - return - } - - var req struct { - AccountID string `json:"account_id"` - PlatformFeePercent *int64 `json:"platform_fee_percent"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "invalid JSON: "+err.Error())) - return - } - if req.AccountID == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "account_id is required", withParam("account_id"))) - return - } - if req.PlatformFeePercent != nil && (*req.PlatformFeePercent < 0 || *req.PlatformFeePercent > 100) { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", - "platform_fee_percent must be between 0 and 100", withParam("platform_fee_percent"))) - return - } - - if err := s.store.SetUserPlatformFeePercent(req.AccountID, req.PlatformFeePercent); err != nil { - s.logger.Error("admin set platform fee: failed", "account_id", req.AccountID, "error", err) - writeJSON(w, http.StatusNotFound, errorResponse("not_found", "user not found or update failed")) - return - } - - resp := map[string]any{ - "status": "platform_fee_updated", - "account_id": req.AccountID, - } - if req.PlatformFeePercent != nil { - resp["platform_fee_percent"] = *req.PlatformFeePercent - } else { - resp["platform_fee_percent"] = nil - resp["note"] = "override cleared — using global default" - } - s.logger.Info("admin: user platform fee updated", "account_id", req.AccountID, "fee", req.PlatformFeePercent) - writeJSON(w, http.StatusOK, resp) -} - -// handleSetPricing handles PUT /v1/pricing. -// Providers set custom prices for models they serve. Requires Privy auth. -func (s *Server) handleSetPricing(w http.ResponseWriter, r *http.Request) { - if s.requirePrivyUser(w, r) == nil { - return - } - var req struct { - Model string `json:"model"` - InputPrice int64 `json:"input_price"` - OutputPrice int64 `json:"output_price"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "invalid JSON: "+err.Error())) - return - } - if req.Model == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "model is required", withParam("model"))) - return - } - if req.InputPrice <= 0 || req.OutputPrice <= 0 { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "input_price and output_price must be positive (micro-USD per 1M tokens)")) - return - } - - accountID := s.resolveAccountID(r) - if err := s.store.SetModelPrice(accountID, req.Model, req.InputPrice, req.OutputPrice); err != nil { - s.logger.Error("pricing: set failed", "error", err) - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to set price")) - return - } - - writeJSON(w, http.StatusOK, map[string]any{ - "status": "updated", - "model": req.Model, - "input_price": req.InputPrice, - "output_price": req.OutputPrice, - "input_usd": fmt.Sprintf("$%.4f per 1M tokens", float64(req.InputPrice)/1_000_000), - "output_usd": fmt.Sprintf("$%.4f per 1M tokens", float64(req.OutputPrice)/1_000_000), - }) -} - -// handleDeletePricing handles DELETE /v1/pricing. -// Removes a custom price override, reverting to platform defaults. -func (s *Server) handleDeletePricing(w http.ResponseWriter, r *http.Request) { - if s.requirePrivyUser(w, r) == nil { - return - } - var req struct { - Model string `json:"model"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "invalid JSON: "+err.Error())) - return - } - if req.Model == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "model is required", withParam("model"))) - return - } - - accountID := s.resolveAccountID(r) - if err := s.store.DeleteModelPrice(accountID, req.Model); err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("not_found", err.Error())) - return - } - - writeJSON(w, http.StatusOK, map[string]any{ - "status": "deleted", - "model": req.Model, - }) -} - -// --- Payment Methods --- - -func (s *Server) handleBillingMethods(w http.ResponseWriter, r *http.Request) { - if s.billing == nil { - writeJSON(w, http.StatusOK, map[string]any{"methods": []any{}}) - return - } - methods := s.billing.SupportedMethods() - resp := map[string]any{"methods": methods} - if s.billing.Referral() != nil { - resp["referral"] = map[string]any{ - "enabled": true, - "share_percent": s.billing.Referral().SharePercent(), - } - } - writeJSON(w, http.StatusOK, resp) -} - -// resolveAccountID returns the internal account ID for the current request. -// Prefers the Privy user's account ID, falls back to API key. -func (s *Server) resolveAccountID(r *http.Request) string { - if user := auth.UserFromContext(r.Context()); user != nil { - return user.AccountID - } - return consumerKeyFromContext(r.Context()) -} - -// isAdmin checks if the user has admin privileges (email in admin list). -func (s *Server) isAdmin(user *store.User) bool { - if user == nil || user.Email == "" || len(s.adminEmails) == 0 { - return false - } - return s.adminEmails[strings.ToLower(user.Email)] -} - -// requirePrivyUser checks that the request is authenticated via Privy (not just API key). -// Returns the user or writes a 401 error and returns nil. -func (s *Server) requirePrivyUser(w http.ResponseWriter, r *http.Request) *store.User { - user := auth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", - "this endpoint requires a Privy account — authenticate with a Privy access token")) - return nil - } - return user -} - -// handleModelCatalog handles GET /v1/models/catalog. -// Public endpoint — returns active models for providers and the install script. -// Cached for 60s — the underlying DB query is fast but this endpoint is hit -// by every provider heartbeat and install script poll. -func modelCatalogCacheKey(typeFilter string, includeAliases bool) string { - return "models:catalog:type=" + typeFilter + ":include_aliases=" + strconv.FormatBool(includeAliases) -} - -func (s *Server) handleModelCatalog(w http.ResponseWriter, r *http.Request) { - // Optional filter: ?type=text - typeFilter := strings.TrimSpace(strings.ToLower(r.URL.Query().Get("type"))) - if typeFilter != "" && typeFilter != "text" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "unsupported catalog type", withParam("type"))) - return - } - includeAliases := r.URL.Query().Get("include_aliases") == "1" || strings.EqualFold(r.URL.Query().Get("include_aliases"), "true") - - cacheKey := modelCatalogCacheKey(typeFilter, includeAliases) - if cached, ok := s.readCache.Get(cacheKey); ok { - writeCachedJSON(w, cached) - return - } - - registryRows, err := s.store.ListActiveModelRegistryWithError() - if err != nil { - s.logger.Error("model registry: failed to list active models", "error", err) - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to fetch model catalog")) - return - } - // The catalog is text-only today; an explicit non-text filter yields nothing. - models := make([]map[string]any, 0, len(registryRows)) - if typeFilter == "" || typeFilter == "text" { - for i := range registryRows { - models = append(models, catalogModelFromRegistryRecord(®istryRows[i])) - } - } - response := map[string]any{"models": models} - if includeAliases { - aliases, err := s.store.ListModelAliases() - if err != nil { - s.logger.Warn("model registry: failed to list aliases for catalog response", "error", err) - } else { - response["aliases"] = catalogAliasesForResponse(models, aliases) - } - } - - body, err := json.Marshal(response) - if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to marshal catalog")) - return - } - s.readCache.Set(cacheKey, body, time.Minute) - writeCachedJSON(w, body) -} - -// handleAccountEarnings handles GET /v1/provider/account-earnings?limit=50. -// Returns recent earnings history, lifetime aggregates, and current account balance -// for the authenticated provider account. -// Cached for 20s per account — dashboard polls this frequently. -func (s *Server) handleAccountEarnings(w http.ResponseWriter, r *http.Request) { - accountID := s.resolveAccountID(r) - - limit := 50 - if v := r.URL.Query().Get("limit"); v != "" { - if parsed, err := strconv.Atoi(v); err == nil && parsed > 0 { - limit = parsed - } - } - if limit > 1000 { - limit = 1000 - } - - cacheKey := "account-earnings:" + accountID + ":" + strconv.Itoa(limit) - if cached, ok := s.readCache.Get(cacheKey); ok { - writeCachedJSON(w, cached) - return - } - - earnings, err := s.store.GetAccountEarnings(accountID, limit) - if err != nil { - s.logger.Error("get account earnings failed", "error", err) - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to fetch earnings")) - return - } - - summary, err := s.store.GetAccountEarningsSummary(accountID) - if err != nil { - s.logger.Error("get account earnings summary failed", "error", err) - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to fetch earnings summary")) - return - } - - availableBalance, withdrawableBalance := s.store.GetBalanceWithWithdrawable(accountID) - - body, err := json.Marshal(map[string]any{ - "account_id": accountID, - "earnings": earnings, - "total_micro_usd": summary.TotalMicroUSD, - "total_usd": fmt.Sprintf("%.6f", float64(summary.TotalMicroUSD)/1_000_000), - "count": summary.Count, - "recent_count": len(earnings), - "history_limit": limit, - "available_balance_micro_usd": availableBalance, - "available_balance_usd": fmt.Sprintf("%.6f", float64(availableBalance)/1_000_000), - "withdrawable_balance_micro_usd": withdrawableBalance, - "withdrawable_balance_usd": fmt.Sprintf("%.6f", float64(withdrawableBalance)/1_000_000), - }) - if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to marshal earnings")) - return - } - s.readCache.Set(cacheKey, body, 20*time.Second) - writeCachedJSON(w, body) -} diff --git a/coordinator/api/billing_settlement_test.go b/coordinator/api/billing_settlement_test.go index 551c440668..875be1904d 100644 --- a/coordinator/api/billing_settlement_test.go +++ b/coordinator/api/billing_settlement_test.go @@ -172,7 +172,7 @@ func TestRefundReservedBalanceDoesNotFinalizeWhenCreditFails(t *testing.T) { ReservedMicroUSD: 50_000, } - if ok := srv.refundReservedBalance(pr, "forced-failure"); ok { + if ok := srv.inferenceSettlement().Refund(pr, "forced-failure"); ok { t.Fatal("refundReservedBalance returned true despite store credit failure") } if ok := pr.MarkReservationFinalized(); !ok { diff --git a/coordinator/api/cache.go b/coordinator/api/cache.go index ec31865f54..a5814ced6f 100644 --- a/coordinator/api/cache.go +++ b/coordinator/api/cache.go @@ -1,129 +1,25 @@ package api import ( - "encoding/json" + "context" "net/http" - "sync" "time" -) - -// ttlCache stores pre-serialized JSON bytes — or, for shared intermediate -// results such as the public model entry list, a typed value — keyed by -// request signature. Skipping both the DB query and json.Marshal on hit makes -// hot endpoints (stats, leaderboard, model catalog) sub-millisecond. -// -// Single-node in-memory only — sized for tens of keys, not millions. Hits -// are just a map lookup under RLock; misses recompute and Set without -// locking the read path. -type ttlCache struct { - mu sync.RWMutex - data map[string]ttlEntry - // generation orders guarded fills against invalidation. - generation uint64 -} - -type ttlEntry struct { - value []byte - obj any - expiresAt time.Time -} - -func newTTLCache() *ttlCache { - return &ttlCache{data: make(map[string]ttlEntry)} -} - -func (c *ttlCache) lookup(key string) (ttlEntry, bool) { - c.mu.RLock() - e, ok := c.data[key] - c.mu.RUnlock() - if !ok || time.Now().After(e.expiresAt) { - return ttlEntry{}, false - } - return e, true -} - -// Get returns the cached bytes if present and not expired. -func (c *ttlCache) Get(key string) ([]byte, bool) { - e, ok := c.lookup(key) - if !ok || e.value == nil { - return nil, false - } - return e.value, true -} - -// GetValue returns the cached typed value if present and not expired. The -// value is shared between all callers and must be treated as immutable. -func (c *ttlCache) GetValue(key string) (any, bool) { - e, ok := c.lookup(key) - if !ok || e.obj == nil { - return nil, false - } - return e.obj, true -} -// Set stores bytes with an absolute expiry time. -func (c *ttlCache) Set(key string, value []byte, ttl time.Duration) { - c.mu.Lock() - c.data[key] = ttlEntry{value: value, expiresAt: time.Now().Add(ttl)} - c.mu.Unlock() -} - -// SetValue stores a typed value with an absolute expiry time. -func (c *ttlCache) SetValue(key string, v any, ttl time.Duration) { - c.mu.Lock() - c.data[key] = ttlEntry{obj: v, expiresAt: time.Now().Add(ttl)} - c.mu.Unlock() -} - -// Invalidate removes a single key. Useful when an action changes the -// underlying data (e.g. registering a new release invalidates cached -// /api/version and /v1/runtime/manifest). -func (c *ttlCache) Invalidate(key string) { - c.mu.Lock() - delete(c.data, key) - c.generation++ - c.mu.Unlock() -} + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/readcache" +) -// Purge expired entries. Called by a background goroutine — bounded -// growth even when keys are added but never re-read. -func (c *ttlCache) PurgeExpired() { - now := time.Now() - c.mu.Lock() - for k, e := range c.data { - if now.After(e.expiresAt) { - delete(c.data, k) - } - } - c.mu.Unlock() -} +// Response cache storage and synchronization live in readcache. +type ttlCache = readcache.Cache -// Len returns the number of entries currently held (including not-yet-purged -// expired ones). Used by the janitor's tests to observe reclamation. -func (c *ttlCache) Len() int { - c.mu.RLock() - defer c.mu.RUnlock() - return len(c.data) -} +func newTTLCache() *ttlCache { return readcache.New() } -// writeCachedJSON writes pre-serialized JSON bytes with the standard -// Content-Type header. Used on cache hit to skip json.Marshal. +// writeCachedJSON serves the exact pre-encoded response body. func writeCachedJSON(w http.ResponseWriter, body []byte) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _, _ = w.Write(body) + httpresponse.WriteCachedJSON(w, body) } -// encodeCachedJSON renders v exactly as writeJSON does (json.Encoder appends -// a trailing newline to the compact encoding), so a cache hit served by -// writeCachedJSON is byte-identical to the miss that populated it. -func encodeCachedJSON(v any) ([]byte, error) { - body, err := json.Marshal(v) - if err != nil { - return nil, err - } - return append(body, '\n'), nil -} +func encodeCachedJSON(v any) ([]byte, error) { return httpresponse.EncodeCachedJSON(v) } // Nil-safe readCache accessors: handlers reached through a bare Server // literal (some tests) have no cache and simply recompute every time. @@ -141,9 +37,31 @@ func (s *Server) readCacheSet(key string, body []byte, ttl time.Duration) { } } -func (s *Server) readCacheGetValue(key string) (any, bool) { +// readCacheJanitorInterval is how often expired readCache entries are reclaimed. +// Get already skips expired entries, so this only frees memory — but without it +// high-cardinality keys (e.g. the per-account "account-earnings:" entries) are +// written and never re-read, so they linger forever and the cache grows unbounded. +const readCacheJanitorInterval = time.Minute + +// StartReadCacheJanitor periodically purges expired entries from the read cache +// so it can't grow unbounded. Call as a goroutine; stops when ctx is cancelled. +func (s *Server) StartReadCacheJanitor(ctx context.Context) { + s.runReadCacheJanitor(ctx, readCacheJanitorInterval) +} + +// runReadCacheJanitor is StartReadCacheJanitor with an injectable interval (tests). +func (s *Server) runReadCacheJanitor(ctx context.Context, interval time.Duration) { if s.readCache == nil { - return nil, false + return + } + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + s.readCache.PurgeExpired() + } } - return s.readCache.GetValue(key) } diff --git a/coordinator/api/cache_attempt_body_limit_test.go b/coordinator/api/cache_attempt_body_limit_test.go index 1247991a02..9ba6fe59ae 100644 --- a/coordinator/api/cache_attempt_body_limit_test.go +++ b/coordinator/api/cache_attempt_body_limit_test.go @@ -2,149 +2,16 @@ package api import ( "context" - "errors" "io" "net/http" - "net/http/httptest" "strings" "testing" "time" + "github.com/eigeninference/d-inference/coordinator/inference/dispatch" "github.com/eigeninference/d-inference/coordinator/protocol" - "github.com/eigeninference/d-inference/coordinator/registry" ) -func TestLegacyCacheIsolationOverflowIsPayloadTooLarge(t *testing.T) { - const prefix = `{"payload":"` - const suffix = `"}` - rawBody := []byte(prefix + - strings.Repeat("x", maxInferenceBodyBytes-len(prefix)-len(suffix)) + - suffix) - if len(rawBody) != maxInferenceBodyBytes { - t.Fatalf("fixture body = %d bytes, want %d", len(rawBody), maxInferenceBodyBytes) - } - - _, err := bodyForCacheAttempt(rawBody, false, nil, ®istry.PendingRequest{ - LegacyCacheBustKey: "legacy-isolation-key", - }) - if !errors.Is(err, errProviderBodyTooLarge) { - t.Fatalf("bodyForCacheAttempt error = %v, want errProviderBodyTooLarge", err) - } - if got := oversizedProviderBodyBytes(err); got <= maxInferenceBodyBytes { - t.Fatalf("oversized body bytes = %d, want > %d", got, maxInferenceBodyBytes) - } - if got := dispatchErrorClass(err.Error()); got != errorClassClientError { - t.Fatalf("dispatch error class = %q, want %s", got, errorClassClientError) - } - traits, traitsErr := routingTraitsForProviderBody(false, rawBody, false) - if !errors.Is(traitsErr, errProviderBodyTooLarge) || - traits.MinPrefixCacheProtocol != 1 { - t.Fatalf("admission traits = %+v, err=%v; want protocol floor 1", traits, traitsErr) - } - outcome := routeOutcome("error", dispatchErrorClass(err.Error()), http.StatusRequestEntityTooLarge) - if outcome.ErrorReason != errorReasonClientError { - t.Fatalf("route error reason = %q, want %s", outcome.ErrorReason, errorReasonClientError) - } - - state := &dispatchState{ - r: httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil), - rawBody: rawBody, - } - state.preflightLegacyCacheBust() - if state.terminalClientError || - state.providerBodyTooLargeErr != "" || - state.minPrefixCacheProtocol != 1 || - state.lastErrCode != 0 { - t.Fatalf("hypothetical overflow was incorrectly latched: %+v", state) - } - bodyBytes, preflightErr := minimumLegacyCacheBustOverflow(rawBody, false) - state.noteProviderBodyTooLarge(preflightErr.Error(), bodyBytes) - state.latchProviderBodyTooLarge(state.providerBodyTooLargeErr) - if !state.terminalClientError || - state.terminalClientErrorCode != http.StatusRequestEntityTooLarge || - state.terminalClientErrorReason != "payload_too_large" || - state.lastErrCode != http.StatusRequestEntityTooLarge { - t.Fatalf("payload-too-large dispatch state = %+v", state) - } - rejection := state.rejectionInfo( - "dispatch", "payload_too_large", http.StatusRequestEntityTooLarge, 0) - if rejection.requestBodyBytes != state.providerBodyTooLargeBytes || - !rejection.servabilityComputed || - rejection.candidateCount != 0 { - t.Fatalf("rejection accounting = %+v, want exact bytes and could_have_served=false", - rejection) - } -} - -func TestBodyAtLimitWithoutLegacyCacheIsolationRemainsAccepted(t *testing.T) { - const prefix = `{"payload":"` - const suffix = `"}` - rawBody := []byte(prefix + - strings.Repeat("x", maxInferenceBodyBytes-len(prefix)-len(suffix)) + - suffix) - - sealed, err := bodyForCacheAttempt(rawBody, false, nil, ®istry.PendingRequest{}) - if err != nil { - t.Fatalf("bodyForCacheAttempt: %v", err) - } - if len(sealed) != maxInferenceBodyBytes { - t.Fatalf("sealed body = %d bytes, want %d", len(sealed), maxInferenceBodyBytes) - } -} - -func TestAdmissionDoesNotInvent413WithoutIncompatibleProvider(t *testing.T) { - s := newTestServerForDispatch(t) - recorder := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) - traits := registry.RequestTraits{MinPrefixCacheProtocol: 1} - sizeErr := &providerBodyTooLargeError{size: maxInferenceBodyBytes + 63} - refunded := false - _, handled := s.runInferenceAdmission( - recorder, - request, - map[string]any{"model": "overflow-model"}, - inferenceAdmissionParams{ - model: "overflow-model", - publicModel: "overflow-model", - traits: &traits, - traitsForModel: func(string) registry.RequestTraits { return traits }, - providerBodyErrorForModel: func(string) error { return sizeErr }, - refundReservation: func() { refunded = true }, - }, - ) - // An empty fleet sheds as transient capacity (429 + Retry-After), never as a - // request-shape error: nothing about this request is too large. - if !handled || !refunded || recorder.Code != http.StatusTooManyRequests { - t.Fatalf("admission handled=%v refunded=%v status=%d body=%s", - handled, refunded, recorder.Code, recorder.Body.String()) - } - if strings.Contains(recorder.Body.String(), `"code":"payload_too_large"`) { - t.Fatalf("empty fleet was misclassified as payload_too_large: %s", recorder.Body.String()) - } - - preferRecorder := httptest.NewRecorder() - preferRefunded := false - _, preferHandled := s.runInferenceAdmission( - preferRecorder, - request, - map[string]any{"model": "overflow-model"}, - inferenceAdmissionParams{ - model: "overflow-model", - publicModel: "overflow-model", - traits: &traits, - traitsForModel: func(string) registry.RequestTraits { return traits }, - providerBodyErrorForModel: func(string) error { return sizeErr }, - policy: selfRoutePolicy{prefer: true, ownerAccountID: "owner"}, - refundReservation: func() { preferRefunded = true }, - }, - ) - if preferHandled || preferRefunded || - strings.Contains(preferRecorder.Body.String(), "payload_too_large") { - t.Fatalf("empty prefer fleet handled=%v refunded=%v body=%s", - preferHandled, preferRefunded, preferRecorder.Body.String()) - } -} - func TestAdmissionReturns413ForActualProtocolZeroIncompatibility(t *testing.T) { reg, _, server := setupFailoverServer(t) // Allow race-instrumented decoding of a maximum-size body on loaded runners. @@ -163,9 +30,9 @@ func TestAdmissionReturns413ForActualProtocolZeroIncompatibility(t *testing.T) { const prefix = `{"model":"overflow-protocol-zero-model","messages":[{"role":"user","content":"` const suffix = `"}],"max_tokens":1}` body := prefix + strings.Repeat( - "x", maxInferenceBodyBytes-len(prefix)-len(suffix)) + suffix - if len(body) != maxInferenceBodyBytes { - t.Fatalf("fixture body = %d, want %d", len(body), maxInferenceBodyBytes) + "x", dispatch.MaxInferenceBodyBytes-len(prefix)-len(suffix)) + suffix + if len(body) != dispatch.MaxInferenceBodyBytes { + t.Fatalf("fixture body = %d, want %d", len(body), dispatch.MaxInferenceBodyBytes) } request, err := http.NewRequestWithContext( ctx, http.MethodPost, server.URL+"/v1/chat/completions", strings.NewReader(body)) @@ -188,76 +55,3 @@ func TestAdmissionReturns413ForActualProtocolZeroIncompatibility(t *testing.T) { t.Fatalf("incompatible provider received %d dispatches", provider.dispatchCount()) } } - -func TestVisionPreflightKeepsLegacyProviderWhenPenaltyStrippingFits(t *testing.T) { - const prefix = `{"payload":"` - const penaltyPrefix = `","repetition_penalty":"` - const penaltyValueBytes = 256 - const suffix = `"}` - const providerMutationBytes = 100 - fillerBytes := maxInferenceBodyBytes + providerMutationBytes - - len(prefix) - len(penaltyPrefix) - penaltyValueBytes - len(suffix) - rawBody := []byte(prefix + - strings.Repeat("x", fillerBytes) + - penaltyPrefix + - strings.Repeat("y", penaltyValueBytes) + - suffix) - if len(rawBody) != maxInferenceBodyBytes+providerMutationBytes { - t.Fatalf("fixture body = %d bytes, want %d", - len(rawBody), maxInferenceBodyBytes+providerMutationBytes) - } - - if _, err := minimumLegacyCacheBustOverflow(rawBody, false); !errors.Is(err, errProviderBodyTooLarge) { - t.Fatalf("unstripped body error = %v, want errProviderBodyTooLarge", err) - } - if _, err := minimumLegacyCacheBustOverflow(rawBody, true); err != nil { - t.Fatalf("vision body should fit after mandatory legacy penalty stripping: %v", err) - } - legacyBody, err := bodyForCacheAttempt( - rawBody, true, ®istry.Provider{Version: "0.6.6"}, ®istry.PendingRequest{}) - if err != nil || len(legacyBody) > maxInferenceBodyBytes { - t.Fatalf("legacy transformed body size=%d err=%v", len(legacyBody), err) - } - if _, err := bodyForCacheAttempt( - rawBody, true, ®istry.Provider{Version: penaltySafeProviderVersion}, - ®istry.PendingRequest{}); !errors.Is(err, errProviderBodyTooLarge) { - t.Fatalf("untransformed modern body error=%v, want payload-too-large", err) - } - if _, err := providerBodySizeError( - rawBody, true, ®istry.Provider{Version: "0.6.6"}); err != nil { - t.Fatalf("legacy pre-pricing size check rejected transformed body: %v", err) - } - if _, err := providerBodySizeError( - rawBody, true, ®istry.Provider{ - Version: penaltySafeProviderVersion, PrefixCacheProtocol: 1, - }); !errors.Is(err, errProviderBodyTooLarge) { - t.Fatalf("modern pre-pricing size check error=%v, want payload-too-large", err) - } - - state := &dispatchState{rawBody: rawBody, requiresVision: true} - state.preflightLegacyCacheBust() - if state.minPrefixCacheProtocol != 0 || state.providerBodyTooLargeErr != "" { - t.Fatalf("vision preflight incorrectly excluded protocol-0 provider: %+v", state) - } - state.lastErr = "prior provider failure" - state.lastErrReason = "jinja_template_error" - state.noteProviderBodyTooLargeFor( - ®istry.Provider{ID: "newer-v0", Version: penaltySafeProviderVersion}, - "provider-specific overflow", - ) - if state.minPrefixCacheProtocol != 0 { - t.Fatalf("one provider-specific overflow excluded all protocol-0 fallbacks: %+v", state) - } - if !state.shouldQueueCompatibleProvider(registry.RoutingDecision{CapacityRejections: 1}) { - t.Fatal("provider-specific overflow did not preserve queueing for a compatible busy fallback") - } - outcome := state.errorRoutingOutcomeFor( - ®istry.PendingRequest{}, "error", errorClassClientError, http.StatusRequestEntityTooLarge) - if outcome.ErrorReason != errorReasonClientError { - t.Fatalf("overflow route inherited stale reason %q", outcome.ErrorReason) - } - excluded := state.excludedProviderIDs() - if len(excluded) != 1 || excluded[0] != "newer-v0" { - t.Fatalf("queued fallback exclusions = %v, want [newer-v0]", excluded) - } -} diff --git a/coordinator/api/cache_concurrency_test.go b/coordinator/api/cache_concurrency_test.go deleted file mode 100644 index e294a44821..0000000000 --- a/coordinator/api/cache_concurrency_test.go +++ /dev/null @@ -1,172 +0,0 @@ -package api - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "sync" - "sync/atomic" - "testing" - "time" - - "github.com/eigeninference/d-inference/coordinator/store" -) - -type blockingDashboardStore struct { - store.Store - entered chan string - release chan struct{} - calls atomic.Int64 -} - -func (s *blockingDashboardStore) AccountEarningsWindows(account string, now time.Time) (store.AccountEarningsWindows, error) { - s.calls.Add(1) - s.entered <- account - <-s.release - return s.Store.AccountEarningsWindows(account, now) -} - -func TestSummaryConcurrentExpiredMissesCoalescePerAccount(t *testing.T) { - srv, base := newMeTestServer(t) - st := &blockingDashboardStore{Store: base, entered: make(chan string, 64), release: make(chan struct{})} - srv.store = st - srv.readCache.Set("me:summary:windows:a", []byte(`{}`), -time.Second) - const callers = 30 - var ready, done sync.WaitGroup - ready.Add(callers) - done.Add(callers) - start := make(chan struct{}) - errs := make(chan error, callers+1) - for range callers { - go func() { - defer done.Done() - ready.Done() - <-start - _, err := srv.accountEarningsWindows("a") - errs <- err - }() - } - ready.Wait() - close(start) - select { - case <-st.entered: - case <-time.After(time.Second): - t.Fatal("first query never started") - } - // Other accounts must not wait behind the first account's query. - otherDone := make(chan struct{}) - go func() { defer close(otherDone); _, err := srv.accountEarningsWindows("b"); errs <- err }() - select { - case account := <-st.entered: - if account != "b" { - close(st.release) - done.Wait() - <-otherDone - t.Fatalf("duplicate account query before release: %q", account) - } - case <-time.After(time.Second): - close(st.release) - done.Wait() - <-otherDone - t.Fatal("different account blocked") - } - close(st.release) - done.Wait() - <-otherDone - close(errs) - for err := range errs { - if err != nil { - t.Fatal(err) - } - } - if got := st.calls.Load(); got != 2 { - t.Fatalf("aggregate calls = %d, want one per account", got) - } -} - -type serialTotalsStore struct { - store.Store - active atomic.Int64 - peak atomic.Int64 - calls atomic.Int64 - entered chan struct{} - release chan struct{} - fail atomic.Bool -} - -func (s *serialTotalsStore) NetworkTotals(since time.Time) (store.NetworkTotalsRow, error) { - active := s.active.Add(1) - defer s.active.Add(-1) - for peak := s.peak.Load(); active > peak; peak = s.peak.Load() { - if s.peak.CompareAndSwap(peak, active) { - break - } - } - s.calls.Add(1) - s.entered <- struct{}{} - <-s.release - if s.fail.Load() { - return store.NetworkTotalsRow{}, errors.New("totals unavailable") - } - return s.Store.NetworkTotals(since) -} - -func TestTotalsColdWindowsSerializeWithBackgroundRefresh(t *testing.T) { - srv, _, base := newStatsRefresherFixture(t) - st := &serialTotalsStore{Store: base, entered: make(chan struct{}, 16), release: make(chan struct{})} - srv.store = st - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - backgroundDone := make(chan struct{}) - go func() { defer close(backgroundDone); srv.runNetworkTotalsRefresher(ctx, time.Hour) }() - select { - case <-st.entered: - case <-time.After(time.Second): - t.Fatal("background query never started") - } - var wg sync.WaitGroup - responses := make(chan int, len(networkTotalsWindows)) - for _, window := range networkTotalsWindows { - wg.Add(1) - go func() { - defer wg.Done() - rr := httptest.NewRecorder() - srv.handleNetworkTotals(rr, httptest.NewRequest(http.MethodGet, "/v1/network/totals?window="+window, nil)) - responses <- rr.Code - }() - } - // Hold the first query while all cold windows contend. A second entry in - // this interval proves that independent keys escaped the shared bound. - select { - case <-st.entered: - close(st.release) - wg.Wait() - cancel() - <-backgroundDone - t.Fatal("totals queries overlapped across windows") - case <-time.After(50 * time.Millisecond): - } - close(st.release) - wg.Wait() - cancel() - <-backgroundDone - close(responses) - for code := range responses { - if code != http.StatusOK { - t.Fatalf("totals status = %d", code) - } - } - if peak := st.peak.Load(); peak != 1 { - t.Fatalf("peak totals concurrency = %d", peak) - } - // Errors must release the shared query lock so a later healthy window can run. - st.fail.Store(true) - if _, err := srv.computeNetworkTotals("all"); err == nil { - t.Fatal("expected store error") - } - st.fail.Store(false) - if _, err := srv.computeNetworkTotals("all"); err != nil { - t.Fatal(err) - } -} diff --git a/coordinator/api/cache_generation.go b/coordinator/api/cache_generation.go deleted file mode 100644 index ce1c33eeee..0000000000 --- a/coordinator/api/cache_generation.go +++ /dev/null @@ -1,34 +0,0 @@ -package api - -import "time" - -// readCacheGeneration snapshots the invalidation generation before a catalog -// computation reads its inputs. A concurrent admin sync may invalidate the -// result while it is being built; that request can finish with its snapshot, -// but must not repopulate the cache for requests after the sync completes. -func (s *Server) readCacheGeneration() uint64 { - if s.readCache == nil { - return 0 - } - c := s.readCache - c.mu.RLock() - defer c.mu.RUnlock() - return c.generation -} - -// readCacheSetEntryIfCurrent publishes a catalog fill only if no invalidation -// has raced it. The comparison and write use the same lock as Invalidate, so -// a successful check cannot race with the eviction it is meant to preserve. -func (s *Server) readCacheSetEntryIfCurrent(key string, entry ttlEntry, ttl time.Duration, generation uint64) { - if s.readCache == nil { - return - } - c := s.readCache - c.mu.Lock() - defer c.mu.Unlock() - if c.generation != generation { - return - } - entry.expiresAt = time.Now().Add(ttl) - c.data[key] = entry -} diff --git a/coordinator/api/cache_model_telemetry.go b/coordinator/api/cache_model_telemetry.go index c7f60cc099..928b8db41a 100644 --- a/coordinator/api/cache_model_telemetry.go +++ b/coordinator/api/cache_model_telemetry.go @@ -4,6 +4,7 @@ import ( "math" "strings" + "github.com/eigeninference/d-inference/coordinator/inference/dispatch" "github.com/eigeninference/d-inference/coordinator/protocol" "github.com/eigeninference/d-inference/coordinator/registry" ) @@ -52,20 +53,20 @@ func (s *Server) emitModelCacheUsage(pr *registry.PendingRequest, usage protocol if pr == nil { return } - model := MetricLabel{"model", s.cacheModelLabel(pr.Model)} + model := MetricLabel{Name: "model", Value: s.cacheModelLabel(pr.Model)} outcome, tier := "unreported", "none" if present && !valid { outcome = "invalid" } else if valid { - outcome, tier = usage.CacheOutcome, lowCardinalityCacheTier(usage.CacheTier) + outcome, tier = usage.CacheOutcome, dispatch.LowCardinalityCacheTier(usage.CacheTier) } - labels := []MetricLabel{model, {"outcome", outcome}, {"tier", tier}} + labels := []MetricLabel{model, {Name: "outcome", Value: outcome}, {Name: "tier", Value: tier}} s.cacheModelCount("usage", 1, labels...) if !valid { return } - s.cacheModelCount("cached_tokens", int64(usage.CachedTokens), model, MetricLabel{"tier", tier}) - s.cacheModelCount("prefill_tokens_saved", int64(usage.PrefillTokensSaved), model, MetricLabel{"tier", tier}) + s.cacheModelCount("cached_tokens", int64(usage.CachedTokens), model, MetricLabel{Name: "tier", Value: tier}) + s.cacheModelCount("prefill_tokens_saved", int64(usage.PrefillTokensSaved), model, MetricLabel{Name: "tier", Value: tier}) s.cacheModelTiming("provider_stage", usage.CacheStageMs, labels...) s.emitModelCacheCoverage("usage", usage, labels) } @@ -76,7 +77,7 @@ func (s *Server) emitModelCacheLookup(msg *protocol.PrefixCacheLookupV2Message, if msg == nil || !receipt.Accepted { return } - labels := []MetricLabel{{"model", s.cacheModelLabel(msg.ModelID)}, {"outcome", msg.Outcome}, {"tier", lowCardinalityCacheTier(msg.Tier)}} + labels := []MetricLabel{{Name: "model", Value: s.cacheModelLabel(msg.ModelID)}, {Name: "outcome", Value: msg.Outcome}, {Name: "tier", Value: dispatch.LowCardinalityCacheTier(msg.Tier)}} s.cacheModelCount("lookup", 1, labels...) // The denominator is the coordinator's exact plan, never a provider value. if receipt.PromptTokens > 0 { @@ -90,8 +91,8 @@ func (s *Server) emitModelCacheDonation(msg *protocol.PrefixCacheReadyV2Message, return } s.cacheModelCount("donation", 1, - MetricLabel{"model", s.cacheModelLabel(msg.ModelID)}, - MetricLabel{"tier", lowCardinalityCacheTier(msg.Tier)}) + MetricLabel{Name: "model", Value: s.cacheModelLabel(msg.ModelID)}, + MetricLabel{Name: "tier", Value: dispatch.LowCardinalityCacheTier(msg.Tier)}) } // Runs inside the existing exactly-once cache terminal claim. "result" is the @@ -110,10 +111,10 @@ func (s *Server) emitModelCacheSelection(pr *registry.PendingRequest, tags []str } func (s *Server) cacheModelSelectionLabels(model string, tags []string) []MetricLabel { - labels := []MetricLabel{{"model", s.cacheModelLabel(model)}} + labels := []MetricLabel{{Name: "model", Value: s.cacheModelLabel(model)}} for _, tag := range tags { name, value, _ := strings.Cut(tag, ":") - labels = append(labels, MetricLabel{name, value}) + labels = append(labels, MetricLabel{Name: name, Value: value}) } return labels } @@ -139,10 +140,10 @@ func (s *Server) emitModelCacheReceipt(model, tier, kind string, receipt registr outcome = "accepted" } s.cacheModelCount("receipt", 1, - MetricLabel{"model", s.cacheModelLabel(model)}, MetricLabel{"tier", lowCardinalityCacheTier(tier)}, - MetricLabel{"type", kind}, MetricLabel{"outcome", outcome}, MetricLabel{"reason", string(receipt.Reason)}) + MetricLabel{Name: "model", Value: s.cacheModelLabel(model)}, MetricLabel{Name: "tier", Value: dispatch.LowCardinalityCacheTier(tier)}, + MetricLabel{Name: "type", Value: kind}, MetricLabel{Name: "outcome", Value: outcome}, MetricLabel{Name: "reason", Value: string(receipt.Reason)}) if receipt.PromptMismatch != "" { - s.cacheModelCount("prompt_mismatch", 1, MetricLabel{"model", s.cacheModelLabel(model)}, - MetricLabel{"tier", lowCardinalityCacheTier(tier)}, MetricLabel{"detail", string(receipt.PromptMismatch)}) + s.cacheModelCount("prompt_mismatch", 1, MetricLabel{Name: "model", Value: s.cacheModelLabel(model)}, + MetricLabel{Name: "tier", Value: dispatch.LowCardinalityCacheTier(tier)}, MetricLabel{Name: "detail", Value: string(receipt.PromptMismatch)}) } } diff --git a/coordinator/api/cache_model_telemetry_test.go b/coordinator/api/cache_model_telemetry_test.go index 44126fde37..8b9359a710 100644 --- a/coordinator/api/cache_model_telemetry_test.go +++ b/coordinator/api/cache_model_telemetry_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "github.com/eigeninference/d-inference/coordinator/inference/providerframe" "github.com/eigeninference/d-inference/coordinator/protocol" "github.com/eigeninference/d-inference/coordinator/registry" ) @@ -54,7 +55,7 @@ func TestModelCacheCompletionsSeparateModelsAndPreserveUsage(t *testing.T) { srv.handleComplete(provider.ID, provider, &msg) if !tc.parked { got := <-pr.CompleteCh - if validCacheUsage(tc.usage) && got.CachedTokens != tc.usage.CachedTokens { + if providerframe.ValidCacheUsage(tc.usage) && got.CachedTokens != tc.usage.CachedTokens { t.Fatalf("telemetry changed response cached tokens: %+v", got) } } @@ -63,14 +64,14 @@ func TestModelCacheCompletionsSeparateModelsAndPreserveUsage(t *testing.T) { for _, tc := range []struct{ model, outcome, tier string }{ {a, "hit", "ssd"}, {b, "miss_absent", "ssd"}, {c, "hit", "ssd"}, {a, "invalid", "none"}, {b, "unreported", "none"}, } { - key := metricKey("cache_model_usage_total", []MetricLabel{{"model", tc.model}, {"outcome", tc.outcome}, {"tier", tc.tier}}) + key := metricKey("cache_model_usage_total", []MetricLabel{{Name: "model", Value: tc.model}, {Name: "outcome", Value: tc.outcome}, {Name: "tier", Value: tc.tier}}) if snap.Counters[key] != 1 { t.Fatalf("%s = %d, want 1", key, snap.Counters[key]) } } for _, model := range []string{a, c} { - labels := []MetricLabel{{"model", model}, {"tier", "ssd"}} - hitLabels := []MetricLabel{{"model", model}, {"outcome", "hit"}, {"tier", "ssd"}} + labels := []MetricLabel{{Name: "model", Value: model}, {Name: "tier", Value: "ssd"}} + hitLabels := []MetricLabel{{Name: "model", Value: model}, {Name: "outcome", Value: "hit"}, {Name: "tier", Value: "ssd"}} if got := snap.Counters[metricKey("cache_model_usage_prompt_tokens_total", hitLabels)]; got != 4096 { t.Fatalf("hit prompt denominator for %s = %d", model, got) } @@ -87,7 +88,7 @@ func TestModelCacheCompletionsSeparateModelsAndPreserveUsage(t *testing.T) { if snap.Counters["exact_cache_usage_total{outcome=hit,tier=ssd}"] != 2 || snap.Counters["exact_cache_prefill_tokens_saved_total{tier=ssd}"] != 4096 { t.Fatal("aggregate usage changed or invalid/duplicate usage was counted") } - stageLabels := []MetricLabel{{"model", a}, {"tier", "ssd"}, {"outcome", "hit"}} + stageLabels := []MetricLabel{{Name: "model", Value: a}, {Name: "tier", Value: "ssd"}, {Name: "outcome", Value: "hit"}} if snap.Counters[metricKey("cache_model_provider_stage_us_total", stageLabels)] != 40250 || snap.Counters[metricKey("cache_model_provider_stage_samples_total", stageLabels)] != 1 { t.Fatal("provider stage sum/sample counters are wrong") } @@ -227,7 +228,7 @@ func TestModelCacheCoverageSeparatesHitAndNonHitDenominators(t *testing.T) { }{ {"hit", 8192, 4096}, {"miss_absent", 16384, 0}, {"invalid", 0, 0}, {"unreported", 0, 0}, } { - labels := []MetricLabel{{"model", model}, {"outcome", tc.outcome}, {"tier", "ssd"}} + labels := []MetricLabel{{Name: "model", Value: model}, {Name: "outcome", Value: tc.outcome}, {Name: "tier", Value: "ssd"}} if got := snap.Counters[metricKey("cache_model_usage_prompt_tokens_total", labels)]; got != tc.prompt { t.Fatalf("%s denominator = %d", tc.outcome, got) } @@ -250,7 +251,7 @@ func TestModelCacheAcceptedLookupAndSelectedCoverage(t *testing.T) { usage := protocol.UsageInfo{PromptTokens: 8192, CachedTokens: 4096, PrefillTokensSaved: 4096, CacheOutcome: "hit", CacheTier: "ssd"} srv.emitCacheSelectionTerminal(pr, usage, true, true) srv.emitCacheSelectionTerminal(pr, usage, true, true) - lookupLabels := []MetricLabel{{"model", model}, {"tier", "ssd"}, {"outcome", "hit"}} + lookupLabels := []MetricLabel{{Name: "model", Value: model}, {Name: "tier", Value: "ssd"}, {Name: "outcome", Value: "hit"}} selectionLabels := srv.cacheModelSelectionLabels(model, cacheSelectionTerminalTags(pr, usage, true, true)) for _, tc := range []struct { name string diff --git a/coordinator/api/cache_opportunity_telemetry.go b/coordinator/api/cache_opportunity_telemetry.go index 22a8ee483d..588393e04a 100644 --- a/coordinator/api/cache_opportunity_telemetry.go +++ b/coordinator/api/cache_opportunity_telemetry.go @@ -6,7 +6,7 @@ func (s *Server) emitCacheOpportunity(pr *registry.PendingRequest) { if pr == nil || !pr.CacheOpportunity.Evaluated { return } - labels := []MetricLabel{{"model", s.cacheModelLabel(pr.Model)}, {"reason", pr.CacheOpportunityReason()}} + labels := []MetricLabel{{Name: "model", Value: s.cacheModelLabel(pr.Model)}, {Name: "reason", Value: pr.CacheOpportunityReason()}} s.cacheModelCount("opportunity", 1, labels...) if pr.CacheOpportunity.AffinityApplied { s.cacheModelCount("opportunity_affinity", 1, labels...) diff --git a/coordinator/api/cache_opportunity_telemetry_test.go b/coordinator/api/cache_opportunity_telemetry_test.go index e4f24a1457..7951342340 100644 --- a/coordinator/api/cache_opportunity_telemetry_test.go +++ b/coordinator/api/cache_opportunity_telemetry_test.go @@ -22,14 +22,14 @@ func TestCacheOpportunityTelemetryIsTerminalOnceAndContainsNoPrivateIdentity(t * srv.emitCacheSelectionTerminal(pr, usage, true, true) srv.emitCacheSelectionTerminal(pr, usage, true, true) snap := srv.metrics.Snapshot() - labels := []MetricLabel{{"model", pr.Model}, {"reason", "repeat_without_holder"}} + labels := []MetricLabel{{Name: "model", Value: pr.Model}, {Name: "reason", Value: "repeat_without_holder"}} if snap.Counters[metricKey("cache_model_opportunity_total", labels)] != 1 { t.Fatal("duplicate terminal counted or opportunity missing") } if snap.Counters[metricKey("cache_model_opportunity_repeated_prefix_tokens_total", labels)] != 1024 { t.Fatal("repeat demand denominator missing") } - if snap.Counters[metricKey("cache_model_prefill_tokens_saved_total", []MetricLabel{{"model", pr.Model}, {"tier", "ssd"}})] != 0 { + if snap.Counters[metricKey("cache_model_prefill_tokens_saved_total", []MetricLabel{{Name: "model", Value: pr.Model}, {Name: "tier", Value: "ssd"}})] != 0 { t.Fatal("demand was counted as saved work") } raw, _ := json.Marshal(snap) diff --git a/coordinator/api/cache_preparation_helpers_test.go b/coordinator/api/cache_preparation_helpers_test.go index 852fd12722..f968600e0e 100644 --- a/coordinator/api/cache_preparation_helpers_test.go +++ b/coordinator/api/cache_preparation_helpers_test.go @@ -70,26 +70,3 @@ func cachePreparationPlanForTest(t testing.TB, reg *registry.Registry, capabilit } return result.Plan } - -func preparedCacheAttemptForTest(t testing.TB) (*registry.Registry, *registry.Provider, *registry.PendingRequest) { - t.Helper() - reg := registry.New(quietLogger()) - configureCachePreparationTest(t, reg) - capability := cacheEligibilityV2Capability("model") - capability.ReadyBoundaryMode = protocol.PrefixCacheReadyBoundaryCheckpoint - provider := reg.Register("provider", nil, &protocol.RegisterMessage{ - Type: protocol.TypeRegister, PrefixCacheProtocol: 2, - Models: []protocol.ModelInfo{{ID: capability.ModelID, WeightHash: capability.ModelAggregateHash}}, - PrefixCacheV2Models: []protocol.PrefixCacheV2Capability{capability}, - }) - pending := ®istry.PendingRequest{RequestID: "request", Model: "model", - CachePlan: cachePreparationPlanForTest(t, reg, capability)} - if err := reg.PrepareCacheAttempt(pending, provider); err != nil { - t.Fatal(err) - } - if !pending.CacheRoutingParticipates() { - t.Fatal("valid registered provider and sidecar plan did not prepare") - } - t.Cleanup(func() { reg.ForgetCacheAttempt(pending) }) - return reg, provider, pending -} diff --git a/coordinator/api/cache_refresher.go b/coordinator/api/cache_refresher.go deleted file mode 100644 index 78f20f1ba8..0000000000 --- a/coordinator/api/cache_refresher.go +++ /dev/null @@ -1,104 +0,0 @@ -package api - -import ( - "context" - "sync" - "time" - - "github.com/eigeninference/d-inference/coordinator/saferun" -) - -const ( - cacheRefreshInterval = time.Minute - // Stats has a shorter freshness window than the network earnings totals. - statsRefreshInterval = 30 * time.Second - // Failed refreshes retain the previous success only until this safety TTL. - refreshedCacheTTL = 5 * time.Minute -) - -// cacheRefresher coalesces computations of one read-cache entry. Only complete -// successful results are cached; query errors never become partial JSON data. -type cacheRefresher struct { - mu sync.Mutex - inflight chan struct{} -} - -// getCachedEntry fills a cold cache. It rechecks the cache under the flight -// lock so a request delayed after its initial miss cannot start a second -// expensive query after another request has already populated the entry. -func (s *Server) getCachedEntry(entry *cacheRefresher, key string, compute func() ([]byte, error)) ([]byte, bool) { - return s.computeCachedEntry(entry, key, false, compute) -} - -// refreshCachedEntry forces a periodic refresh, sharing any existing flight. -func (s *Server) refreshCachedEntry(entry *cacheRefresher, key string, compute func() ([]byte, error)) ([]byte, bool) { - return s.computeCachedEntry(entry, key, true, compute) -} - -func (s *Server) computeCachedEntry(entry *cacheRefresher, key string, refresh bool, compute func() ([]byte, error)) ([]byte, bool) { - entry.mu.Lock() - if !refresh { - if body, ok := s.readCache.Get(key); ok { - entry.mu.Unlock() - return body, true - } - } - if wait := entry.inflight; wait != nil { - entry.mu.Unlock() - <-wait - return s.readCache.Get(key) - } - done := make(chan struct{}) - entry.inflight = done - entry.mu.Unlock() - defer func() { - entry.mu.Lock() - entry.inflight = nil - close(done) - entry.mu.Unlock() - }() - - body, err := compute() - if err != nil { - s.logger.Warn("cache refresh failed; keeping previous value", "key", key, "error", err) - s.ddIncr("cache.refresh_failed", []string{"key:" + key}) - return s.readCache.Get(key) - } - s.readCache.Set(key, body, refreshedCacheTTL) - return body, true -} - -// runCacheRefreshLoop computes once at start and then every interval until -// ctx is cancelled. -func (s *Server) runCacheRefreshLoop(ctx context.Context, interval time.Duration, refresh func()) { - if s.readCache == nil || ctx.Err() != nil { - return - } - refresh() - ticker := time.NewTicker(interval) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - refresh() - } - } -} - -// StartCacheRefreshers starts the goroutines that own the refreshed read-cache -// entries (stats:v1, stats:geography:v1 and network_totals:*). Independent -// loops keep slow geography queries off the core stats path. Stops when ctx -// is cancelled. -func (s *Server) StartCacheRefreshers(ctx context.Context) { - saferun.Go(s.logger, "api.statsGeographyRefresher", func() { - s.runCacheRefreshLoop(ctx, statsRefreshInterval, func() { s.refreshStatsGeography() }) - }) - saferun.Go(s.logger, "api.statsRefresher", func() { - s.runStatsRefresher(ctx, statsRefreshInterval) - }) - saferun.Go(s.logger, "api.networkTotalsRefresher", func() { - s.runNetworkTotalsRefresher(ctx, cacheRefreshInterval) - }) -} diff --git a/coordinator/api/cache_refresher_test.go b/coordinator/api/cache_refresher_test.go deleted file mode 100644 index d65a8bcc50..0000000000 --- a/coordinator/api/cache_refresher_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package api - -import ( - "bytes" - "context" - "testing" - "time" -) - -// A caller can observe a miss, then be descheduled until another caller has -// finished the fill. The flight lock alone does not coalesce that sequence. -func TestCachedEntryRechecksAfterDelayedMiss(t *testing.T) { - srv, _, _ := newStatsRefresherFixture(t) - const key = "test:delayed-miss" - var entry cacheRefresher - if _, ok := srv.readCache.Get(key); ok { - t.Fatal("expected cold cache") - } - calls := 0 - compute := func() ([]byte, error) { calls++; return []byte(`{"value":1}`), nil } - first, ok := srv.getCachedEntry(&entry, key, compute) - if !ok { - t.Fatal("first fill failed") - } - delayed, ok := srv.getCachedEntry(&entry, key, compute) - if !ok || !bytes.Equal(delayed, first) || calls != 1 { - t.Fatalf("delayed miss: ok=%v calls=%d", ok, calls) - } - // The periodic owner still refreshes an unexpired entry. - if _, ok := srv.refreshCachedEntry(&entry, key, compute); !ok || calls != 2 { - t.Fatalf("periodic refresh: ok=%v calls=%d", ok, calls) - } -} - -func TestCacheRefreshLoopCancelledBeforeStart(t *testing.T) { - srv, _, _ := newStatsRefresherFixture(t) - ctx, cancel := context.WithCancel(context.Background()) - cancel() - srv.runCacheRefreshLoop(ctx, time.Minute, func() { t.Fatal("queried after shutdown") }) -} diff --git a/coordinator/api/cache_selection_telemetry.go b/coordinator/api/cache_selection_telemetry.go new file mode 100644 index 0000000000..bc5bb951fd --- /dev/null +++ b/coordinator/api/cache_selection_telemetry.go @@ -0,0 +1,85 @@ +package api + +import ( + "math" + "strconv" + + "github.com/eigeninference/d-inference/coordinator/inference/dispatch" + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" +) + +func cacheSelectionTerminalTags(pr *registry.PendingRequest, usage protocol.UsageInfo, usageValid, usagePresent bool) []string { + mode := "none" + if pr != nil && pr.CacheSelectionMode == "active" { + mode = pr.CacheSelectionMode + } + result := "unreported" + lookupOutcome := "unreported" + read := false + if usagePresent && !usageValid { + result = "invalid" + lookupOutcome = "invalid" + } else if usageValid { + lookupOutcome = usage.CacheOutcome + if usage.CacheOutcome == "hit" { + result = "hit" + read = true + } else { + result = "non_hit" + } + } + tier := "none" + selected := false + if pr != nil { + tier = dispatch.LowCardinalityCacheTier(pr.CacheSelectionTier) + selected = pr.CacheSelectionSelected + } + return []string{ + "mode:" + mode, + "tier:" + tier, + "selected:" + strconv.FormatBool(selected), + "result:" + result, + "lookup_outcome:" + lookupOutcome, + "cache_read:" + strconv.FormatBool(read), + } +} + +func (s *Server) emitCacheSelectionTerminal(pr *registry.PendingRequest, usage protocol.UsageInfo, usageValid, usagePresent bool) bool { + if pr == nil || !pr.CacheRoutingTelemetryEligible() { + return false + } + if !pr.MarkCacheTerminalTelemetryEmitted() { + return false + } + tags := cacheSelectionTerminalTags(pr, usage, usageValid, usagePresent) + s.emitModelCacheSelection(pr, tags, usage, usageValid) + s.ddIncr("routing.cache_selection_terminal", tags) + if pr.CacheSelectionDiscountMs > 0 { + s.ddHistogram("routing.cache_selection_discount_ms", pr.CacheSelectionDiscountMs, tags) + if pr.CacheSelectionMode == "active" && pr.CacheSelectionSelected { + s.ddIncr("routing.cache_selection_precision", tags) + } + } + s.emitExactCacheEstimatedTTFTSaved(pr, tags) + return true +} + +func cacheSelectionTTFTSample(pr *registry.PendingRequest, usage protocol.UsageInfo, usageValid bool, actualTTFTMs float64) (float64, []string, bool) { + if pr == nil || !usageValid || actualTTFTMs <= 0 || math.IsNaN(actualTTFTMs) || math.IsInf(actualTTFTMs, 0) { + return 0, nil, false + } + if pr.CacheSelectionMode != "active" { + return 0, nil, false + } + return actualTTFTMs, cacheSelectionTerminalTags(pr, usage, true, true), true +} + +func (s *Server) emitCacheSelectionTTFT(pr *registry.PendingRequest, usage protocol.UsageInfo, usageValid bool, actualTTFTMs float64) { + value, tags, ok := cacheSelectionTTFTSample(pr, usage, usageValid, actualTTFTMs) + if !ok { + return + } + s.cacheModelTiming("ttft", value, s.cacheModelSelectionLabels(pr.Model, tags)...) + s.ddHistogram("routing.cache_selection_ttft_ms", value, tags) +} diff --git a/coordinator/api/cache_terminal_idempotence_test.go b/coordinator/api/cache_terminal_idempotence_test.go index adb46b6aaf..4a41a9de2f 100644 --- a/coordinator/api/cache_terminal_idempotence_test.go +++ b/coordinator/api/cache_terminal_idempotence_test.go @@ -4,6 +4,7 @@ import ( "strings" "testing" + "github.com/eigeninference/d-inference/coordinator/inference/attempt" "github.com/eigeninference/d-inference/coordinator/protocol" "github.com/eigeninference/d-inference/coordinator/registry" ) @@ -28,15 +29,15 @@ func TestCacheTerminalTelemetryIsIdempotentAcrossTerminalSeams(t *testing.T) { // Models a synthetic WebSocket disconnect consumed through ErrorCh: the // consumer's final route outcome is the only terminal seam. disconnected := cacheTelemetryPending("disconnect-secret") - srv.updateInferenceRouteOutcomeForPending(disconnected, pendingRouteOutcome(disconnected, finalStatusError, "provider_disconnect_pre_commit", 502)) + srv.updateInferenceRouteOutcomeForPending(disconnected, attempt.PendingRouteOutcome(disconnected, attempt.FinalStatusError, "provider_disconnect_pre_commit", 502)) // A racing provider error or late duplicate consumer update must not count it again. srv.emitCacheSelectionTerminal(disconnected, protocol.UsageInfo{}, false, false) - srv.updateInferenceRouteOutcomeForPending(disconnected, pendingRouteOutcome(disconnected, finalStatusError, "provider_disconnect_pre_commit", 502)) + srv.updateInferenceRouteOutcomeForPending(disconnected, attempt.PendingRouteOutcome(disconnected, attempt.FinalStatusError, "provider_disconnect_pre_commit", 502)) // A post-commit parked request has no final consumer outcome before its // provider completion. The validated completion must therefore still count. parked := cacheTelemetryPending("parked-secret") - srv.updateInferenceRouteOutcomeForPending(parked, committedRouteOutcome(parked)) + srv.updateInferenceRouteOutcomeForPending(parked, attempt.CommittedRouteOutcome(parked)) validHit := protocol.UsageInfo{ PromptTokens: 10, CacheOutcome: "hit", CacheTier: "ssd", CachedTokens: 4, PrefillTokensSaved: 3, diff --git a/coordinator/api/cache_test.go b/coordinator/api/cache_test.go index 63b0e2c5ba..83104d1f38 100644 --- a/coordinator/api/cache_test.go +++ b/coordinator/api/cache_test.go @@ -6,25 +6,6 @@ import ( "time" ) -// PurgeExpired removes expired entries and keeps live ones. -func TestTTLCachePurgeExpired(t *testing.T) { - c := newTTLCache() - c.Set("stale", []byte("v"), -time.Second) // already expired - c.Set("fresh", []byte("v"), time.Minute) // live - - c.PurgeExpired() - - if c.Len() != 1 { - t.Fatalf("PurgeExpired: got %d entries, want 1", c.Len()) - } - if _, ok := c.Get("stale"); ok { - t.Error("expired entry should be gone after PurgeExpired") - } - if _, ok := c.Get("fresh"); !ok { - t.Error("live entry should survive PurgeExpired") - } -} - // The janitor actually reclaims expired entries (PurgeExpired was previously // never scheduled, so high-cardinality keys lingered forever) and stops on ctx // cancel. diff --git a/coordinator/api/cache_usage.go b/coordinator/api/cache_usage.go deleted file mode 100644 index da09da234e..0000000000 --- a/coordinator/api/cache_usage.go +++ /dev/null @@ -1,152 +0,0 @@ -package api - -import ( - "encoding/json" - "math" - "strings" - - "github.com/eigeninference/d-inference/coordinator/protocol" -) - -func lowCardinalityCacheTier(tier string) string { - if tier == "memory" || tier == "ssd" { - return tier - } - return "none" -} - -func validCacheUsage(usage protocol.UsageInfo) bool { - switch usage.CacheOutcome { - case "": - return false - case "hit", "miss_absent", "miss_corrupt", "skipped_capacity", "skipped_cost", "skipped_policy": - default: - return false - } - if usage.CacheTier != "" && usage.CacheTier != "memory" && usage.CacheTier != "ssd" { - return false - } - const maxCacheUsageTokens = 1_000_000 - if usage.CachedTokens < 0 || usage.CachedTokens > maxCacheUsageTokens || usage.CachedTokens > usage.PromptTokens || - usage.PrefillTokensSaved < 0 || usage.PrefillTokensSaved > usage.CachedTokens || - usage.CacheStageMs < 0 || usage.CacheStageMs > 10*60*1000 || math.IsNaN(usage.CacheStageMs) || math.IsInf(usage.CacheStageMs, 0) { - return false - } - if usage.CacheOutcome == "hit" { - return usage.CacheTier != "" && usage.CachedTokens > 0 && usage.PrefillTokensSaved > 0 - } - return usage.CachedTokens == 0 && usage.PrefillTokensSaved == 0 -} - -func clearCacheUsage(usage *protocol.UsageInfo) { - if usage == nil { - return - } - usage.CacheOutcome = "" - usage.CacheTier = "" - usage.CachedTokens = 0 - usage.PrefillTokensSaved = 0 - usage.CacheStageMs = 0 -} - -func hasCacheUsage(usage protocol.UsageInfo) bool { - return usage.CacheOutcome != "" || usage.CacheTier != "" || usage.CachedTokens != 0 || - usage.PrefillTokensSaved != 0 || usage.CacheStageMs != 0 -} - -func injectCacheDetailIntoRawUsage(obj map[string]any, usage protocol.UsageInfo) { - setCachedTokenDetail(obj, "prompt_tokens_details", usage.CachedTokens) -} - -func sanitizeCacheDetailIntoRawResponsesUsage(obj map[string]any, usage protocol.UsageInfo) { - setCachedTokenDetail(obj, "input_tokens_details", usage.CachedTokens) -} - -func setCachedTokenDetail(obj map[string]any, detailField string, cachedTokens int) { - usageObj, ok := obj["usage"].(map[string]any) - if !ok { - return - } - details, detailsOK := usageObj[detailField].(map[string]any) - if details == nil { - if cachedTokens <= 0 { - // A malformed/non-object provider detail cannot be selectively - // sanitized, so remove it rather than forwarding untrusted cache data. - if !detailsOK { - delete(usageObj, detailField) - } - return - } - details = map[string]any{} - } - if cachedTokens > 0 { - details["cached_tokens"] = cachedTokens - } else { - delete(details, "cached_tokens") - } - if len(details) == 0 { - delete(usageObj, detailField) - } else { - usageObj[detailField] = details - } -} - -func removeCachedTokenDetail(usageObj map[string]any, detailField string) bool { - details, ok := usageObj[detailField].(map[string]any) - if !ok || details == nil { - return false - } - if _, exists := details["cached_tokens"]; !exists { - return false - } - delete(details, "cached_tokens") - if len(details) == 0 { - delete(usageObj, detailField) - } else { - usageObj[detailField] = details - } - return true -} - -func sanitizeStreamCacheDetailsJSON(raw string) (string, bool) { - var obj map[string]any - if json.Unmarshal([]byte(raw), &obj) != nil { - return raw, false - } - changed := false - if usageObj, ok := obj["usage"].(map[string]any); ok { - changed = removeCachedTokenDetail(usageObj, "prompt_tokens_details") || changed - changed = removeCachedTokenDetail(usageObj, "input_tokens_details") || changed - } - if response, ok := obj["response"].(map[string]any); ok { - if usageObj, ok := response["usage"].(map[string]any); ok { - changed = removeCachedTokenDetail(usageObj, "prompt_tokens_details") || changed - changed = removeCachedTokenDetail(usageObj, "input_tokens_details") || changed - } - } - if !changed { - return raw, false - } - b, err := marshalForwardBody(obj) - if err != nil { - return raw, false - } - return string(b), true -} - -// sanitizeStreamCacheDetails removes provider-supplied cached_tokens from any -// streamed frame before it can reach the consumer. SSE data fields are joined -// per the specification across each blank-line-delimited event, then a changed -// payload is emitted as one safe data line while event/id/comments are retained. -// Terminal usage is validated independently and re-added only to the held usage -// frame at stream completion. -func sanitizeStreamCacheDetails(chunk string) string { - // A normal field takes the literal fast path. A disguised equivalent must use - // a JSON Unicode escape (for example cached\u005ftokens); no other valid JSON - // escape can encode an ASCII letter or underscore. Parse those frames too, - // while leaving the overwhelmingly common escape-free content frame untouched. - if !strings.Contains(chunk, `"cached_tokens"`) && !strings.Contains(chunk, `\u`) { - return chunk - } - return sanitizeStreamJSONEvents(chunk, sanitizeStreamCacheDetailsJSON) -} diff --git a/coordinator/api/cache_usage_test.go b/coordinator/api/cache_usage_test.go index 2f2dbb271e..a3db35c8d2 100644 --- a/coordinator/api/cache_usage_test.go +++ b/coordinator/api/cache_usage_test.go @@ -1,7 +1,6 @@ package api import ( - "encoding/json" "strings" "testing" @@ -22,113 +21,6 @@ func testCachePlan(secret string) registry.CachePlan { } } -func TestInvalidProviderCacheUsageIsCleared(t *testing.T) { - usage := protocol.UsageInfo{ - PromptTokens: 10, CompletionTokens: 2, - CacheOutcome: "hit", CacheTier: "ssd", CachedTokens: 20, - PrefillTokensSaved: 19, CacheStageMs: 3, - } - if validCacheUsage(usage) { - t.Fatal("impossible cached_tokens > prompt_tokens accepted") - } - clearCacheUsage(&usage) - if usage.CacheOutcome != "" || usage.CacheTier != "" || usage.CachedTokens != 0 || usage.PrefillTokensSaved != 0 || usage.CacheStageMs != 0 { - t.Fatalf("cache extension was not cleared: %+v", usage) - } - if usage.PromptTokens != 10 || usage.CompletionTokens != 2 { - t.Fatalf("base completion usage was changed: %+v", usage) - } -} - -func TestOmittedOutcomeWithCacheFieldsRequiresSanitization(t *testing.T) { - usage := protocol.UsageInfo{PromptTokens: 10, CachedTokens: 20, PrefillTokensSaved: 19} - if !hasCacheUsage(usage) { - t.Fatal("cache fields without outcome were not detected") - } - if validCacheUsage(usage) { - t.Fatal("cache fields without outcome were accepted") - } - clearCacheUsage(&usage) - if hasCacheUsage(usage) { - t.Fatalf("invalid cache fields survived sanitization: %+v", usage) - } -} - -func TestCacheUsagePropagatesToOpenAIResponses(t *testing.T) { - usage := protocol.UsageInfo{PromptTokens: 100, CompletionTokens: 2, CacheOutcome: "hit", CacheTier: "ssd", CachedTokens: 80, PrefillTokensSaved: 64} - chat := buildNonStreamingResponse("request", "model", extractedMessage{Content: "ok"}, usage, 10, "", "") - if chat.Usage.PromptTokensDetails == nil || chat.Usage.PromptTokensDetails.CachedTokens != 80 { - t.Fatalf("chat cached usage = %+v", chat.Usage) - } - responses := buildResponsesResponse("request", "model", extractedMessage{Content: "ok"}, usage, 10, "", "") - if responses.Usage.InputTokensDetail.CachedTokens != 80 { - t.Fatalf("Responses cached usage = %+v", responses.Usage) - } - - obj := map[string]any{"usage": map[string]any{ - "prompt_tokens": 100, - "prompt_tokens_details": map[string]any{"cached_tokens": 999, "audio_tokens": 3}, - }, "choices": []any{}} - line := finalizeUsageChunk(obj, usage, ®istry.PendingRequest{Model: "model", PublicModel: "model"}) - var decoded map[string]any - if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &decoded); err != nil { - t.Fatal(err) - } - details := decoded["usage"].(map[string]any)["prompt_tokens_details"].(map[string]any) - if details["cached_tokens"] != float64(80) || details["audio_tokens"] != float64(3) { - t.Fatalf("stream cached usage = %+v", details) - } - - raw := map[string]any{"usage": map[string]any{"prompt_tokens": 100, "prompt_tokens_details": map[string]any{"cached_tokens": 999, "audio_tokens": 3}}} - injectCacheDetailIntoRawUsage(raw, usage) - rawDetails := raw["usage"].(map[string]any)["prompt_tokens_details"].(map[string]any) - if rawDetails["cached_tokens"] != 80 || rawDetails["audio_tokens"] != 3 { - t.Fatalf("raw complete cached usage = %+v", rawDetails) - } -} - -func TestTerminalCacheUsageRemovesUntrustedRawDetails(t *testing.T) { - zero := protocol.UsageInfo{PromptTokens: 100, CompletionTokens: 2} - - chat := map[string]any{"usage": map[string]any{ - "prompt_tokens_details": map[string]any{"cached_tokens": 999, "audio_tokens": 3}, - }} - injectCacheDetailIntoRawUsage(chat, zero) - chatDetails := chat["usage"].(map[string]any)["prompt_tokens_details"].(map[string]any) - if _, exists := chatDetails["cached_tokens"]; exists || chatDetails["audio_tokens"] != 3 { - t.Fatalf("raw chat details were not selectively sanitized: %+v", chatDetails) - } - - streamObj := map[string]any{ - "choices": []any{}, - "usage": map[string]any{"prompt_tokens_details": map[string]any{"cached_tokens": 999, "audio_tokens": 3}}, - } - line := finalizeUsageChunk(streamObj, zero, ®istry.PendingRequest{Model: "model"}) - var streamed map[string]any - if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &streamed); err != nil { - t.Fatal(err) - } - streamDetails := streamed["usage"].(map[string]any)["prompt_tokens_details"].(map[string]any) - if _, exists := streamDetails["cached_tokens"]; exists || streamDetails["audio_tokens"] != float64(3) { - t.Fatalf("held streaming details were not sanitized: %+v", streamDetails) - } - - responses := map[string]any{"usage": map[string]any{ - "input_tokens_details": map[string]any{"cached_tokens": 999, "audio_tokens": 3}, - }} - sanitizeCacheDetailIntoRawResponsesUsage(responses, zero) - responseDetails := responses["usage"].(map[string]any)["input_tokens_details"].(map[string]any) - if _, exists := responseDetails["cached_tokens"]; exists || responseDetails["audio_tokens"] != 3 { - t.Fatalf("native Responses details were not sanitized: %+v", responseDetails) - } - - valid := protocol.UsageInfo{PromptTokens: 100, CacheOutcome: "hit", CacheTier: "memory", CachedTokens: 40, PrefillTokensSaved: 35} - sanitizeCacheDetailIntoRawResponsesUsage(responses, valid) - if got := responseDetails["cached_tokens"]; got != 40 { - t.Fatalf("native Responses cached_tokens = %v, want authoritative 40", got) - } -} - func TestCacheSelectionTerminalTagsAreLowCardinalityAndCorrelated(t *testing.T) { pr := ®istry.PendingRequest{ CachePlan: testCachePlan("secret-route-key"), @@ -150,15 +42,3 @@ func TestCacheSelectionTerminalTagsAreLowCardinalityAndCorrelated(t *testing.T) t.Fatalf("invalid terminal usage was not correlated: %q", invalid) } } - -func TestValidProviderCacheUsageShapes(t *testing.T) { - if !validCacheUsage(protocol.UsageInfo{PromptTokens: 100, CacheOutcome: "hit", CacheTier: "memory", CachedTokens: 80, PrefillTokensSaved: 64, CacheStageMs: 1}) { - t.Fatal("valid hit usage rejected") - } - if !validCacheUsage(protocol.UsageInfo{PromptTokens: 100, CacheOutcome: "miss_absent", CacheStageMs: 1}) { - t.Fatal("valid miss usage rejected") - } - if validCacheUsage(protocol.UsageInfo{PromptTokens: 100, CacheOutcome: "miss_absent", CachedTokens: 1}) { - t.Fatal("non-hit usage with cached tokens accepted") - } -} diff --git a/coordinator/api/cancel_lifecycle.go b/coordinator/api/cancel_lifecycle.go deleted file mode 100644 index aff494911a..0000000000 --- a/coordinator/api/cancel_lifecycle.go +++ /dev/null @@ -1,206 +0,0 @@ -package api - -import ( - "context" - "errors" - "strconv" - "time" - - "github.com/eigeninference/d-inference/coordinator/protocol" - "github.com/eigeninference/d-inference/coordinator/registry" -) - -// Cancel causes: the bounded set of reasons the coordinator sends a WS cancel. -// A cancel is sent ONLY when the attempt's pending record still existed when -// it was abandoned — i.e. no provider terminal had been seen — so a provider -// error or a clean completion never produces one. -const ( - cancelCauseFirstChunkTimeout = "first_chunk_timeout" - cancelCauseHedgeLoser = "hedge_loser" - cancelCauseClientGonePre = "client_gone_pre" - cancelCauseClientGonePost = "client_gone_post" - // cancelCauseStreamTimeout covers every other post-commit exit without a - // terminal — the idle stream timeout in practice. - cancelCauseStreamTimeout = "stream_timeout" - cancelCauseOverflow = "overflow" - cancelCauseLateContent = "late_content" - // cancelCauseStrayChunk is a cancel triggered by a chunk for an id no - // abandon path recorded (genuinely unknown, or predating a restart). - cancelCauseStrayChunk = "stray_chunk" -) - -const ( - metricCancelSent = "inference.cancel_sent" - metricCancelSendFailed = "inference.cancel_send_failed" - metricCancelToTerminalMs = "inference.cancel_to_terminal_ms" - metricCancelledTerminal = "inference.cancelled_terminal" - metricCancelUnresolved = "inference.cancel_unresolved" - metricZombieStreamCancel = "inference.zombie_stream_cancel" - - cancelTerminalComplete = "complete" - cancelTerminalError = "error" - cancelTerminalStrayChunk = "stray_chunk" - - cancelledOutcomeCompletePartial = "complete_partial" - cancelledOutcomeErrorCancelled = "error_cancelled" - cancelledOutcomeErrorOther = "error_other" -) - -func modelTag(model string) string { - if model == "" { - return "unknown" - } - return model -} - -func cancelLatencyMs(d time.Duration) float64 { - if d < 0 { - return 0 - } - return float64(d) / float64(time.Millisecond) -} - -// sendAbandonCancel is the cancel primitive for an abandon path whose pending -// record was removed elsewhere (post-commit defer, handleChunk's overflow and -// late-content aborts): it records the request for terminal correlation and -// zombie re-sends, counts the cause, and sends the frame. -func (s *Server) sendAbandonCancel(provider *registry.Provider, requestID, model, cause string) { - now := time.Now() - _, expired := s.zombieCanceller.record(requestID, model, cause, now) - s.emitExpiredCancelEntries(expired) - s.sendRecordedCancel(provider, requestID, model, cause) -} - -// sendRecordedCancel sends the cancel for a request already recorded in the -// zombie tracker. The send is marked and counted on inference.cancel_sent only -// once the frame was handed to the provider writer: a control lane that is -// full or a writer that has stopped delivered nothing, so the entry is kept -// unsent (sent == 0) for the next stray chunk to retry, and a terminal that -// arrives meanwhile is not reported as cancel-to-terminal. -func (s *Server) sendRecordedCancel(provider *registry.Provider, requestID, model, cause string) { - resendIndex, sent := s.zombieCanceller.send(requestID, func() bool { - return s.sendProviderCancel(provider, requestID) - }) - if !sent { - return - } - if resendIndex > 0 { - // A stray chunk can deliver the first cancel while the abandon - // path releases capacity. This frame is then a resend too. - s.ddIncr(metricZombieStreamCancel, []string{"resend_index:" + strconv.Itoa(resendIndex)}) - return - } - s.ddIncr(metricCancelSent, []string{"cause:" + cause, "model:" + modelTag(model)}) -} - -// cancelSendFailureReason maps an EnqueueText error to a bounded tag value. -func cancelSendFailureReason(err error) string { - switch { - case errors.Is(err, registry.ErrProviderWriterQueueFull): - return "queue_full" - case errors.Is(err, registry.ErrProviderWriterStopped): - return "writer_stopped" - case errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled): - return "ctx" - default: - return "other" - } -} - -// noteStrayChunk handles a chunk for a request the coordinator no longer -// tracks. For a request the coordinator cancelled it is the expected tail of -// that cancel: the cancel is re-sent on the escalating zombie schedule (the -// provider treats duplicates as free) and the log line is rate-limited per -// provider. An id nobody abandoned is counted as an unknown frame and -// cancelled immediately. -func (s *Server) noteStrayChunk(provider *registry.Provider, providerID, requestID string, now time.Time) { - if now.IsZero() { - now = time.Now() - } - res := s.zombieCanceller.strayChunk(requestID, now) - s.emitExpiredCancelEntries(res.expired) - if res.cause == cancelCauseStrayChunk { - s.emitUnknownFrame(unknownFrameKindChunk, provider) - } - // request_id stays out of the log: until it matches coordinator state it is - // provider-controlled and an arbitrary log-exfiltration channel. - if allow, suppressed := s.zombieCanceller.allowStrayWarn(providerID, now); allow { - s.logger.Warn("chunk for unknown request", - "provider_id", providerID, - "suppressed", suppressed, - ) - } - if !res.send { - return - } - resendIndex, sent := s.zombieCanceller.send(requestID, func() bool { - return s.sendProviderCancel(provider, requestID) - }) - if !sent { - return - } - if resendIndex < 0 { - // Untracked (zero-value Server): the frame went out, nothing to count. - return - } - if resendIndex == 0 { - // First cancel DELIVERED for this id: cause stray_chunk when no abandon - // path recorded one, or the abandon path's cause when its own send - // never reached the writer (or lost this race by microseconds). - s.ddIncr(metricCancelSent, []string{"cause:" + res.cause, "model:" + modelTag(res.model)}) - } - s.ddIncr(metricZombieStreamCancel, []string{"resend_index:" + strconv.Itoa(resendIndex)}) -} - -// resolveCancelledTerminal correlates a provider terminal that found no live -// pending record with the cancel the coordinator recorded for it. Metric-only: -// billing for a parked post-commit record still settles in the caller, and a -// pre-commit attempt was refunded when it was abandoned. Returns the entry so -// the caller can classify the terminal instead of logging it as unknown. -// inference.cancelled_terminal is tagged delivered:false when no cancel ever -// reached the provider writer (every enqueue failed): the provider finished -// on its own, and the cancel→terminal latency is not measured for it. -func (s *Server) resolveCancelledTerminal(requestID, terminal, outcome string, now time.Time) (zombieEntry, bool) { - e, ok := s.zombieCanceller.terminal(requestID) - if !ok { - return zombieEntry{}, false - } - delivered := e.sent > 0 - if delivered { - s.ddHistogram(metricCancelToTerminalMs, cancelLatencyMs(now.Sub(e.firstSentAt)), - []string{"terminal:" + terminal, "model:" + modelTag(e.model), "cause:" + e.cause}) - } - s.ddIncr(metricCancelledTerminal, []string{"outcome:" + outcome, "cause:" + e.cause, - "delivered:" + strconv.FormatBool(delivered)}) - return e, true -} - -// cancelledErrorOutcome classifies an error terminal for a cancelled request. -func cancelledErrorOutcome(msg *protocol.InferenceErrorMessage) string { - if msg == nil { - return cancelledOutcomeErrorOther - } - if msg.StatusCode == 499 || - msg.FailureCode == protocol.FailureCodeCancelled || - msg.TerminalCause == terminalCauseCancelled { - return cancelledOutcomeErrorCancelled - } - return cancelledOutcomeErrorOther -} - -// emitExpiredCancelEntries reports cancels that never got a terminal. One -// that delivered a cancel and produced subsequent stray chunks contributes -// its last chunk as the terminal (terminal:stray_chunk). Every other entry -// is counted unresolved — -// the provider honored the cancel silently, disconnected, or never saw it. -func (s *Server) emitExpiredCancelEntries(expired []zombieEntry) { - for i := range expired { - e := &expired[i] - if e.sent > 0 && !e.lastStrayAt.IsZero() && !e.lastStrayAt.Before(e.firstSentAt) { - s.ddHistogram(metricCancelToTerminalMs, cancelLatencyMs(e.lastStrayAt.Sub(e.firstSentAt)), - []string{"terminal:" + cancelTerminalStrayChunk, "model:" + modelTag(e.model), "cause:" + e.cause}) - continue - } - s.ddIncr(metricCancelUnresolved, []string{"cause:" + e.cause, "model:" + modelTag(e.model)}) - } -} diff --git a/coordinator/api/cancel_lifecycle_test.go b/coordinator/api/cancel_lifecycle_test.go index 388f50e411..f1006c4170 100644 --- a/coordinator/api/cancel_lifecycle_test.go +++ b/coordinator/api/cancel_lifecycle_test.go @@ -2,7 +2,6 @@ package api import ( "context" - "errors" "io" "log/slog" "os" @@ -10,30 +9,13 @@ import ( "testing" "time" + "github.com/eigeninference/d-inference/coordinator/inference/attempt" "github.com/eigeninference/d-inference/coordinator/protocol" "github.com/eigeninference/d-inference/coordinator/registry" "github.com/eigeninference/d-inference/coordinator/store" "nhooyr.io/websocket" ) -func TestCancelSendFailureReason(t *testing.T) { - cases := []struct { - err error - want string - }{ - {registry.ErrProviderWriterQueueFull, "queue_full"}, - {registry.ErrProviderWriterStopped, "writer_stopped"}, - {context.DeadlineExceeded, "ctx"}, - {context.Canceled, "ctx"}, - {errors.New("boom"), "other"}, - } - for _, c := range cases { - if got := cancelSendFailureReason(c.err); got != c.want { - t.Errorf("cancelSendFailureReason(%v) = %q, want %q", c.err, got, c.want) - } - } -} - // TestSendProviderCancelMetersDeliveryFailure: a cancel that cannot be handed // to the provider writer is no longer Debug-only — it is counted on // inference.cancel_send_failed with a bounded reason. A provider whose writer @@ -51,12 +33,12 @@ func TestSendProviderCancelMetersDeliveryFailure(t *testing.T) { // Connected as far as the Server can tell (Conn set) but its writer has // been torn down: EnqueueText fails with the writer-stopped sentinel. p := ®istry.Provider{ID: "p-dead", Conn: &websocket.Conn{}} - if srv.sendProviderCancel(p, "req-1") { + if srv.inferenceAttempts().SendCancel(p, "req-1") { t.Fatal("sendProviderCancel must report failure when the writer is gone") } _ = dd.Statsd.Flush() packets := collector.drain() - got := findMetrics(packets, metricCancelSendFailed) + got := findMetrics(packets, attempt.MetricCancelSendFailed) if len(got) != 1 || !strings.Contains(got[0], "reason:writer_stopped") { t.Fatalf("cancel_send_failed packets = %v, want one with reason:writer_stopped", got) } @@ -67,11 +49,11 @@ func TestSendProviderCancelMetersDeliveryFailure(t *testing.T) { } // No socket at all is a test fixture, not a delivery failure: no metric. - if srv.sendProviderCancel(®istry.Provider{ID: "p-nosock"}, "req-2") { + if srv.inferenceAttempts().SendCancel(®istry.Provider{ID: "p-nosock"}, "req-2") { t.Fatal("provider without a socket cannot succeed") } _ = dd.Statsd.Flush() - if extra := findMetrics(collector.drain(), metricCancelSendFailed); len(extra) != 0 { + if extra := findMetrics(collector.drain(), attempt.MetricCancelSendFailed); len(extra) != 0 { t.Fatalf("nil Conn must not be metered as a delivery failure: %v", extra) } } @@ -109,25 +91,25 @@ func TestCancelDispatchSkipsCancelAfterCompletionIngress(t *testing.T) { finished := newPending("req-finished-empty") finished.MarkCompletionIngress(time.Now()) - srv.cancelDispatch(provider, finished, cancelCauseHedgeLoser) + srv.inferenceAttempts().Cancel(provider, finished, attempt.CancelCauseHedgeLoser) if provider.GetPending(finished.RequestID) != nil { t.Fatal("cancelDispatch must still remove the pending record") } - if n := srv.zombieCanceller.size(); n != 0 { - t.Fatalf("a racer that already completed must not be tracked as a zombie (size=%d)", n) + if e, ok := srv.inferenceAttempts().ResolveCancelledTerminal(finished.RequestID, attempt.CancelTerminalComplete, attempt.CancelledOutcomeCompletePartial, time.Now()); ok { + t.Fatalf("a racer that already completed must not be tracked as a zombie: %+v", e) } _ = dd.Statsd.Flush() - if got := findMetrics(collector.drain(), metricCancelSent); len(got) != 0 { + if got := findMetrics(collector.drain(), attempt.MetricCancelSent); len(got) != 0 { t.Fatalf("cancel_sent must not fire for a racer whose completion was ingressed: %v", got) } running := newPending("req-still-running") - srv.cancelDispatch(provider, running, cancelCauseHedgeLoser) - if n := srv.zombieCanceller.size(); n != 1 { - t.Fatalf("a still-running racer must be tracked for terminal correlation (size=%d)", n) + srv.inferenceAttempts().Cancel(provider, running, attempt.CancelCauseHedgeLoser) + if _, ok := srv.inferenceAttempts().ResolveCancelledTerminal(running.RequestID, attempt.CancelTerminalComplete, attempt.CancelledOutcomeCompletePartial, time.Now()); !ok { + t.Fatal("a still-running racer must be tracked for terminal correlation") } _ = dd.Statsd.Flush() - if got := findMetrics(collector.drain(), metricCancelSent); len(got) != 0 { + if got := findMetrics(collector.drain(), attempt.MetricCancelSent); len(got) != 0 { t.Fatalf("no socket, no frame handed over: cancel_sent must not fire, got %v", got) } } @@ -160,15 +142,6 @@ func TestCancelSendCountsOnlyDeliveredFrames(t *testing.T) { } live := reg.GetProvider(ids[0]) dead := ®istry.Provider{ID: "p-dead", Conn: &websocket.Conn{}} - entry := func(id string) zombieEntry { - srv.zombieCanceller.mu.Lock() - defer srv.zombieCanceller.mu.Unlock() - e := srv.zombieCanceller.entries[id] - if e == nil { - t.Fatalf("no zombie entry for %s", id) - } - return *e - } drain := func() []string { _ = dd.Statsd.Flush() return collector.drain() @@ -176,68 +149,70 @@ func TestCancelSendCountsOnlyDeliveredFrames(t *testing.T) { // Enqueue fails: recorded, unsent, not counted. t0 := time.Now() - srv.sendAbandonCancel(dead, "req-fail", model, cancelCauseClientGonePost) + srv.inferenceAttempts().SendAbandonCancel(dead, "req-fail", model, attempt.CancelCauseClientGonePost) packets := drain() - if got := findMetrics(packets, metricCancelSent); len(got) != 0 { + if got := findMetrics(packets, attempt.MetricCancelSent); len(got) != 0 { t.Fatalf("a failed enqueue must not count as sent: %v", got) } - requireMetricWithTags(t, packets, metricCancelSendFailed, "reason:writer_stopped") - if e := entry("req-fail"); e.sent != 0 || e.cause != cancelCauseClientGonePost { - t.Fatalf("entry after failed send = %+v, want sent=0 with the abandon cause", e) - } - + requireMetricWithTags(t, packets, attempt.MetricCancelSendFailed, "reason:writer_stopped") // The provider finishes on its own: correlated, but no cancel was delivered. - e, ok := srv.resolveCancelledTerminal("req-fail", cancelTerminalComplete, cancelledOutcomeCompletePartial, t0.Add(time.Second)) - if !ok || e.sent != 0 { + e, ok := srv.inferenceAttempts().ResolveCancelledTerminal("req-fail", attempt.CancelTerminalComplete, attempt.CancelledOutcomeCompletePartial, t0.Add(time.Second)) + if !ok || e.Deliveries() != 0 { t.Fatalf("terminal correlation = (%+v, %v), want the unsent entry", e, ok) } + if e.Deliveries() != 0 || e.Cause() != attempt.CancelCauseClientGonePost { + t.Fatalf("entry after failed send = %+v, want sent=0 with the abandon cause", e) + } packets = drain() - if got := findMetrics(packets, metricCancelToTerminalMs); len(got) != 0 { + if got := findMetrics(packets, attempt.MetricCancelToTerminalMs); len(got) != 0 { t.Fatalf("no cancel reached the provider, so no cancel→terminal latency: %v", got) } - requireMetricWithTags(t, packets, metricCancelledTerminal, - "outcome:"+cancelledOutcomeCompletePartial, "cause:"+cancelCauseClientGonePost, "delivered:false") + requireMetricWithTags(t, packets, attempt.MetricCancelledTerminal, + "outcome:"+attempt.CancelledOutcomeCompletePartial, "cause:"+attempt.CancelCauseClientGonePost, "delivered:false") // Enqueue fails, then a stray chunk retries on a writer that accepts: the // first DELIVERED cancel counts cancel_sent once under the abandon cause. - srv.sendAbandonCancel(dead, "req-retry", model, cancelCauseFirstChunkTimeout) + srv.inferenceAttempts().SendAbandonCancel(dead, "req-retry", model, attempt.CancelCauseFirstChunkTimeout) packets = drain() - if got := findMetrics(packets, metricCancelSent); len(got) != 0 { + if got := findMetrics(packets, attempt.MetricCancelSent); len(got) != 0 { t.Fatalf("a failed enqueue must not count as sent: %v", got) } - srv.noteStrayChunk(live, live.ID, "req-retry", time.Now().Add(zombieResendRetry)) + // Exercise the existing 250 ms retry policy through the stray-frame path. + srv.inferenceAttempts().StrayChunk(live, live.ID, "req-retry", time.Now().Add(250*time.Millisecond)) packets = drain() - requireMetricWithTags(t, packets, metricCancelSent, "cause:"+cancelCauseFirstChunkTimeout, "model:"+model) - requireMetricWithTags(t, packets, metricZombieStreamCancel, "resend_index:0") - if e := entry("req-retry"); e.sent != 1 { - t.Fatalf("entry after the delivered retry = %+v, want sent=1", e) - } - if _, ok := srv.resolveCancelledTerminal("req-retry", cancelTerminalError, cancelledOutcomeErrorCancelled, time.Now()); !ok { + requireMetricWithTags(t, packets, attempt.MetricCancelSent, "cause:"+attempt.CancelCauseFirstChunkTimeout, "model:"+model) + requireMetricWithTags(t, packets, attempt.MetricZombieStreamCancel, "resend_index:0") + e, ok = srv.inferenceAttempts().ResolveCancelledTerminal("req-retry", attempt.CancelTerminalError, attempt.CancelledOutcomeErrorCancelled, time.Now()) + if !ok { t.Fatal("delivered retry must still correlate its terminal") } + if e.Deliveries() != 1 { + t.Fatalf("entry after the delivered retry = %+v, want sent=1", e) + } packets = drain() - requireMetricWithTags(t, packets, metricCancelToTerminalMs, "terminal:"+cancelTerminalError, "cause:"+cancelCauseFirstChunkTimeout) - requireMetricWithTags(t, packets, metricCancelledTerminal, - "outcome:"+cancelledOutcomeErrorCancelled, "cause:"+cancelCauseFirstChunkTimeout, "delivered:true") + requireMetricWithTags(t, packets, attempt.MetricCancelToTerminalMs, "terminal:"+attempt.CancelTerminalError, "cause:"+attempt.CancelCauseFirstChunkTimeout) + requireMetricWithTags(t, packets, attempt.MetricCancelledTerminal, + "outcome:"+attempt.CancelledOutcomeErrorCancelled, "cause:"+attempt.CancelCauseFirstChunkTimeout, "delivered:true") // A stray chunk can win the initial enqueue while the abandon path is // releasing registry capacity. Its later send is a resend, not another // first cancel for this request. - srv.zombieCanceller.record("req-stray-first", model, cancelCauseClientGonePre, time.Now()) - srv.noteStrayChunk(live, live.ID, "req-stray-first", time.Now()) - srv.sendRecordedCancel(live, "req-stray-first", model, cancelCauseClientGonePre) + srv.inferenceAttempts().RecordAbandon("req-stray-first", model, attempt.CancelCauseClientGonePre, time.Now()) + srv.inferenceAttempts().StrayChunk(live, live.ID, "req-stray-first", time.Now()) + srv.inferenceAttempts().SendRecordedCancel(live, "req-stray-first", model, attempt.CancelCauseClientGonePre) packets = drain() - if got := sumMetric(t, packets, metricCancelSent, "cause:"+cancelCauseClientGonePre, "model:"+model); got != 1 { + if got := sumMetric(t, packets, attempt.MetricCancelSent, "cause:"+attempt.CancelCauseClientGonePre, "model:"+model); got != 1 { t.Fatalf("a stray-first race must count one initial cancel, got %v: %v", got, packets) } // A live writer: counted on the first send, exactly once. - srv.sendAbandonCancel(live, "req-live", model, cancelCauseHedgeLoser) + srv.inferenceAttempts().SendAbandonCancel(live, "req-live", model, attempt.CancelCauseHedgeLoser) packets = drain() - if got := requireMetricWithTags(t, packets, metricCancelSent, "cause:"+cancelCauseHedgeLoser, "model:"+model); len(got) != 1 { + if got := requireMetricWithTags(t, packets, attempt.MetricCancelSent, "cause:"+attempt.CancelCauseHedgeLoser, "model:"+model); len(got) != 1 { t.Fatalf("cancel_sent for a delivered first send = %v, want exactly one", got) } - if e := entry("req-live"); e.sent != 1 { + e, ok = srv.inferenceAttempts().ResolveCancelledTerminal("req-live", attempt.CancelTerminalComplete, attempt.CancelledOutcomeCompletePartial, time.Now()) + if !ok || e.Deliveries() != 1 { t.Fatalf("entry after a delivered first send = %+v, want sent=1", e) } } @@ -252,7 +227,7 @@ func TestUnknownTerminalPathsOnBareServer(t *testing.T) { reg := registry.New(logger) for name, srv := range map[string]*Server{ "nil canceller": {registry: reg, logger: logger}, - "literal canceller": {registry: reg, logger: logger, zombieCanceller: &zombieStreamCanceller{}}, + "literal canceller": {registry: reg, logger: logger, attemptTracker: &attempt.Tracker{}}, } { t.Run(name, func(t *testing.T) { provider := ®istry.Provider{ID: "p-bare"} @@ -274,55 +249,3 @@ func TestUnknownTerminalPathsOnBareServer(t *testing.T) { }) } } - -func TestCancelLatencyUsesFirstSuccessfulSend(t *testing.T) { - collector := newUDPCollector(t) - defer collector.Close() - dd := newTestDD(t, collector) - defer dd.Close() - srv := &Server{dd: dd, zombieCanceller: newZombieStreamCanceller()} - t0 := time.Now() - for _, terminal := range []string{cancelTerminalComplete, cancelTerminalStrayChunk} { - id := "delayed-" + terminal - srv.zombieCanceller.record(id, "m", cancelCauseClientGonePost, t0) - srv.zombieCanceller.noteSendFailed(id, t0) - srv.zombieCanceller.markSent(id, t0.Add(10*time.Second)) - // A later resend must not move the latency anchor. - srv.zombieCanceller.markSent(id, t0.Add(11*time.Second)) - if terminal == cancelTerminalComplete { - srv.resolveCancelledTerminal(id, terminal, cancelledOutcomeCompletePartial, t0.Add(12*time.Second)) - } else { - srv.zombieCanceller.strayChunk(id, t0.Add(12*time.Second)) - e, _ := srv.zombieCanceller.terminal(id) - srv.emitExpiredCancelEntries([]zombieEntry{e}) - } - _ = dd.Statsd.Flush() - packets := collector.drain() - got := requireMetricWithTags(t, packets, metricCancelToTerminalMs, "terminal:"+terminal) - if len(got) != 1 || !strings.Contains(got[0], metricCancelToTerminalMs+":2000|h") { - t.Fatalf("latency must exclude the failed-send delay: %v", got) - } - } -} - -func TestExpiredUndeliveredCancelIsUnresolved(t *testing.T) { - collector := newUDPCollector(t) - defer collector.Close() - dd := newTestDD(t, collector) - defer dd.Close() - srv := &Server{dd: dd, zombieCanceller: newZombieStreamCanceller()} - t0 := time.Now() - // The failed retry sees a stray chunk, but still delivers no cancel. - srv.zombieCanceller.record("unsent", "m", cancelCauseClientGonePre, t0) - srv.zombieCanceller.noteSendFailed("unsent", t0) - srv.zombieCanceller.strayChunk("unsent", t0.Add(time.Second)) - srv.zombieCanceller.noteSendFailed("unsent", t0.Add(time.Second)) - e, _ := srv.zombieCanceller.terminal("unsent") - srv.emitExpiredCancelEntries([]zombieEntry{e}) - _ = dd.Statsd.Flush() - packets := collector.drain() - if got := findMetrics(packets, metricCancelToTerminalMs); len(got) != 0 { - t.Fatalf("undelivered cancel must not contribute latency: %v", got) - } - requireMetricWithTags(t, packets, metricCancelUnresolved, "cause:"+cancelCauseClientGonePre) -} diff --git a/coordinator/api/cancellation_integration_test.go b/coordinator/api/cancellation_integration_test.go index 6c6f3955c9..957c01ff83 100644 --- a/coordinator/api/cancellation_integration_test.go +++ b/coordinator/api/cancellation_integration_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/eigeninference/d-inference/coordinator/inference/attempt" "github.com/eigeninference/d-inference/coordinator/protocol" "github.com/eigeninference/d-inference/coordinator/registry" "nhooyr.io/websocket" @@ -718,10 +719,10 @@ func TestIntegration_NoCancelAfterCleanCompletion(t *testing.T) { t.Fatalf("provider received %d Cancel frame(s) after a clean inference_complete, want 0", n) } packets := dd.packets(collector) - if got := findMetrics(packets, metricCancelSent); len(got) != 0 { + if got := findMetrics(packets, attempt.MetricCancelSent); len(got) != 0 { t.Fatalf("cancel_sent must not fire for a clean completion: %v", got) } - if got := findMetrics(packets, metricCancelToTerminalMs); len(got) != 0 { + if got := findMetrics(packets, attempt.MetricCancelToTerminalMs); len(got) != 0 { t.Fatalf("cancel_to_terminal_ms must not fire for a clean completion: %v", got) } } @@ -769,7 +770,7 @@ func TestIntegration_NoCancelAfterProviderErrorTerminal(t *testing.T) { if n := len(cancels.times()); n != 0 { t.Fatalf("provider received %d Cancel frame(s) after its own inference_error, want 0", n) } - if got := findMetrics(dd.packets(collector), metricCancelSent); len(got) != 0 { + if got := findMetrics(dd.packets(collector), attempt.MetricCancelSent); len(got) != 0 { t.Fatalf("cancel_sent must not fire after a provider error terminal: %v", got) } } @@ -836,7 +837,7 @@ func runZombieStreamScenario(t *testing.T, terminal string, zombieFor time.Durat Error: "request cancelled", StatusCode: 499, FailureCode: protocol.FailureCodeCancelled, - TerminalCause: terminalCauseCancelled, + TerminalCause: attempt.TerminalCauseCancelled, }) default: t.Fatalf("unknown terminal %q", terminal) @@ -879,16 +880,16 @@ func TestIntegration_ZombieStreamRecancelScheduleAndCompleteTerminal(t *testing. t.Fatalf("second re-send at +%v after the first cancel, want ~+3 s", gap2) } - hist := requireMetricWithTags(t, packets, metricCancelToTerminalMs, - "terminal:complete", "model:"+model, "cause:"+cancelCauseClientGonePost) + hist := requireMetricWithTags(t, packets, attempt.MetricCancelToTerminalMs, + "terminal:complete", "model:"+model, "cause:"+attempt.CancelCauseClientGonePost) if v := metricValue(t, hist[0]); v < 0.8*float64(zombieFor/time.Millisecond) { t.Fatalf("cancel_to_terminal_ms = %v, want >= ~%v (the zombie phase)", v, zombieFor) } - requireMetricWithTags(t, packets, metricCancelSent, "cause:"+cancelCauseClientGonePost, "model:"+model) - requireMetricWithTags(t, packets, metricZombieStreamCancel, "resend_index:1") - requireMetricWithTags(t, packets, metricZombieStreamCancel, "resend_index:2") - requireMetricWithTags(t, packets, metricCancelledTerminal, "outcome:"+cancelledOutcomeCompletePartial, "delivered:true") - if got := findMetrics(packets, metricCancelUnresolved); len(got) != 0 { + requireMetricWithTags(t, packets, attempt.MetricCancelSent, "cause:"+attempt.CancelCauseClientGonePost, "model:"+model) + requireMetricWithTags(t, packets, attempt.MetricZombieStreamCancel, "resend_index:1") + requireMetricWithTags(t, packets, attempt.MetricZombieStreamCancel, "resend_index:2") + requireMetricWithTags(t, packets, attempt.MetricCancelledTerminal, "outcome:"+attempt.CancelledOutcomeCompletePartial, "delivered:true") + if got := findMetrics(packets, attempt.MetricCancelUnresolved); len(got) != 0 { t.Fatalf("a correlated terminal must not also count as unresolved: %v", got) } requireNoIdentityInPackets(t, packets, requestID) @@ -904,12 +905,12 @@ func TestIntegration_CancelToTerminalOnLateErrorTerminal(t *testing.T) { if len(cancels) < 2 || len(cancels) > 3 { t.Fatalf("Cancel frames over %v of zombie chunks = %d (%v), want 2: first, +1 s", zombieFor, len(cancels), cancels) } - hist := requireMetricWithTags(t, packets, metricCancelToTerminalMs, - "terminal:error", "model:"+model, "cause:"+cancelCauseClientGonePost) + hist := requireMetricWithTags(t, packets, attempt.MetricCancelToTerminalMs, + "terminal:error", "model:"+model, "cause:"+attempt.CancelCauseClientGonePost) if v := metricValue(t, hist[0]); v < 0.8*float64(zombieFor/time.Millisecond) { t.Fatalf("cancel_to_terminal_ms = %v, want >= ~%v", v, zombieFor) } - requireMetricWithTags(t, packets, metricCancelledTerminal, "outcome:"+cancelledOutcomeErrorCancelled, "delivered:true") - requireMetricWithTags(t, packets, metricZombieStreamCancel, "resend_index:1") + requireMetricWithTags(t, packets, attempt.MetricCancelledTerminal, "outcome:"+attempt.CancelledOutcomeErrorCancelled, "delivered:true") + requireMetricWithTags(t, packets, attempt.MetricZombieStreamCancel, "resend_index:1") requireNoIdentityInPackets(t, packets, requestID) } diff --git a/coordinator/api/capacity_cooldown_test.go b/coordinator/api/capacity_cooldown_test.go index 5da62c70e3..43b1b90d1f 100644 --- a/coordinator/api/capacity_cooldown_test.go +++ b/coordinator/api/capacity_cooldown_test.go @@ -12,56 +12,6 @@ import ( "github.com/eigeninference/d-inference/coordinator/store" ) -// isCapacityRejectStrike must count node-scoped capacity rejections (the -// black-hole vocabulary) and NEVER count request-shape context overflows -// (deterministic for the model — they indict the request, not the provider) -// or genuine faults (owned by the 5xx breakers). -func TestIsCapacityRejectStrike(t *testing.T) { - cases := []struct { - name string - errStr string - want bool - }{ - // Node-scoped capacity rejects: COUNT. These are the incident strings — - // a pair emitting them repeatedly with zero accepts is a black hole. - {"active token budget", "token_budget_exhausted: request exceeds active token budget", true}, - {"requires-but-available", "token_budget_exhausted: request requires 115635 tokens but only 90000 available", true}, - {"kv headroom", "token_budget_exhausted: insufficient global KV cache headroom", true}, - {"queue full", "token_budget_exhausted: request queue full", true}, - {"server busy", "server busy", true}, - {"draining", "provider draining for update", true}, - {"cold not-loaded miss", "model 'gemma-4-26b-8bit' is not loaded on this provider", true}, - // "batch token budget" is deliberately INCLUDED (misreported-budget - // pathology rejects normal prompts with exactly this string). - {"batch token budget", "token_budget_exhausted: request exceeds batch token budget", true}, - - // Request-shape context overflows: NEVER count (identical fleet-wide; - // striking them would cool healthy providers on oversized-prompt bursts). - {"exceeds model context window", "token_budget_exhausted: request exceeds model context window (200000 prompt tokens > 131072 context)", false}, - {"context length exceeded", "context length exceeded", false}, - {"context window bare marker", "prompt too long for context window", false}, - - // Genuine faults / non-capacity: NEVER count (the 5xx breakers own them). - {"panic", "panic: index out of range", false}, - {"internal error", "internal error", false}, - {"bad-weights load fault", "model load failed: corrupt weights", false}, - {"opaque foundation error", "The operation couldn’t be completed. (ProviderCore.InferenceError error 1.)", false}, - {"cancel", "request cancelled", false}, - {"empty", "", false}, - // A 404-shaped "model not found" (unknown model id) is a request-shape - // error, NOT the cold "not loaded" capacity miss — never a strike. - {"unknown model not found", "model not found", false}, - {"unknown model in registry", "model \"nope\" not found in registry", false}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - if got := isCapacityRejectStrike(tc.errStr); got != tc.want { - t.Fatalf("isCapacityRejectStrike(%q) = %v, want %v", tc.errStr, got, tc.want) - } - }) - } -} - func capacityTestPending(model, providerID string, n int) *registry.PendingRequest { return ®istry.PendingRequest{ RequestID: fmt.Sprintf("req-cap-%s-%d", providerID, n), @@ -105,7 +55,7 @@ func TestCapacityCooldownTripsMetricLogAndRoutingDiverts(t *testing.T) { // The incident pattern: every dispatch to the black hole bounces with the // capacity string (classified 503) and it never serves anything. for i := 0; i < 8; i++ { - srv.noteInferenceError(blackHole.ID, capacityTestPending(model, blackHole.ID, i), 503, rejectStr, "", "") + srv.inferenceAttempts().Error(blackHole.ID, capacityTestPending(model, blackHole.ID, i), 503, rejectStr, "", "") } if !reg.CapacityCooldownActive(blackHole.ID, model) { t.Fatal("black-hole provider not in capacity cooldown after 8 zero-accept rejects") @@ -142,9 +92,9 @@ func TestCapacityCooldownTripsMetricLogAndRoutingDiverts(t *testing.T) { // keeps SERVING (accepts interleaved), so it must NEVER trip. for round := 0; round < 5; round++ { for i := 0; i < 4; i++ { - srv.noteInferenceError(healthy.ID, capacityTestPending(model, healthy.ID, round*10+i), 503, rejectStr, "", "") + srv.inferenceAttempts().Error(healthy.ID, capacityTestPending(model, healthy.ID, round*10+i), 503, rejectStr, "", "") } - srv.noteInferenceSuccess(capacityTestPending(model, healthy.ID, round)) + srv.inferenceAttempts().Success(capacityTestPending(model, healthy.ID, round)) } if reg.CapacityCooldownActive(healthy.ID, model) { t.Fatal("busy-but-serving provider was cooled despite interleaved accepts") @@ -153,7 +103,7 @@ func TestCapacityCooldownTripsMetricLogAndRoutingDiverts(t *testing.T) { // Client-shape 4xx carrying a capacity-looking string never strikes. other := makeRoutableProvider(t, reg, "p-4xx", model) for i := 0; i < 10; i++ { - srv.noteInferenceError(other.ID, capacityTestPending(model, other.ID, i), 400, rejectStr, "", "") + srv.inferenceAttempts().Error(other.ID, capacityTestPending(model, other.ID, i), 400, rejectStr, "", "") } if reg.CapacityCooldownActive(other.ID, model) { t.Fatal("client-shape 4xx with a capacity string tripped the capacity cooldown") @@ -163,7 +113,7 @@ func TestCapacityCooldownTripsMetricLogAndRoutingDiverts(t *testing.T) { // request, not the provider. ctxProvider := makeRoutableProvider(t, reg, "p-ctx", model) for i := 0; i < 10; i++ { - srv.noteInferenceError(ctxProvider.ID, capacityTestPending(model, ctxProvider.ID, i), 503, + srv.inferenceAttempts().Error(ctxProvider.ID, capacityTestPending(model, ctxProvider.ID, i), 503, "token_budget_exhausted: request exceeds model context window (200000 prompt tokens > 131072 context)", "", "") } if reg.CapacityCooldownActive(ctxProvider.ID, model) { @@ -211,7 +161,7 @@ func TestCapacityCooldownRetryReselectionEscapesSink(t *testing.T) { // The sink instantly capacity-rejects; the retry loop records the // failure and re-selects. sinkPicks++ - srv.noteInferenceError(sink.ID, pr, 503, rejectStr, "", "") + srv.inferenceAttempts().Error(sink.ID, pr, 503, rejectStr, "", "") reg.SetProviderIdle(sink.ID) continue } diff --git a/coordinator/api/capacity_rejection_lifecycle_test.go b/coordinator/api/capacity_rejection_lifecycle_test.go index d7d5b741a0..d5c71fcf40 100644 --- a/coordinator/api/capacity_rejection_lifecycle_test.go +++ b/coordinator/api/capacity_rejection_lifecycle_test.go @@ -1,18 +1,5 @@ package api -// Follow-up coverage for the capacity-reject cooldown (PR #507 P2s): -// 1. the generic (/v1/completions, /v1/messages) path records the ACCEPT at -// first content, so a long generic stream on a busy box keeps vouching -// for the pair while it sheds concurrent dispatches; -// 2. cold 404 "model not loaded" misses strike (a box that 404s forever is -// a black hole) while the normal 404-then-load-then-serve lifecycle -// never trips (the accept resets the streak); -// 3. an ALL-COOLED model surfaces as TRANSIENT capacity — a preflight 429 -// with Retry-After and zero provider dispatches — not a structural -// "no providers" 503. -// The half-open single-probe semantics are covered in -// registry/capacity_cooldown_test.go (claim lifecycle + concurrency). - import ( "bufio" "bytes" @@ -32,6 +19,19 @@ import ( "github.com/eigeninference/d-inference/coordinator/store" ) +// Follow-up coverage for the capacity-reject cooldown (PR #507 P2s): +// 1. the generic (/v1/completions, /v1/messages) path records the ACCEPT at +// first content, so a long generic stream on a busy box keeps vouching +// for the pair while it sheds concurrent dispatches; +// 2. cold 404 "model not loaded" misses strike (a box that 404s forever is +// a black hole) while the normal 404-then-load-then-serve lifecycle +// never trips (the accept resets the streak); +// 3. an ALL-COOLED model surfaces as TRANSIENT capacity — a preflight 429 +// with Retry-After and zero provider dispatches — not a structural +// "no providers" 503. +// The half-open single-probe semantics are covered in +// registry/capacity_cooldown_test.go (claim lifecycle + concurrency). + // A box that cold-404s ("model not loaded") FOREVER with zero accepts is a // black hole and must trip; a box that 404s while lazily loading and then // SERVES (the normal lifecycle) must never trip — the accept is the safety. @@ -49,9 +49,9 @@ func TestCapacityCooldown404NotLoadedStrikes(t *testing.T) { lazy := makeRoutableProvider(t, reg, "p-lazy-load", model) for round := 0; round < 4; round++ { for i := 0; i < 3; i++ { - srv.noteInferenceError(lazy.ID, capacityTestPending(model, lazy.ID, round*10+i), http.StatusNotFound, notLoaded, "", "") + srv.inferenceAttempts().Error(lazy.ID, capacityTestPending(model, lazy.ID, round*10+i), http.StatusNotFound, notLoaded, "", "") } - srv.noteInferenceSuccess(capacityTestPending(model, lazy.ID, round)) + srv.inferenceAttempts().Success(capacityTestPending(model, lazy.ID, round)) } if reg.CapacityCooldownActive(lazy.ID, model) { t.Fatal("404-then-load-then-serve lifecycle tripped the capacity cooldown") @@ -60,7 +60,7 @@ func TestCapacityCooldown404NotLoadedStrikes(t *testing.T) { // Black hole flavor: 404s forever, zero accepts — trips at the threshold. stuck := makeRoutableProvider(t, reg, "p-never-loads", model) for i := 0; i < 5; i++ { - srv.noteInferenceError(stuck.ID, capacityTestPending(model, stuck.ID, i), http.StatusNotFound, notLoaded, "", "") + srv.inferenceAttempts().Error(stuck.ID, capacityTestPending(model, stuck.ID, i), http.StatusNotFound, notLoaded, "", "") } if !reg.CapacityCooldownActive(stuck.ID, model) { t.Fatal("a box that 404s 'not loaded' forever with zero accepts did not trip") @@ -70,7 +70,7 @@ func TestCapacityCooldown404NotLoadedStrikes(t *testing.T) { // request-shape error) never strikes, no matter how many arrive. notFound := makeRoutableProvider(t, reg, "p-model-not-found", model) for i := 0; i < 10; i++ { - srv.noteInferenceError(notFound.ID, capacityTestPending(model, notFound.ID, i), http.StatusNotFound, "model not found", "", "") + srv.inferenceAttempts().Error(notFound.ID, capacityTestPending(model, notFound.ID, i), http.StatusNotFound, "model not found", "", "") } if reg.CapacityCooldownActive(notFound.ID, model) { t.Fatal("request-shape 404 'model not found' tripped the capacity cooldown") @@ -98,8 +98,8 @@ func TestCapacityRateExcludesColdModelMiss(t *testing.T) { // must stay empty. cold := makeRoutableProvider(t, reg, "p-cold-miss", model) for i := 0; i < sampleFloor; i++ { - srv.noteInferenceError(cold.ID, capacityTestPending(model, cold.ID, i), http.StatusNotFound, notLoaded, "", "") - srv.noteInferenceSuccess(capacityTestPending(model, cold.ID, i)) + srv.inferenceAttempts().Error(cold.ID, capacityTestPending(model, cold.ID, i), http.StatusNotFound, notLoaded, "", "") + srv.inferenceAttempts().Success(capacityTestPending(model, cold.ID, i)) } if rate, samples := reg.CapacityRejectRate(cold.ID, model); samples != 0 || rate != 0 { t.Fatalf("cold 'not loaded' misses derated the capacity-reject rate: rate=%.2f samples=%d, want 0/0", rate, samples) @@ -109,8 +109,8 @@ func TestCapacityRateExcludesColdModelMiss(t *testing.T) { // the rate — the mechanism the penalty exists for. gray := makeRoutableProvider(t, reg, "p-graybox", model) for i := 0; i < sampleFloor; i++ { - srv.noteInferenceError(gray.ID, capacityTestPending(model, gray.ID, i), http.StatusServiceUnavailable, genuine, "", "") - srv.noteInferenceSuccess(capacityTestPending(model, gray.ID, i)) + srv.inferenceAttempts().Error(gray.ID, capacityTestPending(model, gray.ID, i), http.StatusServiceUnavailable, genuine, "", "") + srv.inferenceAttempts().Success(capacityTestPending(model, gray.ID, i)) } if rate, samples := reg.CapacityRejectRate(gray.ID, model); samples == 0 || rate <= 0 { t.Fatalf("genuine token-budget 503s must derate the rate: rate=%.2f samples=%d", rate, samples) @@ -142,7 +142,7 @@ func TestCapacityRejectDeterministicBatchBudgetArmsNoGrayBoxState(t *testing.T) // binding term was the context, identical fleet-wide. det := makeRoutableProvider(t, reg, "p-oversized-prompt", model) setProviderModelBudget(t, reg, det.ID, model, 5_000_000) - srv.noteInferenceError(det.ID, capacityTestPending(model, det.ID, 0), http.StatusServiceUnavailable, batchBudget, "", "") + srv.inferenceAttempts().Error(det.ID, capacityTestPending(model, det.ID, 0), http.StatusServiceUnavailable, batchBudget, "", "") if reg.BudgetClampActive(det.ID, model) { t.Fatal("a request-deterministic batch-budget reject must not arm the budget clamp") } @@ -152,7 +152,7 @@ func TestCapacityRejectDeterministicBatchBudgetArmsNoGrayBoxState(t *testing.T) // ...but repeated ones with zero interleaved accepts still trip the // black-hole cooldown (the budget-misreporting signature). for i := 1; i < 5; i++ { - srv.noteInferenceError(det.ID, capacityTestPending(model, det.ID, i), http.StatusServiceUnavailable, batchBudget, "", "") + srv.inferenceAttempts().Error(det.ID, capacityTestPending(model, det.ID, i), http.StatusServiceUnavailable, batchBudget, "", "") } if !reg.CapacityCooldownActive(det.ID, model) { t.Fatal("repeated deterministic batch-budget rejects with zero accepts must still trip the cooldown") @@ -163,7 +163,7 @@ func TestCapacityRejectDeterministicBatchBudgetArmsNoGrayBoxState(t *testing.T) // provider-specific capacity signal: full gray-box state. pressured := makeRoutableProvider(t, reg, "p-pressured", model) setProviderModelBudget(t, reg, pressured.ID, model, 90_000) - srv.noteInferenceError(pressured.ID, capacityTestPending(model, pressured.ID, 0), http.StatusServiceUnavailable, batchBudget, "", "") + srv.inferenceAttempts().Error(pressured.ID, capacityTestPending(model, pressured.ID, 0), http.StatusServiceUnavailable, batchBudget, "", "") if !reg.BudgetClampActive(pressured.ID, model) { t.Fatal("a node-pressured batch-budget reject (budget < context) must arm the budget clamp") } @@ -195,7 +195,7 @@ func TestGrayBoxClassificationTrustsStructuredReason(t *testing.T) { // wins — full gray-box state (clamp + rate), not the request-shape path. nodeBudget := makeRoutableProvider(t, reg, "p-reasoned-node", model) setProviderModelBudget(t, reg, nodeBudget.ID, model, 5_000_000) - srv.noteInferenceError(nodeBudget.ID, capacityTestPending(model, nodeBudget.ID, 0), + srv.inferenceAttempts().Error(nodeBudget.ID, capacityTestPending(model, nodeBudget.ID, 0), http.StatusServiceUnavailable, batchBudget, "request_exceeds_node_budget", "") if !reg.BudgetClampActive(nodeBudget.ID, model) { t.Fatal("a structured request_exceeds_node_budget reason must feed the clamp despite the stale >=context budget snapshot") @@ -208,7 +208,7 @@ func TestGrayBoxClassificationTrustsStructuredReason(t *testing.T) { // budget >= context reads request-deterministic, strike-only. legacy := makeRoutableProvider(t, reg, "p-reasonless", model) setProviderModelBudget(t, reg, legacy.ID, model, 5_000_000) - srv.noteInferenceError(legacy.ID, capacityTestPending(model, legacy.ID, 0), + srv.inferenceAttempts().Error(legacy.ID, capacityTestPending(model, legacy.ID, 0), http.StatusServiceUnavailable, batchBudget, "", "") if reg.BudgetClampActive(legacy.ID, model) { t.Fatal("reasonless deterministic batch-budget reject must stay strike-only (heuristic unchanged)") @@ -219,7 +219,7 @@ func TestGrayBoxClassificationTrustsStructuredReason(t *testing.T) { // state, even though the budget heuristic alone would have said transient. ctxReason := makeRoutableProvider(t, reg, "p-reasoned-ctx", model) setProviderModelBudget(t, reg, ctxReason.ID, model, 90_000) - srv.noteInferenceError(ctxReason.ID, capacityTestPending(model, ctxReason.ID, 0), + srv.inferenceAttempts().Error(ctxReason.ID, capacityTestPending(model, ctxReason.ID, 0), http.StatusServiceUnavailable, "token_budget_exhausted: request requires 200000 tokens but only 90000 available", "request_exceeds_context", "") diff --git a/coordinator/api/catalog/active_catalog.go b/coordinator/api/catalog/active_catalog.go new file mode 100644 index 0000000000..04a437c20a --- /dev/null +++ b/coordinator/api/catalog/active_catalog.go @@ -0,0 +1,28 @@ +package catalog + +import ( + "github.com/eigeninference/d-inference/coordinator/store" +) + +// activeCatalogLookups builds the two lookups that the model-listing endpoints +// (/v1/models and /v1/models/openrouter) share: the active catalog keyed by +// model ID, and the richer registry entry per model used to populate the +// OpenRouter provider fields, both sourced from the DB-backed model registry. +// The error is returned so each caller can log it with its own context and emit +// a 500. +func (s *Controller) activeCatalogLookups() (catalogByID map[string]store.SupportedModel, registryByID map[string]store.ModelRegistryEntry, err error) { + registryRows, err := s.store().ListActiveModelRegistryWithError() + if err != nil { + return nil, nil, err + } + catalogByID = make(map[string]store.SupportedModel, len(registryRows)) + registryByID = make(map[string]store.ModelRegistryEntry, len(registryRows)) + for _, row := range registryRows { + cm := supportedModelFromRegistryRecord(&row) + if cm.Active { + catalogByID[cm.ID] = cm + registryByID[cm.ID] = row.ModelRegistryEntry + } + } + return catalogByID, registryByID, nil +} diff --git a/coordinator/api/catalog/alias_lineage.go b/coordinator/api/catalog/alias_lineage.go new file mode 100644 index 0000000000..e3f2f70163 --- /dev/null +++ b/coordinator/api/catalog/alias_lineage.go @@ -0,0 +1,43 @@ +package catalog + +import ( + "github.com/eigeninference/d-inference/coordinator/store" +) + +// maxRetiredBuilds bounds the per-alias lineage list; the oldest retirements +// are dropped first once a (pathologically) churned alias exceeds it. +const maxRetiredBuilds = 16 + +// retiredBuildsAfterUpsert computes the alias's lineage after an upsert: prior +// retired builds, plus any prior desired/previous member rotated out by the new +// pointers, minus any build the new pointers re-promote to membership. Bounded +// to maxRetiredBuilds (oldest dropped first). The lineage lets the registration +// gate recognize a provider that was offline through a retirement as part of +// the alias's fleet. +func retiredBuildsAfterUpsert(prior *store.ModelAlias, newDesired, newPrevious string) []string { + if prior == nil { + return nil + } + isMember := func(b string) bool { return b == newDesired || b == newPrevious } + var retired []string + seen := make(map[string]struct{}) + add := func(b string) { + if b == "" || isMember(b) { + return + } + if _, dup := seen[b]; dup { + return + } + seen[b] = struct{}{} + retired = append(retired, b) + } + for _, b := range prior.RetiredBuilds { + add(b) + } + add(prior.DesiredBuild) + add(prior.PreviousBuild) + if len(retired) > maxRetiredBuilds { + retired = retired[len(retired)-maxRetiredBuilds:] + } + return retired +} diff --git a/coordinator/api/catalog/alias_lineage_test.go b/coordinator/api/catalog/alias_lineage_test.go new file mode 100644 index 0000000000..216a3b8a20 --- /dev/null +++ b/coordinator/api/catalog/alias_lineage_test.go @@ -0,0 +1,58 @@ +package catalog + +import ( + "strconv" + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// retiredBuildsAfterUpsert keeps the alias lineage: rotated-out members are +// retained (bounded), re-promoted members leave the list. +func TestRetiredBuildsAfterUpsert(t *testing.T) { + // No prior alias → no lineage. + if got := retiredBuildsAfterUpsert(nil, "b2", ""); got != nil { + t.Fatalf("no prior should yield nil, got %v", got) + } + // Rotation: desired b1→b2 (previous b1) retires nothing (b1 still a member); + // then b2→b3 with previous cleared retires both b2 and b1. + step1 := retiredBuildsAfterUpsert(&store.ModelAlias{DesiredBuild: "b1"}, "b2", "b1") + if len(step1) != 0 { + t.Fatalf("members must not be retired, got %v", step1) + } + step2 := retiredBuildsAfterUpsert(&store.ModelAlias{DesiredBuild: "b2", PreviousBuild: "b1"}, "b3", "") + if len(step2) != 2 || step2[0] != "b2" || step2[1] != "b1" { + t.Fatalf("rotated-out members should be retired, got %v", step2) + } + // Re-promotion: b1 comes back as desired → leaves the lineage. + step3 := retiredBuildsAfterUpsert(&store.ModelAlias{DesiredBuild: "b3", RetiredBuilds: []string{"b2", "b1"}}, "b1", "") + if len(step3) != 2 || step3[0] != "b2" || step3[1] != "b3" { + t.Fatalf("re-promoted build must leave lineage and old desired must join, got %v", step3) + } + // Bound: the oldest entries are dropped first. + var many []string + for i := 0; i < maxRetiredBuilds+4; i++ { + many = append(many, "old-"+strconv.Itoa(i)) + } + bounded := retiredBuildsAfterUpsert(&store.ModelAlias{DesiredBuild: "bX", RetiredBuilds: many}, "bY", "") + if len(bounded) != maxRetiredBuilds { + t.Fatalf("lineage should be bounded to %d, got %d", maxRetiredBuilds, len(bounded)) + } + if bounded[0] == "old-0" { + t.Fatal("oldest entry should be dropped first") + } +} + +func TestStandardAliasCoversEveryBuildState(t *testing.T) { + for name, alias := range map[string]store.ModelAlias{ + "desired": {Active: true, DesiredBuild: "source"}, + "previous": {Active: true, PreviousBuild: "source"}, + "retired": {Active: true, RetiredBuilds: []string{"source"}}, + } { + t.Run(name, func(t *testing.T) { + if !standardAliasCoversBuild(alias, "source") { + t.Fatalf("%s build was not covered: %+v", name, alias) + } + }) + } +} diff --git a/coordinator/api/catalog/alias_ownership.go b/coordinator/api/catalog/alias_ownership.go new file mode 100644 index 0000000000..5e78c4998c --- /dev/null +++ b/coordinator/api/catalog/alias_ownership.go @@ -0,0 +1,48 @@ +package catalog + +import ( + "github.com/eigeninference/d-inference/coordinator/store" +) + +// AliasUsesConcreteSource preserves the legacy meaning of an empty +// source_kind: OpenRouter aliases created before source kinds were persisted +// always cloned a standard alias. +func AliasUsesConcreteSource(alias store.ModelAlias) bool { + return alias.SourceKind == store.ModelAliasSourceConcrete +} + +func standardAliasCoversBuild(alias store.ModelAlias, buildID string) bool { + if !alias.Active || alias.OpenRouterOnly || buildID == "" { + return false + } + if alias.DesiredBuild == buildID || alias.PreviousBuild == buildID { + return true + } + for _, retired := range alias.RetiredBuilds { + if retired == buildID { + return true + } + } + return false +} + +func standardAliasCoveringBuild(aliases []store.ModelAlias, buildID string) (string, bool) { + for _, alias := range aliases { + if standardAliasCoversBuild(alias, buildID) { + return alias.AliasID, true + } + } + return "", false +} + +func concreteOpenRouterAliasUsingBuild(aliases []store.ModelAlias, builds map[string]struct{}) (store.ModelAlias, bool) { + for _, alias := range aliases { + if !alias.Active || !alias.OpenRouterOnly || !AliasUsesConcreteSource(alias) { + continue + } + if _, covered := builds[alias.SourceModel]; covered { + return alias, true + } + } + return store.ModelAlias{}, false +} diff --git a/coordinator/api/catalog/aliases.go b/coordinator/api/catalog/aliases.go new file mode 100644 index 0000000000..2093f0c055 --- /dev/null +++ b/coordinator/api/catalog/aliases.go @@ -0,0 +1,242 @@ +package catalog + +import ( + "encoding/json" + "errors" + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// aliasUpsertRequest is the body for POST /v1/admin/models/aliases. An alias is a +// stable public name resolving to a single desired build, with an optional +// still-acceptable previous build during a staggered rollout. A rollout is just +// setting desired_build; a revert is setting it back. +type aliasUpsertRequest struct { + AliasID string `json:"alias_id"` + DisplayName string `json:"display_name"` + DesiredBuild string `json:"desired_build"` + PreviousBuild string `json:"previous_build"` + Active *bool `json:"active"` // pointer so omission defaults to true + + // Takeover lets a public alias adopt the name of an EXISTING concrete model, + // absorbing that same-named build as its previous_build (fallback). This is the + // only way to migrate a live public name (e.g. "gemma-4-26b") onto a new + // desired build without renaming what providers already advertise — used for + // the 8-bit→4-bit gemma cutover. Fail-closed: only the exact shape + // alias_id == previous_build == an existing concrete model id is permitted, and + // desired_build must still be a distinct registered build. It does NOT touch + // the absorbed model's catalog weight hash, so it never untrusts the providers + // already serving it; they converge to the desired build via desired_models. + Takeover bool `json:"takeover"` +} + +// UpsertAlias creates or replaces a public model alias (idempotent on +// alias_id) and re-syncs the registry so the new desired-build pointer takes +// effect immediately, then declaratively pushes desired_models to every +// connected provider already serving the alias. POST /v1/admin/models/aliases. +func (s *Controller) UpsertAlias(w http.ResponseWriter, r *http.Request) { + if _, ok := s.requirePublishingAPIKey(w, r); !ok { + return + } + + var req aliasUpsertRequest + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + if err := dec.Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + + req.AliasID = strings.TrimSpace(req.AliasID) + req.DisplayName = strings.TrimSpace(req.DisplayName) + req.DesiredBuild = strings.TrimSpace(req.DesiredBuild) + req.PreviousBuild = strings.TrimSpace(req.PreviousBuild) + + if req.AliasID == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "alias_id is required", httpresponse.WithParam("alias_id"))) + return + } + // The alias is spliced into consumer-visible JSON (response bodies, SSE + // chunk rewriting) and into the DELETE URL path — restrict it to the same + // safe charset as registry ids (letters, digits, '.', '_', '-'; no slash so + // it stays a single path segment) and a sane length. + if len(req.AliasID) > maxAliasIDLength || !validRegistryIdentifier(req.AliasID, false) { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "alias_id may only contain letters, digits, '.', '_' and '-' (max 128 chars)", httpresponse.WithParam("alias_id"))) + return + } + if req.DesiredBuild == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "desired_build is required", httpresponse.WithParam("desired_build"))) + return + } + s.modelAliasMutationMu.Lock() + defer s.modelAliasMutationMu.Unlock() + + // Namespace + takeover rules. Normally an alias id must not collide with a + // concrete model id (resolution would be ambiguous), and an alias may never + // name itself as a member. `takeover` is the deliberate exception for the + // public-name migration: an alias adopts the name of an existing concrete + // model and absorbs that same-named build as its previous_build (fallback). + collidingRec, err := s.store().GetModelRegistryRecord(req.AliasID) + if err != nil && !errors.Is(err, store.ErrNotFound) { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to check model namespace")) + return + } + idCollision := collidingRec != nil + prior, found, err := s.store().GetModelAlias(req.AliasID) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to get alias")) + return + } + if !found { + prior = nil + } + if prior != nil && prior.OpenRouterOnly { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("invalid_request_error", "alias_id belongs to the dedicated OpenRouter alias endpoint", httpresponse.WithParam("alias_id"))) + return + } + + // desired_build can NEVER equal the alias name (that would alias to itself). + if req.DesiredBuild == req.AliasID { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "desired_build cannot equal alias_id", httpresponse.WithParam("desired_build"))) + return + } + if idCollision { + if !req.Takeover { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("invalid_request_error", + "alias_id collides with an existing model id (set takeover=true to adopt it as the alias's previous build)", httpresponse.WithParam("alias_id"))) + return + } + // Fail-closed: takeover only permits absorbing the SAME-named concrete + // build as the alias fallback. previous_build must be exactly alias_id. + if req.PreviousBuild != req.AliasID { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "takeover requires previous_build to equal alias_id (the concrete build absorbed as the alias fallback)", httpresponse.WithParam("previous_build"))) + return + } + } else if req.PreviousBuild == req.AliasID { + // No concrete model of this name exists, so there is nothing to absorb. + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "an alias cannot reference itself", httpresponse.WithParam("previous_build"))) + return + } + if req.PreviousBuild != "" && req.PreviousBuild == req.DesiredBuild { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "previous_build must differ from desired_build", httpresponse.WithParam("previous_build"))) + return + } + // Both builds must be registered models so we never alias to a phantom id. + for _, member := range []struct{ field, id string }{ + {"desired_build", req.DesiredBuild}, {"previous_build", req.PreviousBuild}, + } { + if member.id == "" { + continue + } + rec, err := s.store().GetModelRegistryRecord(member.id) + if err != nil && !errors.Is(err, store.ErrNotFound) { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to get alias member")) + return + } + if rec == nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", member.field+" "+member.id+" is not a registered model", httpresponse.WithParam(member.field))) + return + } + } + + active := true + if req.Active != nil { + active = *req.Active + } + retiredBuilds := retiredBuildsAfterUpsert(prior, req.DesiredBuild, req.PreviousBuild) + if active { + aliases, err := s.store().ListModelAliases() + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to validate alias members")) + return + } + members := make(map[string]struct{}, 2+len(retiredBuilds)) + members[req.DesiredBuild] = struct{}{} + if req.PreviousBuild != "" { + members[req.PreviousBuild] = struct{}{} + } + for _, retired := range retiredBuilds { + members[retired] = struct{}{} + } + if clone, conflict := concreteOpenRouterAliasUsingBuild(aliases, members); conflict { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("invalid_request_error", "concrete model "+clone.SourceModel+" is pinned by OpenRouter alias "+clone.AliasID+"; delete or retarget that alias first")) + return + } + } + alias := &store.ModelAlias{ + AliasID: req.AliasID, + DisplayName: req.DisplayName, + DesiredBuild: req.DesiredBuild, + PreviousBuild: req.PreviousBuild, + RetiredBuilds: retiredBuilds, + + Active: active, + } + + if err := s.store().UpsertModelAlias(alias); err != nil { + s.logger.Error("upsert model alias failed", "alias_id", req.AliasID, "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to save alias")) + return + } + s.syncCatalog() + + saved, _, _ := s.store().GetModelAlias(req.AliasID) + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"status": "ok", "alias": saved}) +} + +// maxAliasIDLength bounds the public alias id; it appears in URLs, response +// bodies, and SSE chunks, so it must stay short and single-segment. +const maxAliasIDLength = 128 + +// ListAliases returns standard rollout aliases. OpenRouter-only feed +// aliases have a dedicated management endpoint. +func (s *Controller) ListAliases(w http.ResponseWriter, r *http.Request) { + if _, ok := s.requirePublishingAPIKey(w, r); !ok { + return + } + aliases, err := s.store().ListModelAliases() + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to list aliases")) + return + } + standard := aliases[:0] + for _, alias := range aliases { + if !alias.OpenRouterOnly { + standard = append(standard, alias) + } + } + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"aliases": standard}) + +} + +// DeleteAlias removes an alias. DELETE /v1/admin/models/aliases/{aliasID}. +func (s *Controller) DeleteAlias(w http.ResponseWriter, r *http.Request) { + if _, ok := s.requirePublishingAPIKey(w, r); !ok { + return + } + aliasID := strings.TrimSpace(r.PathValue("aliasID")) + if aliasID == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "alias id is required")) + return + } + if alias, found, err := s.store().GetModelAlias(aliasID); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to get alias")) + return + } else if found && alias.OpenRouterOnly { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("invalid_request_error", "OpenRouter-only alias must be deleted through its dedicated endpoint")) + return + } + if err := s.store().DeleteModelAlias(aliasID); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to delete alias")) + return + } + s.syncCatalog() + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"status": "deleted", "alias_id": aliasID}) +} diff --git a/coordinator/api/catalog/artifact_test.go b/coordinator/api/catalog/artifact_test.go new file mode 100644 index 0000000000..fe0efbeb72 --- /dev/null +++ b/coordinator/api/catalog/artifact_test.go @@ -0,0 +1,22 @@ +package catalog + +import ( + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestRegisterModelRejectsMutableHuggingFaceRevision(t *testing.T) { + err := validateRegisterModelRequest(registerModelRequest{HuggingFaceArtifact: &store.HuggingFaceArtifact{RepoID: "EigenLabs/test", Revision: "main"}}) + if err == nil || !strings.Contains(err.Error(), "hugging_face_artifact.revision") { + t.Fatalf("expected pinned-revision rejection, got %v", err) + } +} + +func TestLegacyCatalogOmitsHuggingFaceArtifact(t *testing.T) { + model := catalogModelFromRegistryRecord(&store.ModelRegistryRecord{ActiveVersion: &store.ModelVersion{Version: "v1"}}) + if _, ok := model["hugging_face_artifact"]; ok { + t.Fatal("legacy catalog must omit optional artifact") + } +} diff --git a/coordinator/api/catalog/cache.go b/coordinator/api/catalog/cache.go new file mode 100644 index 0000000000..00297f8c07 --- /dev/null +++ b/coordinator/api/catalog/cache.go @@ -0,0 +1,37 @@ +package catalog + +import "time" + +// Cache adapters retain the API's optional-cache behavior. +func (s *Controller) readCacheGet(key string) ([]byte, bool) { + if s.readCache == nil { + return nil, false + } + return s.readCache.Get(key) +} + +func (s *Controller) readCacheGetValue(key string) (any, bool) { + if s.readCache == nil { + return nil, false + } + return s.readCache.GetValue(key) +} + +func (s *Controller) readCacheGeneration() uint64 { + if s.readCache == nil { + return 0 + } + return s.readCache.Generation() +} + +func (s *Controller) readCacheSetIfCurrent(key string, body []byte, ttl time.Duration, generation uint64) { + if s.readCache != nil { + s.readCache.SetIfCurrent(key, body, ttl, generation) + } +} + +func (s *Controller) readCacheSetValueIfCurrent(key string, value any, ttl time.Duration, generation uint64) { + if s.readCache != nil { + s.readCache.SetValueIfCurrent(key, value, ttl, generation) + } +} diff --git a/coordinator/api/catalog/concrete_models.go b/coordinator/api/catalog/concrete_models.go new file mode 100644 index 0000000000..c26c81659a --- /dev/null +++ b/coordinator/api/catalog/concrete_models.go @@ -0,0 +1,157 @@ +package catalog + +import ( + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// modelEntryForConcrete builds the consumer catalog representation of one +// provider-advertised concrete model. Callers decide whether the entry is hidden +// behind a standard rollout alias; OpenRouter-only aliases never hide it. +func (s *Controller) modelEntryForConcrete( + model registry.AggregateModel, + capacity *registry.ModelCapacity, + catalogModel store.SupportedModel, + inCatalog bool, + registryEntry store.ModelRegistryEntry, + hasRegistryEntry bool, +) types.ModelEntry { + metadata := types.ModelMetadata{ + ModelType: model.ModelType, + Quantization: model.Quantization, + ProviderCount: model.Providers, + AttestedProviders: model.AttestedProviders, + TrustLevel: string(model.TrustLevel), + } + if capacity != nil { + metadata.RoutableProviders = capacity.RoutableProviders + metadata.WarmProviders = capacity.WarmProviders + metadata.CanAccept = capacity.CanAccept + } + if model.Attestation != nil { + metadata.Attestation = &types.ModelAttestation{ + SecureEnclave: model.Attestation.SecureEnclave, + SIPEnabled: model.Attestation.SIPEnabled, + SecureBoot: model.Attestation.SecureBoot, + } + } + if inCatalog && catalogModel.DisplayName != "" { + metadata.DisplayName = catalogModel.DisplayName + } + + entry := types.ModelEntry{ + ID: model.ID, + Object: "model", + OwnedBy: "eigeninference", + Name: metadata.DisplayName, + HuggingFaceID: huggingFaceIDForModel(model.ID, registryEntry.Metadata), + Metadata: metadata, + } + s.openRouterModelFieldsFor(model.ID, model.Quantization, registryEntry, hasRegistryEntry).applyToModelEntry(&entry) + + var capabilities []string + if hasRegistryEntry { + capabilities = registryEntry.Capabilities + } + entry.InputModalities, entry.OutputModalities = deriveModalities(model.ModelType, capabilities) + return entry +} + +// modelEntryForCatalogConcrete builds exact-retrieval metadata for an active +// concrete model even when no provider is connected. Live counts remain zero; +// the durable registry supplies identity, limits, pricing, and capabilities. +func (s *Controller) modelEntryForCatalogConcrete( + modelID string, + catalogByID map[string]store.SupportedModel, + registryByID map[string]store.ModelRegistryEntry, +) (types.ModelEntry, bool) { + catalogModel, ok := catalogByID[modelID] + if !ok { + return types.ModelEntry{}, false + } + registryEntry, hasRegistryEntry := registryByID[modelID] + entry := s.modelEntryForConcrete( + registry.AggregateModel{ + ID: modelID, + ModelType: catalogModel.ModelType, + Quantization: registryEntry.Quantization, + }, + nil, + catalogModel, + true, + registryEntry, + hasRegistryEntry, + ) + return entry, true +} + +func (s *Controller) openRouterAggregateTypeByID() map[string]string { + typesByID := make(map[string]string) + for _, model := range s.registry.ListModels() { + if model.ModelType != "" { + typesByID[model.ID] = model.ModelType + } + } + return typesByID +} + +func concreteModelEligibleForOpenRouterFeed( + modelID string, + catalogByID map[string]store.SupportedModel, + aggregateTypeByID map[string]string, +) bool { + catalogModel, ok := catalogByID[modelID] + if !ok { + return false + } + modelType := catalogModel.ModelType + if aggregateType, found := aggregateTypeByID[modelID]; found { + modelType = aggregateType + } + return !isNonTextModelType(modelType) +} + +// openRouterEntryForConcrete builds the dedicated provider-feed representation +// of one active concrete catalog model. It remains independently listed when an +// OpenRouter-only alias clones it. +func (s *Controller) openRouterEntryForConcrete( + modelID string, + catalogByID map[string]store.SupportedModel, + registryByID map[string]store.ModelRegistryEntry, + aggregateTypeByID map[string]string, +) (types.OpenRouterModel, bool) { + catalogModel, ok := catalogByID[modelID] + if !ok || !concreteModelEligibleForOpenRouterFeed(modelID, catalogByID, aggregateTypeByID) { + return types.OpenRouterModel{}, false + } + + registryEntry, hasRegistryEntry := registryByID[modelID] + modelType := catalogModel.ModelType + if aggregateType, found := aggregateTypeByID[modelID]; found { + modelType = aggregateType + } + var capabilities []string + if hasRegistryEntry { + capabilities = registryEntry.Capabilities + } + inputModalities, outputModalities := deriveModalities(modelType, capabilities) + entry := types.OpenRouterModel{ + ID: modelID, + HuggingFaceID: huggingFaceIDForModel(modelID, registryEntry.Metadata), + Name: openRouterModelName(catalogModel, registryEntry, hasRegistryEntry, modelID), + InputModalities: inputModalities, + OutputModalities: outputModalities, + SupportedFeatures: []string{}, + IsReady: true, + } + s.openRouterModelFieldsFor(modelID, registryEntry.Quantization, registryEntry, hasRegistryEntry).applyToFeed(&entry) + if hasRegistryEntry { + entry.IsReady = openRouterIsReady(registryEntry.Metadata) + entry.OpenRouter = &types.OpenRouterSlug{Slug: openRouterSlug(modelID, registryEntry.Metadata)} + } else { + entry.OpenRouter = &types.OpenRouterSlug{Slug: openRouterSlug(modelID, nil)} + } + entry.Datacenters = s.modelDatacenters(modelID) + return entry, true +} diff --git a/coordinator/api/catalog/consumer_aliases.go b/coordinator/api/catalog/consumer_aliases.go new file mode 100644 index 0000000000..1547e4b9c7 --- /dev/null +++ b/coordinator/api/catalog/consumer_aliases.go @@ -0,0 +1,125 @@ +package catalog + +import ( + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func hideAliasBuild(hidden map[string]struct{}, catalogByID map[string]store.SupportedModel, buildID string) { + if buildID == "" { + return + } + if _, inCatalog := catalogByID[buildID]; inCatalog { + hidden[buildID] = struct{}{} + } +} + +// aliasModelEntries builds consumer-facing /v1/models entries for active +// standard aliases and returns the concrete build ids they hide. OpenRouter-only +// aliases are deliberately excluded; they are discoverable only through the +// dedicated /v1/models/openrouter marketplace feed. +func (s *Controller) aliasModelEntries( + capByModel map[string]*registry.ModelCapacity, + catalogByID map[string]store.SupportedModel, + registryByID map[string]store.ModelRegistryEntry, +) ([]types.ModelEntry, map[string]struct{}, error) { + hidden := make(map[string]struct{}) + aliases, err := s.store().ListModelAliases() + if err != nil { + return nil, nil, err + } + + entries := make([]types.ModelEntry, 0, len(aliases)) + for _, a := range aliases { + if !a.Active || a.OpenRouterOnly || a.DesiredBuild == "" { + continue + } + // A consumer must only ever see the alias, never a concrete build behind + // it. Hide EVERY build this alias references — desired, previous, AND the + // retired lineage — from the standalone listing, even if the alias itself + // isn't advertisable right now. (Capacity below aggregates only the + // routable desired/previous members; retired builds are hide-only.) + hideAliasBuild(hidden, catalogByID, a.DesiredBuild) + hideAliasBuild(hidden, catalogByID, a.PreviousBuild) + for _, b := range a.RetiredBuilds { + hideAliasBuild(hidden, catalogByID, b) + } + // Primary build = the desired build when it's in the catalog, else the + // previous build (so the alias keeps a real entry while the desired build + // is mid-registration). An alias whose builds are all out of catalog + // resolves to nothing and must not be advertised (it would 503). + members := make([]string, 0, 2) + desiredInCatalog := false + if _, ok := catalogByID[a.DesiredBuild]; ok { + members = append(members, a.DesiredBuild) + desiredInCatalog = true + } + previousInCatalog := false + if a.PreviousBuild != "" { + if _, ok := catalogByID[a.PreviousBuild]; ok { + members = append(members, a.PreviousBuild) + previousInCatalog = true + } + } + var primary string + switch { + case desiredInCatalog: + primary = a.DesiredBuild + case previousInCatalog: + primary = a.PreviousBuild + default: + // No in-catalog build backs this alias — don't advertise it. + continue + } + + routable, warm := 0, 0 + canAccept := false + for _, b := range members { + if cap, ok := capByModel[b]; ok { + routable += cap.RoutableProviders + warm += cap.WarmProviders + canAccept = canAccept || cap.CanAccept + } + } + + cm := catalogByID[primary] + reg, hasReg := registryByID[primary] + displayName := a.DisplayName + if displayName == "" { + displayName = cm.DisplayName + } + metadata := types.ModelMetadata{ + ModelType: cm.ModelType, + Quantization: "", // an alias spans quants; omit the per-build quant + DisplayName: displayName, + RoutableProviders: routable, + WarmProviders: warm, + CanAccept: canAccept, + } + entry := types.ModelEntry{ + ID: a.AliasID, + Object: "model", + OwnedBy: "eigeninference", + Name: displayName, + HuggingFaceID: huggingFaceIDForModel(primary, reg.Metadata), + Metadata: metadata, + } + // Pricing / context / features come from the primary build's registry + // entry. Quantization is intentionally left blank on the alias. + primaryQuant := "" + if hasReg { + primaryQuant = reg.Quantization + } + s.openRouterModelFieldsFor(primary, primaryQuant, reg, hasReg).applyToModelEntry(&entry) + entry.Quantization = "" + var caps []string + if hasReg { + caps = reg.Capabilities + } + entry.InputModalities, entry.OutputModalities = deriveModalities(cm.ModelType, caps) + entries = append(entries, entry) + } + + return entries, hidden, nil +} diff --git a/coordinator/api/catalog/consumer_aliases_test.go b/coordinator/api/catalog/consumer_aliases_test.go new file mode 100644 index 0000000000..89976595d6 --- /dev/null +++ b/coordinator/api/catalog/consumer_aliases_test.go @@ -0,0 +1,184 @@ +package catalog + +import ( + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// aliasModelEntries returns the alias entry and the set of builds it covers, +// hiding retired lineage while aggregating active capacity from desired + previous. +func TestAliasModelEntriesHidesBuilds(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + srv := newTestController(registry.New(logger), st, logger) + + seedActiveModel(t, st, aliasFP8, "Gemma 4 26B (fp8)") + seedActiveModel(t, st, aliasQAT, "Gemma 4 26B (qat-4bit)") + if err := st.UpsertModelAlias(&store.ModelAlias{ + AliasID: "gemma-4-26b", DisplayName: "Gemma 4 26B", Active: true, + DesiredBuild: aliasQAT, PreviousBuild: aliasFP8, RetiredBuilds: []string{"gemma-4-26b-retired"}, + }); err != nil { + t.Fatal(err) + } + + _, registryByID, err := srv.activeCatalogLookups() + if err != nil { + t.Fatal(err) + } + catalogByID := map[string]store.SupportedModel{ + aliasFP8: {ID: aliasFP8, Active: true, ModelType: "text"}, + aliasQAT: {ID: aliasQAT, Active: true, ModelType: "text"}, + "gemma-4-26b-retired": {ID: "gemma-4-26b-retired", Active: true, ModelType: "text"}, + } + capByModel := map[string]*registry.ModelCapacity{ + aliasQAT: {ModelID: aliasQAT, RoutableProviders: 2, WarmProviders: 1, CanAccept: true}, + aliasFP8: {ModelID: aliasFP8, RoutableProviders: 1, WarmProviders: 0, CanAccept: false}, + "gemma-4-26b-retired": {ModelID: "gemma-4-26b-retired", RoutableProviders: 10, WarmProviders: 10, CanAccept: true}, + } + + entries, hidden, err := srv.aliasModelEntries(capByModel, catalogByID, registryByID) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].ID != "gemma-4-26b" { + t.Fatalf("expected one alias entry, got %+v", entries) + } + if entries[0].HuggingFaceID != aliasQAT { + t.Fatalf("alias hugging_face_id = %q, want primary build %q", entries[0].HuggingFaceID, aliasQAT) + } + // Capacity aggregates across desired + previous only (2 + 1 = 3 routable); + // retired builds are hide-only and must not count as active alias capacity. + if entries[0].Metadata.RoutableProviders != 3 || entries[0].Metadata.WarmProviders != 1 || !entries[0].Metadata.CanAccept { + t.Fatalf("alias capacity not aggregated: %+v", entries[0].Metadata) + } + if _, ok := hidden[aliasFP8]; !ok { + t.Fatalf("fp8 (previous) build should be hidden: %v", hidden) + } + if _, ok := hidden[aliasQAT]; !ok { + t.Fatalf("qat (desired) build should be hidden: %v", hidden) + } + if _, ok := hidden["gemma-4-26b-retired"]; !ok { + t.Fatalf("retired build should be hidden without counting capacity: %v", hidden) + } +} + +// An alias whose desired build isn't in the catalog yet falls back to the +// previous build for its primary metadata; an alias with no in-catalog build is +// not advertised. +func TestAliasModelEntriesDesiredNotInCatalog(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + srv := newTestController(registry.New(logger), st, logger) + + seedActiveModel(t, st, aliasFP8, "fp8 only") + // Only fp8 (previous) is in the catalog; qat (desired) isn't registered yet. + if err := st.UpsertModelAlias(&store.ModelAlias{ + AliasID: "gemma-4-26b", DisplayName: "Gemma 4 26B", Active: true, + DesiredBuild: aliasQAT, PreviousBuild: aliasFP8, + }); err != nil { + t.Fatal(err) + } + // An alias whose desired build is empty / has no in-catalog build is skipped. + if err := st.UpsertModelAlias(&store.ModelAlias{ + AliasID: "ghost", DisplayName: "Ghost", Active: true, + DesiredBuild: "mlx-community/not-registered", + }); err != nil { + t.Fatal(err) + } + + _, registryByID, err := srv.activeCatalogLookups() + if err != nil { + t.Fatal(err) + } + catalogByID := map[string]store.SupportedModel{aliasFP8: {ID: aliasFP8, Active: true, ModelType: "text"}} + entries, hidden, err := srv.aliasModelEntries(map[string]*registry.ModelCapacity{}, catalogByID, registryByID) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].ID != "gemma-4-26b" { + t.Fatalf("only the alias with an in-catalog build should list, got %+v", entries) + } + if _, ok := hidden[aliasFP8]; !ok { + t.Fatalf("previous build should still be hidden, got %v", hidden) + } + if _, ok := hidden["mlx-community/not-registered"]; ok { + t.Fatalf("a skipped alias must not hide its build, got %v", hidden) + } +} + +// After full retirement (previous_build cleared, the old build moved into the +// retired lineage but still a registered/active model), /v1/models must STILL +// show only the alias — never the raw retired quant. Regression for the +// retired-build listing leak: a consumer must only ever see the alias. +func TestListModelsHidesRetiredAliasBuild(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + srv := newTestController(registry.New(logger), st, logger) + + seedActiveModel(t, st, aliasFP8, "Gemma 4 26B (fp8)") + seedActiveModel(t, st, aliasQAT, "Gemma 4 26B (qat-4bit)") + // Fully retired: desired=qat, previous cleared, fp8 in the retired lineage + // (still registered + active in the catalog — the exact leak condition). + if err := st.UpsertModelAlias(&store.ModelAlias{ + AliasID: "gemma-4-26b", DisplayName: "Gemma 4 26B", Active: true, + DesiredBuild: aliasQAT, RetiredBuilds: []string{aliasFP8}, + }); err != nil { + t.Fatal(err) + } + srv.Invalidate() + + rec := httptest.NewRecorder() + srv.ListModels(rec, httptest.NewRequest(http.MethodGet, "/v1/models", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String()) + } + var resp struct { + Data []struct { + ID string `json:"id"` + } `json:"data"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + sawAlias, leakedFP8, leakedQAT := false, false, false + for _, m := range resp.Data { + switch m.ID { + case "gemma-4-26b": + sawAlias = true + case aliasFP8: + leakedFP8 = true + case aliasQAT: + leakedQAT = true + } + } + if !sawAlias { + t.Fatalf("alias gemma-4-26b missing from /v1/models: %+v", resp.Data) + } + if leakedFP8 { + t.Fatalf("retired build %q leaked into /v1/models — consumers must only ever see the alias", aliasFP8) + } + if leakedQAT { + t.Fatalf("desired build %q leaked into /v1/models", aliasQAT) + } + + // The hidden set covers the retired build directly too. + _, registryByID, err := srv.activeCatalogLookups() + if err != nil { + t.Fatal(err) + } + catalogByID := map[string]store.SupportedModel{aliasFP8: {ID: aliasFP8, Active: true, ModelType: "text"}, aliasQAT: {ID: aliasQAT, Active: true, ModelType: "text"}} + _, hidden, err := srv.aliasModelEntries(map[string]*registry.ModelCapacity{}, catalogByID, registryByID) + if err != nil { + t.Fatal(err) + } + if _, ok := hidden[aliasFP8]; !ok { + t.Fatalf("retired build should be in the hidden set: %v", hidden) + } +} diff --git a/coordinator/api/catalog/consumer_cache.go b/coordinator/api/catalog/consumer_cache.go new file mode 100644 index 0000000000..350ca2818c --- /dev/null +++ b/coordinator/api/catalog/consumer_cache.go @@ -0,0 +1,66 @@ +package catalog + +import ( + "strconv" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/types" +) + +// modelListCacheTTL bounds staleness of the public model list. It carries live +// capacity fields (routable/warm providers, can_accept), so it matches the 2s +// window GET /v1/models/capacity already uses. Catalog sync invalidates these +// entries and prevents an older in-flight fill from publishing afterward. +const modelListCacheTTL = 2 * time.Second + +func modelEntriesCacheKey(includeBuilds bool) string { + return "models:entries:v1:include_builds=" + strconv.FormatBool(includeBuilds) +} + +func modelListBodyCacheKey(includeBuilds bool) string { + return "models:list:v1:include_builds=" + strconv.FormatBool(includeBuilds) +} + +// Entries returns the public catalog's consumer-facing entries, +// memoized for modelListCacheTTL. The slice is shared between callers and +// must not be mutated (handlers copy the entry they return). +func (s *Controller) Entries(includeBuilds bool) ([]types.ModelEntry, error) { + key := modelEntriesCacheKey(includeBuilds) + if v, ok := s.readCacheGetValue(key); ok { + if entries, ok := v.([]types.ModelEntry); ok { + return entries, nil + } + } + generation := s.readCacheGeneration() + entries, err := s.listModelEntries(includeBuilds) + if err != nil { + return nil, err + } + s.readCacheSetValueIfCurrent(key, entries, modelListCacheTTL, generation) + return entries, nil +} + +// cachedModelListBody returns the pre-serialized GET /v1/models response for +// the public catalog, byte-identical to what writeJSON would produce. A body +// miss recomputes the entries (refreshing the entries memo alongside) rather +// than reusing an almost-expired memo, so the body is never older than +// modelListCacheTTL. +func (s *Controller) cachedModelListBody(includeBuilds bool) ([]byte, error) { + key := modelListBodyCacheKey(includeBuilds) + if body, ok := s.readCacheGet(key); ok { + return body, nil + } + generation := s.readCacheGeneration() + entries, err := s.listModelEntries(includeBuilds) + if err != nil { + return nil, err + } + body, err := httpresponse.EncodeCachedJSON(types.ModelListResponse{Object: "list", Data: entries}) + if err != nil { + return nil, err + } + s.readCacheSetValueIfCurrent(modelEntriesCacheKey(includeBuilds), entries, modelListCacheTTL, generation) + s.readCacheSetIfCurrent(key, body, modelListCacheTTL, generation) + return body, nil +} diff --git a/coordinator/api/catalog/consumer_get.go b/coordinator/api/catalog/consumer_get.go new file mode 100644 index 0000000000..5903d1788c --- /dev/null +++ b/coordinator/api/catalog/consumer_get.go @@ -0,0 +1,82 @@ +package catalog + +import ( + "fmt" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" + "github.com/eigeninference/d-inference/coordinator/api/types" +) + +// GetModel handles GET /v1/models/{id...} — the OpenAI "retrieve model" +// endpoint. Model IDs may contain slashes (HuggingFace paths), hence the +// wildcard path segment. Hidden quant builds and marketplace-only OpenRouter +// aliases remain retrievable by exact id for inference-client parity. +func (s *Controller) GetModel(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + // Self-route requests retrieve from their owned live models (mirrors + // ListModels, including the header-based opt-in): list and retrieve + // must agree, or an OpenAI client that validates a model id via + // retrieve-model can never use a listed local model. + if policy := s.selfRoute(r); policy.enabled { + entries := filterEntriesByKeyAllowList(s.OwnedModelEntries(policy.ownerAccountID, true), requestcontext.APIKey(r.Context())) + for _, entry := range entries { + if entry.ID == id { + httpresponse.WriteJSON(w, http.StatusOK, entry) + return + } + } + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("model_not_found", + fmt.Sprintf("model %q not found", id), httpresponse.WithParam("model"))) + return + } + // Shares the memoized public catalog with GET /v1/models; the per-id scan + // and the alias fallback below stay uncached. + data, err := s.Entries(true) + if err != nil { + s.logger.Error("model registry: failed to list active models", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to list models")) + return + } + for _, entry := range data { + if entry.ID == id { + httpresponse.WriteJSON(w, http.StatusOK, entry) + return + } + } + alias, found, aliasErr := s.store().GetModelAlias(id) + if aliasErr != nil { + s.logger.Error("model registry: failed to retrieve model alias", "model", id, "error", aliasErr) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to retrieve model")) + return + } + if found && alias.Active && alias.OpenRouterOnly { + var sourceEntry types.ModelEntry + sourceFound := false + for _, entry := range data { + if entry.ID == alias.SourceModel { + sourceEntry = entry + sourceFound = true + break + } + } + if !sourceFound && AliasUsesConcreteSource(*alias) { + catalogByID, registryByID, catalogErr := s.activeCatalogLookups() + if catalogErr != nil { + s.logger.Error("model registry: failed to retrieve concrete alias source", "model", id, "source_model", alias.SourceModel, "error", catalogErr) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to retrieve model")) + return + } + sourceEntry, sourceFound = s.modelEntryForCatalogConcrete(alias.SourceModel, catalogByID, registryByID) + } + if sourceFound { + sourceEntry.ID = alias.AliasID + sourceEntry.HuggingFaceID = alias.HuggingFaceID + httpresponse.WriteJSON(w, http.StatusOK, sourceEntry) + return + } + } + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("model_not_found", + fmt.Sprintf("model %q not found", id), httpresponse.WithParam("model"))) +} diff --git a/coordinator/api/catalog/consumer_list.go b/coordinator/api/catalog/consumer_list.go new file mode 100644 index 0000000000..1b04eab591 --- /dev/null +++ b/coordinator/api/catalog/consumer_list.go @@ -0,0 +1,116 @@ +package catalog + +import ( + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/requestcontext" + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// listModelEntries assembles the consumer-facing model entries shared by +// GET /v1/models and GET /v1/models/{id}. includeBuilds also lists the raw +// quant builds hidden behind public aliases (ops/debug). +func (s *Controller) listModelEntries(includeBuilds bool) ([]types.ModelEntry, error) { + models := s.registry.ListModels() + + capacities := s.registry.ModelCapacitySnapshot() + capByModel := make(map[string]*registry.ModelCapacity, len(capacities)) + for i := range capacities { + capByModel[capacities[i].ModelID] = &capacities[i] + } + + catalogByID, registryByID, err := s.activeCatalogLookups() + if err != nil { + return nil, err + } + + // Build each concrete entry once. OpenRouter-only aliases may clone these + // entries, while standard aliases independently decide which builds to hide. + concreteEntries := make(map[string]types.ModelEntry, len(models)) + concreteOrder := make([]string, 0, len(models)) + for _, model := range models { + catalogModel, inCatalog := catalogByID[model.ID] + if len(catalogByID) > 0 && !inCatalog { + continue + } + registryEntry, hasRegistryEntry := registryByID[model.ID] + concreteEntries[model.ID] = s.modelEntryForConcrete( + model, + capByModel[model.ID], + catalogModel, + inCatalog, + registryEntry, + hasRegistryEntry, + ) + concreteOrder = append(concreteOrder, model.ID) + } + + aliasEntries, hiddenBuilds, err := s.aliasModelEntries(capByModel, catalogByID, registryByID) + if err != nil { + return nil, err + } + data := make([]types.ModelEntry, 0, len(concreteEntries)+len(aliasEntries)) + data = append(data, aliasEntries...) + for _, modelID := range concreteOrder { + if _, hidden := hiddenBuilds[modelID]; hidden && !includeBuilds { + continue + } + data = append(data, concreteEntries[modelID]) + } + return data, nil +} + +func (s *Controller) ListModels(w http.ResponseWriter, r *http.Request) { + // The owned-model view follows the request's resolved route mode, exactly + // like inference: a SelfRouteOnly key always, or any key sending + // X-Darkbloom-Route: self — so a client that lists (or validates) models + // with the same header it will infer with discovers the same ids the + // inference path accepts. Header-less requests on ordinary keys see the + // public catalog, matching their public routing. (prefer falls back to the + // paid fleet, so it keeps the public view.) + if policy := s.selfRoute(r); policy.enabled { + entries := s.OwnedModelEntries(policy.ownerAccountID, r.URL.Query().Get("include_builds") == "1") + httpresponse.WriteJSON(w, http.StatusOK, types.ModelListResponse{ + Object: "list", + Data: filterEntriesByKeyAllowList(entries, requestcontext.APIKey(r.Context())), + }) + return + } + + // Pass ?include_builds=1 (ops/debug) to also list the raw quant builds. + // The public catalog is the same for every caller (no per-key filtering + // applies to it), so the whole response is served from the read cache. + body, err := s.cachedModelListBody(r.URL.Query().Get("include_builds") == "1") + if err != nil { + s.logger.Error("model registry: failed to list active models", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to list models")) + return + } + httpresponse.WriteCachedJSON(w, body) +} + +// filterEntriesByKeyAllowList restricts a self-route model view to the key's +// allow-list when one is set. Owned live models are private inventory (unlike +// the public catalog): a restricted key handed out for one local model must +// not enumerate — or retrieve metadata for — the account's other machine +// models, mirroring what keyModelAllowed would let it actually use. An empty +// allow-list means the key may use (and therefore see) everything. +func filterEntriesByKeyAllowList(entries []types.ModelEntry, k *store.APIKey) []types.ModelEntry { + if k == nil || len(k.AllowedModels) == 0 { + return entries + } + allowed := make(map[string]struct{}, len(k.AllowedModels)) + for _, m := range k.AllowedModels { + allowed[m] = struct{}{} + } + filtered := make([]types.ModelEntry, 0, len(entries)) + for _, e := range entries { + if _, ok := allowed[e.ID]; ok { + filtered = append(filtered, e) + } + } + return filtered +} diff --git a/coordinator/api/catalog/controller.go b/coordinator/api/catalog/controller.go new file mode 100644 index 0000000000..1725839e40 --- /dev/null +++ b/coordinator/api/catalog/controller.go @@ -0,0 +1,71 @@ +// Package catalog owns model discovery, publishing, and alias HTTP operations. +// Routing snapshots and catalog publication remain dependencies of the owner. +package catalog + +import ( + "log/slog" + "net/http" + "sync" + + "github.com/eigeninference/d-inference/coordinator/api/readcache" + "github.com/eigeninference/d-inference/coordinator/registry" +) + +// ModelViews supplies read-only views of the live fleet. The registry retains +// provider locks, routing policy, and reservation state. +type ModelViews interface { + ListModels() []registry.AggregateModel + ModelCapacitySnapshot() []registry.ModelCapacity + OwnedModels(accountID string) []registry.AggregateModel + ModelCountryCodes(modelID string) []string +} + +// Dependencies binds the catalog to the API's current persistence and runtime +// configuration. Cache must be the same instance invalidated by catalog sync. +// Store and AdminKey are getters so post-construction updates remain visible. +// SelfRouteAccount uses the existing authenticated routing policy; it returns +// true only for exclusive self-route. SyncCatalog retains the API's synchronous +// catalog reread and publication; a successful reread invalidates this shared +// cache. The callback retains its existing log-and-return handling of read errors. +type Dependencies struct { + Store func() Store + Models ModelViews + Cache *readcache.Cache + Logger *slog.Logger + AdminKey func() string + SelfRouteAccount func(*http.Request) (accountID string, enabled bool) + SyncCatalog func() +} + +// Controller owns the shared alias mutation lock and catalog operations. +// Create one per server; standard and marketplace aliases must use the same +// instance so cross-endpoint ownership checks stay serialized. +type Controller struct { + store func() Store + registry ModelViews + readCache *readcache.Cache + logger *slog.Logger + adminKey func() string + selfRouteAccount func(*http.Request) (string, bool) + syncCatalog func() + modelAliasMutationMu sync.Mutex +} + +// New binds dependencies without loading the catalog or starting background work. +func New(deps Dependencies) *Controller { + return &Controller{ + store: deps.Store, registry: deps.Models, readCache: deps.Cache, + logger: deps.Logger, adminKey: deps.AdminKey, + selfRouteAccount: deps.SelfRouteAccount, syncCatalog: deps.SyncCatalog, + } +} + +type selfRoutePolicy struct { + ownerAccountID string + enabled bool +} + +func (s *Controller) selfRoute(r *http.Request) selfRoutePolicy { + accountID, enabled := s.selfRouteAccount(r) + return selfRoutePolicy{ownerAccountID: accountID, enabled: enabled} +} diff --git a/coordinator/api/catalog/controller_fixture_test.go b/coordinator/api/catalog/controller_fixture_test.go new file mode 100644 index 0000000000..2e8d468fae --- /dev/null +++ b/coordinator/api/catalog/controller_fixture_test.go @@ -0,0 +1,29 @@ +package catalog + +import ( + "log/slog" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/readcache" +) + +// Catalog-only fixtures exercise the same controllers without starting unrelated +// API services. Live publication, middleware, and provider tests stay in api. +type testController struct { + *Controller + adminCredential string +} + +func newTestController(models ModelViews, st Store, logger *slog.Logger) *testController { + h := &testController{} + h.Controller = New(Dependencies{ + Store: func() Store { return st }, Models: models, + Cache: readcache.New(), Logger: logger, + AdminKey: func() string { return h.adminCredential }, + SelfRouteAccount: func(*http.Request) (string, bool) { return "", false }, + SyncCatalog: func() { h.Invalidate() }, + }) + return h +} + +func (h *testController) SetAdminKey(key string) { h.adminCredential = key } diff --git a/coordinator/api/catalog/fixtures_test.go b/coordinator/api/catalog/fixtures_test.go new file mode 100644 index 0000000000..6973d9ae91 --- /dev/null +++ b/coordinator/api/catalog/fixtures_test.go @@ -0,0 +1,83 @@ +package catalog + +import ( + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +const testHash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + +const ( + aliasFP8 = "mlx-community/gemma-4-26b-a4b-it-fp8" + aliasQAT = "mlx-community/gemma-4-26B-A4B-it-qat-4bit" +) + +func seedActiveModel(t *testing.T, st store.Store, modelID, displayName string) { + t.Helper() + entry := &store.ModelRegistryEntry{ + ID: modelID, DisplayName: displayName, Quantization: "4bit", + MaxContextLength: 131072, MaxOutputLength: 8192, MinRAMGB: 24, + Capabilities: []string{"chat"}, Status: "active", + } + files := []store.ModelVersionFile{{Path: "config.json", SizeBytes: 1, SHA256: testHash, Role: "config"}} + if err := st.SetModelVersion(entry, &store.ModelVersion{ + ModelID: modelID, Version: "v1", R2Prefix: ModelR2Prefix(modelID, "v1"), + AggregateSHA256: testHash, TotalSizeBytes: 1, FileCount: 1, Status: "ready", + }, files); err != nil { + t.Fatal(err) + } + if err := st.PromoteModelVersion(modelID, "v1"); err != nil { + t.Fatal(err) + } +} + +func validTestManifest() *store.ModelManifest { + files := []store.ManifestFile{{ + Path: "config.json", + SizeBytes: 123, + SHA256: testHash, + Role: "config", + }} + return &store.ModelManifest{ + SchemaVersion: 1, + ModelID: "mlx-community/test", + Version: "v1", + R2Prefix: ModelR2Prefix("mlx-community/test", "v1"), + AggregateSHA256: aggregateManifestFileHashes(files), + TotalSizeBytes: 123, + FileCount: 1, + Files: files, + CreatedAt: time.Now(), + } +} + +func containsStr(s []string, v string) bool { + for _, x := range s { + if x == v { + return true + } + } + return false +} + +type failingModelRegistryStore struct { + *store.MemoryStore + listErr error + keyErr error +} + +func (s *failingModelRegistryStore) ListActiveModelRegistryWithError() ([]store.ModelRegistryRecord, error) { + if s.listErr != nil { + return nil, s.listErr + } + return s.MemoryStore.ListActiveModelRegistryWithError() +} + +func (s *failingModelRegistryStore) FindPublishingAPIKeysWithError() ([]store.PublishingAPIKey, error) { + if s.keyErr != nil { + return nil, s.keyErr + } + return s.MemoryStore.FindPublishingAPIKeysWithError() +} diff --git a/coordinator/api/catalog/install_get.go b/coordinator/api/catalog/install_get.go new file mode 100644 index 0000000000..851012aa18 --- /dev/null +++ b/coordinator/api/catalog/install_get.go @@ -0,0 +1,61 @@ +package catalog + +import ( + "net/http" + "net/url" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" +) + +func (s *Controller) GetInstallModel(w http.ResponseWriter, r *http.Request) { + modelID, ok := parseModelCatalogPath(r.URL.Path) + if !ok || modelID == "" { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "model not found")) + return + } + rec, err := s.store().GetModelRegistryRecord(modelID) + if err != nil { + s.writeModelRegistryStoreError(w, "get model", err) + return + } + httpresponse.WriteJSON(w, http.StatusOK, catalogModelFromRegistryRecord(rec)) +} + +func (s *Controller) GetInstallManifest(w http.ResponseWriter, r *http.Request) { + modelID, ok := parseModelCatalogManifestPath(r.URL.Path) + if !ok || modelID == "" { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "model manifest not found")) + return + } + m, err := s.store().GetModelManifest(modelID) + if err != nil { + s.writeModelRegistryStoreError(w, "get manifest", err) + return + } + httpresponse.WriteJSON(w, http.StatusOK, m) +} + +func parseModelCatalogPath(p string) (string, bool) { + rest := strings.TrimPrefix(p, "/v1/models/catalog/") + if rest == p || rest == "" { + return "", false + } + modelID, err := url.PathUnescape(rest) + if err != nil { + return "", false + } + return modelID, true +} + +func parseModelCatalogManifestPath(p string) (string, bool) { + rest := strings.TrimPrefix(p, "/v1/models/catalog/manifest/") + if rest == p || rest == "" { + return "", false + } + modelID, err := url.PathUnescape(rest) + if err != nil { + return "", false + } + return modelID, true +} diff --git a/coordinator/api/catalog/install_list.go b/coordinator/api/catalog/install_list.go new file mode 100644 index 0000000000..5bc3bdff99 --- /dev/null +++ b/coordinator/api/catalog/install_list.go @@ -0,0 +1,66 @@ +package catalog + +import ( + "encoding/json" + "net/http" + "strconv" + "strings" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" +) + +// ListInstallCatalog handles GET /v1/models/catalog. +// Public endpoint — returns active models for providers and the install script. +// Cached for 60s — the underlying DB query is fast but this endpoint is hit +// by every provider heartbeat and install script poll. +func modelCatalogCacheKey(typeFilter string, includeAliases bool) string { + return "models:catalog:type=" + typeFilter + ":include_aliases=" + strconv.FormatBool(includeAliases) +} + +func (s *Controller) ListInstallCatalog(w http.ResponseWriter, r *http.Request) { + // Optional filter: ?type=text + typeFilter := strings.TrimSpace(strings.ToLower(r.URL.Query().Get("type"))) + if typeFilter != "" && typeFilter != "text" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "unsupported catalog type", httpresponse.WithParam("type"))) + return + } + includeAliases := r.URL.Query().Get("include_aliases") == "1" || strings.EqualFold(r.URL.Query().Get("include_aliases"), "true") + + cacheKey := modelCatalogCacheKey(typeFilter, includeAliases) + if cached, ok := s.readCache.Get(cacheKey); ok { + httpresponse.WriteCachedJSON(w, cached) + return + } + + registryRows, err := s.store().ListActiveModelRegistryWithError() + if err != nil { + s.logger.Error("model registry: failed to list active models", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to fetch model catalog")) + return + } + // The catalog is text-only today; an explicit non-text filter yields nothing. + models := make([]map[string]any, 0, len(registryRows)) + if typeFilter == "" || typeFilter == "text" { + for i := range registryRows { + models = append(models, catalogModelFromRegistryRecord(®istryRows[i])) + } + } + response := map[string]any{"models": models} + if includeAliases { + aliases, err := s.store().ListModelAliases() + if err != nil { + s.logger.Warn("model registry: failed to list aliases for catalog response", "error", err) + } else { + response["aliases"] = catalogAliasesForResponse(models, aliases) + } + } + + body, err := json.Marshal(response) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to marshal catalog")) + return + } + s.readCache.Set(cacheKey, body, time.Minute) + httpresponse.WriteCachedJSON(w, body) +} diff --git a/coordinator/api/catalog/install_records.go b/coordinator/api/catalog/install_records.go new file mode 100644 index 0000000000..3bbc4f1145 --- /dev/null +++ b/coordinator/api/catalog/install_records.go @@ -0,0 +1,124 @@ +package catalog + +import ( + "github.com/eigeninference/d-inference/coordinator/store" +) + +func catalogModelFromRegistryRecord(rec *store.ModelRegistryRecord) map[string]any { + supported := supportedModelFromRegistryRecord(rec) + version := rec.ActiveVersion + inputModalities, outputModalities := deriveModalities(supported.ModelType, rec.Capabilities) + model := map[string]any{ + "id": supported.ID, + "s3_name": supported.S3Name, + "display_name": supported.DisplayName, + "model_type": supported.ModelType, + "size_gb": supported.SizeGB, + "architecture": supported.Architecture, + "description": supported.Description, + "min_ram_gb": supported.MinRAMGB, + "active": supported.Active, + "weight_hash": supported.WeightHash, + "family": rec.Family, + "quantization": rec.Quantization, + "max_context_length": rec.MaxContextLength, + "max_output_length": rec.MaxOutputLength, + "capabilities": rec.Capabilities, + "required_provider_capabilities": append( + []string{}, rec.RequiredProviderCapabilities...), + "runtime_parameters": rec.RuntimeParameters, + "metadata": rec.Metadata, + "status": rec.Status, + + // OpenRouter-shaped fields (mirrors /v1/models) for UI consistency. + "name": supported.DisplayName, + "hugging_face_id": huggingFaceIDForModel(supported.ID, rec.Metadata), + "input_modalities": inputModalities, + "output_modalities": outputModalities, + "supported_features": supportedFeaturesFromCapabilities(rec.Capabilities), + "supported_sampling_parameters": defaultSamplingParameters(), + } + if !rec.CreatedAt.IsZero() { + model["created"] = rec.CreatedAt.Unix() + } + if version != nil { + if version.HuggingFaceArtifact != nil { + model["hugging_face_artifact"] = version.HuggingFaceArtifact + } + model["version"] = version.Version + model["r2_prefix"] = version.R2Prefix + model["aggregate_sha256"] = version.AggregateSHA256 + model["total_size_bytes"] = version.TotalSizeBytes + model["file_count"] = version.FileCount + } + return model +} + +func catalogAliasesForResponse(models []map[string]any, aliases []store.ModelAlias) []map[string]any { + catalogIDs := make(map[string]struct{}, len(models)) + for _, model := range models { + id, _ := model["id"].(string) + if id != "" { + catalogIDs[id] = struct{}{} + } + } + response := make([]map[string]any, 0, len(aliases)) + for _, alias := range aliases { + if !alias.Active || alias.DesiredBuild == "" { + continue + } + displayName := alias.DisplayName + if displayName == "" { + displayName = alias.AliasID + } + retiredBuilds := alias.RetiredBuilds + if retiredBuilds == nil { + retiredBuilds = []string{} + } + entry := map[string]any{ + "id": alias.AliasID, + "display_name": displayName, + "desired_build": alias.DesiredBuild, + "retired_builds": retiredBuilds, + } + if alias.PreviousBuild != "" { + entry["previous_build"] = alias.PreviousBuild + } + if _, ok := catalogIDs[alias.DesiredBuild]; ok { + entry["primary_build"] = alias.DesiredBuild + } else if alias.PreviousBuild != "" { + if _, ok := catalogIDs[alias.PreviousBuild]; ok { + entry["primary_build"] = alias.PreviousBuild + } + } + if entry["primary_build"] == nil { + continue + } + response = append(response, entry) + } + return response +} + +func supportedModelFromRegistryRecord(rec *store.ModelRegistryRecord) store.SupportedModel { + active := rec.Status == "active" || rec.Status == "beta" + model := store.SupportedModel{ + ID: rec.ID, + DisplayName: rec.DisplayName, + ModelType: "text", + Architecture: rec.Architecture, + Description: rec.Description, + MinRAMGB: rec.MinRAMGB, + Active: active, + RequiredProviderCapabilities: append( + []string{}, rec.RequiredProviderCapabilities...), + } + if rec.ActiveVersion != nil { + model.S3Name = rec.ActiveVersion.R2Prefix + model.SizeGB = float64(rec.ActiveVersion.TotalSizeBytes) / 1e9 + model.WeightHash = rec.ActiveVersion.AggregateSHA256 + model.Active = active && rec.ActiveVersion.Status == "ready" + } else { + model.Active = false + } + return model +} diff --git a/coordinator/api/catalog/install_records_test.go b/coordinator/api/catalog/install_records_test.go new file mode 100644 index 0000000000..d5e63915a1 --- /dev/null +++ b/coordinator/api/catalog/install_records_test.go @@ -0,0 +1,106 @@ +package catalog + +import ( + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestCatalogAliasesForResponse(t *testing.T) { + models := []map[string]any{ + {"id": "gemma-4-26b-qat-4bit"}, + {"id": "gemma-4-26b"}, + } + aliases := []store.ModelAlias{ + { + AliasID: "gemma-4-26b", + DisplayName: "Gemma 4 26B", + DesiredBuild: "gemma-4-26b-qat-4bit", + PreviousBuild: "gemma-4-26b", + RetiredBuilds: []string{"gemma-4-26b-old"}, + Active: true, + }, + {AliasID: "inactive", DesiredBuild: "missing", Active: false}, + } + + got := catalogAliasesForResponse(models, aliases) + if len(got) != 1 { + t.Fatalf("alias count = %d, want 1", len(got)) + } + alias := got[0] + if alias["id"] != "gemma-4-26b" || alias["display_name"] != "Gemma 4 26B" { + t.Fatalf("unexpected alias identity: %#v", alias) + } + if alias["desired_build"] != "gemma-4-26b-qat-4bit" || alias["previous_build"] != "gemma-4-26b" { + t.Fatalf("unexpected alias builds: %#v", alias) + } + if alias["primary_build"] != "gemma-4-26b-qat-4bit" { + t.Fatalf("primary_build = %v, want desired", alias["primary_build"]) + } + retired, ok := alias["retired_builds"].([]string) + if !ok || len(retired) != 1 || retired[0] != "gemma-4-26b-old" { + t.Fatalf("retired_builds = %#v", alias["retired_builds"]) + } +} + +func TestModelCatalogRejectsAliasCacheKeyCollisionType(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + srv := newTestController(registry.New(logger), st, logger) + seedActiveModel(t, st, aliasQAT, "Gemma 4 26B (qat-4bit)") + if err := st.UpsertModelAlias(&store.ModelAlias{ + AliasID: "gemma-4-26b", DisplayName: "Gemma 4 26B", Active: true, + DesiredBuild: aliasQAT, + }); err != nil { + t.Fatal(err) + } + + bad := httptest.NewRecorder() + srv.ListInstallCatalog(bad, httptest.NewRequest(http.MethodGet, "/v1/models/catalog?type=text:include_aliases=true", nil)) + if bad.Code != http.StatusBadRequest { + t.Fatalf("collision-shaped type status = %d, want 400 (body=%s)", bad.Code, bad.Body.String()) + } + + good := httptest.NewRecorder() + srv.ListInstallCatalog(good, httptest.NewRequest(http.MethodGet, "/v1/models/catalog?type=text&include_aliases=true", nil)) + if good.Code != http.StatusOK { + t.Fatalf("catalog status = %d body=%s", good.Code, good.Body.String()) + } + var resp struct { + Models []map[string]any `json:"models"` + Aliases []map[string]any `json:"aliases"` + } + if err := json.Unmarshal(good.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if len(resp.Models) != 1 || len(resp.Aliases) != 1 { + t.Fatalf("legitimate alias catalog was lost after rejected collision key: models=%#v aliases=%#v", resp.Models, resp.Aliases) + } +} + +func TestParseModelCatalogPathsDisambiguatesManifestSuffix(t *testing.T) { + modelID, ok := parseModelCatalogPath("/v1/models/catalog/org/manifest") + if !ok || modelID != "org/manifest" { + t.Fatalf("expected catalog item path to preserve /manifest model id, got %q ok=%v", modelID, ok) + } + manifestID, ok := parseModelCatalogManifestPath("/v1/models/catalog/manifest/org%2Fmanifest") + if !ok || manifestID != "org/manifest" { + t.Fatalf("expected manifest route to decode model id, got %q ok=%v", manifestID, ok) + } +} + +func TestModelRegistryNotFoundClassification(t *testing.T) { + if !isModelRegistryNotFound(fmt.Errorf("model %q not found", "x")) { + t.Fatal("expected not found error to classify as not found") + } + if isModelRegistryNotFound(fmt.Errorf("store: get model registry record: connection refused")) { + t.Fatal("expected DB error not to classify as not found") + } +} diff --git a/coordinator/api/catalog/invalidate.go b/coordinator/api/catalog/invalidate.go new file mode 100644 index 0000000000..f20616f0a3 --- /dev/null +++ b/coordinator/api/catalog/invalidate.go @@ -0,0 +1,26 @@ +package catalog + +// Invalidate removes all cached model catalog responses so the +// next request picks up any changes made by admin endpoints. +func (s *Controller) Invalidate() { + if s.readCache == nil { + return + } + for _, typeFilter := range []string{"", "text"} { + for _, includeAliases := range []bool{false, true} { + s.readCache.Invalidate(modelCatalogCacheKey(typeFilter, includeAliases)) + } + } + // /v1/models entry memo + list bodies (both include_builds values) and the + // OpenRouter feed are derived from the same catalog; drop them too so an + // admin alias/registry change is visible on the next request instead of + // after their 2s/5s TTLs (which remain the bound for out-of-band DB edits). + for _, includeBuilds := range []bool{false, true} { + s.readCache.Invalidate(modelEntriesCacheKey(includeBuilds)) + s.readCache.Invalidate(modelListBodyCacheKey(includeBuilds)) + } + s.readCache.Invalidate(openRouterFeedCacheKey) + // stats:v1 is deliberately NOT evicted here: the stats refresher recomputes + // it every minute, and evicting it made every concurrent /v1/stats request + // rerun the multi-second usage analytics statements. +} diff --git a/coordinator/api/catalog/manifest_fetch.go b/coordinator/api/catalog/manifest_fetch.go new file mode 100644 index 0000000000..87dbd34f86 --- /dev/null +++ b/coordinator/api/catalog/manifest_fetch.go @@ -0,0 +1,122 @@ +package catalog + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "sync" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +const defaultModelRegistryCDNBaseURL = "https://models.darkbloom.ai" + +func fetchModelManifest(ctx context.Context, baseURL, r2Prefix string) (*store.ModelManifest, error) { + manifestURL, err := url.JoinPath(baseURL, r2Prefix, "manifest.json") + if err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, manifestURL, nil) + if err != nil { + return nil, err + } + client := &http.Client{Timeout: 30 * time.Second} + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, fmt.Errorf("manifest GET returned %s", resp.Status) + } + body, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20)) + if err != nil { + return nil, err + } + var manifest store.ModelManifest + if err := json.Unmarshal(body, &manifest); err != nil { + return nil, err + } + return &manifest, nil +} + +func verifyManifestFiles(ctx context.Context, baseURL string, manifest *store.ModelManifest, logger interface{ Warn(string, ...any) }) error { + client := &http.Client{Timeout: 30 * time.Second} + errCh := make(chan error, len(manifest.Files)) + fileCh := make(chan store.ManifestFile) + var wg sync.WaitGroup + workers := 8 + if len(manifest.Files) < workers { + workers = len(manifest.Files) + } + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for file := range fileCh { + if err := verifyManifestFileHEAD(ctx, client, baseURL, manifest.R2Prefix, file, logger); err != nil { + errCh <- err + } + } + }() + } + for _, file := range manifest.Files { + select { + case fileCh <- file: + case <-ctx.Done(): + close(fileCh) + wg.Wait() + close(errCh) + return ctx.Err() + } + } + close(fileCh) + wg.Wait() + close(errCh) + for err := range errCh { + if err != nil { + return err + } + } + return nil +} + +func verifyManifestFileHEAD(ctx context.Context, client *http.Client, baseURL, r2Prefix string, file store.ManifestFile, logger interface{ Warn(string, ...any) }) error { + fileURL, err := url.JoinPath(baseURL, r2Prefix, file.Path) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodHead, fileURL, nil) + if err != nil { + return err + } + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("HEAD %s: %w", file.Path, err) + } + resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("HEAD %s returned %s", file.Path, resp.Status) + } + if resp.ContentLength >= 0 && resp.ContentLength != file.SizeBytes { + return fmt.Errorf("HEAD %s content length %d != manifest size %d", file.Path, resp.ContentLength, file.SizeBytes) + } + if resp.ContentLength < 0 && logger != nil { + logger.Warn("model registry: HEAD missing Content-Length", "path", file.Path) + } + return nil +} + +func registryCDNBaseURL() string { + base := strings.TrimRight(strings.TrimSpace(os.Getenv("MODEL_REGISTRY_CDN_BASE_URL")), "/") + if base == "" { + return defaultModelRegistryCDNBaseURL + } + return base +} diff --git a/coordinator/api/catalog/manifest_paths.go b/coordinator/api/catalog/manifest_paths.go new file mode 100644 index 0000000000..1e1c4865c8 --- /dev/null +++ b/coordinator/api/catalog/manifest_paths.go @@ -0,0 +1,52 @@ +package catalog + +import ( + "crypto/sha256" + "encoding/hex" + "strings" +) + +func containsTraversal(value string) bool { + return strings.Contains(value, "..") +} + +func validRegistryIdentifier(value string, allowSlash bool) bool { + if value == "" || strings.HasPrefix(value, "/") || containsTraversal(value) { + return false + } + for _, r := range value { + if r >= '0' && r <= '9' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r == '.' || r == '_' || r == '-' { + continue + } + if allowSlash && r == '/' { + continue + } + return false + } + return true +} + +func ModelR2Prefix(modelID, version string) string { + return "v2/" + readableModelSlug(modelID) + "/" + version +} + +func readableModelSlug(modelID string) string { + var b strings.Builder + b.Grow(len(modelID) + 14) + for _, r := range modelID { + switch { + case r >= '0' && r <= '9', r >= 'A' && r <= 'Z', r >= 'a' && r <= 'z', r == '.', r == '_', r == '-': + b.WriteRune(r) + case r == '/': + b.WriteByte('-') + default: + b.WriteByte('-') + } + } + slug := strings.Trim(b.String(), "-") + if slug == "" { + slug = "model" + } + sum := sha256.Sum256([]byte(modelID)) + return slug + "--" + hex.EncodeToString(sum[:])[:12] +} diff --git a/coordinator/api/catalog/manifest_validation.go b/coordinator/api/catalog/manifest_validation.go new file mode 100644 index 0000000000..3304b42e9b --- /dev/null +++ b/coordinator/api/catalog/manifest_validation.go @@ -0,0 +1,106 @@ +package catalog + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "sort" + "strings" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func validateModelManifest(manifest *store.ModelManifest, modelID, version, r2Prefix string) error { + if manifest == nil { + return fmt.Errorf("manifest is empty") + } + if manifest.SchemaVersion != 1 { + return fmt.Errorf("unsupported manifest schema_version %d", manifest.SchemaVersion) + } + if manifest.ModelID != modelID || manifest.Version != version || manifest.R2Prefix != r2Prefix { + return fmt.Errorf("manifest fields do not match registration request") + } + if !isLowerSHA256Hex(manifest.AggregateSHA256) { + return fmt.Errorf("manifest aggregate_sha256 must be 64 lowercase hex characters") + } + if manifest.TotalSizeBytes < 0 { + return fmt.Errorf("manifest total_size_bytes must be nonnegative") + } + if manifest.FileCount != len(manifest.Files) { + return fmt.Errorf("manifest file_count does not match files length") + } + if len(manifest.Files) == 0 { + return fmt.Errorf("manifest must contain at least one file") + } + var totalSize int64 + seenPaths := make(map[string]bool, len(manifest.Files)) + for _, file := range manifest.Files { + if err := validateManifestFile(file); err != nil { + return err + } + pathKey := strings.ToLower(file.Path) + if seenPaths[pathKey] { + return fmt.Errorf("manifest file path %q is duplicated", file.Path) + } + seenPaths[pathKey] = true + totalSize += file.SizeBytes + } + if totalSize != manifest.TotalSizeBytes { + return fmt.Errorf("manifest total_size_bytes does not match files sum") + } + if aggregate := aggregateManifestFileHashes(manifest.Files); aggregate != manifest.AggregateSHA256 { + return fmt.Errorf("manifest aggregate_sha256 does not match file hashes") + } + return nil +} + +func aggregateManifestFileHashes(files []store.ManifestFile) string { + sorted := append([]store.ManifestFile(nil), files...) + sort.Slice(sorted, func(i, j int) bool { return sorted[i].Path < sorted[j].Path }) + h := sha256.New() + for _, file := range sorted { + digest, err := hex.DecodeString(file.SHA256) + if err != nil || len(digest) != sha256.Size { + return "" + } + h.Write(digest) + } + return hex.EncodeToString(h.Sum(nil)) +} + +func validateManifestFile(file store.ManifestFile) error { + if !validManifestRelativePath(file.Path) { + return fmt.Errorf("manifest file path %q is invalid", file.Path) + } + if file.SizeBytes < 0 { + return fmt.Errorf("manifest file %q size_bytes must be nonnegative", file.Path) + } + if !isLowerSHA256Hex(file.SHA256) { + return fmt.Errorf("manifest file %q sha256 must be 64 lowercase hex characters", file.Path) + } + return nil +} + +func validManifestRelativePath(path string) bool { + if path == "" || strings.HasPrefix(path, "/") || strings.Contains(path, "\\") { + return false + } + for _, part := range strings.Split(path, "/") { + if part == "" || part == "." || part == ".." { + return false + } + } + return true +} + +func isLowerSHA256Hex(value string) bool { + if len(value) != 64 { + return false + } + for _, r := range value { + if !(r >= '0' && r <= '9') && !(r >= 'a' && r <= 'f') { + return false + } + } + return true +} diff --git a/coordinator/api/catalog/manifest_validation_test.go b/coordinator/api/catalog/manifest_validation_test.go new file mode 100644 index 0000000000..2f088dc795 --- /dev/null +++ b/coordinator/api/catalog/manifest_validation_test.go @@ -0,0 +1,111 @@ +package catalog + +import ( + "testing" +) + +func TestValidateModelManifestRejectsTraversalAndBadHashes(t *testing.T) { + prefix := ModelR2Prefix("mlx-community/test", "v1") + manifest := validTestManifest() + manifest.Files[0].Path = "weights/../config.json" + if err := validateModelManifest(manifest, "mlx-community/test", "v1", prefix); err == nil { + t.Fatal("expected traversal path to be rejected") + } + + manifest = validTestManifest() + manifest.AggregateSHA256 = "ABC" + if err := validateModelManifest(manifest, "mlx-community/test", "v1", prefix); err == nil { + t.Fatal("expected bad aggregate hash to be rejected") + } + + manifest = validTestManifest() + manifest.AggregateSHA256 = testHash + if err := validateModelManifest(manifest, "mlx-community/test", "v1", prefix); err == nil { + t.Fatal("expected mismatched aggregate hash to be rejected") + } + + manifest = validTestManifest() + manifest.Files[0].SHA256 = "bbbb" + if err := validateModelManifest(manifest, "mlx-community/test", "v1", prefix); err == nil { + t.Fatal("expected bad file hash to be rejected") + } + + manifest = validTestManifest() + manifest.TotalSizeBytes = 999 + if err := validateModelManifest(manifest, "mlx-community/test", "v1", prefix); err == nil { + t.Fatal("expected mismatched total_size_bytes to be rejected") + } + + manifest = validTestManifest() + manifest.Files = nil + manifest.FileCount = 0 + manifest.TotalSizeBytes = 0 + if err := validateModelManifest(manifest, "mlx-community/test", "v1", prefix); err == nil { + t.Fatal("expected empty manifest to be rejected") + } + + manifest = validTestManifest() + manifest.Files = append(manifest.Files, manifest.Files[0]) + manifest.FileCount = 2 + manifest.TotalSizeBytes = 246 + if err := validateModelManifest(manifest, "mlx-community/test", "v1", prefix); err == nil { + t.Fatal("expected duplicate manifest paths to be rejected") + } + + manifest = validTestManifest() + caseCollidingFile := manifest.Files[0] + caseCollidingFile.Path = "Config.json" + manifest.Files = append(manifest.Files, caseCollidingFile) + manifest.FileCount = 2 + manifest.TotalSizeBytes = 246 + if err := validateModelManifest(manifest, "mlx-community/test", "v1", prefix); err == nil { + t.Fatal("expected case-colliding manifest paths to be rejected") + } + + for _, badPath := range []string{"a//b", "./x", "x/.", "x/../y"} { + manifest = validTestManifest() + manifest.Files[0].Path = badPath + if err := validateModelManifest(manifest, "mlx-community/test", "v1", prefix); err == nil { + t.Fatalf("expected path %q to be rejected", badPath) + } + } +} + +func TestRegisterValidationAndR2Prefix(t *testing.T) { + for _, req := range []registerModelRequest{ + {ModelID: "bad id", Version: "v1"}, + {ModelID: "../bad", Version: "v1"}, + {ModelID: "ok/model", Version: "bad/version"}, + {ModelID: "ok/model", Version: "bad..version"}, + {ModelID: "ok/model", Version: "v1", Quantization: "", MaxContextLength: 1, MaxOutputLength: 1, MinRAMGB: 1}, + {ModelID: "ok/model", Version: "v1", Quantization: "8bit", MaxContextLength: 0, MaxOutputLength: 1, MinRAMGB: 1}, + {ModelID: "ok/model", Version: "v1", Quantization: "8bit", MaxContextLength: 1, MaxOutputLength: 0, MinRAMGB: 1}, + {ModelID: "ok/model", Version: "v1", Quantization: "8bit", MaxContextLength: 1, MaxOutputLength: 1, MinRAMGB: 0}, + } { + if err := validateRegisterModelRequest(req); err == nil { + t.Fatalf("expected invalid request to fail: %#v", req) + } + } + // Verify missing pricing is rejected. + if err := validateRegisterModelRequest(registerModelRequest{ModelID: "ok/model", Version: "v1", Quantization: "8bit", MaxContextLength: 1, MaxOutputLength: 1, MinRAMGB: 1, InputPrice: 0, OutputPrice: 100}); err == nil { + t.Fatal("expected missing input_price to fail") + } + if err := validateRegisterModelRequest(registerModelRequest{ModelID: "ok/model", Version: "v1", Quantization: "8bit", MaxContextLength: 1, MaxOutputLength: 1, MinRAMGB: 1, InputPrice: 100, OutputPrice: 0}); err == nil { + t.Fatal("expected missing output_price to fail") + } + if err := validateRegisterModelRequest(registerModelRequest{ModelID: "mlx-community/gemma-4-26b-a4b-it-8bit", Version: "2026-05-23-r1", Quantization: "8bit", MaxContextLength: 32768, MaxOutputLength: 8192, MinRAMGB: 36, InputPrice: 30000, OutputPrice: 165000}); err != nil { + t.Fatalf("expected valid request: %v", err) + } + if ModelR2Prefix("foo/bar", "v1") == ModelR2Prefix("foo__bar", "v1") { + t.Fatal("modelR2Prefix must not collide for slash vs underscore model IDs") + } + if got := ModelR2Prefix("mlx-community/openai-gpt-oss-20b", "2026-05-23-r1"); got != "v2/mlx-community-openai-gpt-oss-20b--8f458c9d97d4/2026-05-23-r1" { + t.Fatalf("unexpected human-readable R2 prefix: %s", got) + } + if got := ModelR2Prefix("foo/bar", "v1"); got != "v2/foo-bar--cc5d46bdb499/v1" { + t.Fatalf("unexpected slash slug prefix: %s", got) + } + if got := ModelR2Prefix("foo__bar", "v1"); got != "v2/foo__bar--a3a759156e88/v1" { + t.Fatalf("unexpected underscore slug prefix: %s", got) + } +} diff --git a/coordinator/api/catalog/marketplace_alias_entries.go b/coordinator/api/catalog/marketplace_alias_entries.go new file mode 100644 index 0000000000..b72d3a14a8 --- /dev/null +++ b/coordinator/api/catalog/marketplace_alias_entries.go @@ -0,0 +1,147 @@ +package catalog + +import ( + "sort" + + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// openRouterAliasEntries builds the OpenRouter feed entries for public model +// aliases and the set of member build ids to hide from the raw listing — +// mirroring aliasModelEntries on /v1/models. The entry's identity (id, slug) +// is the ALIAS so the marketplace listing is stable across build migrations; +// per-build fields (pricing, context, readiness) come from the alias's primary +// build (the desired build when in catalog, else the previous build). +// HuggingFaceID stays the primary build's configured HF path — OpenRouter +// ingests it for model metadata, and a fabricated path would break that; the +// routing name consumers send/receive is still only ever the alias. +func (s *Controller) openRouterAliasEntries( + catalogByID map[string]store.SupportedModel, + registryByID map[string]store.ModelRegistryEntry, + aggTypeByID map[string]string, +) ([]types.OpenRouterModel, map[string]struct{}, error) { + hidden := make(map[string]struct{}) + aliases, err := s.store().ListModelAliases() + if err != nil { + return nil, nil, err + } + sort.Slice(aliases, func(i, j int) bool { return aliases[i].AliasID < aliases[j].AliasID }) + + entries := make([]types.OpenRouterModel, 0, len(aliases)) + standardEntries := make(map[string]types.OpenRouterModel, len(aliases)) + openRouterAliases := make([]store.ModelAlias, 0) + for _, a := range aliases { + if !a.Active { + continue + } + if a.OpenRouterOnly { + openRouterAliases = append(openRouterAliases, a) + continue + } + if a.DesiredBuild == "" { + continue + } + // Never sell a raw build behind a public alias: hide EVERY build the + // alias references — desired, previous, AND the retired lineage — from + // the marketplace feed, even if the alias itself isn't listable right now. + hideAliasBuild(hidden, catalogByID, a.DesiredBuild) + hideAliasBuild(hidden, catalogByID, a.PreviousBuild) + for _, b := range a.RetiredBuilds { + hideAliasBuild(hidden, catalogByID, b) + } + members := make([]string, 0, 2) + if _, ok := catalogByID[a.DesiredBuild]; ok { + members = append(members, a.DesiredBuild) + } + if a.PreviousBuild != "" { + if _, ok := catalogByID[a.PreviousBuild]; ok { + members = append(members, a.PreviousBuild) + } + } + if len(members) == 0 { + continue + } + primary := members[0] + + cm := catalogByID[primary] + modelType := cm.ModelType + if at, ok := aggTypeByID[primary]; ok { + modelType = at + } + if isNonTextModelType(modelType) { + continue + } + + reg, hasReg := registryByID[primary] + var capabilities []string + if hasReg { + capabilities = reg.Capabilities + } + inputModalities, outputModalities := deriveModalities(modelType, capabilities) + displayName := a.DisplayName + if displayName == "" { + displayName = openRouterModelName(cm, reg, hasReg, a.AliasID) + } + entry := types.OpenRouterModel{ + ID: a.AliasID, + HuggingFaceID: huggingFaceIDForModel(primary, reg.Metadata), + Name: displayName, + InputModalities: inputModalities, + OutputModalities: outputModalities, + SupportedFeatures: []string{}, + IsReady: true, + } + s.openRouterModelFieldsFor(primary, "", reg, hasReg).applyToFeed(&entry) + if hasReg { + entry.IsReady = openRouterIsReady(reg.Metadata) + entry.OpenRouter = &types.OpenRouterSlug{Slug: openRouterSlug(a.AliasID, reg.Metadata)} + } else { + entry.OpenRouter = &types.OpenRouterSlug{Slug: openRouterSlug(a.AliasID, nil)} + } + entry.Datacenters = s.aliasDatacenters(members) + entries = append(entries, entry) + standardEntries[a.AliasID] = entry + } + + // OpenRouter-only aliases clone the complete source entry, then replace only + // the three configured identities. Persisted source kind prevents a later + // standard-alias mutation from changing concrete-source routing or feeds. + for _, a := range openRouterAliases { + var source types.OpenRouterModel + var ok bool + if AliasUsesConcreteSource(a) { + source, ok = s.openRouterEntryForConcrete(a.SourceModel, catalogByID, registryByID, aggTypeByID) + } else { + source, ok = standardEntries[a.SourceModel] + } + if !ok || a.OpenRouterSlug == "" || a.HuggingFaceID == "" { + s.logger.Warn("OpenRouter alias source or identities unavailable", "alias_id", a.AliasID, "source_model", a.SourceModel) + continue + } + clone := source + clone.ID = a.AliasID + clone.HuggingFaceID = a.HuggingFaceID + clone.OpenRouter = &types.OpenRouterSlug{Slug: a.OpenRouterSlug} + entries = append(entries, clone) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].ID < entries[j].ID }) + return entries, hidden, nil +} + +// aliasDatacenters unions the datacenter country codes across an alias's member +// builds (providers may be mid-migration, serving either build). +func (s *Controller) aliasDatacenters(members []string) []types.OpenRouterDatacenter { + seen := make(map[string]struct{}) + var dcs []types.OpenRouterDatacenter + for _, m := range members { + for _, dc := range s.modelDatacenters(m) { + if _, dup := seen[dc.CountryCode]; dup { + continue + } + seen[dc.CountryCode] = struct{}{} + dcs = append(dcs, dc) + } + } + return dcs +} diff --git a/coordinator/api/catalog/marketplace_aliases.go b/coordinator/api/catalog/marketplace_aliases.go new file mode 100644 index 0000000000..acdb64661d --- /dev/null +++ b/coordinator/api/catalog/marketplace_aliases.go @@ -0,0 +1,187 @@ +package catalog + +import ( + "encoding/json" + "errors" + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// openRouterAliasUpsertRequest configures one OpenRouter-only clone of an +// existing standard alias or concrete catalog model. OpenRouter sends ID to the +// inference API; SourceModel supplies every non-identity feed field and routing. +type openRouterAliasUpsertRequest struct { + ID string `json:"id"` + SourceModel string `json:"source_model"` + OpenRouterSlug string `json:"openrouter_slug"` + HuggingFaceID string `json:"hugging_face_id"` + Active *bool `json:"active"` +} + +// UpsertOpenRouterAlias creates or replaces an OpenRouter-only alias. +// POST /v1/admin/models/openrouter-aliases. +func (s *Controller) UpsertOpenRouterAlias(w http.ResponseWriter, r *http.Request) { + if _, ok := s.requirePublishingAPIKey(w, r); !ok { + return + } + + var req openRouterAliasUpsertRequest + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + if err := dec.Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + req.ID = strings.TrimSpace(req.ID) + req.SourceModel = strings.TrimSpace(req.SourceModel) + req.OpenRouterSlug = strings.TrimSpace(req.OpenRouterSlug) + req.HuggingFaceID = strings.TrimSpace(req.HuggingFaceID) + + switch { + case req.ID == "": + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "id is required", httpresponse.WithParam("id"))) + return + case len(req.ID) > maxAliasIDLength || !validRegistryIdentifier(req.ID, false): + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "id may only contain letters, digits, '.', '_' and '-' (max 128 chars)", httpresponse.WithParam("id"))) + return + case req.SourceModel == "": + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "source_model is required", httpresponse.WithParam("source_model"))) + return + case req.SourceModel == req.ID: + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "source_model cannot equal id", httpresponse.WithParam("source_model"))) + return + case req.OpenRouterSlug == "": + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "openrouter_slug is required", httpresponse.WithParam("openrouter_slug"))) + return + case req.HuggingFaceID == "": + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "hugging_face_id is required", httpresponse.WithParam("hugging_face_id"))) + return + } + s.modelAliasMutationMu.Lock() + defer s.modelAliasMutationMu.Unlock() + + sourceKind := store.ModelAliasSourceAlias + source, found, err := s.store().GetModelAlias(req.SourceModel) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to get source model")) + return + } + sourceAvailable := found && !source.OpenRouterOnly && source.Active && source.DesiredBuild != "" + if !sourceAvailable { + sourceKind = store.ModelAliasSourceConcrete + catalogByID, _, catalogErr := s.activeCatalogLookups() + if catalogErr != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to get source model")) + return + } + _, concreteFound := catalogByID[req.SourceModel] + if concreteFound && !concreteModelEligibleForOpenRouterFeed(req.SourceModel, catalogByID, s.openRouterAggregateTypeByID()) { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "concrete source_model is not eligible for the OpenRouter text feed", httpresponse.WithParam("source_model"))) + return + } + sourceAvailable = concreteFound + if sourceAvailable { + aliases, listErr := s.store().ListModelAliases() + if listErr != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to validate source model")) + return + } + if coveringAlias, covered := standardAliasCoveringBuild(aliases, req.SourceModel); covered { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("invalid_request_error", "concrete source_model is covered by standard alias "+coveringAlias+"; use that alias as source_model", httpresponse.WithParam("source_model"))) + return + } + } + } + if !sourceAvailable { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "source_model must be an active standard alias or concrete catalog model", httpresponse.WithParam("source_model"))) + return + } + if rec, err := s.store().GetModelRegistryRecord(req.ID); err != nil && !errors.Is(err, store.ErrNotFound) { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to check model namespace")) + return + } else if rec != nil { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("invalid_request_error", "id collides with an existing model id", httpresponse.WithParam("id"))) + return + } + if existing, exists, err := s.store().GetModelAlias(req.ID); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to get alias")) + return + } else if exists && !existing.OpenRouterOnly { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("invalid_request_error", "id collides with an existing standard alias", httpresponse.WithParam("id"))) + return + } + + active := true + if req.Active != nil { + active = *req.Active + } + alias := &store.ModelAlias{ + AliasID: req.ID, + OpenRouterOnly: true, + SourceModel: req.SourceModel, + SourceKind: sourceKind, + OpenRouterSlug: req.OpenRouterSlug, + HuggingFaceID: req.HuggingFaceID, + Active: active, + } + if err := s.store().UpsertModelAlias(alias); err != nil { + s.logger.Error("upsert OpenRouter alias failed", "alias_id", req.ID, "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to save OpenRouter alias")) + return + } + s.syncCatalog() + + saved, _, _ := s.store().GetModelAlias(req.ID) + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"status": "ok", "alias": saved}) +} + +// ListOpenRouterAliases lists only OpenRouter feed aliases. +// GET /v1/admin/models/openrouter-aliases. +func (s *Controller) ListOpenRouterAliases(w http.ResponseWriter, r *http.Request) { + if _, ok := s.requirePublishingAPIKey(w, r); !ok { + return + } + aliases, err := s.store().ListModelAliases() + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to list OpenRouter aliases")) + return + } + out := aliases[:0] + for _, alias := range aliases { + if alias.OpenRouterOnly { + out = append(out, alias) + } + } + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"aliases": out}) +} + +// DeleteOpenRouterAlias removes one OpenRouter feed alias. +// DELETE /v1/admin/models/openrouter-aliases/{aliasID}. +func (s *Controller) DeleteOpenRouterAlias(w http.ResponseWriter, r *http.Request) { + if _, ok := s.requirePublishingAPIKey(w, r); !ok { + return + } + aliasID := strings.TrimSpace(r.PathValue("aliasID")) + if aliasID == "" { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "alias id is required")) + return + } + alias, found, err := s.store().GetModelAlias(aliasID) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to get OpenRouter alias")) + return + } + if !found || !alias.OpenRouterOnly { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("invalid_request_error", "OpenRouter alias not found")) + return + } + if err := s.store().DeleteModelAlias(aliasID); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to delete OpenRouter alias")) + return + } + s.syncCatalog() + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"status": "deleted", "id": aliasID}) +} diff --git a/coordinator/api/catalog/marketplace_feed.go b/coordinator/api/catalog/marketplace_feed.go new file mode 100644 index 0000000000..625ac03552 --- /dev/null +++ b/coordinator/api/catalog/marketplace_feed.go @@ -0,0 +1,97 @@ +package catalog + +import ( + "net/http" + "sort" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/api/types" +) + +// ListOpenRouterModels handles GET /v1/models/openrouter. +// +// It emits the pure OpenRouter provider "List Models" schema (no Darkbloom +// metadata block) for the models we want OpenRouter to sell. +// +// The feed is driven by the active CATALOG, not by live provider availability: +// a registered model stays listed even when no provider is momentarily +// online/warm for it. That matches OpenRouter's model, where transient capacity +// is handled by 429s and launch state by the is_ready flag — a provider restart +// must not make the model vanish from the marketplace. Live provider data is +// used only as supplemental signal (datacenters, and excluding a model whose +// providers report a non-text aggregate type). +// +// The feed is the same for every caller and is polled by OpenRouter, so the +// serialized response is served from the read cache for openRouterFeedCacheTTL. +func (s *Controller) ListOpenRouterModels(w http.ResponseWriter, r *http.Request) { + if body, ok := s.readCacheGet(openRouterFeedCacheKey); ok { + httpresponse.WriteCachedJSON(w, body) + return + } + generation := s.readCacheGeneration() + data, err := s.openRouterFeedEntries() + if err != nil { + s.logger.Error("openrouter models: failed to list active models", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to list models")) + return + } + body, err := httpresponse.EncodeCachedJSON(types.OpenRouterModelsResponse{Data: data}) + if err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to encode models")) + return + } + s.readCacheSetIfCurrent(openRouterFeedCacheKey, body, openRouterFeedCacheTTL, generation) + httpresponse.WriteCachedJSON(w, body) +} + +// openRouterFeedCacheTTL bounds staleness of the marketplace feed. The feed is +// catalog-driven (DB), with live providers contributing only datacenters and +// non-text exclusions. Catalog sync invalidates the feed immediately and +// rejects any stale publication from an in-flight pre-sync read. +const openRouterFeedCacheTTL = 5 * time.Second + +const openRouterFeedCacheKey = "models:openrouter:v1" + +// openRouterFeedEntries assembles the feed: public aliases first, then the +// active concrete catalog models not hidden behind an alias, in stable order. +func (s *Controller) openRouterFeedEntries() ([]types.OpenRouterModel, error) { + catalogByID, registryByID, err := s.activeCatalogLookups() + if err != nil { + return nil, err + } + + // Provider-reported model types override the catalog's text fallback so + // known non-text models never enter the OpenRouter provider feed. + aggTypeByID := s.openRouterAggregateTypeByID() + + // Public aliases get the same treatment as /v1/models: the alias is the + // purchasable entry and its member builds are hidden, so the marketplace + // never lists a raw quant build that a migration will later retire (a + // retired build would otherwise stay listed and black-hole requests). + aliasEntries, hiddenBuilds, err := s.openRouterAliasEntries(catalogByID, registryByID, aggTypeByID) + if err != nil { + return nil, err + } + + // Stable output order. + ids := make([]string, 0, len(catalogByID)) + for id := range catalogByID { + ids = append(ids, id) + } + sort.Strings(ids) + + data := make([]types.OpenRouterModel, 0, len(ids)+len(aliasEntries)) + data = append(data, aliasEntries...) + for _, id := range ids { + if _, hidden := hiddenBuilds[id]; hidden { + continue + } + entry, ok := s.openRouterEntryForConcrete(id, catalogByID, registryByID, aggTypeByID) + if !ok { + continue + } + data = append(data, entry) + } + return data, nil +} diff --git a/coordinator/api/catalog/marketplace_feed_test.go b/coordinator/api/catalog/marketplace_feed_test.go new file mode 100644 index 0000000000..09da5ea6c8 --- /dev/null +++ b/coordinator/api/catalog/marketplace_feed_test.go @@ -0,0 +1,201 @@ +package catalog + +import ( + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// The feed is catalog-driven: an active model stays listed even when NO provider +// is currently online for it (transient capacity is OpenRouter's concern via +// 429s, not a reason to delist). Datacenters are empty in that case. +func TestOpenRouterFeedSurvivesProviderOutage(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{AdminKey: "test-key"}) + reg := registry.New(logger) + srv := newTestController(reg, st, logger) + + const modelID = "mlx-community/orphan-model" + entry := &store.ModelRegistryEntry{ + ID: modelID, DisplayName: "Orphan", Quantization: "4bit", + MaxContextLength: 8192, MaxOutputLength: 2048, MinRAMGB: 8, Status: "active", + Capabilities: []string{"tools"}, + } + files := []store.ModelVersionFile{{Path: "config.json", SizeBytes: 1, SHA256: testHash, Role: "config"}} + if err := st.SetModelVersion(entry, &store.ModelVersion{ModelID: modelID, Version: "v1", R2Prefix: ModelR2Prefix(modelID, "v1"), AggregateSHA256: testHash, TotalSizeBytes: 1, FileCount: 1, Status: "ready"}, files); err != nil { + t.Fatal(err) + } + if err := st.PromoteModelVersion(modelID, "v1"); err != nil { + t.Fatal(err) + } + srv.Invalidate() + // Note: NO provider connected. registry.ListModels() is empty. + + rec := httptest.NewRecorder() + srv.ListOpenRouterModels(rec, httptest.NewRequest(http.MethodGet, "/v1/models/openrouter", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d body = %s", rec.Code, rec.Body.String()) + } + var resp types.OpenRouterModelsResponse + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + var found *types.OpenRouterModel + for i := range resp.Data { + if resp.Data[i].ID == modelID { + found = &resp.Data[i] + break + } + } + if found == nil { + t.Fatalf("active model must remain in the feed with no provider online: %s", rec.Body.String()) + } + if !found.IsReady { + t.Error("active model should be is_ready even with no provider") + } + if len(found.Datacenters) != 0 { + t.Errorf("datacenters should be empty with no provider, got %v", found.Datacenters) + } + if found.ContextLength != 8192 || !containsStr(found.SupportedFeatures, "tools") { + t.Errorf("registry-derived fields missing: ctx=%d feats=%v", found.ContextLength, found.SupportedFeatures) + } +} + +// Public aliases get the /v1/models treatment in the OpenRouter feed too: the +// alias is the purchasable entry, member builds are hidden, and the marketplace +// never sees a raw quant build that a migration will later retire. +func TestOpenRouterModelsAliasEntriesHideBuilds(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + reg := registry.New(logger) + srv := newTestController(reg, st, logger) + + seedActiveModel(t, st, aliasFP8, "Gemma 4 26B fp8") + seedActiveModel(t, st, aliasQAT, "Gemma 4 26B qat") + const aliasHuggingFaceID = "google/gemma-4-26b-it" + primaryRecord, err := st.GetModelRegistryRecord(aliasQAT) + if err != nil { + t.Fatal(err) + } + primaryEntry := registryEntryFromRecord(primaryRecord) + primaryEntry.Metadata = map[string]any{huggingFaceIDMetadataKey: aliasHuggingFaceID} + if err := st.UpsertModelRegistryEntry(primaryEntry); err != nil { + t.Fatal(err) + } + seedActiveModel(t, st, "mlx-community/unrelated-9b", "Unrelated 9B") + if err := st.UpsertModelAlias(&store.ModelAlias{ + AliasID: "gemma-4-26b", DisplayName: "Gemma 4 26B", Active: true, + DesiredBuild: aliasQAT, PreviousBuild: aliasFP8, + }); err != nil { + t.Fatal(err) + } + srv.Invalidate() + + rec := httptest.NewRecorder() + srv.ListOpenRouterModels(rec, httptest.NewRequest(http.MethodGet, "/v1/models/openrouter", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d body = %s", rec.Code, rec.Body.String()) + } + var resp types.OpenRouterModelsResponse + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + + byID := make(map[string]types.OpenRouterModel, len(resp.Data)) + for _, m := range resp.Data { + byID[m.ID] = m + } + alias, ok := byID["gemma-4-26b"] + if !ok { + t.Fatalf("alias entry missing from feed: %+v", resp.Data) + } + if alias.Name != "Gemma 4 26B" { + t.Fatalf("alias display name = %q", alias.Name) + } + // Identity (slug) is the alias — stable across build migrations. The HF id + // stays the primary (desired) build's real HuggingFace path. + if alias.OpenRouter == nil || alias.OpenRouter.Slug != "gemma-4-26b" { + t.Fatalf("alias slug = %+v, want gemma-4-26b", alias.OpenRouter) + } + if alias.HuggingFaceID != aliasHuggingFaceID { + t.Fatalf("alias hugging_face_id = %q, want %q", alias.HuggingFaceID, aliasHuggingFaceID) + } + // Member builds are hidden from the raw listing. + if _, leaked := byID[aliasFP8]; leaked { + t.Fatal("previous build leaked into the OpenRouter feed") + } + if _, leaked := byID[aliasQAT]; leaked { + t.Fatal("desired build leaked into the OpenRouter feed") + } + // Unaliased models keep their raw entries. + if _, ok := byID["mlx-community/unrelated-9b"]; !ok { + t.Fatal("unaliased model missing from feed") + } +} + +// The OpenRouter marketplace feed must also hide a retired build: once fp8 is +// retired (moved to the lineage) it must not reappear as a sellable entry — +// otherwise OpenRouter lists it is_ready:true with zero providers, a black-hole. +func TestOpenRouterModelsHidesRetiredAliasBuild(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + srv := newTestController(registry.New(logger), st, logger) + + seedActiveModel(t, st, aliasFP8, "Gemma 4 26B fp8") + seedActiveModel(t, st, aliasQAT, "Gemma 4 26B qat") + if err := st.UpsertModelAlias(&store.ModelAlias{ + AliasID: "gemma-4-26b", DisplayName: "Gemma 4 26B", Active: true, + DesiredBuild: aliasQAT, RetiredBuilds: []string{aliasFP8}, + }); err != nil { + t.Fatal(err) + } + srv.Invalidate() + + rec := httptest.NewRecorder() + srv.ListOpenRouterModels(rec, httptest.NewRequest(http.MethodGet, "/v1/models/openrouter", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String()) + } + var resp types.OpenRouterModelsResponse + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + sawAlias := false + for _, m := range resp.Data { + if m.ID == aliasFP8 { + t.Fatalf("retired build %q leaked into the OpenRouter feed", aliasFP8) + } + if m.ID == aliasQAT { + t.Fatalf("desired build %q leaked into the OpenRouter feed", aliasQAT) + } + if m.ID == "gemma-4-26b" { + sawAlias = true + } + } + if !sawAlias { + t.Fatalf("alias gemma-4-26b missing from OpenRouter feed: %+v", resp.Data) + } +} + +func TestConcreteModelEligibleForOpenRouterFeed(t *testing.T) { + const modelID = "model" + catalog := map[string]store.SupportedModel{ + modelID: {ID: modelID, ModelType: "text", Active: true}, + } + if !concreteModelEligibleForOpenRouterFeed(modelID, catalog, nil) { + t.Fatal("text catalog model without providers should be feed-eligible") + } + if concreteModelEligibleForOpenRouterFeed(modelID, catalog, map[string]string{modelID: "embedding"}) { + t.Fatal("provider-reported non-text model should not be feed-eligible") + } + if concreteModelEligibleForOpenRouterFeed("missing", catalog, nil) { + t.Fatal("missing catalog model should not be feed-eligible") + } +} diff --git a/coordinator/api/catalog/marketplace_fields.go b/coordinator/api/catalog/marketplace_fields.go new file mode 100644 index 0000000000..001d328917 --- /dev/null +++ b/coordinator/api/catalog/marketplace_fields.go @@ -0,0 +1,106 @@ +package catalog + +import ( + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/payments" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// buildModelPricing resolves the per-token USD pricing block for a model from +// micro-USD-per-million-token rates. +func buildModelPricing(inputPerMillion, outputPerMillion int64) *types.ModelPricing { + return &types.ModelPricing{ + Prompt: payments.FormatPerTokenUSD(inputPerMillion), + Completion: payments.FormatPerTokenUSD(outputPerMillion), + Image: "0", + Request: "0", + InputCacheRead: "0", + } +} + +// resolvePlatformPricing returns the platform-level input/output micro-USD +// per-million rates for a model, falling back to the global defaults when no +// override is configured. +func (s *Controller) resolvePlatformPricing(model string) (inputPerMillion, outputPerMillion int64) { + if in, out, ok := s.store().GetModelPrice("platform", model); ok { + return in, out + } + return payments.DefaultInputPricePerMillion, payments.DefaultOutputPricePerMillion +} + +// openRouterModelFields holds the OpenRouter-schema values that both the +// /v1/models enrichment and the dedicated /v1/models/openrouter feed derive +// identically from a model and its (optional) registry entry. Centralizing the +// derivation keeps the two endpoints in lockstep; each maps these onto its own +// response struct via the applyTo* helpers below. +type openRouterModelFields struct { + Quantization string + Pricing *types.ModelPricing + SupportedSamplingParameters []string + Created int64 + Description string + ContextLength int + MaxOutputLength int + SupportedFeatures []string + DeprecationDate string +} + +// openRouterModelFieldsFor derives the shared OpenRouter fields for a model. +// Pricing and sampling parameters come from the platform price table; the +// quantization is mapped from rawQuantization (the aggregate's value for +// /v1/models, or the registry entry's value for the catalog-driven feed); the +// remaining fields come from the registry entry and are left at their zero +// values when hasReg is false (a model present in routing but without a +// registry record). +func (s *Controller) openRouterModelFieldsFor(modelID, rawQuantization string, reg store.ModelRegistryEntry, hasReg bool) openRouterModelFields { + inPM, outPM := s.resolvePlatformPricing(modelID) + f := openRouterModelFields{ + Quantization: mapQuantizationToOpenRouter(rawQuantization), + Pricing: buildModelPricing(inPM, outPM), + SupportedSamplingParameters: defaultSamplingParameters(), + } + if hasReg { + if !reg.CreatedAt.IsZero() { + f.Created = reg.CreatedAt.Unix() + } + f.Description = reg.Description + f.ContextLength = reg.MaxContextLength + f.MaxOutputLength = reg.MaxOutputLength + f.SupportedFeatures = supportedFeaturesFromCapabilities(reg.Capabilities) + f.DeprecationDate = deprecationDateFromMetadata(reg.Metadata) + } + return f +} + +// applyToModelEntry copies the shared OpenRouter fields onto a /v1/models +// ModelEntry (which also carries the Darkbloom metadata block). Modalities are +// set by the caller, which derives them from the model's capabilities. +func (f openRouterModelFields) applyToModelEntry(entry *types.ModelEntry) { + entry.Quantization = f.Quantization + entry.Pricing = f.Pricing + entry.SupportedSamplingParameters = f.SupportedSamplingParameters + entry.Created = f.Created + entry.Description = f.Description + entry.ContextLength = f.ContextLength + entry.MaxOutputLength = f.MaxOutputLength + entry.SupportedFeatures = f.SupportedFeatures + entry.DeprecationDate = f.DeprecationDate +} + +// applyToFeed copies the shared OpenRouter fields onto a pure feed entry. The +// feed emits required fields without omitempty, so an empty feature set is left +// as the caller's pre-initialized []string{} (never nilled out), and modalities +// / is_ready / slug remain the caller's responsibility. +func (f openRouterModelFields) applyToFeed(entry *types.OpenRouterModel) { + entry.Quantization = f.Quantization + entry.Pricing = *f.Pricing + entry.SupportedSamplingParameters = f.SupportedSamplingParameters + entry.Created = f.Created + entry.Description = f.Description + entry.ContextLength = f.ContextLength + entry.MaxOutputLength = f.MaxOutputLength + if len(f.SupportedFeatures) > 0 { + entry.SupportedFeatures = f.SupportedFeatures + } + entry.DeprecationDate = f.DeprecationDate +} diff --git a/coordinator/api/catalog/marketplace_fields_test.go b/coordinator/api/catalog/marketplace_fields_test.go new file mode 100644 index 0000000000..4ebae8d70d --- /dev/null +++ b/coordinator/api/catalog/marketplace_fields_test.go @@ -0,0 +1,143 @@ +package catalog + +import ( + "reflect" + "testing" +) + +func TestMapQuantizationToOpenRouter(t *testing.T) { + cases := map[string]string{ + "4bit": "int4", + "4-bit": "int4", + "8bit": "int8", + "6bit": "fp6", + "3bit": "int4", + "2bit": "int4", + "bf16": "bf16", + "fp16": "fp16", + "float16": "fp16", + "bfloat16": "bf16", + "int8": "int8", + "4bit-gs64": "int4", // tolerate descriptor suffixes + "mxfp4": "fp4", + "bfloat16-gs64": "bf16", + " BFLOAT16-GS64 ": "bf16", + "float16-gs64": "fp16", + "q4-bfloat16": "int4", // leading weight format wins over compute dtype + "4bit-float16": "int4", + "bfloat16-q4": "bf16", + "float16-4bit": "fp16", + "int8-4bit": "int8", // independent spellings prefer the first + "4bit-int8": "int4", + "": "", + "weird-format": "", + } + for in, want := range cases { + t.Run(in, func(t *testing.T) { + // Repeated calls must not depend on randomized map iteration. + for range 128 { + if got := mapQuantizationToOpenRouter(in); got != want { + t.Fatalf("mapQuantizationToOpenRouter(%q) = %q, want %q", in, got, want) + } + } + }) + } +} + +func TestDeriveModalities(t *testing.T) { + in, out := deriveModalities("text", nil) + if !reflect.DeepEqual(in, []string{"text"}) || !reflect.DeepEqual(out, []string{"text"}) { + t.Errorf("text model = (%v,%v), want ([text],[text])", in, out) + } + + in, out = deriveModalities("text", []string{"tools", "vision"}) + if !reflect.DeepEqual(in, []string{"text", "image"}) { + t.Errorf("vision input = %v, want [text image]", in) + } + if !reflect.DeepEqual(out, []string{"text"}) { + t.Errorf("vision output = %v, want [text]", out) + } + + in, out = deriveModalities("embedding", nil) + if !reflect.DeepEqual(in, []string{"text"}) || !reflect.DeepEqual(out, []string{"embedding"}) { + t.Errorf("embedding = (%v,%v), want ([text],[embedding])", in, out) + } + + in, _ = deriveModalities("text", []string{"video"}) + if !reflect.DeepEqual(in, []string{"text", "video"}) { + t.Errorf("video input = %v, want [text video]", in) + } + + in, _ = deriveModalities("text", []string{"video_input"}) + if !reflect.DeepEqual(in, []string{"text", "video"}) { + t.Errorf("video_input alias = %v, want [text video]", in) + } + + // Gemma 4-style: image + audio + video together, order preserved, deduped. + in, _ = deriveModalities("text", []string{"vision", "audio", "video", "video"}) + if !reflect.DeepEqual(in, []string{"text", "image", "audio", "video"}) { + t.Errorf("multimodal input = %v, want [text image audio video]", in) + } +} + +func TestSupportedFeaturesFromCapabilities(t *testing.T) { + // Aliases map onto OpenRouter's vocabulary; result is sorted + deduped. + got := supportedFeaturesFromCapabilities([]string{"function_calling", "tools", "thinking", "json_schema"}) + want := []string{"reasoning", "structured_outputs", "tools"} + if !reflect.DeepEqual(got, want) { + t.Errorf("features = %v, want %v", got, want) + } + + if got := supportedFeaturesFromCapabilities(nil); got != nil { + t.Errorf("nil caps = %v, want nil", got) + } + if got := supportedFeaturesFromCapabilities([]string{"unknown_cap"}); got != nil { + t.Errorf("unknown-only caps = %v, want nil", got) + } +} + +func TestDefaultSamplingParameters(t *testing.T) { + got := defaultSamplingParameters() + // Only parameters the Swift inference engine actually honors should be + // advertised; OpenRouter-valid-but-unhonored ones must be excluded. + honored := map[string]bool{ + "temperature": true, "top_p": true, "top_k": true, + "frequency_penalty": true, "presence_penalty": true, + "repetition_penalty": true, "stop": true, "seed": true, + "max_tokens": true, + } + if len(got) == 0 { + t.Fatal("expected non-empty sampling parameters") + } + gotSet := map[string]bool{} + for _, p := range got { + gotSet[p] = true + if !honored[p] { + t.Errorf("advertised sampling parameter %q is not honored by the provider", p) + } + } + // These are OpenRouter-valid but NOT decoded by the Swift provider — must + // not be advertised. + for _, p := range []string{"min_p", "top_a", "logit_bias"} { + if gotSet[p] { + t.Errorf("must not advertise %q (provider silently ignores it)", p) + } + } +} + +func TestBuildModelPricing(t *testing.T) { + p := buildModelPricing(DefaultInputPricePerMillionForTest(), 200_000) + if p.Prompt != "0.00000005" { + t.Errorf("prompt = %q, want 0.00000005", p.Prompt) + } + if p.Completion != "0.0000002" { + t.Errorf("completion = %q, want 0.0000002", p.Completion) + } + if p.Image != "0" || p.Request != "0" || p.InputCacheRead != "0" { + t.Errorf("image/request/input_cache_read should default to \"0\", got %q/%q/%q", p.Image, p.Request, p.InputCacheRead) + } +} + +// DefaultInputPricePerMillionForTest mirrors the payments default so the test +// stays readable without importing the constant directly here. +func DefaultInputPricePerMillionForTest() int64 { return 50_000 } diff --git a/coordinator/api/catalog/marketplace_identity.go b/coordinator/api/catalog/marketplace_identity.go new file mode 100644 index 0000000000..64ca2393cd --- /dev/null +++ b/coordinator/api/catalog/marketplace_identity.go @@ -0,0 +1,65 @@ +package catalog + +import ( + "strings" +) + +// deprecationDateFromMetadata extracts the optional "deprecation_date" string +// from a model's registry metadata, returning "" when it is absent or empty. +func deprecationDateFromMetadata(meta map[string]any) string { + if dd, ok := meta["deprecation_date"].(string); ok { + return dd + } + return "" +} + +// openRouterIsReady decides whether a model is live on OpenRouter. This is a +// launch/staging flag, NOT a live-capacity signal — transient capacity is +// handled by 429s. Active catalog models default to ready; an operator can +// stage a model by setting metadata "openrouter_is_ready": false (or the alias +// "openrouter_staged": true). +func openRouterIsReady(meta map[string]any) bool { + if meta == nil { + return true + } + if v, ok := meta["openrouter_is_ready"].(bool); ok { + return v + } + if staged, ok := meta["openrouter_staged"].(bool); ok { + return !staged + } + return true +} + +const huggingFaceIDMetadataKey = "hugging_face_id" + +// huggingFaceIDForModel returns the exact Hugging Face repository OpenRouter +// should inspect. Most concrete model ids are already Hugging Face paths; an +// explicit metadata value supports internal routing ids without conflating the +// two identities. +func huggingFaceIDForModel(modelID string, meta map[string]any) string { + if id, ok := meta[huggingFaceIDMetadataKey].(string); ok { + if id = strings.TrimSpace(id); id != "" { + return id + } + } + return modelID +} + +// openRouterSlug returns the OpenRouter marketplace slug for a model: an +// operator override from registry metadata ("openrouter_slug") if present, +// otherwise the model id itself. +// +// OpenRouter's provider spec leaves the slug underspecified and its own example +// sets slug == id, so the globally unique model id is a safe, collision-free +// default. Operators map a model onto an existing marketplace +// slug (e.g. "qwen/qwen3.5-9b") explicitly via the openrouter_slug metadata +// override / the admin openrouter-slug action. +func openRouterSlug(modelID string, meta map[string]any) string { + if meta != nil { + if s, ok := meta["openrouter_slug"].(string); ok && strings.TrimSpace(s) != "" { + return strings.TrimSpace(s) + } + } + return modelID +} diff --git a/coordinator/api/catalog/marketplace_identity_test.go b/coordinator/api/catalog/marketplace_identity_test.go new file mode 100644 index 0000000000..38423ac966 --- /dev/null +++ b/coordinator/api/catalog/marketplace_identity_test.go @@ -0,0 +1,61 @@ +package catalog + +import ( + "testing" +) + +func TestOpenRouterSlug(t *testing.T) { + const id = "mlx-community/Qwen3.5-9B-MLX-4bit" + + // Metadata override wins (operator maps onto a canonical marketplace slug). + if got := openRouterSlug(id, map[string]any{"openrouter_slug": "qwen/qwen3.5-9b"}); got != "qwen/qwen3.5-9b" { + t.Errorf("override slug = %q, want qwen/qwen3.5-9b", got) + } + // Default is the unique model id (collision-free, doc-aligned slug==id). + if got := openRouterSlug(id, nil); got != id { + t.Errorf("default slug = %q, want the model id %q", got, id) + } + // Blank override falls back to the id. + if got := openRouterSlug(id, map[string]any{"openrouter_slug": " "}); got != id { + t.Errorf("blank override slug = %q, want the model id", got) + } + // Two same-named repos under different owners get DISTINCT default slugs. + a := openRouterSlug("org-a/Foo-7B", nil) + b := openRouterSlug("org-b/Foo-7B", nil) + if a == b { + t.Errorf("default slugs must be unique per id: both = %q", a) + } +} + +func TestOpenRouterIsReady(t *testing.T) { + if !openRouterIsReady(nil) { + t.Error("nil metadata should default to ready") + } + if !openRouterIsReady(map[string]any{}) { + t.Error("empty metadata should default to ready") + } + if openRouterIsReady(map[string]any{"openrouter_is_ready": false}) { + t.Error("explicit openrouter_is_ready=false should be not-ready") + } + if openRouterIsReady(map[string]any{"openrouter_staged": true}) { + t.Error("openrouter_staged=true should be not-ready") + } + if !openRouterIsReady(map[string]any{"openrouter_staged": false}) { + t.Error("openrouter_staged=false should be ready") + } +} + +func TestIsNonTextModelType(t *testing.T) { + // Text-ish and unknown types are NOT excluded (kept in the feed). + for _, mt := range []string{"", "text", "chat", "Completion", "test", "future-type"} { + if isNonTextModelType(mt) { + t.Errorf("isNonTextModelType(%q) = true, want false (should stay in feed)", mt) + } + } + // Known non-text modalities are excluded. + for _, mt := range []string{"embedding", "tts", "image", "audio", "Rerank"} { + if !isNonTextModelType(mt) { + t.Errorf("isNonTextModelType(%q) = false, want true (should be excluded)", mt) + } + } +} diff --git a/coordinator/api/catalog/marketplace_locations.go b/coordinator/api/catalog/marketplace_locations.go new file mode 100644 index 0000000000..0e35b83d39 --- /dev/null +++ b/coordinator/api/catalog/marketplace_locations.go @@ -0,0 +1,34 @@ +package catalog + +import ( + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// openRouterModelName resolves the feed display name for a model: the catalog +// display name, then the registry display name, then the model ID as a last +// resort. +func openRouterModelName(cm store.SupportedModel, reg store.ModelRegistryEntry, hasReg bool, modelID string) string { + if cm.DisplayName != "" { + return cm.DisplayName + } + if hasReg && reg.DisplayName != "" { + return reg.DisplayName + } + return modelID +} + +// modelDatacenters maps the country codes of providers serving a model into the +// OpenRouter "datacenters" shape, returning nil when none are known so the +// omitempty field is omitted. +func (s *Controller) modelDatacenters(modelID string) []types.OpenRouterDatacenter { + ccs := s.registry.ModelCountryCodes(modelID) + if len(ccs) == 0 { + return nil + } + dcs := make([]types.OpenRouterDatacenter, 0, len(ccs)) + for _, cc := range ccs { + dcs = append(dcs, types.OpenRouterDatacenter{CountryCode: cc}) + } + return dcs +} diff --git a/coordinator/api/catalog/marketplace_modalities.go b/coordinator/api/catalog/marketplace_modalities.go new file mode 100644 index 0000000000..8212ba4f52 --- /dev/null +++ b/coordinator/api/catalog/marketplace_modalities.go @@ -0,0 +1,123 @@ +package catalog + +import ( + "sort" + "strings" +) + +// deriveModalities returns the input and output modalities for a model. Text is +// always present; a vision/multimodal capability adds image input, an audio +// capability adds audio, and a video capability adds video. Embedding models +// report a text->embedding shape. +func deriveModalities(modelType string, capabilities []string) (input, output []string) { + mt := strings.ToLower(strings.TrimSpace(modelType)) + switch mt { + case "embedding", "embeddings": + return []string{"text"}, []string{"embedding"} + } + + input = []string{"text"} + output = []string{"text"} + for _, c := range capabilities { + switch strings.ToLower(strings.TrimSpace(c)) { + case "vision", "image", "image_input", "multimodal": + if !contains(input, "image") { + input = append(input, "image") + } + case "audio", "audio_input": + if !contains(input, "audio") { + input = append(input, "audio") + } + case "video", "video_input": + if !contains(input, "video") { + input = append(input, "video") + } + case "file", "pdf": + if !contains(input, "file") { + input = append(input, "file") + } + } + } + return input, output +} + +// featureAliases maps internal capability strings onto OpenRouter's feature +// vocabulary. +var featureAliases = map[string]string{ + "tools": "tools", + "tool_use": "tools", + "tool_calling": "tools", + "function_calling": "tools", + "functions": "tools", + "json": "json_mode", + "json_mode": "json_mode", + "json_object": "json_mode", + "structured_outputs": "structured_outputs", + "structured_output": "structured_outputs", + "json_schema": "structured_outputs", + "logprobs": "logprobs", + "web_search": "web_search", + "search": "web_search", + "reasoning": "reasoning", + "thinking": "reasoning", + "reasoning_parser": "reasoning", +} + +// supportedFeaturesFromCapabilities translates internal capability labels into +// OpenRouter feature names, de-duplicated and sorted for stable output. +func supportedFeaturesFromCapabilities(capabilities []string) []string { + if len(capabilities) == 0 { + return nil + } + seen := map[string]bool{} + for _, c := range capabilities { + if mapped, ok := featureAliases[strings.ToLower(strings.TrimSpace(c))]; ok { + seen[mapped] = true + } + } + if len(seen) == 0 { + return nil + } + out := make([]string, 0, len(seen)) + for f := range seen { + out = append(out, f) + } + sort.Strings(out) + return out +} + +// defaultSamplingParameters is the set of sampling parameters the Swift +// inference engine actually decodes and applies (see ChatCompletionRequest in +// provider-swift). We deliberately exclude OpenRouter-valid-but-unhonored +// parameters (min_p, top_a, logit_bias) so the feed never advertises sampling +// behavior the provider would silently ignore. +func defaultSamplingParameters() []string { + return []string{ + "temperature", "top_p", "top_k", + "frequency_penalty", "presence_penalty", "repetition_penalty", + "stop", "seed", "max_tokens", + } +} + +func contains(s []string, v string) bool { + for _, x := range s { + if x == v { + return true + } + } + return false +} + +// isNonTextModelType reports whether a model type is a KNOWN non-text modality +// that must be excluded from the text-only OpenRouter feed. Unknown/empty and +// text-ish types (text, chat, completion) are NOT excluded, so the filter only +// drops models we're confident are not text generation (embeddings, audio, +// image, rerank). +func isNonTextModelType(modelType string) bool { + switch strings.ToLower(strings.TrimSpace(modelType)) { + case "embedding", "embeddings", "tts", "stt", "speech", "audio", "image", "vision", "rerank", "reranker": + return true + default: + return false + } +} diff --git a/coordinator/api/catalog/marketplace_quantization.go b/coordinator/api/catalog/marketplace_quantization.go new file mode 100644 index 0000000000..338a9fdb17 --- /dev/null +++ b/coordinator/api/catalog/marketplace_quantization.go @@ -0,0 +1,43 @@ +package catalog + +import ( + "strings" +) + +// quantAliases maps common MLX / HuggingFace quantization spellings onto the +// OpenRouter-accepted vocabulary. +var quantAliases = map[string]string{ + "4bit": "int4", "4-bit": "int4", "q4": "int4", "int4": "int4", + "8bit": "int8", "8-bit": "int8", "q8": "int8", "int8": "int8", + "6bit": "fp6", "6-bit": "fp6", + "3bit": "int4", "3-bit": "int4", // no int3 in OpenRouter; nearest is int4 + "2bit": "int4", "2-bit": "int4", // no int2 in OpenRouter; nearest is int4 + "fp4": "fp4", "fp6": "fp6", "fp8": "fp8", + "fp16": "fp16", "bf16": "bf16", "fp32": "fp32", + "float16": "fp16", "bfloat16": "bf16", "float32": "fp32", +} + +// mapQuantizationToOpenRouter normalizes an internal quantization label to the +// OpenRouter vocabulary. Returns "" when no confident mapping exists so the +// caller can omit the field. +func mapQuantizationToOpenRouter(q string) string { + key := strings.ToLower(strings.TrimSpace(q)) + if key == "" { + return "" + } + if mapped, ok := quantAliases[key]; ok { + return mapped + } + // Tolerate descriptors like "4bit-gs64" or "mxfp4". The earliest + // recognized format wins, preserving "q4" in "q4-bfloat16" and + // "bfloat16" over its later "float16" suffix. At the same position, + // prefer the longest spelling. + bestAlias, bestMapping, bestIndex := "", "", len(key) + for alias, mapped := range quantAliases { + if index := strings.Index(key, alias); index >= 0 && + (index < bestIndex || index == bestIndex && len(alias) > len(bestAlias)) { + bestAlias, bestMapping, bestIndex = alias, mapped, index + } + } + return bestMapping +} diff --git a/coordinator/api/catalog/owned_models.go b/coordinator/api/catalog/owned_models.go new file mode 100644 index 0000000000..c13c703bce --- /dev/null +++ b/coordinator/api/catalog/owned_models.go @@ -0,0 +1,108 @@ +package catalog + +import ( + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/registry" +) + +// OwnedModelEntries assembles the /v1/models view for a self-route-only +// key: the account's own live machine models instead of the public catalog. +// Owned catalog builds behind an active public alias are presented under the +// alias id — the documented, consumer-facing name that self-route inference +// resolves too — with the concrete quant builds hidden, mirroring the public +// listing. includeHidden re-exposes those covered builds so retrieve-by-exact- +// id keeps working (parity with the public GET /v1/models/{id}, which serves +// hidden builds via listModelEntries(true)). +func (s *Controller) OwnedModelEntries(accountID string, includeHidden bool) []types.ModelEntry { + models := s.registry.OwnedModels(accountID) + byID := make(map[string]registry.AggregateModel, len(models)) + for _, m := range models { + byID[m.ID] = m + } + + aliases, err := s.store().ListModelAliases() + if err != nil { + // Degrade to the raw build listing rather than hiding the owner's + // models outright. + s.logger.Error("model registry: failed to list aliases for self-route models", "error", err) + aliases = nil + } + + covered := make(map[string]struct{}) + data := make([]types.ModelEntry, 0, len(models)) + for _, a := range aliases { + if !a.Active || a.DesiredBuild == "" { + continue + } + // Owned members: the alias's live builds this account's machines + // actually serve. Retired builds stay raw — the alias would not + // resolve to them for inference. + members := make([]registry.AggregateModel, 0, 2) + for _, b := range []string{a.DesiredBuild, a.PreviousBuild} { + if m, ok := byID[b]; b != "" && ok { + members = append(members, m) + } + } + if len(members) == 0 { + continue + } + // Primary member (desired-first order above) carries the metadata; + // provider counts aggregate across members, mirroring the public + // alias entry's capacity roll-up. + agg := members[0] + for _, m := range members[1:] { + agg.Providers += m.Providers + agg.AttestedProviders += m.AttestedProviders + } + agg.ID = a.AliasID + // An alias spans quants; omit the per-build quant like the public list. + agg.Quantization = "" + entry := ownedModelEntry(agg) + if a.DisplayName != "" { + entry.Name = a.DisplayName + entry.Metadata.DisplayName = a.DisplayName + } + data = append(data, entry) + for _, m := range members { + covered[m.ID] = struct{}{} + } + } + + for _, m := range models { + if _, hidden := covered[m.ID]; hidden && !includeHidden { + continue + } + data = append(data, ownedModelEntry(m)) + } + return data +} + +// ownedModelEntry converts one owned-model aggregate into the consumer-facing +// entry shape shared by the self-route list and retrieve endpoints. +func ownedModelEntry(m registry.AggregateModel) types.ModelEntry { + metadata := types.ModelMetadata{ + ModelType: m.ModelType, + Quantization: m.Quantization, + ProviderCount: m.Providers, + AttestedProviders: m.AttestedProviders, + TrustLevel: string(m.TrustLevel), + RoutableProviders: m.Providers, + CanAccept: m.Providers > 0, + } + if m.Attestation != nil { + metadata.Attestation = &types.ModelAttestation{ + SecureEnclave: m.Attestation.SecureEnclave, + SIPEnabled: m.Attestation.SIPEnabled, + SecureBoot: m.Attestation.SecureBoot, + } + } + return types.ModelEntry{ + ID: m.ID, + Object: "model", + OwnedBy: "self", + Name: m.ID, + HuggingFaceID: m.ID, + Quantization: m.Quantization, + Metadata: metadata, + } +} diff --git a/coordinator/api/catalog/provider_capabilities_test.go b/coordinator/api/catalog/provider_capabilities_test.go new file mode 100644 index 0000000000..ce95f0cdb8 --- /dev/null +++ b/coordinator/api/catalog/provider_capabilities_test.go @@ -0,0 +1,86 @@ +package catalog + +import ( + "reflect" + "testing" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestRequiredProviderCapabilitiesMemoryAndCatalogRoundTrip(t *testing.T) { + st := store.NewMemory(store.Config{}) + entry := &store.ModelRegistryEntry{ + ID: registry.Qwen38NAXModelID, DisplayName: "Qwen3.8 27B", + Quantization: "4bit", MaxContextLength: 131072, + MaxOutputLength: 8192, MinRAMGB: 64, Status: "active", + RequiredProviderCapabilities: []string{ + registry.ProviderCapabilityAppleM5, + registry.ProviderCapabilityMLXNAX, + }, + } + version := &store.ModelVersion{ + ModelID: entry.ID, Version: "v1", R2Prefix: "models/qwen38/v1", + AggregateSHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + Status: "ready", + } + if err := st.SetModelVersion(entry, version, nil); err != nil { + t.Fatal(err) + } + if err := st.PromoteModelVersion(entry.ID, version.Version); err != nil { + t.Fatal(err) + } + record, err := st.GetModelRegistryRecord(entry.ID) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(record.RequiredProviderCapabilities, entry.RequiredProviderCapabilities) { + t.Fatalf("store round trip = %v, want %v", + record.RequiredProviderCapabilities, entry.RequiredProviderCapabilities) + } + + catalog := catalogModelFromRegistryRecord(record) + if got := catalog["required_provider_capabilities"]; !reflect.DeepEqual(got, entry.RequiredProviderCapabilities) { + t.Fatalf("catalog API field = %#v, want %v", got, entry.RequiredProviderCapabilities) + } + supported := supportedModelFromRegistryRecord(record) + if !reflect.DeepEqual(supported.RequiredProviderCapabilities, entry.RequiredProviderCapabilities) { + t.Fatalf("supported model field = %v", supported.RequiredProviderCapabilities) + } + + // Returned slices are detached from memory storage. + record.RequiredProviderCapabilities[0] = "mutated" + again, err := st.GetModelRegistryRecord(entry.ID) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(again.RequiredProviderCapabilities, entry.RequiredProviderCapabilities) { + t.Fatalf("memory clone leaked caller mutation: %v", again.RequiredProviderCapabilities) + } +} + +func TestValidateRequiredProviderCapabilities(t *testing.T) { + valid := []string{ + registry.ProviderCapabilityAppleM5, + registry.ProviderCapabilityMLXNAX, + } + if err := validateRequiredProviderCapabilities(registry.Qwen38NAXModelID, valid); err != nil { + t.Fatalf("valid protected requirements rejected: %v", err) + } + for name, capabilities := range map[string][]string{ + "missing": {registry.ProviderCapabilityAppleM5}, + "empty": {""}, + "whitespace": {" apple_m5", registry.ProviderCapabilityMLXNAX}, + "duplicate": {registry.ProviderCapabilityAppleM5, registry.ProviderCapabilityAppleM5}, + "unknown": {registry.ProviderCapabilityAppleM5, registry.ProviderCapabilityMLXNAX, "future"}, + } { + t.Run(name, func(t *testing.T) { + if err := validateRequiredProviderCapabilities(registry.Qwen38NAXModelID, capabilities); err == nil { + t.Fatalf("accepted invalid requirements %v", capabilities) + } + }) + } + if err := validateRequiredProviderCapabilities("unrelated-model", nil); err != nil { + t.Fatalf("empty requirements broke existing model: %v", err) + } +} diff --git a/coordinator/api/catalog/publishing_auth.go b/coordinator/api/catalog/publishing_auth.go new file mode 100644 index 0000000000..742cb23b87 --- /dev/null +++ b/coordinator/api/catalog/publishing_auth.go @@ -0,0 +1,73 @@ +package catalog + +import ( + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "net/http" + "os" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" +) + +type publishingActor struct { + ID string + Name string +} + +func (s *Controller) requirePublishingAPIKey(w http.ResponseWriter, r *http.Request) (publishingActor, bool) { + provided := strings.TrimSpace(r.Header.Get("X-Darkbloom-Publishing-Key")) + if provided == "" { + authz := strings.TrimSpace(r.Header.Get("Authorization")) + if strings.HasPrefix(strings.ToLower(authz), "bearer ") { + provided = strings.TrimSpace(authz[len("Bearer "):]) + } + } + if provided == "" { + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("authentication_error", "missing publishing API key")) + return publishingActor{}, false + } + + if bootstrap := os.Getenv("MODEL_REGISTRY_PUBLISHING_KEY"); bootstrap != "" && constantTimeStringEqual(provided, bootstrap) { + return publishingActor{ID: "env-bootstrap", Name: "env-bootstrap"}, true + } + // The admin key (EIGENINFERENCE_ADMIN_KEY) is the highest privilege and is + // also accepted for any publishing/registry action (register, promote, + // status, runtime-parameters, capabilities). + if s.adminKey() != "" && constantTimeStringEqual(provided, s.adminKey()) { + return publishingActor{ID: "admin", Name: "admin"}, true + } + providedHash := publishingSHA256Hex(provided) + keys, err := s.store().FindPublishingAPIKeysWithError() + if err != nil { + s.logger.Error("model registry: failed to find publishing API keys", "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to verify publishing API key")) + return publishingActor{}, false + } + for _, key := range keys { + if !key.Active { + continue + } + if constantTimeStringEqual(providedHash, key.KeyHash) { + if err := s.store().MarkPublishingAPIKeyUsed(key.ID); err != nil { + s.logger.Warn("model registry: failed to mark publishing key used", "key_id", key.ID, "error", err) + } + return publishingActor{ID: key.ID, Name: key.Name}, true + } + } + httpresponse.WriteJSON(w, http.StatusUnauthorized, httpresponse.ErrorBody("authentication_error", "invalid publishing API key")) + return publishingActor{}, false +} + +func publishingSHA256Hex(value string) string { + sum := sha256.Sum256([]byte(value)) + return hex.EncodeToString(sum[:]) +} + +func constantTimeStringEqual(a, b string) bool { + if len(a) != len(b) { + return false + } + return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 +} diff --git a/coordinator/api/catalog/publishing_auth_test.go b/coordinator/api/catalog/publishing_auth_test.go new file mode 100644 index 0000000000..233e9bcf0b --- /dev/null +++ b/coordinator/api/catalog/publishing_auth_test.go @@ -0,0 +1,38 @@ +package catalog + +import ( + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestPublishingAPIKeyStoreErrorSurfacesButBootstrapStillWorks(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := &failingModelRegistryStore{MemoryStore: store.NewMemory(store.Config{}), keyErr: errors.New("database unavailable")} + srv := newTestController(registry.New(logger), st, logger) + + t.Setenv("MODEL_REGISTRY_PUBLISHING_KEY", "") + req := httptest.NewRequest(http.MethodPost, "/v1/admin/models/register", nil) + req.Header.Set("Authorization", "Bearer db-key") + rec := httptest.NewRecorder() + if _, ok := srv.requirePublishingAPIKey(rec, req); ok { + t.Fatal("expected DB-backed key lookup to fail") + } + if rec.Code != http.StatusInternalServerError { + t.Fatalf("auth failure status = %d body = %s", rec.Code, rec.Body.String()) + } + + t.Setenv("MODEL_REGISTRY_PUBLISHING_KEY", "bootstrap") + req = httptest.NewRequest(http.MethodPost, "/v1/admin/models/register", nil) + req.Header.Set("Authorization", "Bearer bootstrap") + rec = httptest.NewRecorder() + if actor, ok := srv.requirePublishingAPIKey(rec, req); !ok || actor.ID != "env-bootstrap" { + t.Fatalf("expected bootstrap key to bypass DB, actor=%#v ok=%v", actor, ok) + } +} diff --git a/coordinator/api/catalog/register_model.go b/coordinator/api/catalog/register_model.go new file mode 100644 index 0000000000..f3c81ffadb --- /dev/null +++ b/coordinator/api/catalog/register_model.go @@ -0,0 +1,142 @@ +package catalog + +import ( + "encoding/json" + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" + "github.com/eigeninference/d-inference/coordinator/store" +) + +type registerModelRequest struct { + HuggingFaceArtifact *store.HuggingFaceArtifact `json:"hugging_face_artifact,omitempty"` + ModelID string `json:"model_id"` + Version string `json:"version"` + DisplayName string `json:"display_name"` + Family string `json:"family"` + Architecture string `json:"architecture"` + Quantization string `json:"quantization"` + MaxContextLength int `json:"max_context_length"` + MaxOutputLength int `json:"max_output_length"` + MinRAMGB int `json:"min_ram_gb"` + Capabilities []string `json:"capabilities"` + RequiredProviderCapabilities []string `json:"required_provider_capabilities"` + Description string `json:"description"` + RuntimeParameters map[string]any `json:"runtime_parameters"` + Metadata map[string]any `json:"metadata"` + Promote bool `json:"promote"` + InputPrice int64 `json:"input_price"` // micro-USD per 1M tokens (required) + OutputPrice int64 `json:"output_price"` // micro-USD per 1M tokens (required) +} + +func (s *Controller) RegisterModel(w http.ResponseWriter, r *http.Request) { + actor, ok := s.requirePublishingAPIKey(w, r) + if !ok { + return + } + + var req registerModelRequest + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + if err := dec.Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if err := validateRegisterModelRequest(req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", err.Error())) + return + } + + // Reverse namespace guard (mirror of the alias upsert's collision check): a + // concrete model id must not collide with an existing public alias, or the + // alias map would hijack raw-id requests for the new model at resolution. + if _, found, err := s.store().GetModelAlias(req.ModelID); err != nil { + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to check model alias namespace")) + return + } else if found { + httpresponse.WriteJSON(w, http.StatusConflict, httpresponse.ErrorBody("invalid_request_error", + "model_id collides with an existing public alias", httpresponse.WithParam("model_id"))) + return + } + + r2Prefix := ModelR2Prefix(req.ModelID, req.Version) + manifest, err := fetchModelManifest(r.Context(), registryCDNBaseURL(), r2Prefix) + if err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "failed to fetch manifest: "+err.Error())) + return + } + if err := validateModelManifest(manifest, req.ModelID, req.Version, r2Prefix); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", err.Error())) + return + } + if err := verifyManifestFiles(r.Context(), registryCDNBaseURL(), manifest, s.logger); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "manifest file verification failed: "+err.Error())) + return + } + + entry := &store.ModelRegistryEntry{ + ID: req.ModelID, + DisplayName: req.DisplayName, + Family: req.Family, + Architecture: req.Architecture, + Quantization: req.Quantization, + MaxContextLength: req.MaxContextLength, + MaxOutputLength: req.MaxOutputLength, + MinRAMGB: req.MinRAMGB, + Capabilities: req.Capabilities, + RequiredProviderCapabilities: append( + []string{}, req.RequiredProviderCapabilities...), + Status: "beta", + Description: req.Description, + RuntimeParameters: req.RuntimeParameters, + Metadata: req.Metadata, + } + if entry.DisplayName == "" { + entry.DisplayName = req.ModelID + } + version := &store.ModelVersion{ + HuggingFaceArtifact: req.HuggingFaceArtifact, + ModelID: req.ModelID, + Version: req.Version, + R2Prefix: r2Prefix, + AggregateSHA256: manifest.AggregateSHA256, + TotalSizeBytes: manifest.TotalSizeBytes, + FileCount: manifest.FileCount, + Status: "ready", + UploadedBy: actor.Name, + Metadata: req.Metadata, + } + files := make([]store.ModelVersionFile, len(manifest.Files)) + for i, f := range manifest.Files { + files[i] = store.ModelVersionFile{Path: f.Path, SizeBytes: f.SizeBytes, SHA256: f.SHA256, Role: f.Role} + } + if err := s.store().SetModelVersion(entry, version, files); err != nil { + s.logger.Error("model registry: register failed", "model_id", req.ModelID, "version", req.Version, "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "failed to save model version")) + return + } + // Set platform pricing for this model. + if err := s.store().SetModelPrice("platform", req.ModelID, req.InputPrice, req.OutputPrice); err != nil { + s.logger.Error("model registry: set pricing failed", "model_id", req.ModelID, "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "model registered but failed to set pricing")) + return + } + + if req.Promote { + if err := s.store().PromoteModelVersion(req.ModelID, req.Version); err != nil { + s.logger.Error("model registry: promote after register failed", "model_id", req.ModelID, "version", req.Version, "error", err) + s.writeModelRegistryStoreError(w, "promote model version", err) + return + } + } + s.syncCatalog() + + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "registered", + "model": entry, + "version": version, + "files": len(files), + "input_price": req.InputPrice, + "output_price": req.OutputPrice, + }) +} diff --git a/coordinator/api/catalog/registry_action.go b/coordinator/api/catalog/registry_action.go new file mode 100644 index 0000000000..443f172ba9 --- /dev/null +++ b/coordinator/api/catalog/registry_action.go @@ -0,0 +1,277 @@ +package catalog + +import ( + "encoding/json" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" +) + +func (s *Controller) AdminModelAction(w http.ResponseWriter, r *http.Request) { + if _, ok := s.requirePublishingAPIKey(w, r); !ok { + return + } + modelID, action, ok := parseAdminModelActionPath(r.URL.Path) + if !ok || modelID == "" { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "model action not found")) + return + } + switch action { + case "promote": + var req struct { + Version string `json:"version"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.Version == "" || strings.Contains(req.Version, "/") || containsTraversal(req.Version) { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "valid version is required")) + return + } + if err := s.store().PromoteModelVersion(modelID, req.Version); err != nil { + s.writeModelRegistryStoreError(w, "promote model version", err) + return + } + s.syncCatalog() + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"status": "promoted", "model_id": modelID, "version": req.Version}) + case "status": + var req struct { + Status string `json:"status"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if !validModelStatus(req.Status) { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "status must be beta, active, deprecated, or retired")) + return + } + if err := s.store().SetModelStatus(modelID, req.Status); err != nil { + s.writeModelRegistryStoreError(w, "set model status", err) + return + } + s.syncCatalog() + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{"status": "updated", "model_id": modelID, "model_status": req.Status}) + case "runtime-parameters": + var req struct { + RuntimeParameters map[string]any `json:"runtime_parameters"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.RuntimeParameters == nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "runtime_parameters is required")) + return + } + rec, err := s.store().GetModelRegistryRecord(modelID) + if err != nil { + s.writeModelRegistryStoreError(w, "get model for runtime_parameters update", err) + return + } + // Merge new parameters into existing ones (allows partial updates). + if rec.RuntimeParameters == nil { + rec.RuntimeParameters = make(map[string]any) + } + for k, v := range req.RuntimeParameters { + rec.RuntimeParameters[k] = v + } + entry := registryEntryFromRecord(rec) + if err := s.store().UpsertModelRegistryEntry(entry); err != nil { + s.writeModelRegistryStoreError(w, "update runtime_parameters", err) + return + } + s.syncCatalog() + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "updated", + "model_id": modelID, + "runtime_parameters": rec.RuntimeParameters, + }) + case "capabilities": + var req struct { + Capabilities []string `json:"capabilities"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + if req.Capabilities == nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "capabilities is required (array of strings)")) + return + } + rec, err := s.store().GetModelRegistryRecord(modelID) + if err != nil { + s.writeModelRegistryStoreError(w, "get model for capabilities update", err) + return + } + // Replace capabilities wholesale (normalized: trimmed, de-duped, ordered). + caps := normalizeCapabilities(req.Capabilities) + entry := registryEntryFromRecord(rec) + entry.Capabilities = caps + if err := s.store().UpsertModelRegistryEntry(entry); err != nil { + s.writeModelRegistryStoreError(w, "update capabilities", err) + return + } + s.syncCatalog() + httpresponse.WriteJSON(w, http.StatusOK, map[string]any{ + "status": "updated", + "model_id": modelID, + "capabilities": caps, + }) + case "deprecation": + // Sets (or clears) the OpenRouter deprecation_date in model metadata. + // An omitted/empty deprecation_date clears it — i.e. clear by default — + // so an empty body or {} removes any existing deprecation date. + var req struct { + DeprecationDate string `json:"deprecation_date"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + date := strings.TrimSpace(req.DeprecationDate) + if date != "" { + if _, perr := time.Parse("2006-01-02", date); perr != nil { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", + "deprecation_date must be an ISO 8601 date (YYYY-MM-DD)", httpresponse.WithParam("deprecation_date"))) + return + } + } + rec, err := s.store().GetModelRegistryRecord(modelID) + if err != nil { + s.writeModelRegistryStoreError(w, "get model for deprecation update", err) + return + } + entry := registryEntryFromRecord(rec) + // Clone metadata before mutating so the stored record is never aliased. + meta := make(map[string]any, len(entry.Metadata)) + for k, v := range entry.Metadata { + meta[k] = v + } + if date == "" { + delete(meta, "deprecation_date") + } else { + meta["deprecation_date"] = date + } + entry.Metadata = meta + if err := s.store().UpsertModelRegistryEntry(entry); err != nil { + s.writeModelRegistryStoreError(w, "update deprecation_date", err) + return + } + s.syncCatalog() + resp := map[string]any{"status": "updated", "model_id": modelID} + if date == "" { + resp["deprecation_date"] = nil + resp["note"] = "deprecation date cleared" + } else { + resp["deprecation_date"] = date + } + httpresponse.WriteJSON(w, http.StatusOK, resp) + case "openrouter-slug": + // Sets (or clears) the OpenRouter marketplace slug in model metadata. + // An omitted/empty slug clears the override — clear by default — so the + // feed falls back to the model id. Use this to map a model onto an + // existing OpenRouter slug (e.g. "qwen/qwen3.5-9b"). + var req struct { + Slug string `json:"slug"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + slug := strings.TrimSpace(req.Slug) + rec, err := s.store().GetModelRegistryRecord(modelID) + if err != nil { + s.writeModelRegistryStoreError(w, "get model for openrouter-slug update", err) + return + } + entry := registryEntryFromRecord(rec) + meta := make(map[string]any, len(entry.Metadata)) + for k, v := range entry.Metadata { + meta[k] = v + } + if slug == "" { + delete(meta, "openrouter_slug") + } else { + meta["openrouter_slug"] = slug + } + entry.Metadata = meta + if err := s.store().UpsertModelRegistryEntry(entry); err != nil { + s.writeModelRegistryStoreError(w, "update openrouter-slug", err) + return + } + s.syncCatalog() + resp := map[string]any{"status": "updated", "model_id": modelID} + if slug == "" { + resp["openrouter_slug"] = nil + resp["note"] = "openrouter slug cleared — feed falls back to the model id" + } else { + resp["openrouter_slug"] = slug + } + httpresponse.WriteJSON(w, http.StatusOK, resp) + case "hugging-face-id": + // Sets (or clears) the exact Hugging Face repository exposed in model + // feeds. Internal routing ids need not be valid Hugging Face paths. + var req struct { + HuggingFaceID string `json:"hugging_face_id"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF { + httpresponse.WriteJSON(w, http.StatusBadRequest, httpresponse.ErrorBody("invalid_request_error", "invalid JSON: "+err.Error())) + return + } + huggingFaceID := strings.TrimSpace(req.HuggingFaceID) + rec, err := s.store().GetModelRegistryRecord(modelID) + if err != nil { + s.writeModelRegistryStoreError(w, "get model for hugging-face-id update", err) + return + } + entry := registryEntryFromRecord(rec) + meta := make(map[string]any, len(entry.Metadata)) + for k, v := range entry.Metadata { + meta[k] = v + } + if huggingFaceID == "" { + delete(meta, huggingFaceIDMetadataKey) + } else { + meta[huggingFaceIDMetadataKey] = huggingFaceID + } + entry.Metadata = meta + if err := s.store().UpsertModelRegistryEntry(entry); err != nil { + s.writeModelRegistryStoreError(w, "update hugging-face-id", err) + return + } + s.syncCatalog() + resp := map[string]any{"status": "updated", "model_id": modelID} + if huggingFaceID == "" { + resp["hugging_face_id"] = nil + resp["note"] = "Hugging Face ID cleared — feed falls back to the model id" + } else { + resp["hugging_face_id"] = huggingFaceID + } + httpresponse.WriteJSON(w, http.StatusOK, resp) + default: + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", "model action not found")) + } +} + +func parseAdminModelActionPath(p string) (string, string, bool) { + rest := strings.TrimPrefix(p, "/v1/admin/models/") + if rest == p || rest == "" { + return "", "", false + } + for _, action := range []string{"/promote", "/status", "/runtime-parameters", "/capabilities", "/deprecation", "/openrouter-slug", "/hugging-face-id"} { + if strings.HasSuffix(rest, action) { + modelID, err := url.PathUnescape(strings.TrimSuffix(rest, action)) + if err != nil { + return "", "", false + } + return modelID, strings.TrimPrefix(action, "/"), true + } + } + return "", "", false +} diff --git a/coordinator/api/catalog/registry_capabilities_test.go b/coordinator/api/catalog/registry_capabilities_test.go new file mode 100644 index 0000000000..409a314fa5 --- /dev/null +++ b/coordinator/api/catalog/registry_capabilities_test.go @@ -0,0 +1,117 @@ +package catalog + +import ( + "bytes" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Admins can update a model's capabilities in place, which flows through to the +// OpenRouter feed's supported_features. +func TestAdminUpdateModelCapabilities(t *testing.T) { + t.Setenv("MODEL_REGISTRY_PUBLISHING_KEY", "publish-secret") + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + reg := registry.New(logger) + srv := newTestController(reg, st, logger) + + const modelID = "mlx-community/gpt-oss-20b" + entry := &store.ModelRegistryEntry{ + ID: modelID, DisplayName: "GPT-OSS 20B", Quantization: "4bit", + MaxContextLength: 131072, MaxOutputLength: 8192, MinRAMGB: 24, + Capabilities: []string{"chat"}, Status: "active", + } + files := []store.ModelVersionFile{{Path: "config.json", SizeBytes: 1, SHA256: testHash, Role: "config"}} + if err := st.SetModelVersion(entry, &store.ModelVersion{ModelID: modelID, Version: "v1", R2Prefix: ModelR2Prefix(modelID, "v1"), AggregateSHA256: testHash, TotalSizeBytes: 1, FileCount: 1, Status: "ready"}, files); err != nil { + t.Fatal(err) + } + if err := st.PromoteModelVersion(modelID, "v1"); err != nil { + t.Fatal(err) + } + + // Update capabilities via the admin action (note dupes + whitespace get normalized). + body, _ := json.Marshal(map[string]any{"capabilities": []string{"tools", " reasoning ", "tools", ""}}) + req := httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+modelID+"/capabilities", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer publish-secret") + rec := httptest.NewRecorder() + srv.AdminModelAction(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("update status = %d body = %s", rec.Code, rec.Body.String()) + } + + rec2, err := st.GetModelRegistryRecord(modelID) + if err != nil { + t.Fatal(err) + } + want := []string{"tools", "reasoning"} + if len(rec2.Capabilities) != 2 || rec2.Capabilities[0] != "tools" || rec2.Capabilities[1] != "reasoning" { + t.Fatalf("capabilities = %v, want %v", rec2.Capabilities, want) + } + + // Confirm it lights up supported_features in the OpenRouter mapping. + feats := supportedFeaturesFromCapabilities(rec2.Capabilities) + if !containsStr(feats, "tools") || !containsStr(feats, "reasoning") { + t.Errorf("supported_features = %v, want tools+reasoning", feats) + } + + // Missing body field is rejected. + bad := httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+modelID+"/capabilities", bytes.NewReader([]byte(`{}`))) + bad.Header.Set("Authorization", "Bearer publish-secret") + badRec := httptest.NewRecorder() + srv.AdminModelAction(badRec, bad) + if badRec.Code != http.StatusBadRequest { + t.Errorf("missing capabilities status = %d, want 400", badRec.Code) + } +} + +// The admin key also authorizes registry actions (capabilities update here). +func TestAdminKeyAuthorizesCapabilitiesUpdate(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + reg := registry.New(logger) + srv := newTestController(reg, st, logger) + srv.SetAdminKey("admin-key") + + const modelID = "mlx-community/gemma-4-26b" + entry := &store.ModelRegistryEntry{ + ID: modelID, DisplayName: "Gemma 4 26B", Quantization: "4bit", + MaxContextLength: 131072, MaxOutputLength: 8192, MinRAMGB: 32, + Capabilities: []string{"chat"}, Status: "active", + } + files := []store.ModelVersionFile{{Path: "config.json", SizeBytes: 1, SHA256: testHash, Role: "config"}} + if err := st.SetModelVersion(entry, &store.ModelVersion{ModelID: modelID, Version: "v1", R2Prefix: ModelR2Prefix(modelID, "v1"), AggregateSHA256: testHash, TotalSizeBytes: 1, FileCount: 1, Status: "ready"}, files); err != nil { + t.Fatal(err) + } + if err := st.PromoteModelVersion(modelID, "v1"); err != nil { + t.Fatal(err) + } + + body, _ := json.Marshal(map[string]any{"capabilities": []string{"tools", "reasoning"}}) + req := httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+modelID+"/capabilities", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer admin-key") + rec := httptest.NewRecorder() + srv.AdminModelAction(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("admin-key update status = %d body = %s", rec.Code, rec.Body.String()) + } + rec2, _ := st.GetModelRegistryRecord(modelID) + if len(rec2.Capabilities) != 2 { + t.Fatalf("capabilities = %v, want [tools reasoning]", rec2.Capabilities) + } + + // A wrong key is still rejected. + bad := httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+modelID+"/capabilities", bytes.NewReader(body)) + bad.Header.Set("Authorization", "Bearer wrong-key") + badRec := httptest.NewRecorder() + srv.AdminModelAction(badRec, bad) + if badRec.Code != http.StatusUnauthorized { + t.Errorf("wrong key status = %d, want 401", badRec.Code) + } +} diff --git a/coordinator/api/catalog/registry_errors.go b/coordinator/api/catalog/registry_errors.go new file mode 100644 index 0000000000..1bfc100d3f --- /dev/null +++ b/coordinator/api/catalog/registry_errors.go @@ -0,0 +1,24 @@ +package catalog + +import ( + "net/http" + "strings" + + "github.com/eigeninference/d-inference/coordinator/api/httpresponse" +) + +func (s *Controller) writeModelRegistryStoreError(w http.ResponseWriter, operation string, err error) { + if isModelRegistryNotFound(err) { + httpresponse.WriteJSON(w, http.StatusNotFound, httpresponse.ErrorBody("not_found", err.Error())) + return + } + s.logger.Error("model registry store error", "operation", operation, "error", err) + httpresponse.WriteJSON(w, http.StatusInternalServerError, httpresponse.ErrorBody("internal_error", "model registry store error")) +} + +func isModelRegistryNotFound(err error) bool { + if err == nil { + return false + } + return strings.Contains(strings.ToLower(err.Error()), "not found") +} diff --git a/coordinator/api/catalog/registry_metadata_test.go b/coordinator/api/catalog/registry_metadata_test.go new file mode 100644 index 0000000000..8bfbca6b14 --- /dev/null +++ b/coordinator/api/catalog/registry_metadata_test.go @@ -0,0 +1,218 @@ +package catalog + +import ( + "bytes" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestAdminSetAndClearDeprecationDate(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + reg := registry.New(logger) + srv := newTestController(reg, st, logger) + srv.SetAdminKey("admin-key") + + const modelID = "mlx-community/dep-model" + entry := &store.ModelRegistryEntry{ + ID: modelID, DisplayName: "Dep Model", Quantization: "4bit", + MaxContextLength: 8192, MaxOutputLength: 2048, MinRAMGB: 8, Status: "active", + Metadata: map[string]any{"tier": "test"}, + } + files := []store.ModelVersionFile{{Path: "config.json", SizeBytes: 1, SHA256: testHash, Role: "config"}} + if err := st.SetModelVersion(entry, &store.ModelVersion{ModelID: modelID, Version: "v1", R2Prefix: ModelR2Prefix(modelID, "v1"), AggregateSHA256: testHash, TotalSizeBytes: 1, FileCount: 1, Status: "ready"}, files); err != nil { + t.Fatal(err) + } + if err := st.PromoteModelVersion(modelID, "v1"); err != nil { + t.Fatal(err) + } + + call := func(body string) *httptest.ResponseRecorder { + var r *http.Request + if body == "" { + r = httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+modelID+"/deprecation", nil) + } else { + r = httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+modelID+"/deprecation", bytes.NewReader([]byte(body))) + } + r.Header.Set("Authorization", "Bearer admin-key") + rec := httptest.NewRecorder() + srv.AdminModelAction(rec, r) + return rec + } + + // Set a deprecation date. + if rec := call(`{"deprecation_date":"2026-06-01"}`); rec.Code != http.StatusOK { + t.Fatalf("set status = %d body = %s", rec.Code, rec.Body.String()) + } + rec1, _ := st.GetModelRegistryRecord(modelID) + if rec1.Metadata["deprecation_date"] != "2026-06-01" { + t.Fatalf("metadata deprecation_date = %v", rec1.Metadata["deprecation_date"]) + } + if rec1.Metadata["tier"] != "test" { + t.Errorf("existing metadata clobbered: %v", rec1.Metadata) + } + + // Invalid date rejected. + if rec := call(`{"deprecation_date":"June 1 2026"}`); rec.Code != http.StatusBadRequest { + t.Errorf("invalid date status = %d, want 400", rec.Code) + } + + // Clear by default: empty body removes it. + if rec := call(""); rec.Code != http.StatusOK { + t.Fatalf("clear (empty body) status = %d body = %s", rec.Code, rec.Body.String()) + } + rec2, _ := st.GetModelRegistryRecord(modelID) + if _, present := rec2.Metadata["deprecation_date"]; present { + t.Errorf("deprecation_date should be cleared, metadata = %v", rec2.Metadata) + } + if rec2.Metadata["tier"] != "test" { + t.Errorf("clear should preserve other metadata: %v", rec2.Metadata) + } + + // Set again, then clear via empty string. + _ = call(`{"deprecation_date":"2027-01-01"}`) + if rec := call(`{"deprecation_date":""}`); rec.Code != http.StatusOK { + t.Fatalf("clear (empty string) status = %d", rec.Code) + } + rec3, _ := st.GetModelRegistryRecord(modelID) + if _, present := rec3.Metadata["deprecation_date"]; present { + t.Error("empty-string deprecation_date should clear") + } +} + +func TestAdminSetAndClearOpenRouterSlug(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + reg := registry.New(logger) + srv := newTestController(reg, st, logger) + srv.SetAdminKey("admin-key") + + const modelID = "mlx-community/slug-model" + entry := &store.ModelRegistryEntry{ + ID: modelID, DisplayName: "Slug Model", Quantization: "4bit", + MaxContextLength: 8192, MaxOutputLength: 2048, MinRAMGB: 8, Status: "active", + Metadata: map[string]any{"tier": "test"}, + } + files := []store.ModelVersionFile{{Path: "config.json", SizeBytes: 1, SHA256: testHash, Role: "config"}} + if err := st.SetModelVersion(entry, &store.ModelVersion{ModelID: modelID, Version: "v1", R2Prefix: ModelR2Prefix(modelID, "v1"), AggregateSHA256: testHash, TotalSizeBytes: 1, FileCount: 1, Status: "ready"}, files); err != nil { + t.Fatal(err) + } + if err := st.PromoteModelVersion(modelID, "v1"); err != nil { + t.Fatal(err) + } + + call := func(body string) *httptest.ResponseRecorder { + var r *http.Request + if body == "" { + r = httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+modelID+"/openrouter-slug", nil) + } else { + r = httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+modelID+"/openrouter-slug", bytes.NewReader([]byte(body))) + } + r.Header.Set("Authorization", "Bearer admin-key") + rec := httptest.NewRecorder() + srv.AdminModelAction(rec, r) + return rec + } + + // Set the slug to a canonical marketplace value. + if rec := call(`{"slug":"qwen/qwen3.5-9b"}`); rec.Code != http.StatusOK { + t.Fatalf("set slug status = %d body = %s", rec.Code, rec.Body.String()) + } + rec1, _ := st.GetModelRegistryRecord(modelID) + if rec1.Metadata["openrouter_slug"] != "qwen/qwen3.5-9b" { + t.Fatalf("metadata openrouter_slug = %v", rec1.Metadata["openrouter_slug"]) + } + if openRouterSlug(modelID, rec1.Metadata) != "qwen/qwen3.5-9b" { + t.Error("override should win in the feed mapping") + } + if rec1.Metadata["tier"] != "test" { + t.Errorf("other metadata clobbered: %v", rec1.Metadata) + } + + // Clear by default (empty body) → falls back to the model id. + if rec := call(""); rec.Code != http.StatusOK { + t.Fatalf("clear slug status = %d body = %s", rec.Code, rec.Body.String()) + } + rec2, _ := st.GetModelRegistryRecord(modelID) + if _, present := rec2.Metadata["openrouter_slug"]; present { + t.Errorf("openrouter_slug should be cleared, metadata = %v", rec2.Metadata) + } + if got := openRouterSlug(modelID, rec2.Metadata); got != modelID { + t.Errorf("after clear, slug = %q, want the model id", got) + } +} + +func TestAdminSetAndClearHuggingFaceID(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{}) + reg := registry.New(logger) + srv := newTestController(reg, st, logger) + srv.SetAdminKey("admin-key") + + const ( + modelID = "qwen3.6-35b-a3b-vl-mtp-mxfp8" + huggingFaceID = "EigenLabs/Qwen3.6-35B-A3B-MLX-VL-4bit-g64-router8" + ) + entry := &store.ModelRegistryEntry{ + ID: modelID, DisplayName: "Qwen3.6 35B A3B", Quantization: "4bit", + MaxContextLength: 262144, MaxOutputLength: 8192, MinRAMGB: 32, Status: "active", + Metadata: map[string]any{"tier": "test"}, + } + files := []store.ModelVersionFile{{Path: "config.json", SizeBytes: 1, SHA256: testHash, Role: "config"}} + if err := st.SetModelVersion(entry, &store.ModelVersion{ModelID: modelID, Version: "v1", R2Prefix: ModelR2Prefix(modelID, "v1"), AggregateSHA256: testHash, TotalSizeBytes: 1, FileCount: 1, Status: "ready"}, files); err != nil { + t.Fatal(err) + } + if err := st.PromoteModelVersion(modelID, "v1"); err != nil { + t.Fatal(err) + } + + call := func(body string) *httptest.ResponseRecorder { + var r *http.Request + if body == "" { + r = httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+modelID+"/hugging-face-id", nil) + } else { + r = httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+modelID+"/hugging-face-id", bytes.NewReader([]byte(body))) + } + r.Header.Set("Authorization", "Bearer admin-key") + rec := httptest.NewRecorder() + srv.AdminModelAction(rec, r) + return rec + } + + if rec := call(`{"hugging_face_id":" ` + huggingFaceID + ` "}`); rec.Code != http.StatusOK { + t.Fatalf("set Hugging Face ID status = %d body = %s", rec.Code, rec.Body.String()) + } + rec1, err := st.GetModelRegistryRecord(modelID) + if err != nil { + t.Fatal(err) + } + if rec1.Metadata[huggingFaceIDMetadataKey] != huggingFaceID { + t.Fatalf("metadata hugging_face_id = %v", rec1.Metadata[huggingFaceIDMetadataKey]) + } + if got := huggingFaceIDForModel(modelID, rec1.Metadata); got != huggingFaceID { + t.Fatalf("feed hugging_face_id = %q, want %q", got, huggingFaceID) + } + if rec1.Metadata["tier"] != "test" { + t.Errorf("other metadata clobbered: %v", rec1.Metadata) + } + + if rec := call(""); rec.Code != http.StatusOK { + t.Fatalf("clear Hugging Face ID status = %d body = %s", rec.Code, rec.Body.String()) + } + rec2, err := st.GetModelRegistryRecord(modelID) + if err != nil { + t.Fatal(err) + } + if _, present := rec2.Metadata[huggingFaceIDMetadataKey]; present { + t.Errorf("hugging_face_id should be cleared, metadata = %v", rec2.Metadata) + } + if got := huggingFaceIDForModel(modelID, rec2.Metadata); got != modelID { + t.Errorf("after clear, hugging_face_id = %q, want model id %q", got, modelID) + } +} diff --git a/coordinator/api/catalog/registry_record.go b/coordinator/api/catalog/registry_record.go new file mode 100644 index 0000000000..1ce0219f7c --- /dev/null +++ b/coordinator/api/catalog/registry_record.go @@ -0,0 +1,47 @@ +package catalog + +import ( + "strings" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// registryEntryFromRecord copies the mutable model fields out of a stored +// record into a fresh ModelRegistryEntry, so an in-place admin update can +// change one field (e.g. capabilities or runtime parameters) and upsert it +// without dropping the others. +func registryEntryFromRecord(rec *store.ModelRegistryRecord) *store.ModelRegistryEntry { + return &store.ModelRegistryEntry{ + ID: rec.ID, + DisplayName: rec.DisplayName, + Family: rec.Family, + Architecture: rec.Architecture, + Quantization: rec.Quantization, + MaxContextLength: rec.MaxContextLength, + MaxOutputLength: rec.MaxOutputLength, + MinRAMGB: rec.MinRAMGB, + Capabilities: rec.Capabilities, + RequiredProviderCapabilities: append( + []string{}, rec.RequiredProviderCapabilities...), + Status: rec.Status, + Description: rec.Description, + RuntimeParameters: rec.RuntimeParameters, + Metadata: rec.Metadata, + } +} + +// normalizeCapabilities trims, drops empties, and de-duplicates a capability +// list while preserving first-seen order. +func normalizeCapabilities(in []string) []string { + seen := make(map[string]bool, len(in)) + out := make([]string, 0, len(in)) + for _, c := range in { + c = strings.TrimSpace(c) + if c == "" || seen[c] { + continue + } + seen[c] = true + out = append(out, c) + } + return out +} diff --git a/coordinator/api/catalog/registry_status_test.go b/coordinator/api/catalog/registry_status_test.go new file mode 100644 index 0000000000..6b61458476 --- /dev/null +++ b/coordinator/api/catalog/registry_status_test.go @@ -0,0 +1,46 @@ +package catalog + +import ( + "testing" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestRegisteringNewVersionPreservesRetiredStatus(t *testing.T) { + st := store.NewMemory(store.Config{}) + entry := &store.ModelRegistryEntry{ID: "mlx-community/retired", DisplayName: "Retired", Status: "retired", Quantization: "8bit", MaxContextLength: 32768, MaxOutputLength: 8192, MinRAMGB: 32} + files := []store.ModelVersionFile{{Path: "config.json", SizeBytes: 1, SHA256: testHash, Role: "config"}} + if err := st.SetModelVersion(entry, &store.ModelVersion{ModelID: entry.ID, Version: "v1", R2Prefix: ModelR2Prefix(entry.ID, "v1"), AggregateSHA256: testHash, TotalSizeBytes: 1, FileCount: 1, Status: "ready"}, files); err != nil { + t.Fatal(err) + } + if err := st.PromoteModelVersion(entry.ID, "v1"); err != nil { + t.Fatal(err) + } + + entry.Status = "beta" + if err := st.SetModelVersion(entry, &store.ModelVersion{ModelID: entry.ID, Version: "v2", R2Prefix: ModelR2Prefix(entry.ID, "v2"), AggregateSHA256: testHash, TotalSizeBytes: 1, FileCount: 1, Status: "ready"}, files); err != nil { + t.Fatal(err) + } + if err := st.PromoteModelVersion(entry.ID, "v2"); err != nil { + t.Fatal(err) + } + if active := st.ListActiveModelRegistry(); len(active) != 0 { + t.Fatalf("expected retired model to remain hidden after registering a new version, got %#v", active) + } +} + +func TestUpsertModelRegistryEntryPreservesExistingStatus(t *testing.T) { + st := store.NewMemory(store.Config{}) + entry := &store.ModelRegistryEntry{ID: "mlx-community/upsert", DisplayName: "Upsert", Status: "retired", Quantization: "8bit", MaxContextLength: 32768, MaxOutputLength: 8192, MinRAMGB: 32} + if err := st.UpsertModelRegistryEntry(entry); err != nil { + t.Fatal(err) + } + entry.Status = "beta" + entry.DisplayName = "Updated" + if err := st.UpsertModelRegistryEntry(entry); err != nil { + t.Fatal(err) + } + if _, err := st.GetModelRegistryRecord(entry.ID); err == nil { + t.Fatal("expected retired model to remain hidden after upsert") + } +} diff --git a/coordinator/api/catalog/registry_validation.go b/coordinator/api/catalog/registry_validation.go new file mode 100644 index 0000000000..eee4ef3fe3 --- /dev/null +++ b/coordinator/api/catalog/registry_validation.go @@ -0,0 +1,88 @@ +package catalog + +import ( + "fmt" + "strings" + + "github.com/eigeninference/d-inference/coordinator/registry" +) + +func validateRegisterModelRequest(req registerModelRequest) error { + if err := req.HuggingFaceArtifact.Validate(); err != nil { + return err + } + if strings.TrimSpace(req.ModelID) == "" { + return fmt.Errorf("model_id is required") + } + if strings.TrimSpace(req.Version) == "" { + return fmt.Errorf("version is required") + } + if !validRegistryIdentifier(req.ModelID, true) { + return fmt.Errorf("model_id contains invalid characters or path components") + } + if !validRegistryIdentifier(req.Version, false) { + return fmt.Errorf("version contains invalid characters or path components") + } + if strings.TrimSpace(req.Quantization) == "" { + return fmt.Errorf("quantization is required") + } + if req.MaxContextLength <= 0 { + return fmt.Errorf("max_context_length must be greater than zero") + } + if req.MaxOutputLength <= 0 { + return fmt.Errorf("max_output_length must be greater than zero") + } + if req.MinRAMGB <= 0 { + return fmt.Errorf("min_ram_gb must be greater than zero") + } + if req.InputPrice <= 0 { + return fmt.Errorf("input_price is required and must be positive (micro-USD per 1M tokens)") + } + if req.OutputPrice <= 0 { + return fmt.Errorf("output_price is required and must be positive (micro-USD per 1M tokens)") + } + if err := validateRequiredProviderCapabilities( + req.ModelID, req.RequiredProviderCapabilities); err != nil { + return err + } + return nil +} + +func validateRequiredProviderCapabilities(modelID string, capabilities []string) error { + seen := make(map[string]struct{}, len(capabilities)) + for _, capability := range capabilities { + if capability == "" || capability != strings.TrimSpace(capability) { + return fmt.Errorf("required_provider_capabilities contains a malformed capability name") + } + switch capability { + case registry.ProviderCapabilityAppleM5, registry.ProviderCapabilityMLXNAX: + default: + return fmt.Errorf("required_provider_capabilities contains unknown capability %q", capability) + } + if _, duplicate := seen[capability]; duplicate { + return fmt.Errorf("required_provider_capabilities contains duplicate capability %q", capability) + } + seen[capability] = struct{}{} + } + if modelID == registry.Qwen38NAXModelID { + for _, required := range []string{ + registry.ProviderCapabilityAppleM5, + registry.ProviderCapabilityMLXNAX, + } { + if _, ok := seen[required]; !ok { + return fmt.Errorf( + "model %q requires provider capability %q", modelID, required) + } + } + } + return nil +} + +func validModelStatus(status string) bool { + switch status { + case "beta", "active", "deprecated", "retired": + return true + default: + return false + } +} diff --git a/coordinator/api/catalog/store.go b/coordinator/api/catalog/store.go new file mode 100644 index 0000000000..8f733937f8 --- /dev/null +++ b/coordinator/api/catalog/store.go @@ -0,0 +1,23 @@ +package catalog + +import "github.com/eigeninference/d-inference/coordinator/store" + +// Store is the persistence surface used by model publishing and discovery. +// Transaction, validation, and record-cache ownership stay in the store layer. +type Store interface { + ListActiveModelRegistryWithError() ([]store.ModelRegistryRecord, error) + GetModelRegistryRecord(modelID string) (*store.ModelRegistryRecord, error) + GetModelManifest(modelID string) (*store.ModelManifest, error) + UpsertModelRegistryEntry(entry *store.ModelRegistryEntry) error + SetModelVersion(entry *store.ModelRegistryEntry, version *store.ModelVersion, files []store.ModelVersionFile) error + PromoteModelVersion(modelID, version string) error + SetModelStatus(modelID, status string) error + GetModelPrice(accountID, model string) (inputPrice, outputPrice int64, ok bool) + SetModelPrice(accountID, model string, inputPrice, outputPrice int64) error + FindPublishingAPIKeysWithError() ([]store.PublishingAPIKey, error) + MarkPublishingAPIKeyUsed(id string) error + GetModelAlias(aliasID string) (alias *store.ModelAlias, ok bool, err error) + ListModelAliases() ([]store.ModelAlias, error) + UpsertModelAlias(alias *store.ModelAlias) error + DeleteModelAlias(aliasID string) error +} diff --git a/coordinator/api/catalog_controller.go b/coordinator/api/catalog_controller.go new file mode 100644 index 0000000000..fda3dfd401 --- /dev/null +++ b/coordinator/api/catalog_controller.go @@ -0,0 +1,123 @@ +package api + +import ( + "net/http" + + "github.com/eigeninference/d-inference/coordinator/api/catalog" + "github.com/eigeninference/d-inference/coordinator/inference/ingress" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// catalogController shares one alias lock and the API's existing cache across +// every catalog route and runtime sync. Lazy binding also supports focused API +// fixtures that construct a Server before using catalog operations. +func (s *Server) catalogController() *catalog.Controller { + s.catalogOnce.Do(func() { + s.modelCatalog = catalog.New(catalog.Dependencies{ + Store: func() catalog.Store { return s.store }, + Models: s.registry, Cache: s.readCache, Logger: s.logger, + AdminKey: func() string { return s.adminKey }, + SelfRouteAccount: func(r *http.Request) (string, bool) { + policy := ingress.ResolveSelfRoutePolicy(r) + return policy.OwnerAccountID, policy.Enabled + }, + SyncCatalog: s.SyncModelCatalog, + }) + }) + return s.modelCatalog +} + +// SyncModelCatalog reads active models from the store and updates the +// registry's model catalog. Call this at startup and after admin catalog changes. +func (s *Server) SyncModelCatalog() { + registryRows, err := s.store.ListActiveModelRegistryWithError() + if err != nil { + s.logger.Error("model registry catalog sync failed", "error", err) + return + } + entries := make([]registry.CatalogEntry, 0, len(registryRows)) + for _, row := range registryRows { + if row.ActiveVersion == nil { + continue + } + entries = append(entries, registry.CatalogEntry{ + ID: row.ID, + WeightHash: row.ActiveVersion.AggregateSHA256, + SizeGB: float64(row.ActiveVersion.TotalSizeBytes) / 1e9, + MinRAMGB: row.MinRAMGB, + RequiredProviderCapabilities: append( + []string{}, row.RequiredProviderCapabilities...), + }) + } + // Advance the prompt-artifact generation before publishing new routing + // hashes. Cache planning also carries and compares the aggregate hash, so + // either side of this handoff is fail-cold under concurrent requests. + if err := s.reconcilePromptArtifacts(registryRows); err != nil { + s.logger.Error("prompt artifact catalog reconcile rejected", "error", err) + } + s.registry.SetModelCatalog(entries) + s.logger.Info("model registry catalog synced to registry", "active_models", len(entries)) + + s.syncModelAliases(registryRows) + // Catalog capability changes can invalidate an in-flight desired-model + // prefetch even when alias pointers did not change. Re-publish the filtered + // desired state immediately; newly ineligible providers receive an empty + // set, which cancels stale reconciliation work. + s.fanOutDesiredModels() + s.invalidateCatalogCache() +} + +// syncModelAliases loads standard rollout aliases first, then resolves +// OpenRouter-only aliases through either a standard alias or an active concrete +// catalog model. OpenRouter-only targets route requests but do not participate +// in provider convergence or canonical public naming. +func (s *Server) syncModelAliases(registryRows []store.ModelRegistryRecord) { + aliases, err := s.store.ListModelAliases() + if err != nil { + s.logger.Error("model alias sync failed", "error", err) + return + } + resolved := make(map[string]registry.AliasTarget, len(aliases)) + activeConcreteModels := make(map[string]struct{}, len(registryRows)) + for _, row := range registryRows { + if row.ActiveVersion != nil { + activeConcreteModels[row.ID] = struct{}{} + } + } + for _, a := range aliases { + if !a.Active || a.OpenRouterOnly || a.DesiredBuild == "" { + continue + } + resolved[a.AliasID] = registry.AliasTarget{ + Desired: a.DesiredBuild, + Previous: a.PreviousBuild, + Retired: a.RetiredBuilds, + } + } + for _, a := range aliases { + if !a.Active || !a.OpenRouterOnly { + continue + } + var target registry.AliasTarget + var ok bool + if catalog.AliasUsesConcreteSource(a) { + if _, ok = activeConcreteModels[a.SourceModel]; ok { + target = registry.AliasTarget{Desired: a.SourceModel} + } + } else { + target, ok = resolved[a.SourceModel] + } + if !ok { + s.logger.Warn("OpenRouter alias source is unavailable", "alias_id", a.AliasID, "source_model", a.SourceModel) + continue + } + target.OpenRouterOnly = true + resolved[a.AliasID] = target + } + s.registry.SetModelAliases(resolved) + s.logger.Info("model aliases synced to registry", "active_aliases", len(resolved)) +} + +// invalidateCatalogCache applies the catalog owner's existing shared-cache invalidation. +func (s *Server) invalidateCatalogCache() { s.catalogController().Invalidate() } diff --git a/coordinator/api/catalog_controller_test.go b/coordinator/api/catalog_controller_test.go new file mode 100644 index 0000000000..9e74e02fde --- /dev/null +++ b/coordinator/api/catalog_controller_test.go @@ -0,0 +1,101 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/eigeninference/d-inference/coordinator/api/types" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// The mounted catalog routes must keep current publishing credentials and +// persistence bindings. A successful mutation also publishes routing state and +// removes the previously cached listing before the next request. +func TestCatalogControllerUsesCurrentBindingsAndInvalidatesPublishedViews(t *testing.T) { + t.Setenv("MODEL_REGISTRY_PUBLISHING_KEY", "") + srv, initial := newKeyTestServer(t) + t.Cleanup(srv.Close) + const modelID, replacementID = "catalog-controller-model", "catalog-controller-replacement" + seedActiveModel(t, initial, modelID, "Before replacement") + srv.SyncModelCatalog() + srv.SetAdminKey("catalog-admin-before") + handler := srv.Handler() + request := func(method, path, token, body string, want int) *httptest.ResponseRecorder { + t.Helper() + r := httptest.NewRequest(method, path, strings.NewReader(body)) + if token != "" { + r.Header.Set("Authorization", "Bearer "+token) + } + w := httptest.NewRecorder() + handler.ServeHTTP(w, r) + if w.Code != want { + t.Fatalf("%s %s: status=%d want=%d body=%s", method, path, w.Code, want, w.Body.String()) + } + return w + } + feed := func(token, wantID, wantName string) types.OpenRouterModel { + t.Helper() + w := request(http.MethodGet, "/v1/models/openrouter", token, "", http.StatusOK) + var response types.OpenRouterModelsResponse + if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + if len(response.Data) != 1 || response.Data[0].ID != wantID || response.Data[0].Name != wantName { + t.Fatalf("feed=%+v, want the current %q model", response.Data, wantName) + } + return response.Data[0] + } + feed("catalog-admin-before", modelID, "Before replacement") + request(http.MethodGet, "/v1/models/catalog", "", "", http.StatusOK) + + replacement := store.NewMemory(store.Config{}) + seedActiveModel(t, replacement, replacementID, "After replacement") + // Existing API fixtures replace persistence after routes are mounted. The + // controller must resolve that same live binding for reads and writes. + srv.store = replacement + srv.SetAdminKey("catalog-admin-after") + path := "/v1/admin/models/" + replacementID + "/capabilities" + body := `{"capabilities":["tools","reasoning"]}` + request(http.MethodPost, path, "catalog-admin-before", body, http.StatusUnauthorized) + request(http.MethodPost, path, "catalog-admin-after", body, http.StatusOK) + old, err := initial.GetModelRegistryRecord(modelID) + if err != nil { + t.Fatal(err) + } + if len(old.Capabilities) != 1 || old.Capabilities[0] != "chat" { + t.Fatalf("mutation reached the replaced store: %+v", old.Capabilities) + } + current, err := replacement.GetModelRegistryRecord(replacementID) + if err != nil { + t.Fatal(err) + } + if len(current.Capabilities) != 2 || current.Capabilities[0] != "tools" || current.Capabilities[1] != "reasoning" { + t.Fatalf("current store did not receive capabilities: %+v", current.Capabilities) + } + if !srv.registry.IsModelInCatalog(replacementID) || srv.registry.IsModelInCatalog(modelID) { + t.Fatal("successful mutation did not publish the routing catalog") + } + model := feed("catalog-admin-after", replacementID, "After replacement") + if len(model.SupportedFeatures) != 2 || model.SupportedFeatures[0] != "reasoning" || model.SupportedFeatures[1] != "tools" { + t.Fatalf("cached feed did not observe the mutation: %+v", model.SupportedFeatures) + } + w := request(http.MethodGet, "/v1/models/catalog", "", "", http.StatusOK) + var install struct { + Models []struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + Capabilities []string `json:"capabilities"` + } `json:"models"` + } + if err := json.Unmarshal(w.Body.Bytes(), &install); err != nil { + t.Fatal(err) + } + if len(install.Models) != 1 || install.Models[0].ID != replacementID || install.Models[0].DisplayName != "After replacement" || len(install.Models[0].Capabilities) != 2 { + t.Fatalf("cached install catalog did not observe the mutation: %+v", install.Models) + } + srv.SetAdminKey("") + request(http.MethodPost, path, "catalog-admin-after", body, http.StatusUnauthorized) +} diff --git a/coordinator/api/catalog_fixture_helpers_test.go b/coordinator/api/catalog_fixture_helpers_test.go new file mode 100644 index 0000000000..133a2e9052 --- /dev/null +++ b/coordinator/api/catalog_fixture_helpers_test.go @@ -0,0 +1,21 @@ +package api + +import ( + "strconv" +) + +func modelEntriesCacheKey(includeBuilds bool) string { + return "models:entries:v1:include_builds=" + strconv.FormatBool(includeBuilds) +} + +func modelListBodyCacheKey(includeBuilds bool) string { + return "models:list:v1:include_builds=" + strconv.FormatBool(includeBuilds) +} + +const openRouterFeedCacheKey = "models:openrouter:v1" + +const huggingFaceIDMetadataKey = "hugging_face_id" + +// maxAliasIDLength bounds the public alias id; it appears in URLs, response +// bodies, and SSE chunks, so it must stay short and single-segment. +const maxAliasIDLength = 128 diff --git a/coordinator/api/chat_response.go b/coordinator/api/chat_response.go deleted file mode 100644 index f628cba6b7..0000000000 --- a/coordinator/api/chat_response.go +++ /dev/null @@ -1,298 +0,0 @@ -package api - -import ( - "encoding/json" - "math" - "regexp" - "strconv" - "strings" - "time" - - "github.com/eigeninference/d-inference/coordinator/api/types" - "github.com/eigeninference/d-inference/coordinator/protocol" -) - -var thinkBlockPattern = regexp.MustCompile(`(?is)(.*?)\s*`) - -// rewriteRawFinishReason corrects a provider-reported "stop" finish_reason to -// "length" on a raw chat.completion object when the authoritative token counts -// show generation consumed the entire max-tokens budget. -func rewriteRawFinishReason(obj map[string]any, usage protocol.UsageInfo, requestedMax int) { - if !truncatedByMaxTokens(usage, requestedMax) { - return - } - choices, ok := obj["choices"].([]any) - if !ok { - return - } - for _, rawChoice := range choices { - if choice, ok := rawChoice.(map[string]any); ok { - if fr, _ := choice["finish_reason"].(string); fr == "stop" { - choice["finish_reason"] = "length" - } - } - } -} - -func normalizeCompleteChatResponse(obj map[string]any, requestedModel string) { - if requestedModel != "" { - obj["model"] = requestedModel - } - for _, key := range []string{"system_fingerprint"} { - if v, ok := obj[key]; ok && v == nil { - delete(obj, key) - } - } - choices, ok := obj["choices"].([]any) - if !ok { - return - } - for choicePosition, rawChoice := range choices { - choice, ok := rawChoice.(map[string]any) - if !ok { - continue - } - choiceIndex := normalizedChoiceIndex(choice["index"], choicePosition) - if message, ok := choice["message"].(map[string]any); ok { - normalizeCompleteMessage(message, choiceIndex) - } - if delta, ok := choice["delta"].(map[string]any); ok { - normalizeCompleteMessage(delta, choiceIndex) - } - } -} - -func canonicalReasoningDetails(reasoning string, choiceIndex int) []types.ReasoningDetail { - return []types.ReasoningDetail{{ - Type: "reasoning.text", - Text: reasoning, - ID: "reasoning-text-" + strconv.Itoa(choiceIndex), - Format: "unknown", - Index: 0, - }} -} - -func normalizedChoiceIndex(raw any, fallback int) int { - switch index := raw.(type) { - case int: - if index >= 0 { - return index - } - case int64: - converted := int(index) - if index >= 0 && int64(converted) == index { - return converted - } - case float64: - intLimit := math.Ldexp(1, strconv.IntSize-1) - if math.IsNaN(index) || math.IsInf(index, 0) || index < 0 || index >= intLimit || math.Trunc(index) != index { - break - } - return int(index) - case json.Number: - if parsed, err := strconv.ParseInt(index.String(), 10, strconv.IntSize); err == nil && parsed >= 0 { - return int(parsed) - } - } - return fallback -} - -func normalizeCompleteMessage(message map[string]any, choiceIndex int) { - var extractedReasoning string - if content, ok := message["content"]; !ok || content == nil { - message["content"] = "" - } else if contentText, ok := content.(string); ok { - cleaned, reasoning := stripThinkBlocks(contentText) - message["content"] = cleaned - extractedReasoning = reasoning - } - - if rc, ok := message["reasoning_content"]; ok { - if rcText, ok := rc.(string); ok && rcText != "" { - mergeReasoningField(message, rcText) - } - delete(message, "reasoning_content") - } - if reasoning, ok := message["reasoning"]; ok && reasoning == nil { - delete(message, "reasoning") - } - if extractedReasoning != "" { - mergeReasoningField(message, extractedReasoning) - } - if reasoning, ok := message["reasoning"].(string); ok && reasoning != "" { - message["reasoning_content"] = reasoning - if _, hasDetails := message["reasoning_details"]; !hasDetails { - message["reasoning_details"] = canonicalReasoningDetails(reasoning, choiceIndex) - } - } - for _, key := range []string{"tool_calls", "refusal"} { - if v, ok := message[key]; ok && v == nil { - delete(message, key) - } - } -} - -func mergeReasoningField(message map[string]any, reasoning string) { - reasoning = strings.TrimSpace(reasoning) - if reasoning == "" { - return - } - if existing, ok := message["reasoning"].(string); ok && strings.TrimSpace(existing) != "" { - if existing != reasoning && !strings.Contains(existing, reasoning) { - message["reasoning"] = existing + "\n\n" + reasoning - } - return - } - message["reasoning"] = reasoning -} - -func stripThinkBlocks(text string) (string, string) { - matches := thinkBlockPattern.FindAllStringSubmatch(text, -1) - reasoningParts := make([]string, 0, len(matches)+1) - found := len(matches) > 0 - for _, match := range matches { - if len(match) > 1 { - if part := strings.TrimSpace(match[1]); part != "" { - reasoningParts = append(reasoningParts, part) - } - } - } - cleaned := thinkBlockPattern.ReplaceAllString(text, "") - lower := strings.ToLower(cleaned) - if idx := strings.Index(lower, ""); idx >= 0 { - found = true - if part := strings.TrimSpace(cleaned[idx+len(""):]); part != "" { - reasoningParts = append(reasoningParts, part) - } - cleaned = cleaned[:idx] - } - if !found { - return text, "" - } - return strings.TrimSpace(cleaned), strings.Join(reasoningParts, "\n\n") -} - -// injectReasoningDetailIntoRawUsage splices -// completion_tokens_details.reasoning_tokens into a passthrough -// chat.completion object when the provider reported an accurate -// reasoning-token count (UsageInfo.ReasoningTokens) and the raw usage -// object didn't already carry the detail. It never overrides a value the -// provider already supplied, and is a no-op when there is no reasoning -// count or no usage object. -func injectReasoningDetailIntoRawUsage(obj map[string]any, usage protocol.UsageInfo) { - if usage.ReasoningTokens <= 0 { - return - } - usageObj, ok := obj["usage"].(map[string]any) - if !ok { - return - } - details, _ := usageObj["completion_tokens_details"].(map[string]any) - if details == nil { - details = map[string]any{} - } - if _, exists := details["reasoning_tokens"]; exists { - return - } - details["reasoning_tokens"] = usage.ReasoningTokens - usageObj["completion_tokens_details"] = details - obj["usage"] = usageObj -} - -// truncatedByMaxTokens reports whether generation consumed the entire -// max-tokens budget. requestedMax is the effective bound — the consumer's -// explicit max_tokens or the coordinator-injected default — so hitting it -// means the engine cut generation short. -func truncatedByMaxTokens(usage protocol.UsageInfo, requestedMax int) bool { - return requestedMax > 0 && usage.CompletionTokens >= requestedMax -} - -// effectiveFinishReason resolves the finish_reason for a reconstructed -// response. The provider engine reports "stop" unconditionally, so a -// truncation-aware reason is re-derived from the authoritative token counts. -func effectiveFinishReason(extracted string, hasToolCalls bool, usage protocol.UsageInfo, requestedMax int) string { - if extracted != "" && extracted != "stop" { - return extracted - } - if truncatedByMaxTokens(usage, requestedMax) { - return "length" - } - if hasToolCalls { - return "tool_calls" - } - return "stop" -} - -// resolveReasoningTokens returns the reasoning-token count to report. -// It prefers the provider's tokenizer-accurate count -// (UsageInfo.ReasoningTokens) and falls back to the coarse "all -// completion tokens" estimate only for older providers that emit -// reasoning content without a count — so a reasoning response never -// reports zero reasoning tokens, while up-to-date providers report the -// real split. -func resolveReasoningTokens(usage protocol.UsageInfo, reasoning string) uint64 { - if usage.ReasoningTokens > 0 { - return uint64(usage.ReasoningTokens) - } - if reasoning != "" { - return uint64(usage.CompletionTokens) - } - return 0 -} - -func buildNonStreamingResponse(requestID, model string, msg extractedMessage, usage protocol.UsageInfo, requestedMax int, seSignature, responseHash string) types.ChatCompletionResponse { - message := types.ChatCompletionMessage{ - Role: "assistant", - Content: msg.Content, - } - if msg.Reasoning != "" { - message.Reasoning = msg.Reasoning - message.ReasoningContent = msg.Reasoning - } - if msg.ReasoningDetailsPresent { - message.ReasoningDetails = msg.ReasoningDetails - } else if msg.Reasoning != "" { - message.ReasoningDetails = canonicalReasoningDetails(msg.Reasoning, 0) - } - - if len(msg.ToolCalls) > 0 { - message.ToolCalls = msg.ToolCalls - } - finishReason := effectiveFinishReason(msg.FinishReason, len(msg.ToolCalls) > 0, usage, requestedMax) - - resp := types.ChatCompletionResponse{ - ID: "chatcmpl-" + requestID, - Object: "chat.completion", - Created: time.Now().Unix(), - Model: model, - Choices: []types.ChatCompletionChoice{{ - Index: 0, - Message: message, - FinishReason: finishReason, - }}, - Usage: types.ChatCompletionUsage{ - PromptTokens: usage.PromptTokens, - CompletionTokens: usage.CompletionTokens, - TotalTokens: usage.PromptTokens + usage.CompletionTokens, - }, - } - - // Surface the OpenAI-standard reasoning-token breakdown when present - // so non-streaming chat-completions consumers can read it (the - // streaming path carries it on the provider's verbatim usage chunk). - if rt := resolveReasoningTokens(usage, msg.Reasoning); rt > 0 { - resp.Usage.CompletionTokensDetails = &types.CompletionTokensDetails{ - ReasoningTokens: int(rt), - } - } - if usage.CachedTokens > 0 { - resp.Usage.PromptTokensDetails = &types.PromptTokensDetails{CachedTokens: usage.CachedTokens} - } - - if seSignature != "" { - resp.SESignature = seSignature - resp.ResponseHash = responseHash - } - - return resp -} diff --git a/coordinator/api/chat_stream_relay_test.go b/coordinator/api/chat_stream_relay_test.go index 1893cf2835..bbb9e83902 100644 --- a/coordinator/api/chat_stream_relay_test.go +++ b/coordinator/api/chat_stream_relay_test.go @@ -9,15 +9,13 @@ package api import ( "bytes" "context" + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" "net/http" "net/http/httptest" "strconv" "strings" "testing" - "time" - - "github.com/eigeninference/d-inference/coordinator/protocol" - "github.com/eigeninference/d-inference/coordinator/registry" ) // capturingResponseWriter is countingResponseWriter plus the body itself and @@ -41,77 +39,6 @@ func (w *capturingResponseWriter) Write(p []byte) (int, error) { return w.countingResponseWriter.Write(p) } -// Frames whose total exceeds the cap go out in batches no larger than the cap, -// in order and byte-for-byte, the profile still counts every frame, and the -// buffer that carried them does not keep a backing array larger than the cap. -func TestChatStreamRelay_ByteCapFlushesBeforeAppendExceedsIt(t *testing.T) { - w := newCapturingResponseWriter() - rp := registry.NewRequestProfile(time.Now(), "c", nil, 0) - relay := newChatStreamRelay(®istry.PendingRequest{}, w, w, newRelayStamps(rp)) - - // 100 KiB frames against the 256 KiB cap: two fit, the third would - // overflow and forces the flush before it is appended. - frame := "data: " + strings.Repeat("x", 100<<10) - const n = 7 - var want strings.Builder - for i := 0; i < n; i++ { - relay.writeFrame(frame) - want.WriteString(frame + "\n\n") - } - if w.flushes != 3 || w.writes != 3 { - t.Fatalf("after %d frames: %d writes / %d flushes, want 3 / 3 (two frames per batch, one pending)", n, w.writes, w.flushes) - } - relay.flush() - if w.flushes != 4 || w.writes != 4 { - t.Fatalf("final flush: %d writes / %d flushes, want 4 / 4", w.writes, w.flushes) - } - if w.body.String() != want.String() { - t.Fatalf("byte stream diverged: got %d bytes, want %d", w.body.Len(), want.Len()) - } - if w.maxWrite > maxCoalescedBatchBytes { - t.Fatalf("largest write = %d bytes, exceeds the %d-byte cap", w.maxWrite, maxCoalescedBatchBytes) - } - if got := relay.buf.Cap(); got > maxCoalescedBatchBytes { - t.Fatalf("buffer retained %d bytes of capacity after the burst, want <= %d", got, maxCoalescedBatchBytes) - } - if rp.ChunksOut.Load() != n || rp.BytesOut.Load() != int64(want.Len()) { - t.Fatalf("profile chunks_out=%d bytes_out=%d, want %d / %d", rp.ChunksOut.Load(), rp.BytesOut.Load(), n, want.Len()) - } -} - -// A frame larger than the cap (a provider chunk near the 10 MiB read limit) is -// still relayed intact as one write — after the pending batch — and the buffer -// that held it is released rather than pinned for the rest of the stream. -func TestChatStreamRelay_OversizedFrameIsWrittenWholeAndReleased(t *testing.T) { - w := newCapturingResponseWriter() - relay := newChatStreamRelay(®istry.PendingRequest{}, w, w, nil) - - small := `data: {"a":1}` - big := "data: " + strings.Repeat("y", 2*maxCoalescedBatchBytes) - relay.writeFrame(small) - relay.writeFrame(big) - if w.writes != 1 || w.body.String() != small+"\n\n" { - t.Fatalf("the pending frame must be flushed ahead of an oversized one: writes=%d body=%q", w.writes, w.body.String()) - } - relay.flush() - want := small + "\n\n" + big + "\n\n" - if w.writes != 2 || w.flushes != 2 || w.body.String() != want { - t.Fatalf("oversized frame: %d writes / %d flushes, body %d bytes; want 2 / 2 / %d", w.writes, w.flushes, w.body.Len(), len(want)) - } - if w.maxWrite != len(big)+2 { - t.Fatalf("oversized frame was not written whole: largest write = %d, want %d", w.maxWrite, len(big)+2) - } - if got := relay.buf.Cap(); got != 0 { - t.Fatalf("buffer retained %d bytes of capacity after an oversized batch, want released", got) - } - // The relay keeps working on a fresh buffer. - relay.writeFrame(small) - relay.flush() - if w.body.String() != want+small+"\n\n" { - t.Fatalf("relay broken after releasing the buffer: %q", w.body.String()) - } -} - // A prefilled burst of large chunks relayed through the chat streaming path // never puts more than maxCoalescedBatchBytes in one write, costs more flushes // than the chunk-count bound alone would allow (the byte cap engaged), and diff --git a/coordinator/api/chunk_key_cache.go b/coordinator/api/chunk_key_cache.go deleted file mode 100644 index 92db6d996e..0000000000 --- a/coordinator/api/chunk_key_cache.go +++ /dev/null @@ -1,71 +0,0 @@ -package api - -import ( - "sync" - - "github.com/eigeninference/d-inference/coordinator/internal/e2e" -) - -// chunkKeyCacheMax bounds the cache. Entries are removed proactively when a -// request completes or errors; the cap is a safety net for abandoned requests -// (provider disconnect mid-stream). At 8192 entries the cache is ~1 MiB. When -// full it is dropped wholesale — it is a pure cache, so a reset only costs one -// X25519 recompute per live stream. -const chunkKeyCacheMax = 8192 - -// chunkKeyCache memoizes the NaCl box shared key per inference request so the -// per-token chunk decrypt path performs only the symmetric open, not a fresh -// X25519 scalar multiplication per chunk (~40-60µs each, serialized on the -// provider's single read goroutine). -// -// Keyed by the request's SessionPrivKey pointer, which is unique and stable -// per PendingRequest. The provider public key is stored alongside so a peer -// key change (paranoia: reconnect races) invalidates the entry instead of -// decrypting with a stale shared key. -// -// The zero value is ready to use. -type chunkKeyCache struct { - mu sync.Mutex - m map[*[32]byte]chunkKeyEntry -} - -type chunkKeyEntry struct { - peerPub string - shared *[32]byte -} - -// sharedKey returns the memoized shared key for (priv, peerPub), computing and -// caching it on first use. peerPub is the provider's base64 X25519 public key, -// already validated by the caller against the chunk's ephemeral key. -func (c *chunkKeyCache) sharedKey(priv *[32]byte, peerPub string) (*[32]byte, error) { - c.mu.Lock() - if e, ok := c.m[priv]; ok && e.peerPub == peerPub { - c.mu.Unlock() - return e.shared, nil - } - c.mu.Unlock() - - pub, err := e2e.ParsePublicKey(peerPub) - if err != nil { - return nil, err - } - shared := e2e.PrecomputeSharedKey(&pub, priv) - - c.mu.Lock() - if c.m == nil || len(c.m) >= chunkKeyCacheMax { - c.m = make(map[*[32]byte]chunkKeyEntry) - } - c.m[priv] = chunkKeyEntry{peerPub: peerPub, shared: shared} - c.mu.Unlock() - return shared, nil -} - -// forget drops the cached shared key for a finished request. -func (c *chunkKeyCache) forget(priv *[32]byte) { - if priv == nil { - return - } - c.mu.Lock() - delete(c.m, priv) - c.mu.Unlock() -} diff --git a/coordinator/api/chunk_key_cache_test.go b/coordinator/api/chunk_key_cache_test.go deleted file mode 100644 index 52d781bac4..0000000000 --- a/coordinator/api/chunk_key_cache_test.go +++ /dev/null @@ -1,299 +0,0 @@ -package api - -import ( - "crypto/rand" - "encoding/base64" - "sync" - "testing" - - "golang.org/x/crypto/nacl/box" - - "github.com/eigeninference/d-inference/coordinator/internal/e2e" -) - -// testPeerKeyB64 generates a fresh X25519 keypair and returns the base64 -// public key plus the raw pair, for driving chunkKeyCache directly. -func testPeerKeyB64(t *testing.T) (string, *[32]byte, *[32]byte) { - t.Helper() - pub, priv, err := box.GenerateKey(rand.Reader) - if err != nil { - t.Fatalf("generate peer keys: %v", err) - } - return base64.StdEncoding.EncodeToString(pub[:]), pub, priv -} - -func TestChunkKeyCacheHitReturnsIdenticalPointer(t *testing.T) { - var c chunkKeyCache - peerPub, _, _ := testPeerKeyB64(t) - priv := new([32]byte) - if _, err := rand.Read(priv[:]); err != nil { - t.Fatalf("rand: %v", err) - } - - first, err := c.sharedKey(priv, peerPub) - if err != nil { - t.Fatalf("sharedKey (miss): %v", err) - } - second, err := c.sharedKey(priv, peerPub) - if err != nil { - t.Fatalf("sharedKey (hit): %v", err) - } - if first != second { - t.Error("cache hit should return the identical *[32]byte pointer") - } -} - -// TestChunkKeyCacheSharedKeyDecrypts verifies the cached key is the real NaCl -// box shared key: a payload encrypted by the peer must open with it, matching -// the e2e.Decrypt reference path. -func TestChunkKeyCacheSharedKeyDecrypts(t *testing.T) { - var c chunkKeyCache - peerPubB64, peerPub, peerPriv := testPeerKeyB64(t) - - session, err := e2e.GenerateSessionKeys() - if err != nil { - t.Fatalf("GenerateSessionKeys: %v", err) - } - plaintext := []byte(`data: {"choices":[{"delta":{"content":"tok"}}]}`) - payload, err := e2e.Encrypt(plaintext, session.PublicKey, &e2e.SessionKeys{ - PublicKey: *peerPub, - PrivateKey: *peerPriv, - }) - if err != nil { - t.Fatalf("Encrypt: %v", err) - } - - shared, err := c.sharedKey(&session.PrivateKey, peerPubB64) - if err != nil { - t.Fatalf("sharedKey: %v", err) - } - got, err := e2e.DecryptWithSharedKey(payload, shared) - if err != nil { - t.Fatalf("DecryptWithSharedKey: %v", err) - } - if string(got) != string(plaintext) { - t.Errorf("decrypted = %q, want %q", got, plaintext) - } -} - -func TestChunkKeyCachePeerPubChangeRecomputes(t *testing.T) { - var c chunkKeyCache - peerA, _, _ := testPeerKeyB64(t) - peerB, _, _ := testPeerKeyB64(t) - priv := new([32]byte) - if _, err := rand.Read(priv[:]); err != nil { - t.Fatalf("rand: %v", err) - } - - forA, err := c.sharedKey(priv, peerA) - if err != nil { - t.Fatalf("sharedKey(A): %v", err) - } - forB, err := c.sharedKey(priv, peerB) - if err != nil { - t.Fatalf("sharedKey(B): %v", err) - } - if forA == forB { - t.Error("a different peer key must not reuse the stale cached shared key") - } - if *forA == *forB { - t.Error("shared keys for different peers should differ in value") - } - - // The entry now belongs to peerB: a repeat for B hits the cache, and a - // repeat for A recomputes (single-entry-per-priv semantics). - if again, _ := c.sharedKey(priv, peerB); again != forB { - t.Error("repeat lookup for the new peer should hit the cache") - } - if againA, _ := c.sharedKey(priv, peerA); againA == forA { - t.Error("lookup for the replaced peer should recompute, not return the old pointer") - } -} - -func TestChunkKeyCacheForgetRemoves(t *testing.T) { - var c chunkKeyCache - peerPub, _, _ := testPeerKeyB64(t) - priv := new([32]byte) - if _, err := rand.Read(priv[:]); err != nil { - t.Fatalf("rand: %v", err) - } - - first, err := c.sharedKey(priv, peerPub) - if err != nil { - t.Fatalf("sharedKey: %v", err) - } - c.forget(priv) - - c.mu.Lock() - _, stillThere := c.m[priv] - c.mu.Unlock() - if stillThere { - t.Fatal("forget should remove the entry") - } - - recomputed, err := c.sharedKey(priv, peerPub) - if err != nil { - t.Fatalf("sharedKey after forget: %v", err) - } - if recomputed == first { - t.Error("post-forget lookup should be a fresh computation (new pointer)") - } - if *recomputed != *first { - t.Error("recomputed shared key should have the same value for the same inputs") - } -} - -func TestChunkKeyCacheForgetNilAndEmptyAreSafe(t *testing.T) { - var c chunkKeyCache - c.forget(nil) // nil priv is a documented no-op - c.forget(new([32]byte)) // forget on a zero-value cache (nil map) must not panic -} - -func TestChunkKeyCacheInvalidPeerKeyNotCached(t *testing.T) { - var c chunkKeyCache - priv := new([32]byte) - if _, err := c.sharedKey(priv, "not-valid-base64!!!"); err == nil { - t.Fatal("invalid peer key should error") - } - if _, err := c.sharedKey(priv, base64.StdEncoding.EncodeToString(make([]byte, 16))); err == nil { - t.Fatal("wrong-length peer key should error") - } - c.mu.Lock() - n := len(c.m) - c.mu.Unlock() - if n != 0 { - t.Errorf("failed lookups must not populate the cache, have %d entries", n) - } -} - -// TestChunkKeyCacheCapResets fills the cache past chunkKeyCacheMax and checks -// the wholesale-reset safety net: the map is dropped, stays bounded, and the -// cache keeps functioning afterwards. -func TestChunkKeyCacheCapResets(t *testing.T) { - if testing.Short() { - t.Skip("fills chunkKeyCacheMax entries (~0.5s of X25519)") - } - var c chunkKeyCache - peerPub, _, _ := testPeerKeyB64(t) - - privs := make([]*[32]byte, chunkKeyCacheMax) - for i := range privs { - privs[i] = new([32]byte) - privs[i][0] = byte(i) - privs[i][1] = byte(i >> 8) - if _, err := c.sharedKey(privs[i], peerPub); err != nil { - t.Fatalf("sharedKey fill %d: %v", i, err) - } - } - c.mu.Lock() - filled := len(c.m) - c.mu.Unlock() - if filled != chunkKeyCacheMax { - t.Fatalf("cache size after fill = %d, want %d", filled, chunkKeyCacheMax) - } - - // One past the cap: the map is reset wholesale, then the new entry lands. - overflowPriv := new([32]byte) - overflowPriv[2] = 0xAA - overflowShared, err := c.sharedKey(overflowPriv, peerPub) - if err != nil { - t.Fatalf("sharedKey overflow: %v", err) - } - c.mu.Lock() - afterReset := len(c.m) - c.mu.Unlock() - if afterReset != 1 { - t.Errorf("cache size after overflow = %d, want 1 (wholesale reset + new entry)", afterReset) - } - - // Still functions: the overflow entry hits, and an evicted entry - // recomputes to the same key value under a new pointer. - if again, _ := c.sharedKey(overflowPriv, peerPub); again != overflowShared { - t.Error("overflow entry should be cached after the reset") - } - recomputed, err := c.sharedKey(privs[0], peerPub) - if err != nil { - t.Fatalf("sharedKey recompute after reset: %v", err) - } - if recomputed == nil { - t.Fatal("recomputed shared key is nil") - } -} - -// TestChunkKeyCacheConcurrentAccess hammers sharedKey/forget from parallel -// goroutines. Run with -race. Pointer identity is deliberately NOT asserted -// across goroutines: two concurrent first-uses may both compute (the lock is -// dropped during the X25519), which is benign — the values must still match. -func TestChunkKeyCacheConcurrentAccess(t *testing.T) { - var c chunkKeyCache - peerA, _, _ := testPeerKeyB64(t) - peerB, _, _ := testPeerKeyB64(t) - - const workers = 16 - const iters = 200 - - // A mix of shared and per-goroutine privs. - sharedPrivs := make([]*[32]byte, 4) - for i := range sharedPrivs { - sharedPrivs[i] = new([32]byte) - sharedPrivs[i][0] = byte(i) - } - - // The shared key is a deterministic function of (priv, peer): precompute - // the expected value for every combination so workers can assert exact - // values no matter how lookups interleave with forgets and peer flips. - type comboKey struct { - priv *[32]byte - peer string - } - expected := make(map[comboKey][32]byte) - for _, priv := range sharedPrivs { - for _, peer := range []string{peerA, peerB} { - var ref chunkKeyCache - k, err := ref.sharedKey(priv, peer) - if err != nil { - t.Fatalf("precompute expected key: %v", err) - } - expected[comboKey{priv, peer}] = *k - } - } - - var wg sync.WaitGroup - for w := 0; w < workers; w++ { - wg.Add(1) - go func(w int) { - defer wg.Done() - ownPriv := new([32]byte) - ownPriv[0] = 0x80 - ownPriv[1] = byte(w) - for i := 0; i < iters; i++ { - priv := sharedPrivs[i%len(sharedPrivs)] - peer := peerA - if i%3 == 0 { - peer = peerB - } - k, err := c.sharedKey(priv, peer) - if err != nil { - t.Errorf("worker %d: sharedKey: %v", w, err) - return - } - if want := expected[comboKey{priv, peer}]; *k != want { - t.Errorf("worker %d: shared key value mismatch for (priv[0]=%d, peer=%s...)", - w, priv[0], peer[:8]) - return - } - if _, err := c.sharedKey(ownPriv, peerA); err != nil { - t.Errorf("worker %d: own sharedKey: %v", w, err) - return - } - if i%7 == 0 { - c.forget(priv) - } - if i%11 == 0 { - c.forget(ownPriv) - } - } - }(w) - } - wg.Wait() -} diff --git a/coordinator/api/code_attest_admission_test.go b/coordinator/api/code_attest_admission_test.go deleted file mode 100644 index c4b0f942b5..0000000000 --- a/coordinator/api/code_attest_admission_test.go +++ /dev/null @@ -1,642 +0,0 @@ -package api - -import ( - "context" - "fmt" - "io" - "log/slog" - "sync" - "sync/atomic" - "testing" - "time" - - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" -) - -type blockingCodeAttestStore struct { - *store.MemoryStore - blockSE string - started chan struct{} - release chan struct{} - once sync.Once - mu sync.Mutex - calls map[string]int -} - -func (s *blockingCodeAttestStore) ReserveCodeAttestPushBudget( - ctx context.Context, - seKey, tokenHash string, - now, nextPushAt time.Time, -) (bool, error) { - s.mu.Lock() - s.calls[seKey]++ - s.mu.Unlock() - if seKey == s.blockSE { - s.once.Do(func() { close(s.started) }) - select { - case <-ctx.Done(): - return false, ctx.Err() - case <-s.release: - } - } - return s.MemoryStore.ReserveCodeAttestPushBudget( - ctx, seKey, tokenHash, now, nextPushAt, - ) -} - -func (s *blockingCodeAttestStore) callCount(seKey string) int { - s.mu.Lock() - defer s.mu.Unlock() - return s.calls[seKey] -} - -func TestCodeAttestPushAdmissionAtomicAcrossLoopGenerations(t *testing.T) { - st := store.NewMemory(store.Config{}) - th := newCodeAttestThrottle() - th.store = st - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return now } - oldGeneration := th.beginLoop("se-one") - newGeneration := th.beginLoop("se-one") - if th.tryReservePush(context.Background(), "se-one", "token", false, oldGeneration) { - t.Fatal("superseded registration loop spent APNs budget") - } - - var admitted atomic.Int32 - var wg sync.WaitGroup - for range 64 { - wg.Add(1) - go func() { - defer wg.Done() - if th.tryReservePush(context.Background(), "se-one", "token", false, newGeneration) { - admitted.Add(1) - } - }() - } - wg.Wait() - if admitted.Load() != 1 { - t.Fatalf("concurrent registration/rearm admissions = %d, want 1", admitted.Load()) - } -} - -func TestCodeAttestTokenRotationSerializesBudgetResetWithReservation(t *testing.T) { - st := &blockingCodeAttestStore{ - MemoryStore: store.NewMemory(store.Config{}), - blockSE: "se-rotate", - started: make(chan struct{}), - release: make(chan struct{}), - calls: make(map[string]int), - } - th := newCodeAttestThrottle() - th.store = st - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return now } - oldGeneration := th.beginLoop("se-rotate") - oldResult := make(chan bool, 1) - go func() { - oldResult <- th.tryReservePush( - context.Background(), "se-rotate", "old-token", false, - oldGeneration, - ) - }() - <-st.started - - rotated := make(chan uint64, 1) - go func() { - rotated <- th.rotateLoopAndClearPushBudget(context.Background(), "se-rotate") - }() - select { - case <-rotated: - t.Fatal("token rotation bypassed the in-flight per-device reservation") - case <-time.After(20 * time.Millisecond): - } - close(st.release) - if !<-oldResult { - t.Fatal("old reservation did not complete before rotation") - } - newGeneration := <-rotated - if th.loopCurrent("se-rotate", oldGeneration) || - !th.loopCurrent("se-rotate", newGeneration) { - t.Fatal("token rotation did not atomically transfer loop ownership") - } - if !th.tryReservePush( - context.Background(), "se-rotate", "new-token", false, - newGeneration, - ) { - t.Fatal("new-token loop could not use the atomically cleared budget") - } -} - -func TestCodeAttestZeroCooldownStillMakesValidDurableReservation(t *testing.T) { - st := store.NewMemory(store.Config{}) - th := newCodeAttestThrottle() - th.store = st - th.backgroundPushCooldown = 0 - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return now } - generation := th.beginLoop("se-zero-cooldown") - if !th.tryReservePush( - context.Background(), "se-zero-cooldown", "token", false, generation, - ) { - t.Fatal("zero cooldown produced an invalid durable reservation window") - } - rows, err := st.ListCodeAttestPushBudgets(context.Background()) - if err != nil || len(rows) != 2 { // token row + admission-floor sentinel - t.Fatalf("zero-cooldown durable reservation = %+v, err=%v", rows, err) - } - for _, row := range rows { - if !row.NextPushAt.After(now) { - t.Fatalf("zero cooldown produced a non-future reservation window: %+v", row) - } - } -} - -func TestCodeAttestSlowReservationDoesNotBlockOtherDevices(t *testing.T) { - st := &blockingCodeAttestStore{ - MemoryStore: store.NewMemory(store.Config{}), - blockSE: "se-slow", started: make(chan struct{}), release: make(chan struct{}), - calls: make(map[string]int), - } - th := newCodeAttestThrottle() - th.store = st - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return now } - slowGeneration := th.beginLoop("se-slow") - fastGeneration := th.beginLoop("se-fast") - slowResult := make(chan bool, 1) - go func() { - slowResult <- th.tryReservePush( - context.Background(), "se-slow", "slow-token", false, slowGeneration, - ) - }() - <-st.started - - fastResult := make(chan bool, 1) - go func() { - fastResult <- th.tryReservePush( - context.Background(), "se-fast", "fast-token", false, fastGeneration, - ) - }() - select { - case admitted := <-fastResult: - if !admitted { - t.Fatal("unblocked device reservation was denied") - } - case <-time.After(time.Second): - t.Fatal("slow durable reservation held the fleet-global throttle mutex") - } - close(st.release) - if !<-slowResult { - t.Fatal("slow device reservation was denied after release") - } -} - -func TestCodeAttestSameDeviceConcurrentReservationAdmitsOnce(t *testing.T) { - st := &blockingCodeAttestStore{ - MemoryStore: store.NewMemory(store.Config{}), - blockSE: "se-one", started: make(chan struct{}), release: make(chan struct{}), - calls: make(map[string]int), - } - th := newCodeAttestThrottle() - th.store = st - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return now } - generation := th.beginLoop("se-one") - results := make(chan bool, 2) - go func() { - results <- th.tryReservePush( - context.Background(), "se-one", "token", false, generation, - ) - }() - <-st.started - go func() { - results <- th.tryReservePush( - context.Background(), "se-one", "token", false, generation, - ) - }() - close(st.release) - admitted := 0 - for range 2 { - if <-results { - admitted++ - } - } - if admitted != 1 { - t.Fatalf("same-device concurrent admissions = %d, want 1", admitted) - } - if calls := st.callCount("se-one"); calls != 1 { - t.Fatalf("same-device durable reservations = %d, want 1", calls) - } - th.mu.Lock() - retainedLocks := len(th.reservationLocks) - th.mu.Unlock() - if retainedLocks != 0 { - t.Fatalf("completed reservations retained %d per-device locks", retainedLocks) - } -} - -func TestCodeAttestReservationLeaseCoversPushDispatch(t *testing.T) { - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - srv := NewServer( - registry.New(logger), store.NewMemory(store.Config{}), - ServerConfig{}, logger, - ) - t.Cleanup(srv.Close) - srv.codeAttestThrottle.backgroundPushCooldown = 0 - srv.codeAttestThrottle.retrySpacing = time.Millisecond - srv.codeAttestThrottle.retryJitter = 0 - srv.codeAttestThrottle.maxAttempts = 1 - kPub, _, _, sePub := providerKeyMaterial(t) - provider := newCodeAttestProvider(kPub, sePub) - rotated := make(chan uint64, 1) - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, _, _ string) error { - go func() { - rotated <- srv.codeAttestThrottle.beginLoop(sePub) - }() - select { - case <-rotated: - t.Fatal("loop ownership rotated before reserved push dispatch finished") - case <-time.After(20 * time.Millisecond): - } - return nil - }}) - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - srv.codeAttestLoop(ctx, provider.ID, provider) - select { - case generation := <-rotated: - if generation == 0 { - t.Fatal("rotation did not acquire ownership after push dispatch") - } - case <-time.After(time.Second): - t.Fatal("reservation lease was not released after push dispatch") - } -} - -func TestCodeAttestLoopGenerationChurnRetainsNoSEKeys(t *testing.T) { - th := newCodeAttestThrottle() - const churn = 2000 - for i := range churn { - seKey := fmt.Sprintf("se-loop-churn-%d", i) - generation := th.beginLoop(seKey) - th.endLoop(seKey, generation) - } - th.mu.Lock() - generations := len(th.loopGenerations) - tokens := len(th.loopTokens) - th.mu.Unlock() - if generations != 0 || tokens != 0 { - t.Fatalf("loop churn retained per-SE state: generations=%d tokens=%d", generations, tokens) - } - if generation := th.loopGeneration.Load(); generation != churn { - t.Fatalf("global loop generation = %d, want %d", generation, churn) - } -} - -func TestCodeAttestPushCooldownSurvivesCoordinatorRestart(t *testing.T) { - st := store.NewMemory(store.Config{}) - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - first := newCodeAttestThrottle() - first.store = st - first.now = func() time.Time { return now } - gen := first.beginLoop("se-restart") - if !first.tryReservePush(context.Background(), "se-restart", "token", false, gen) { - t.Fatal("initial durable push admission rejected") - } - - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - srv := NewServer(registry.New(logger), st, ServerConfig{}, logger) - t.Cleanup(srv.Close) - srv.codeAttestThrottle.now = func() time.Time { return now.Add(time.Minute) } - srv.SeedCodeAttestCache(context.Background()) - restartedGeneration := srv.codeAttestThrottle.beginLoop("se-restart") - if srv.codeAttestThrottle.tryReservePush(context.Background(), "se-restart", "token", false, restartedGeneration) { - t.Fatal("restart forgot the persisted APNs cooldown") - } -} - -// Codex P1 (durable half): the novel-token admission floor survives a -// coordinator restart, so a reconnect churn of fabricated tokens cannot mint -// immediate pushes against a fresh instance. The novel token waits out the -// seeded floor, then admits; the old token stays on its own exact cooldown -// (A-B-A retention). -func TestCodeAttestNovelTokenAfterRestartWaitsForSeededFloor(t *testing.T) { - st := store.NewMemory(store.Config{}) - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - if ok, err := st.ReserveCodeAttestPushBudget( - context.Background(), "se-rotated-after-restart", - codeAttestTokenHash("old-token"), now, - now.Add(20*time.Minute), - ); err != nil || !ok { - t.Fatalf("seed old-token budget: ok=%v err=%v", ok, err) - } - - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - srv := NewServer(registry.New(logger), st, ServerConfig{}, logger) - t.Cleanup(srv.Close) - cur := now.Add(time.Minute) - srv.codeAttestThrottle.now = func() time.Time { return cur } - srv.SeedCodeAttestCache(context.Background()) - generation := srv.codeAttestThrottle.beginLoop("se-rotated-after-restart") - if srv.codeAttestThrottle.tryReservePush( - context.Background(), "se-rotated-after-restart", - "new-token", false, generation, - ) { - t.Fatal("novel token bypassed the seeded per-device admission floor after restart") - } - oldGeneration := srv.codeAttestThrottle.beginLoop( - "se-rotated-after-restart", - ) - if srv.codeAttestThrottle.tryReservePush( - context.Background(), "se-rotated-after-restart", - "old-token", false, oldGeneration, - ) { - t.Fatal("restart forgot the old token's exact cooldown") - } - cur = now.Add(21 * time.Minute) - lateGeneration := srv.codeAttestThrottle.beginLoop( - "se-rotated-after-restart", - ) - if !srv.codeAttestThrottle.tryReservePush( - context.Background(), "se-rotated-after-restart", - "new-token", false, lateGeneration, - ) { - t.Fatal("novel token stayed blocked after the seeded floor elapsed") - } -} - -func TestCodeAttestNovelTokenChurnHonorsPerDeviceFloor(t *testing.T) { - th := newCodeAttestThrottle() - cur := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return cur } - th.budgetClearCooldown = 10 * time.Minute - th.backgroundPushCooldown = 10 * time.Minute - genA := th.beginLoop("se-token-churn") - if !th.tryReservePush( - context.Background(), "se-token-churn", "token-a", false, genA, - ) { - t.Fatal("initial token was not admitted") - } - genB := th.rotateLoopAndClearPushBudget(context.Background(), "se-token-churn") - if !th.tryReservePush( - context.Background(), "se-token-churn", "token-b", false, genB, - ) { - t.Fatal("first genuine token rotation was not admitted") - } - cur = cur.Add(time.Minute) - genC := th.rotateLoopAndClearPushBudget(context.Background(), "se-token-churn") - if th.tryReservePush( - context.Background(), "se-token-churn", "token-c", false, genC, - ) { - t.Fatal("novel token bypassed the per-device rotation floor") - } - cur = cur.Add(10 * time.Minute) - if !th.tryReservePush( - context.Background(), "se-token-churn", "token-c", false, genC, - ) { - t.Fatal("novel token stayed blocked after the rotation floor elapsed") - } -} - -func TestCodeAttestLocalBudgetPreservesABACooldown(t *testing.T) { - th := newCodeAttestThrottle() - cur := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return cur } - th.budgetClearCooldown = time.Minute - genA := th.beginLoop("se-aba") - if !th.tryReservePush( - context.Background(), "se-aba", "token-a", false, genA, - ) { - t.Fatal("initial token A was not admitted") - } - genB := th.rotateLoopAndClearPushBudget(context.Background(), "se-aba") - if !th.tryReservePush( - context.Background(), "se-aba", "token-b", false, genB, - ) { - t.Fatal("token B did not receive an independent budget") - } - cur = cur.Add(2 * time.Minute) - genA = th.rotateLoopAndClearPushBudget(context.Background(), "se-aba") - if th.tryReservePush( - context.Background(), "se-aba", "token-a", false, genA, - ) { - t.Fatal("A-B-A rotation forgot token A's original cooldown") - } -} - -func TestCodeAttestTokenRotationInvalidatesLoopAndProofNotDeviceEvidence(t *testing.T) { - th := newCodeAttestThrottle() - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return now } - th.recordAttestedForProcess("se", "1.0", "old-token", "process", trHashA) - oldGeneration := th.beginLoop("se") - th.invalidateReuse("se") - newGeneration := th.rotateLoopAndClearPushBudget(context.Background(), "se") - if th.loopCurrent("se", oldGeneration) { - t.Fatal("token rotation did not invalidate prior loop generation") - } - if !th.loopCurrent("se", newGeneration) { - t.Fatal("new token loop does not own generation") - } - if th.reuseAttestation("se", "1.0", "old-token", "process") { - t.Fatal("old-token application proof survived rotation") - } - // The throttle owns only application/APNs evidence. No operation above can - // delete or mutate the independent provider device-evidence store. - st := store.NewMemory(store.Config{}) - _, err := st.UpsertProviderTrustReuse(context.Background(), store.ProviderTrustReuse{ - SEPubKey: "se", Serial: "serial", TrustLevel: "hardware", - HardwareProofVerifiedAt: now, EvidenceGeneration: 1, - }, 0) - if err != nil { - t.Fatal(err) - } - rows, err := st.ListProviderTrustReuse(context.Background()) - if err != nil || len(rows) != 1 || rows[0].SEPubKey != "se" { - t.Fatalf("device evidence changed during token rotation: %+v, %v", rows, err) - } -} - -// Codex P1 acceptance: a provider reconnecting rapidly with a fresh fabricated -// APNs token per registration (beginLoop path — no rotation allowance) gets -// exactly ONE immediate push; every further novel token is paced by the -// per-SE-key admission floor, and both durable rows and in-memory budget maps -// stay bounded. -func TestCodeAttestReconnectTokenChurnPacedByAdmissionFloor(t *testing.T) { - st := store.NewMemory(store.Config{}) - th := newCodeAttestThrottle() - th.store = st - cur := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return cur } - const se = "se-reconnect-churn" - ctx := context.Background() - - admitted := 0 - for i := range 20 { - generation := th.beginLoop(se) - if th.tryReservePush( - ctx, se, fmt.Sprintf("fabricated-token-%d", i), false, generation, - ) { - admitted++ - } - } - if admitted != 1 { - t.Fatalf("rapid reconnect churn admissions = %d, want 1 immediate push", admitted) - } - rows, err := st.ListCodeAttestPushBudgets(ctx) - if err != nil || len(rows) != 2 { // one token row + the floor sentinel - t.Fatalf("token churn minted durable budget rows: %+v, err=%v", rows, err) - } - - // Once the floor elapses, exactly one more novel token is admitted. - cur = cur.Add(th.backgroundPushCooldown) - admitted = 0 - for i := range 5 { - generation := th.beginLoop(se) - if th.tryReservePush( - ctx, se, fmt.Sprintf("late-token-%d", i), false, generation, - ) { - admitted++ - } - } - if admitted != 1 { - t.Fatalf("post-floor churn admissions = %d, want 1", admitted) - } - - // Long-run floor-paced churn keeps durable rows and in-memory maps bounded. - for i := range 3 * store.CodeAttestPushBudgetMaxTokenRows { - cur = cur.Add(th.backgroundPushCooldown) - generation := th.beginLoop(se) - if !th.tryReservePush( - ctx, se, fmt.Sprintf("slow-token-%d", i), false, generation, - ) { - t.Fatalf("floor-spaced push %d was denied", i) - } - } - rows, err = st.ListCodeAttestPushBudgets(ctx) - if err != nil { - t.Fatal(err) - } - tokenRows := 0 - for _, row := range rows { - if row.TokenHash != "" { - tokenRows++ - } - } - if tokenRows > store.CodeAttestPushBudgetMaxTokenRows || - len(rows) > store.CodeAttestPushBudgetMaxTokenRows+1 { - t.Fatalf("durable budget rows unbounded: tokens=%d total=%d", tokenRows, len(rows)) - } - th.mu.Lock() - inMemory := len(th.lastPush) + len(th.durableNextPush) - th.mu.Unlock() - if inMemory > 2*store.CodeAttestPushBudgetMaxTokenRows { - t.Fatalf("in-memory budget maps unbounded: %d entries", inMemory) - } -} - -// A genuine (heartbeat-rotation) budget clear lifts the DURABLE admission floor -// too, so the rotated token is challenged promptly even against the durable -// gate — preserving Codex #9 while the floor blocks registration churn. -func TestCodeAttestGenuineRotationClearsDurableFloor(t *testing.T) { - st := store.NewMemory(store.Config{}) - th := newCodeAttestThrottle() - th.store = st - cur := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return cur } - const se = "se-genuine-rotation" - - generation := th.beginLoop(se) - if !th.tryReservePush(context.Background(), se, "token-a", false, generation) { - t.Fatal("initial token was not admitted") - } - rotated := th.rotateLoopAndClearPushBudget(context.Background(), se) - if !th.tryReservePush(context.Background(), se, "token-b", false, rotated) { - t.Fatal("genuinely rotated token was blocked by the durable admission floor") - } -} - -// Codex 06:36Z P1: the genuine-rotation floor clear is throttled by a DURABLE -// cooldown, not just the process-local lastBudgetClear map. A coordinator -// restart (fresh throttle over the same store) whose durable state records a -// recent clear must NOT clear the floor again — otherwise a provider could -// reconnect with one token and heartbeat another once per deploy for an -// immediate push. After the cooldown elapses, rotation clears work again. -func TestCodeAttestRotationClearCooldownSurvivesRestart(t *testing.T) { - st := store.NewMemory(store.Config{}) - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - const se = "se-restart-rotation" - ctx := context.Background() - - first := newCodeAttestThrottle() - first.store = st - first.now = func() time.Time { return now } - generation := first.beginLoop(se) - if !first.tryReservePush(ctx, se, "token-a", false, generation) { - t.Fatal("initial token was not admitted") - } - // Genuine rotation: honored immediately (quiet period), spends the durable - // clear budget, and the rotated token pushes right away (Codex #9 UX). - rotated := first.rotateLoopAndClearPushBudget(ctx, se) - if !first.tryReservePush(ctx, se, "token-b", false, rotated) { - t.Fatal("genuinely rotated token was not admitted") - } - - // RESTART: a fresh throttle over the SAME store one minute later has an - // empty lastBudgetClear map, but the durable last-clear is recent. - cur := now.Add(time.Minute) - second := newCodeAttestThrottle() - second.store = st - second.now = func() time.Time { return cur } - rotatedAfterRestart := second.rotateLoopAndClearPushBudget(ctx, se) - if second.tryReservePush(ctx, se, "token-c", false, rotatedAfterRestart) { - t.Fatal("restart re-granted the rotation floor clear within the durable cooldown") - } - - // Once the durable cooldown elapses, a rotation clear is honored again. - cur = now.Add(second.budgetClearCooldown + time.Minute) - lateRotation := second.rotateLoopAndClearPushBudget(ctx, se) - if !second.tryReservePush(ctx, se, "token-c", false, lateRotation) { - t.Fatal("rotation clear stayed blocked after the durable cooldown elapsed") - } -} - -// Codex 06:36Z P1 (blue-green half): two live throttle instances over one -// store share the durable clear budget — only one rotation clear is honored -// within the window, and the loser's novel token stays paced. -func TestCodeAttestRotationClearAdmitsOnceAcrossPeers(t *testing.T) { - st := store.NewMemory(store.Config{}) - cur := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - const se = "se-blue-green-rotation" - ctx := context.Background() - - blue := newCodeAttestThrottle() - blue.store = st - blue.now = func() time.Time { return cur } - green := newCodeAttestThrottle() - green.store = st - green.now = func() time.Time { return cur } - - generation := blue.beginLoop(se) - if !blue.tryReservePush(ctx, se, "token-a", false, generation) { - t.Fatal("initial token was not admitted") - } - cur = cur.Add(time.Minute) - clearedBlue := blue.clearPushBudget(ctx, se) - clearedGreen := green.clearPushBudget(ctx, se) - if !clearedBlue || clearedGreen { - t.Fatalf("rotation clears across peers = blue:%v green:%v, want exactly the first", - clearedBlue, clearedGreen) - } - // The loser's novel token stays blocked for the rest of the window... - greenGeneration := green.beginLoop(se) - if green.tryReservePush(ctx, se, "token-b", false, greenGeneration) { - t.Fatal("throttled peer still minted an immediate novel-token push") - } - // ...and the shared durable cooldown governs both peers going forward. - cur = cur.Add(green.budgetClearCooldown) - if !green.clearPushBudget(ctx, se) { - t.Fatal("peer rotation clear stayed blocked after the shared cooldown elapsed") - } -} diff --git a/coordinator/api/code_attest_cached_store_test.go b/coordinator/api/code_attest_cached_store_test.go deleted file mode 100644 index 226436b4a3..0000000000 --- a/coordinator/api/code_attest_cached_store_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package api - -import ( - "context" - "io" - "log/slog" - "testing" - "time" - - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" -) - -// main.go wraps the backend in store.CachedStore, whose static Store method -// set hides the optional codeAttestPushBudgetStore capability from a direct -// type assertion. These tests run the durable reserve, clear and restart-seed -// paths over NewCached(NewMemory(...)) exactly as the bare-store tests do, and -// first prove the wrapped shape is what is under test. -func newCachedCodeAttestStore(t *testing.T) *store.CachedStore { - t.Helper() - cached := store.NewCached(store.NewMemory(store.Config{}), store.CacheConfig{}) - if _, direct := any(cached).(codeAttestPushBudgetStore); direct { - t.Fatal("direct assertion on CachedStore succeeded; this test no longer exercises the wrapped path") - } - if _, ok := store.As[codeAttestPushBudgetStore](cached); !ok { - t.Fatal("store.As cannot find codeAttestPushBudgetStore through CachedStore") - } - return cached -} - -func TestCodeAttestDurableReservationThroughCachedStore(t *testing.T) { - cached := newCachedCodeAttestStore(t) - th := newCodeAttestThrottle() - th.store = cached - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - th.now = func() time.Time { return now } - - generation := th.beginLoop("se-cached") - if !th.tryReservePush(context.Background(), "se-cached", "token", false, generation) { - t.Fatal("first push not admitted over the cached store") - } - budgets, _ := store.As[codeAttestPushBudgetStore](cached) - rows, err := budgets.ListCodeAttestPushBudgets(context.Background()) - if err != nil || len(rows) != 2 { // token row + admission-floor sentinel - t.Fatalf("durable reservation missing over cached store: rows=%+v err=%v", rows, err) - } - for _, row := range rows { - if !row.NextPushAt.After(now) { - t.Fatalf("non-future reservation window persisted: %+v", row) - } - } - - // The durable row, not just in-memory state, blocks a second instance. - other := newCodeAttestThrottle() - other.store = cached - other.now = th.now - if other.tryReservePush(context.Background(), "se-cached", "token", false, other.beginLoop("se-cached")) { - t.Fatal("second instance re-spent a budget the durable store already holds") - } -} - -func TestCodeAttestDurableClearThroughCachedStore(t *testing.T) { - cached := newCachedCodeAttestStore(t) - now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) - first := newCodeAttestThrottle() - first.store = cached - first.now = func() time.Time { return now } - if !first.clearPushBudget(context.Background(), "se-clear") { - t.Fatal("first rotation clear rejected over the cached store") - } - - // A fresh instance (empty in-memory state) sharing the store must see - // the durably spent clear window and refuse. - second := newCodeAttestThrottle() - second.store = cached - second.now = first.now - if second.clearPushBudget(context.Background(), "se-clear") { - t.Fatal("durable clear cooldown not honored through the cached store") - } -} - -func TestCodeAttestSeedRestoresDurableBudgetsThroughCachedStore(t *testing.T) { - cached := newCachedCodeAttestStore(t) - now := time.Now().UTC() - next := now.Add(time.Hour) - tokenHash := codeAttestTokenHash("token-1") - budgets, _ := store.As[codeAttestPushBudgetStore](cached) - if ok, err := budgets.ReserveCodeAttestPushBudget(context.Background(), "se-seed", tokenHash, now, next); err != nil || !ok { - t.Fatalf("pre-restart reservation: ok=%v err=%v", ok, err) - } - - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - srv := NewServer(registry.New(logger), cached, ServerConfig{}, logger) - t.Cleanup(srv.Close) - srv.SeedCodeAttestCache(context.Background()) - - th := srv.codeAttestThrottle - th.mu.Lock() - seeded, ok := th.durableNextPush[codeAttestPushBudgetKey("se-seed", tokenHash)] - th.mu.Unlock() - if !ok || !seeded.Equal(next) { - t.Fatalf("restart seed over cached store: durableNextPush = %v (present=%v), want %v", seeded, ok, next) - } - if th.tryReservePush(context.Background(), "se-seed", "token-1", false, th.beginLoop("se-seed")) { - t.Fatal("seeded durable budget did not block an immediate re-push") - } -} diff --git a/coordinator/api/code_attest_coverage.go b/coordinator/api/code_attest_coverage.go deleted file mode 100644 index dcacaccfaa..0000000000 --- a/coordinator/api/code_attest_coverage.go +++ /dev/null @@ -1,113 +0,0 @@ -package api - -import ( - "context" - "time" - - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" -) - -// This is a same-process continuity bound, never a new lifetime for an APNs -// proof. Changed process keys and release transitions still need a recent proof. -const codeAttestContinuityGap = 120 * time.Second - -type codeAttestCoverageStore interface { - AdvanceCodeAttestationCoverage(context.Context, []store.CodeAttestation) error -} - -func (r codeAttestRecord) recent(now time.Time, window time.Duration) bool { - age := now.Sub(r.at) - return age >= -clockSkewTolerance && age < window -} - -func (r codeAttestRecord) continuous(now time.Time) bool { - if r.binaryHash == "" || r.nodeKey == "" || r.token == "" || r.coveredUntil.IsZero() || r.coveredUntil.Before(r.at) { - return false - } - gap := now.Sub(r.coveredUntil) - return gap >= 0 && gap <= codeAttestContinuityGap -} - -func (r codeAttestRecord) persisted(seKey string) store.CodeAttestation { - out := store.CodeAttestation{SEPubKey: seKey, Version: r.version, AttestedAt: r.at, - APNsToken: r.token, NodePublicKey: r.nodeKey, BinaryHash: r.binaryHash} - if !r.coveredUntil.IsZero() { - until := r.coveredUntil - out.ContinuousCoverageUntil = &until - } - return out -} - -// Observation is authorized by an already verified connection, not by a -// heartbeat claiming a version/token. Capture the timestamp with the flags. -// Only final disconnect stamping may observe the just-offlined connection; -// periodic and shutdown sweeps must not extend coverage for offline providers. -func (s *Server) codeCoverageObservation(p *registry.Provider, allowOffline bool) (store.CodeAttestation, bool) { - if p == nil || s.codeAttestThrottle == nil { - return store.CodeAttestation{}, false - } - p.Mu().Lock() - at := s.codeAttestThrottle.now().Truncate(time.Microsecond) - statusAllowed := p.Status == registry.StatusOnline || (allowOffline && p.Status == registry.StatusOffline) - if !p.CodeAttested || !p.FreshCodeAttested || !statusAllowed || p.TrustLevel != registry.TrustHardware || p.AttestationResult == nil || !p.AttestationResult.Valid { - p.Mu().Unlock() - return store.CodeAttestation{}, false - } - seKey, version, token, nodeKey := p.AttestationResult.PublicKey, p.Version, p.APNsDeviceToken, p.PublicKey - binary, _ := normalizeSHA256Hex(p.AttestationResult.BinaryHash, "binary_hash") - p.Mu().Unlock() - binary = providerApplicationBinaryHash(p, seKey, binary) - t := s.codeAttestThrottle - t.mu.Lock() - defer t.mu.Unlock() - r, ok := t.attested[seKey] - if !ok || seKey == "" || version == "" || token == "" || nodeKey == "" || binary == "" || r.binaryHash != binary || r.version != version || r.token != token || r.nodeKey != nodeKey || r.at.After(at) { - return store.CodeAttestation{}, false - } - if at.After(r.coveredUntil) { - r.coveredUntil = at - t.attested[seKey] = r - } - return r.persisted(seKey), true -} - -func (s *Server) persistCodeCoverage(rows []store.CodeAttestation) { - if len(rows) == 0 || s.codeAttestThrottle == nil { - return - } - st, ok := store.As[codeAttestCoverageStore](s.store) - if !ok { - return - } // no durable continuity on unsupported stores - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if err := st.AdvanceCodeAttestationCoverage(ctx, rows); err != nil { - s.ddIncr("code_attest.coverage_persist", []string{"outcome:error"}) - s.logger.Warn("code-attest: failed to persist process continuity coverage", "providers", len(rows)) - } else { - s.ddIncr("code_attest.coverage_persist", []string{"outcome:success"}) - } -} - -func (s *Server) sweepCodeAttestCoverage() { - if s == nil || s.registry == nil { - return - } - rows := []store.CodeAttestation{} - s.registry.ForEachProvider(func(p *registry.Provider) { - if r, ok := s.codeCoverageObservation(p, false); ok { - rows = append(rows, r) - } - }) - s.persistCodeCoverage(rows) -} - -func (s *Server) stopCodeAttestCoverageForProvider(providerID string) { - if s == nil || s.registry == nil { - return - } - if r, ok := s.codeCoverageObservation(s.registry.GetProvider(providerID), true); ok { - s.persistCodeCoverage([]store.CodeAttestation{r}) - } -} diff --git a/coordinator/api/code_attest_coverage_test.go b/coordinator/api/code_attest_coverage_test.go index 936d71a221..4db0d5a721 100644 --- a/coordinator/api/code_attest_coverage_test.go +++ b/coordinator/api/code_attest_coverage_test.go @@ -2,167 +2,21 @@ package api import ( "context" + "github.com/eigeninference/d-inference/coordinator/providercontrol/codeidentity" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" "strings" "testing" "time" - - "github.com/eigeninference/d-inference/coordinator/protocol" - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" ) -func TestCodeContinuityResumeStillRequiresLiveProcessProof(t *testing.T) { - ctx := context.Background() - st := store.NewCached(store.NewMemory(store.Config{}), store.DefaultCacheConfig()) - old := NewServer(registry.New(quietLogger()), st, ServerConfig{}, quietLogger()) - t.Cleanup(old.Close) - now := time.Date(2026, 9, 8, 0, 0, 0, 0, time.UTC) - old.codeAttestThrottle.now = func() time.Time { return now } - old.SeedCodeAttestCache(ctx) - old.codeAttestThrottle.retrySpacing = time.Millisecond - old.codeAttestThrottle.retryJitter = 0 - pub, priv, seKey, sePub := providerKeyMaterial(t) - p := newCodeAttestProvider(pub, sePub) - p.Version = "0.9.0" - p.Status = registry.StatusOnline - p.TrustLevel = registry.TrustHardware - p.AttestationResult.BinaryHash = strings.Repeat("a", 64) - old.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, key, nonce string) error { - return completeRoundTrip(t, old, p, p.ID, priv, seKey, key, nonce) - }}) - old.codeAttestLoop(ctx, p.ID, p) - if !p.GetFreshCodeAttested() { - t.Fatal("real initial process proof failed") - } - proofAt := now - // Persist deterministically; the production asynchronous write is identical. - old.codeAttestThrottle.mu.Lock() - proof := old.codeAttestThrottle.attested[sePub].persisted(sePub) - old.codeAttestThrottle.mu.Unlock() - if err := st.UpsertCodeAttestation(ctx, proof); err != nil { - t.Fatal(err) - } - now = now.Add(2 * time.Hour) - observation, ok := old.codeCoverageObservation(p, false) - if !ok { - t.Fatal("verified live process did not produce coverage") - } - old.persistCodeCoverage([]store.CodeAttestation{observation}) - rows, err := st.ListCodeAttestations(ctx) - if err != nil || len(rows) != 1 || !rows[0].AttestedAt.Equal(proofAt) { - t.Fatal("coverage changed original APNs proof time") - } - now = now.Add(60 * time.Second) - next := NewServer(registry.New(quietLogger()), st, ServerConfig{}, quietLogger()) - t.Cleanup(next.Close) - next.codeAttestThrottle.now = func() time.Time { return now } - next.SeedCodeAttestCache(ctx) - reconnect := newCodeAttestProvider(pub, sePub) - reconnect.Version = p.Version - reconnect.AttestationResult.BinaryHash = p.AttestationResult.BinaryHash - pushes, resumes := 0, 0 - next.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, _, _ string) error { pushes++; return nil }}) - next.codeResumeSender = func(_ string, m protocol.CodeAttestationResumeChallenge) error { - resumes++ - return completeResumeRoundTrip(t, next, reconnect, reconnect.ID, priv, seKey, m) - } - next.codeAttestLoop(ctx, reconnect.ID, reconnect) - if pushes != 0 || resumes != 1 || !reconnect.GetFreshCodeAttested() { - t.Fatalf("pushes=%d resumes=%d fresh=%v", pushes, resumes, reconnect.GetFreshCodeAttested()) - } - rows, _ = st.ListCodeAttestations(ctx) - if !rows[0].AttestedAt.Equal(proofAt) { - t.Fatal("resume fabricated a new APNs timestamp") - } -} - -func TestCodeContinuityRefusesChangedOrExpiredIdentity(t *testing.T) { - now := time.Unix(1_800_000_000, 0) - covered := now.Add(-60 * time.Second) - base := store.CodeAttestation{SEPubKey: "se", Version: "0.9.0", APNsToken: "token", NodePublicKey: "process", BinaryHash: strings.Repeat("a", 64), AttestedAt: now.Add(-time.Hour), ContinuousCoverageUntil: &covered} - for _, tc := range []struct { - name string - modify func(*store.CodeAttestation) - se, version, token, node string - }{ - {"same process", func(*store.CodeAttestation) {}, "se", "0.9.0", "token", "process"}, - {"changed process", func(*store.CodeAttestation) {}, "se", "0.9.0", "token", "new-process"}, - {"changed token", func(*store.CodeAttestation) {}, "se", "0.9.0", "new-token", "process"}, - {"changed version", func(*store.CodeAttestation) {}, "se", "0.9.1", "token", "process"}, - {"missing coverage", func(r *store.CodeAttestation) { r.ContinuousCoverageUntil = nil }, "se", "0.9.0", "token", "process"}, - {"expired coverage", func(r *store.CodeAttestation) { v := now.Add(-121 * time.Second); r.ContinuousCoverageUntil = &v }, "se", "0.9.0", "token", "process"}, - {"future coverage", func(r *store.CodeAttestation) { v := now.Add(time.Millisecond); r.ContinuousCoverageUntil = &v }, "se", "0.9.0", "token", "process"}, - {"missing binary", func(r *store.CodeAttestation) { r.BinaryHash = "" }, "se", "0.9.0", "token", "process"}, - } { - t.Run(tc.name, func(t *testing.T) { - th := newCodeAttestThrottle() - th.now = func() time.Time { return now } - r := base - tc.modify(&r) - th.seed([]store.CodeAttestation{r}) - got := th.reuseAttestation(tc.se, tc.version, tc.token, tc.node) - if got != (tc.name == "same process") { - t.Fatalf("reuse=%v", got) - } - if _, ok := th.reuseAttestationForTransition("se", "token"); ok { - t.Fatal("old proof must never authorize a process/release transition") - } - th.invalidateReuse("se") - if th.reuseAttestation("se", "0.9.0", "token", "process") { - t.Fatal("invalidation bypassed") - } - }) - } -} - -func TestCodeCoverageRequiresVerifiedCurrentBinding(t *testing.T) { - srv := NewServer(registry.New(quietLogger()), store.NewMemory(store.Config{}), ServerConfig{}, quietLogger()) - t.Cleanup(srv.Close) - now := time.Unix(1_800_000_000, 0) - srv.codeAttestThrottle.now = func() time.Time { return now } - pub, _, _, se := providerKeyMaterial(t) - p := newCodeAttestProvider(pub, se) - p.Version = "0.9.0" - p.Status = registry.StatusOnline - p.TrustLevel = registry.TrustHardware - p.AttestationResult.BinaryHash = strings.Repeat("a", 64) - srv.codeAttestThrottle.recordAttestedForProcess(se, p.Version, p.APNsDeviceToken, p.PublicKey, p.AttestationResult.BinaryHash) - for _, tc := range []struct { - name string - change func(*registry.Provider) - }{ - {"unverified", func(p *registry.Provider) { p.CodeAttested = false }}, - {"no live process proof", func(p *registry.Provider) { p.FreshCodeAttested = false }}, - {"untrusted", func(p *registry.Provider) { p.Status = registry.StatusUntrusted }}, - {"no hardware trust", func(p *registry.Provider) { p.TrustLevel = registry.TrustSelfSigned }}, - {"new node", func(p *registry.Provider) { p.PublicKey = "other" }}, - {"new binary", func(p *registry.Provider) { p.AttestationResult.BinaryHash = strings.Repeat("b", 64) }}, - } { - t.Run(tc.name, func(t *testing.T) { - p.CodeAttested = true - p.FreshCodeAttested = true - p.Status = registry.StatusOnline - p.TrustLevel = registry.TrustHardware - p.PublicKey = pub - p.AttestationResult.BinaryHash = strings.Repeat("a", 64) - tc.change(p) - for _, allowOffline := range []bool{false, true} { - if allowOffline && p.Status == registry.StatusOnline { - p.Status = registry.StatusOffline - } - if _, ok := srv.codeCoverageObservation(p, allowOffline); ok { - t.Fatalf("unproven binding advanced coverage (allowOffline=%v)", allowOffline) - } - } - }) - } -} - func TestCodeCoverageSweepDisconnectAndClose(t *testing.T) { st := store.NewMemory(store.Config{}) srv := NewServer(registry.New(quietLogger()), st, ServerConfig{}, quietLogger()) now := time.Date(2026, 9, 8, 0, 0, 0, 0, time.UTC) - srv.codeAttestThrottle.now = func() time.Time { return now } + cfg := codeidentity.DefaultConfig() + cfg.Now = func() time.Time { return now } + configureCodeIdentityFixture(srv, cfg) p := newTrustReuseProvider(t, srv, "coverage-p", "coverage-se", "serial") p.Mu().Lock() p.Version = "0.9.0" @@ -173,13 +27,10 @@ func TestCodeCoverageSweepDisconnectAndClose(t *testing.T) { p.FreshCodeAttested = true p.AttestationResult.BinaryHash = strings.Repeat("a", 64) p.Mu().Unlock() - srv.codeAttestThrottle.recordAttestedForProcess("coverage-se", p.Version, p.APNsDeviceToken, p.PublicKey, p.AttestationResult.BinaryHash) - srv.codeAttestThrottle.mu.Lock() - proof := srv.codeAttestThrottle.attested["coverage-se"].persisted("coverage-se") - srv.codeAttestThrottle.mu.Unlock() - if err := st.UpsertCodeAttestation(context.Background(), proof); err != nil { - t.Fatal(err) - } + proof := store.CodeAttestation{SEPubKey: "coverage-se", Version: p.Version, + APNsToken: p.APNsDeviceToken, NodePublicKey: p.PublicKey, BinaryHash: p.AttestationResult.BinaryHash, + AttestedAt: now} + seedCodeIdentityProof(t, srv, proof) check := func(want time.Time) { t.Helper() rows, _ := st.ListCodeAttestations(context.Background()) @@ -206,10 +57,17 @@ func TestCodeCoverageSweepDisconnectAndClose(t *testing.T) { t.Fatal(err) } for _, gap := range []time.Duration{100 * time.Second, 120 * time.Second, 121 * time.Second} { - th := newCodeAttestThrottle() - th.now = func() time.Time { return disconnectedAt.Add(gap) } - th.seed(rows) - if got := th.reuseAttestation("coverage-se", p.Version, p.APNsDeviceToken, p.PublicKey); got != (gap <= codeAttestContinuityGap) { + fixtureStore := store.NewMemory(store.Config{}) + for _, row := range rows { + if err := fixtureStore.UpsertCodeAttestation(context.Background(), row); err != nil { + t.Fatal(err) + } + } + cfg := codeidentity.DefaultConfig() + cfg.Now = func() time.Time { return disconnectedAt.Add(gap) } + th := codeidentity.New(cfg, srv.codeIdentityDependencies()) + th.Seed(context.Background(), fixtureStore) + if got := th.ReuseBasis("coverage-se", p.Version, p.APNsDeviceToken, p.PublicKey) != ""; got != (gap <= 120*time.Second) { t.Fatalf("reuse after disconnect gap %s = %v", gap, got) } } diff --git a/coordinator/api/code_attest_persistence_test.go b/coordinator/api/code_attest_persistence_test.go index 4effe9b302..52c6d9406a 100644 --- a/coordinator/api/code_attest_persistence_test.go +++ b/coordinator/api/code_attest_persistence_test.go @@ -17,7 +17,7 @@ func TestSeededReuseSkipsRePush(t *testing.T) { logger := quietLogger() st := store.NewMemory(store.Config{}) srv := NewServer(registry.New(logger), st, ServerConfig{}, logger) - fastBudgets(srv) + srvControls := fastBudgets(srv) kPubB64, kPriv, seKey, sePubB64 := providerKeyMaterial(t) @@ -35,7 +35,7 @@ func TestSeededReuseSkipsRePush(t *testing.T) { }}) provider := newCodeAttestProvider(kPubB64, sePubB64) provider.Version = "0.6.0" - srv.codeResumeSender = func( + srvControls.resumeSender = func( _ string, message protocol.CodeAttestationResumeChallenge, ) error { return completeResumeRoundTrip( @@ -100,10 +100,10 @@ func TestSeededStalePersistedRowForcesRealChallenge(t *testing.T) { logger := quietLogger() st := store.NewMemory(store.Config{}) srv := NewServer(registry.New(logger), st, ServerConfig{}, logger) - fastBudgets(srv) + srvControls := fastBudgets(srv) cur := time.Unix(1_700_000_000, 0) - srv.codeAttestThrottle.now = func() time.Time { return cur } + srvControls.now = func() time.Time { return cur } kPubB64, kPriv, seKey, sePubB64 := providerKeyMaterial(t) @@ -117,9 +117,9 @@ func TestSeededStalePersistedRowForcesRealChallenge(t *testing.T) { // ...then advance the clock so the seeded row is now PAST the reuse window. cur = cur.Add(15 * time.Minute) // row is now 35m old > 30m window - if srv.codeAttestThrottle.reuseAttestation( + if srv.codeIdentity.ReuseBasis( sePubB64, "0.6.0", "devtok", kPubB64, - ) { + ) != "" { t.Fatal("an aged-out seeded row must not be reusable (fail-closed staleness)") } @@ -164,9 +164,9 @@ func TestSeededWrongVersionRowForcesRealChallenge(t *testing.T) { } srv.SeedCodeAttestCache(context.Background()) - if srv.codeAttestThrottle.reuseAttestation( + if srv.codeIdentity.ReuseBasis( sePubB64, "0.6.0", "devtok", kPubB64, - ) { + ) != "" { t.Fatal("a seeded row for a different version must not be reusable") } @@ -259,7 +259,7 @@ func TestHashlessRegistrationPersistsApplicationEvidenceHashForRestartReuse(t *t if !provider.GetFreshCodeAttested() { t.Fatal("production-shape hashless registration did not complete its genuine APNs proof") } - if got, ok := srv.codeAttestThrottle.reuseAttestationForTransition( + if got, ok := srv.codeIdentity.TransitionBinaryHash( sePubB64, provider.APNsDeviceToken, ); !ok || got != trHashA { t.Fatalf("in-memory APNs proof binary hash = %q, ok=%v; want application hash %q", got, ok, trHashA) @@ -283,9 +283,9 @@ func TestHashlessRegistrationPersistsApplicationEvidenceHashForRestartReuse(t *t } restarted := NewServer(registry.New(logger), st, ServerConfig{}, logger) - fastBudgets(restarted) + restartedControls := fastBudgets(restarted) restarted.SeedCodeAttestCache(context.Background()) - if got, ok := restarted.codeAttestThrottle.reuseAttestationForTransition( + if got, ok := restarted.codeIdentity.TransitionBinaryHash( sePubB64, provider.APNsDeviceToken, ); !ok || got != trHashA { t.Fatalf("restart-seeded APNs proof binary hash = %q, ok=%v; want %q", got, ok, trHashA) @@ -306,7 +306,7 @@ func TestHashlessRegistrationPersistsApplicationEvidenceHashForRestartReuse(t *t atomic.AddInt32(&pushes, 1) return nil }}) - restarted.codeResumeSender = func( + restartedControls.resumeSender = func( _ string, message protocol.CodeAttestationResumeChallenge, ) error { return completeResumeRoundTrip( @@ -343,7 +343,7 @@ func TestHashlessRegistrationWithoutApplicationEvidenceRemainsIdentityless(t *te if !provider.GetFreshCodeAttested() { t.Fatal("identity-less registration did not complete its genuine APNs proof") } - if hash, ok := srv.codeAttestThrottle.reuseAttestationForTransition( + if hash, ok := srv.codeIdentity.TransitionBinaryHash( sePubB64, provider.APNsDeviceToken, ); ok || hash != "" { t.Fatalf("identity-less proof authorized transition reuse: hash=%q ok=%v", hash, ok) diff --git a/coordinator/api/code_attest_rearm_test.go b/coordinator/api/code_attest_rearm_test.go deleted file mode 100644 index 7e63a91005..0000000000 --- a/coordinator/api/code_attest_rearm_test.go +++ /dev/null @@ -1,322 +0,0 @@ -package api - -import ( - "context" - "github.com/eigeninference/d-inference/coordinator/attestation" - "github.com/eigeninference/d-inference/coordinator/protocol" - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" - "strings" - "sync/atomic" - "testing" - "time" -) - -// TestRearmOnHeartbeatTokenArrivalTriggersChallenge proves W5 Fix 2 (2a): a -// provider that registered WITHOUT an APNs device token (headless/late-token Mac) -// and later reports one in a HEARTBEAT is re-armed and attests via the full -// round-trip — no reconnect required. -func TestRearmOnHeartbeatTokenArrivalTriggersChallenge(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) - - kPubB64, kPriv, seKey, sePubB64 := providerKeyMaterial(t) - provider := newCodeAttestProvider(kPubB64, sePubB64) - provider.APNsDeviceToken = "" // registered token-less - provider.Version = "0.6.0" - - var pushes int32 - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, pubKeyB64, nonceB64 string) error { - atomic.AddInt32(&pushes, 1) - return completeRoundTrip(t, srv, provider, "p1", kPriv, seKey, pubKeyB64, nonceB64) - }}) - - // A heartbeat now carries the token that arrived after registration. - srv.maybeRearmCodeAttest(context.Background(), "p1", provider, &protocol.HeartbeatMessage{ - Type: protocol.TypeHeartbeat, - Status: "idle", - APNsDeviceToken: "late-tok", - APNsEnvironment: "production", - }) - - if got := providerToken(provider); got != "late-tok" { - t.Fatalf("heartbeat token not recorded on provider: %q", got) - } - if !waitForCond(2*time.Second, provider.GetCodeAttested) { - t.Fatal("late heartbeat token must re-arm and attest via the round-trip (no reconnect)") - } - if atomic.LoadInt32(&pushes) == 0 { - t.Fatal("re-arm must SEND a code-identity challenge") - } -} - -// TestHeartbeatTokenAloneNeverGrantsAttestation is the core security invariant: -// the heartbeat token only lets the coordinator SEND a challenge — it never by -// itself grants CodeAttested. With the push delivered but never answered, the -// connection stays un-attested (fail-closed). -func TestHeartbeatTokenAloneNeverGrantsAttestation(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) - srv.codeAttestThrottle.maxAttempts = 2 - - kPubB64, _, _, sePubB64 := providerKeyMaterial(t) - provider := newCodeAttestProvider(kPubB64, sePubB64) - provider.APNsDeviceToken = "" - provider.Version = "0.6.0" - - var pushes int32 - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, _, _ string) error { - atomic.AddInt32(&pushes, 1) // delivered, but the provider never replies - return nil - }}) - - srv.maybeRearmCodeAttest(context.Background(), "p1", provider, &protocol.HeartbeatMessage{ - Type: protocol.TypeHeartbeat, - Status: "idle", - APNsDeviceToken: "tok", - }) - - // Let the re-arm loop run to exhaustion (maxAttempts pushes, no reply). - waitForCond(2*time.Second, func() bool { return atomic.LoadInt32(&pushes) >= 2 }) - if provider.GetCodeAttested() { - t.Fatal("a heartbeat token without a verified round-trip must NEVER attest (fail-closed)") - } -} - -// TestRearmChangedTokenForcesRealChallengeNoReuseBypass proves the "changed -// token forces a re-challenge (no bypass)" invariant: a provider that is already -// attested (with a live reuse record) and whose token CHANGES must (1) be reset -// to un-attested (fail-closed) and (2) run a REAL challenge push rather than -// short-circuiting on the prior proof via the reuse cache. -func TestRearmChangedTokenForcesRealChallengeNoReuseBypass(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) - - kPubB64, kPriv, seKey, sePubB64 := providerKeyMaterial(t) - p := newCodeAttestProvider(kPubB64, sePubB64) - p.APNsDeviceToken = "tok1" - p.Version = "0.6.0" - - // Phase 1: a genuine attestation establishes a reuse record + CodeAttested. - complete := int32(1) - var pushes int32 - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, pubKeyB64, nonceB64 string) error { - atomic.AddInt32(&pushes, 1) - if atomic.LoadInt32(&complete) == 1 { - return completeRoundTrip(t, srv, p, "p1", kPriv, seKey, pubKeyB64, nonceB64) - } - return nil // phase 2: deliver but drop (so we can observe a real push, no reply) - }}) - srv.codeAttestLoop(context.Background(), "p1", p) - if !p.GetCodeAttested() { - t.Fatal("phase 1 should attest") - } - if !srv.codeAttestThrottle.reuseAttestation( - sePubB64, "0.6.0", "tok1", kPubB64, - ) { - t.Fatal("phase 1 should leave a reusable record") - } - pushesAfterP1 := atomic.LoadInt32(&pushes) - p.Mu().Lock() - p.DeviceEvidence = registry.DeviceEvidence{ - SEPublicKey: sePubB64, Serial: "SERIAL", - VerifiedAt: time.Now(), EvidenceGeneration: 1, - } - p.ApplicationEvidence = registry.ApplicationEvidence{ - SEPublicKey: sePubB64, Serial: "SERIAL", - ProcessPublicKey: kPubB64, APNsToken: "tok1", - BinaryHash: strings.Repeat("a", 64), Version: "0.6.0", - Backend: "mlx-swift", VerifiedAt: time.Now(), - EvidenceGeneration: 1, PolicyGeneration: 1, - } - p.Mu().Unlock() - - // Phase 2: the APNs token changes in a heartbeat. - atomic.StoreInt32(&complete, 0) - srv.maybeRearmCodeAttest(context.Background(), "p1", p, &protocol.HeartbeatMessage{ - Type: protocol.TypeHeartbeat, - Status: "idle", - APNsDeviceToken: "tok2", - }) - - // Synchronous, fail-closed effects of a changed token. - if p.GetCodeAttested() { - t.Fatal("a changed token must reset CodeAttested (fail-closed) until re-proven") - } - if srv.codeAttestThrottle.reuseAttestation( - sePubB64, "0.6.0", "tok2", kPubB64, - ) { - t.Fatal("a changed token must invalidate the reuse record (no bypass)") - } - if got := providerToken(p); got != "tok2" { - t.Fatalf("changed token not recorded: %q", got) - } - if _, ok := p.ApplicationEvidenceSnapshot(); ok { - t.Fatal("token rotation retained stale application/process evidence") - } - p.Mu().Lock() - deviceEvidence := p.DeviceEvidence - p.Mu().Unlock() - if deviceEvidence.EvidenceGeneration != 1 || - deviceEvidence.SEPublicKey != sePubB64 { - t.Fatalf("token rotation cleared independent device proof: %+v", deviceEvidence) - } - - // A REAL challenge must be pushed (proving the loop did NOT reuse). If it had - // bypassed via reuse, pushes would not increase and CodeAttested would flip. - if !waitForCond(2*time.Second, func() bool { return atomic.LoadInt32(&pushes) > pushesAfterP1 }) { - t.Fatal("a changed token must force a real challenge push (no reuse bypass)") - } - if p.GetCodeAttested() { - t.Fatal("the forced re-challenge was never answered, so CodeAttested must stay false") - } -} - -// TestRearmChangedTokenDeletesPersistedReuse proves the Codex #6 fix: a changed -// APNs token must delete the PERSISTED reuse row (not just the in-memory one), so -// a coordinator restart before the forced re-challenge completes cannot reseed and -// reuse the pre-rotation proof. -func TestRearmChangedTokenDeletesPersistedReuse(t *testing.T) { - logger := quietLogger() - st := store.NewMemory(store.Config{}) - srv := NewServer(registry.New(logger), st, ServerConfig{}, logger) - fastBudgets(srv) - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, _, _ string) error { return nil }}) - - kPubB64, _, _, sePubB64 := providerKeyMaterial(t) - p := newCodeAttestProvider(kPubB64, sePubB64) - p.APNsDeviceToken = "tok1" - p.Version = "0.6.0" - - // A genuine prior attestation is persisted, and the store seam is wired. - if err := st.UpsertCodeAttestation(context.Background(), store.CodeAttestation{ - SEPubKey: sePubB64, - Version: "0.6.0", - AttestedAt: time.Now(), - }); err != nil { - t.Fatal(err) - } - srv.SeedCodeAttestCache(context.Background()) - - // Token rotation in a heartbeat. - srv.maybeRearmCodeAttest(context.Background(), "p1", p, &protocol.HeartbeatMessage{ - Type: protocol.TypeHeartbeat, - Status: "idle", - APNsDeviceToken: "tok2", - }) - - if !waitForCond(2*time.Second, func() bool { - rows, err := st.ListCodeAttestations(context.Background()) - if err != nil { - return false - } - for _, r := range rows { - if r.SEPubKey == sePubB64 { - return false // persisted row still present - } - } - return true // deleted - }) { - t.Fatal("a changed APNs token must delete the persisted reuse row so a restart cannot reseed it (Codex #6)") - } -} - -// TestRearmChangedTokenKicksImmediateOrdinaryChallenge proves the Codex 05:33Z -// #2 fix: token rotation clears application evidence, and that evidence is -// regenerated ONLY by the connection's ordinary attestation challenge loop — -// so the rearm path must kick that loop immediately (RequestImmediateChallenge) -// rather than leaving the provider unroutable until the 5-minute periodic -// tick while queued requests expire at 120s. A first-token arrival clears no -// evidence and must NOT kick. -func TestRearmChangedTokenKicksImmediateOrdinaryChallenge(t *testing.T) { - logger := quietLogger() - reg := registry.New(logger) - srv := NewServer(reg, store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, _, _ string) error { return nil }}) - - _, _, _, sePubB64 := providerKeyMaterial(t) - // Registry-created provider: carries the real challengeKick channel the - // connection's challengeLoop selects on. - p := makeRoutableProvider(t, reg, "kick-provider", "kick-model") - p.Mu().Lock() - p.AttestationResult = &attestation.VerificationResult{Valid: true, PublicKey: sePubB64} - p.APNsDeviceToken = "tok1" - p.CodeAttested = true - p.ApplicationEvidence = registry.ApplicationEvidence{ - SEPublicKey: sePubB64, Serial: "SERIAL", - ProcessPublicKey: p.PublicKey, APNsToken: "tok1", - BinaryHash: strings.Repeat("a", 64), VerifiedAt: time.Now(), - EvidenceGeneration: 1, PolicyGeneration: 1, - } - p.Mu().Unlock() - select { - case <-p.ImmediateChallengeChan(): - t.Fatal("precondition: unexpected pending challenge kick") - default: - } - - // Steady state: an unchanged token must not kick. - srv.maybeRearmCodeAttest(context.Background(), "kick-provider", p, &protocol.HeartbeatMessage{ - Type: protocol.TypeHeartbeat, Status: "idle", APNsDeviceToken: "tok1", - }) - select { - case <-p.ImmediateChallengeChan(): - t.Fatal("unchanged token must not kick the ordinary challenge loop") - default: - } - - // Rotation: evidence is cleared AND the ordinary challenge loop is kicked. - srv.maybeRearmCodeAttest(context.Background(), "kick-provider", p, &protocol.HeartbeatMessage{ - Type: protocol.TypeHeartbeat, Status: "idle", APNsDeviceToken: "tok2", - }) - if _, ok := p.ApplicationEvidenceSnapshot(); ok { - t.Fatal("token rotation retained stale application evidence") - } - if p.GetCodeAttested() { - t.Fatal("token rotation must reset CodeAttested (fail-closed)") - } - select { - case <-p.ImmediateChallengeChan(): - default: - t.Fatal("token rotation must kick an immediate ordinary challenge, not wait for the 5-minute tick") - } - - // First-token arrival on a token-less provider clears no evidence: no kick. - late := makeRoutableProvider(t, reg, "late-provider", "kick-model") - late.Mu().Lock() - late.AttestationResult = &attestation.VerificationResult{Valid: true, PublicKey: sePubB64} - late.APNsDeviceToken = "" - late.Mu().Unlock() - srv.maybeRearmCodeAttest(context.Background(), "late-provider", late, &protocol.HeartbeatMessage{ - Type: protocol.TypeHeartbeat, Status: "idle", APNsDeviceToken: "late-tok", - }) - select { - case <-late.ImmediateChallengeChan(): - t.Fatal("first token arrival clears no evidence and must not kick") - default: - } -} - -// TestClearChallengeDropsOutstanding proves the Codex #1 hardening: clearing the -// outstanding challenge (done on APNs token rotation) drops it unconditionally, -// so a stale reply to the pre-rotation challenge can never complete the forced -// re-challenge — even before the fresh push records a new nonce. -func TestClearChallengeDropsOutstanding(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) - - const seKey = "se-key-1" - srv.codeAttestThrottle.recordChallenge(seKey, "old-nonce") - if _, ok := srv.codeAttestThrottle.outstandingChallenge(seKey); !ok { - t.Fatal("precondition: a recorded challenge must be outstanding") - } - srv.codeAttestThrottle.clearChallenge(seKey) - if _, ok := srv.codeAttestThrottle.outstandingChallenge(seKey); ok { - t.Fatal("clearChallenge must drop the outstanding challenge so a stale reply can't attest") - } -} diff --git a/coordinator/api/code_attest_resume_test.go b/coordinator/api/code_attest_resume_test.go index 9f66903839..7595444df1 100644 --- a/coordinator/api/code_attest_resume_test.go +++ b/coordinator/api/code_attest_resume_test.go @@ -21,7 +21,7 @@ import ( func TestRestartFreshProcessKeyTransitionsViaResumeWithoutPush(t *testing.T) { logger := quietLogger() srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) + srvControls := fastBudgets(srv) srv.minProviderVersion = "0.6.0" k1Pub, k1Priv, seKey, sePub := providerKeyMaterial(t) @@ -37,7 +37,7 @@ func TestRestartFreshProcessKeyTransitionsViaResumeWithoutPush(t *testing.T) { if !k1.GetFreshCodeAttested() { t.Fatal("precondition: K1 did not complete a genuine APNs proof") } - if _, ok := srv.codeAttestThrottle.reuseAttestationForTransition( + if _, ok := srv.codeIdentity.TransitionBinaryHash( sePub, k1.APNsDeviceToken, ); !ok { t.Fatal("precondition: K1 proof was not cached for this SE identity + token") @@ -54,7 +54,7 @@ func TestRestartFreshProcessKeyTransitionsViaResumeWithoutPush(t *testing.T) { atomic.AddInt32(&pushes, 1) return nil }}) - srv.codeResumeSender = func( + srvControls.resumeSender = func( _ string, message protocol.CodeAttestationResumeChallenge, ) error { // completeResumeRoundTrip asserts no code trust was granted before the @@ -129,16 +129,16 @@ func TestRestartTransitionWithoutCurrentEvidenceForcesFreshAPNsChallenge(t *test func TestRestartTransitionRotatedTokenRefused(t *testing.T) { logger := quietLogger() srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) + srvControls := fastBudgets(srv) srv.minProviderVersion = "0.6.0" kPub, _, _, sePub := providerKeyMaterial(t) provider := crossVersionProvider(kPub, sePub, "0.6.14") provider.APNsDeviceToken = "newtok" // Cached genuine proof was earned under the OLD token (by some process key). - seedFreshProcessAttestation(srv, sePub, "0.6.13", "oldtok", "old-process-key", trHashB) + seedFreshProcessAttestation(t, srv, sePub, "0.6.13", "oldtok", "old-process-key", trHashB) armCrossVersionApplicationEvidence(t, srv, provider, sePub) - srv.codeResumeSender = func(string, protocol.CodeAttestationResumeChallenge) error { + srvControls.resumeSender = func(string, protocol.CodeAttestationResumeChallenge) error { t.Error("rotated token must never receive a transition resume challenge") return nil } @@ -158,7 +158,7 @@ func TestRestartTransitionRotatedTokenRefused(t *testing.T) { func TestRestartTransitionWrongSESignatureRefused(t *testing.T) { logger := quietLogger() srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) + srvControls := fastBudgets(srv) srv.minProviderVersion = "0.6.0" ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -166,14 +166,14 @@ func TestRestartTransitionWrongSESignatureRefused(t *testing.T) { kPub, kPriv, _, sePub := providerKeyMaterial(t) _, _, wrongSE, _ := providerKeyMaterial(t) provider := crossVersionProvider(kPub, sePub, "0.6.14") - seedFreshProcessAttestation( + seedFreshProcessAttestation(t, srv, sePub, "0.6.13", provider.APNsDeviceToken, "old-process-key", trHashB) armCrossVersionApplicationEvidence(t, srv, provider, sePub) srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, _, _ string) error { return nil }}) - srv.codeResumeSender = func( + srvControls.resumeSender = func( _ string, message protocol.CodeAttestationResumeChallenge, ) error { // The genuine process key decrypts, but a WRONG SE key signs. @@ -199,7 +199,7 @@ func TestRestartTransitionWrongSESignatureRefused(t *testing.T) { func TestRestartTransitionDeactivatedReleaseProofForcesFreshAPNsChallenge(t *testing.T) { logger := quietLogger() srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) + srvControls := fastBudgets(srv) srv.minProviderVersion = "0.6.0" // K1 earns a genuine APNs proof while running release A (trHashB). @@ -224,7 +224,7 @@ func TestRestartTransitionDeactivatedReleaseProofForcesFreshAPNsChallenge(t *tes map[string][]approvedReleasePolicy{ trHashA: {{Version: k2.Version, Platform: "macos-arm64", Backend: k2.Backend}}, }) - srv.codeResumeSender = func(string, protocol.CodeAttestationResumeChallenge) error { + srvControls.resumeSender = func(string, protocol.CodeAttestationResumeChallenge) error { t.Error("a proof earned by a deactivated release must never authorize a transition resume") return nil } @@ -264,13 +264,13 @@ func TestRestartTransitionDeactivatedReleaseProofForcesFreshAPNsChallenge(t *tes func TestRestartSameBinaryTransitionsViaResumeWithoutPush(t *testing.T) { logger := quietLogger() srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) + srvControls := fastBudgets(srv) srv.minProviderVersion = "0.6.0" kPub, kPriv, seKey, sePub := providerKeyMaterial(t) provider := crossVersionProvider(kPub, sePub, "0.6.14") // Cached genuine proof earned under a PRIOR process key by the SAME binary. - seedFreshProcessAttestation( + seedFreshProcessAttestation(t, srv, sePub, "0.6.14", provider.APNsDeviceToken, "old-process-key", trHashA) armCrossVersionApplicationEvidenceWithPolicy(t, srv, provider, sePub, map[string][]approvedReleasePolicy{ @@ -282,7 +282,7 @@ func TestRestartSameBinaryTransitionsViaResumeWithoutPush(t *testing.T) { atomic.AddInt32(&pushes, 1) return nil }}) - srv.codeResumeSender = func( + srvControls.resumeSender = func( _ string, message protocol.CodeAttestationResumeChallenge, ) error { return completeResumeRoundTrip(t, srv, provider, "p1", kPriv, seKey, message) diff --git a/coordinator/api/code_attest_reuse_helpers_test.go b/coordinator/api/code_attest_reuse_helpers_test.go index 66b271af01..77cabf0718 100644 --- a/coordinator/api/code_attest_reuse_helpers_test.go +++ b/coordinator/api/code_attest_reuse_helpers_test.go @@ -1,10 +1,14 @@ package api import ( - "github.com/eigeninference/d-inference/coordinator/registry" + "context" "strings" "testing" "time" + + "github.com/eigeninference/d-inference/coordinator/providercontrol/codeidentity" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" ) // waitForCond polls cond up to d, returning its final value. Used to observe a @@ -20,18 +24,28 @@ func waitForCond(d time.Duration, cond func() bool) bool { return cond() } -func fastBudgets(srv *Server) { - srv.codeAttestThrottle.backgroundPushCooldown = time.Millisecond - srv.codeAttestThrottle.alertPushCooldown = time.Millisecond - srv.codeAttestThrottle.budgetClearCooldown = time.Millisecond - srv.codeAttestThrottle.retrySpacing = time.Millisecond - srv.codeAttestThrottle.retryJitter = 0 +type codeIdentityFixture struct { + now func() time.Time + resumeSender codeidentity.ResumeSender +} + +func configureCodeIdentityFixture(srv *Server, cfg codeidentity.Config) *codeIdentityFixture { + control := &codeIdentityFixture{now: cfg.Now} + cfg.Now = func() time.Time { return control.now() } + deps := srv.codeIdentityDependencies() + deps.ResumeSender = func() codeidentity.ResumeSender { return control.resumeSender } + srv.codeIdentity = codeidentity.New(cfg, deps) + return control } -func providerToken(p *registry.Provider) string { - p.Mu().Lock() - defer p.Mu().Unlock() - return p.APNsDeviceToken +func fastBudgets(srv *Server) *codeIdentityFixture { + cfg := codeidentity.DefaultConfig() + cfg.BackgroundPushCooldown = time.Millisecond + cfg.AlertPushCooldown = time.Millisecond + cfg.BudgetClearCooldown = time.Millisecond + cfg.RetrySpacing = time.Millisecond + cfg.RetryJitter = 0 + return configureCodeIdentityFixture(srv, cfg) } // crossVersionProvider builds a fully-fenced provider running newVersion: valid @@ -52,10 +66,22 @@ func crossVersionProvider(kPubB64, sePubB64, newVersion string) *registry.Provid } func seedFreshProcessAttestation( - srv *Server, seKey, oldVersion, token, nodeKey, binaryHash string, + t *testing.T, srv *Server, seKey, oldVersion, token, nodeKey, binaryHash string, ) { - srv.codeAttestThrottle.recordAttestedForProcess( - seKey, oldVersion, token, nodeKey, binaryHash) + t.Helper() + proof := store.CodeAttestation{SEPubKey: seKey, Version: oldVersion, APNsToken: token, + NodePublicKey: nodeKey, BinaryHash: binaryHash, AttestedAt: time.Now()} + seedCodeIdentityProof(t, srv, proof) +} + +// Seed through the real store interface rather than reaching into the owner's +// private cache. This is fixture evidence, never a live trust grant. +func seedCodeIdentityProof(t *testing.T, srv *Server, proof store.CodeAttestation) { + t.Helper() + if err := srv.store.UpsertCodeAttestation(context.Background(), proof); err != nil { + t.Fatal(err) + } + srv.SeedCodeAttestCache(context.Background()) } // armCrossVersionApplicationEvidence publishes a release policy whose ACTIVE @@ -79,7 +105,7 @@ func armCrossVersionApplicationEvidenceWithPolicy( ) { t.Helper() const policyGeneration = 1 - srv.releaseTrustPolicy.Store(&releaseTrustPolicySnapshot{ + seedReleasePolicyForTest(t, srv, releasePolicyObservation{ Generation: policyGeneration, Required: true, ByBinaryHash: byBinaryHash, diff --git a/coordinator/api/code_attest_reuse_policy_test.go b/coordinator/api/code_attest_reuse_policy_test.go index 6099c6d3e4..75774f490b 100644 --- a/coordinator/api/code_attest_reuse_policy_test.go +++ b/coordinator/api/code_attest_reuse_policy_test.go @@ -17,12 +17,12 @@ import ( func TestCrossVersionReuseAboveFloorSameProcessKeyReuses(t *testing.T) { logger := quietLogger() srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) + srvControls := fastBudgets(srv) srv.minProviderVersion = "0.6.0" kPubB64, kPriv, seKey, sePubB64 := providerKeyMaterial(t) provider := crossVersionProvider(kPubB64, sePubB64, "0.6.14") // bumped, above floor - seedFreshProcessAttestation( + seedFreshProcessAttestation(t, srv, sePubB64, "0.6.13", provider.APNsDeviceToken, provider.PublicKey, trHashB) armCrossVersionApplicationEvidence(t, srv, provider, sePubB64) @@ -32,7 +32,7 @@ func TestCrossVersionReuseAboveFloorSameProcessKeyReuses(t *testing.T) { atomic.AddInt32(&pushes, 1) return nil }}) - srv.codeResumeSender = func( + srvControls.resumeSender = func( _ string, message protocol.CodeAttestationResumeChallenge, ) error { return completeResumeRoundTrip( @@ -62,7 +62,7 @@ func TestCrossVersionReuseBelowFloorForcesChallenge(t *testing.T) { var pushes int32 provider := crossVersionProvider(kPubB64, sePubB64, "0.6.0") // DOWNGRADE, below floor - seedFreshProcessAttestation( + seedFreshProcessAttestation(t, srv, sePubB64, "0.6.13", provider.APNsDeviceToken, provider.PublicKey, trHashB) srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, pubKeyB64, nonceB64 string) error { @@ -91,7 +91,7 @@ func TestCrossVersionReuseTokenChangeForcesChallenge(t *testing.T) { var pushes int32 provider := crossVersionProvider(kPubB64, sePubB64, "0.6.14") provider.APNsDeviceToken = "newtok" // rotated token - seedFreshProcessAttestation( + seedFreshProcessAttestation(t, srv, sePubB64, "0.6.13", "oldtok", provider.PublicKey, trHashB) srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, pubKeyB64, nonceB64 string) error { atomic.AddInt32(&pushes, 1) @@ -119,7 +119,7 @@ func TestCrossVersionReuseUnfencedForcesChallenge(t *testing.T) { // newCodeAttestProvider sets AttestationResult.Valid but leaves // RuntimeVerified / RuntimeManifestChecked / ChallengeVerifiedSIP false. provider := newCodeAttestProvider(kPubB64, sePubB64) - seedFreshProcessAttestation( + seedFreshProcessAttestation(t, srv, sePubB64, "0.6.13", provider.APNsDeviceToken, provider.PublicKey, trHashB) provider.Version = "0.6.14" @@ -147,7 +147,7 @@ func TestCrossVersionReuseEmptyVersionForcesChallenge(t *testing.T) { var pushes int32 provider := crossVersionProvider(kPubB64, sePubB64, "") // NO version reported - seedFreshProcessAttestation( + seedFreshProcessAttestation(t, srv, sePubB64, "0.6.13", provider.APNsDeviceToken, provider.PublicKey, trHashB) srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, pubKeyB64, nonceB64 string) error { @@ -168,12 +168,12 @@ func TestCrossVersionReuseEmptyVersionForcesChallenge(t *testing.T) { func TestCrossVersionReuseCurrentApplicationEvidenceSameProcessReuses(t *testing.T) { logger := quietLogger() srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - fastBudgets(srv) + srvControls := fastBudgets(srv) srv.minProviderVersion = "0.6.0" kPubB64, kPriv, seKey, sePubB64 := providerKeyMaterial(t) provider := crossVersionProvider(kPubB64, sePubB64, "0.6.14") - seedFreshProcessAttestation( + seedFreshProcessAttestation(t, srv, sePubB64, "0.6.13", provider.APNsDeviceToken, provider.PublicKey, trHashB) armCrossVersionApplicationEvidence(t, srv, provider, sePubB64) @@ -182,7 +182,7 @@ func TestCrossVersionReuseCurrentApplicationEvidenceSameProcessReuses(t *testing atomic.AddInt32(&pushes, 1) return nil }}) - srv.codeResumeSender = func( + srvControls.resumeSender = func( _ string, message protocol.CodeAttestationResumeChallenge, ) error { return completeResumeRoundTrip( @@ -221,7 +221,7 @@ func TestCrossVersionReuseUsesLiveTokenNotCaptured(t *testing.T) { var pushes int32 provider := crossVersionProvider(kPubB64, sePubB64, "0.6.14") provider.APNsDeviceToken = "newtok" // live token already rotated (rotation won the lock) - seedFreshProcessAttestation( + seedFreshProcessAttestation(t, srv, sePubB64, "0.6.13", "oldtok", provider.PublicKey, trHashB) srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, pubKeyB64, nonceB64 string) error { atomic.AddInt32(&pushes, 1) diff --git a/coordinator/api/code_attest_throttle.go b/coordinator/api/code_attest_throttle.go deleted file mode 100644 index cbff647c0c..0000000000 --- a/coordinator/api/code_attest_throttle.go +++ /dev/null @@ -1,1088 +0,0 @@ -package api - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "math/rand/v2" - "slices" - "sync" - "sync/atomic" - "time" - - "github.com/eigeninference/d-inference/coordinator/saferun" - "github.com/eigeninference/d-inference/coordinator/store" -) - -// codeAttestStore is the minimal slice of store.Store the code-identity reuse -// cache needs to survive coordinator restarts/blue-green deploys (W5 Fix 2). -// store.Store satisfies it; tests can inject a fake. SECURITY: persistence is a -// performance optimization (avoid re-pushing within the reuse window), not an -// unconditional grant. reuseAttestation re-applies version, freshness, current -// token, and exact registration process-key gates to every seeded row. -type codeAttestStore interface { - ListCodeAttestations(ctx context.Context) ([]store.CodeAttestation, error) - UpsertCodeAttestation(ctx context.Context, rec store.CodeAttestation) error - DeleteCodeAttestation(ctx context.Context, seKey string) error -} - -type codeAttestPushBudgetStore interface { - ListCodeAttestPushBudgets(ctx context.Context) ([]store.CodeAttestPushBudget, error) - ReserveCodeAttestPushBudget( - ctx context.Context, - seKey, tokenHash string, - now, nextPushAt time.Time, - ) (bool, error) - ClearCodeAttestPushFloor( - ctx context.Context, - seKey string, - now time.Time, - cooldown time.Duration, - ) (time.Time, bool, error) -} - -// codeAttestThrottle keeps APNs code-identity pushes within Apple's background- -// push budget, reuses a recent attestation across reconnects, and tracks the -// per-device outstanding challenge so the WebSocket read-loop delivery path can -// verify a reply that lands on ANY connection (W5b Fix 1, reconnect-safe). -// -// Apple throttles silent/background notifications to roughly 2-3 per device per -// hour and drops the rest. Background pushes therefore use a long budget; alert -// pushes (apns-priority 10) are NOT background-throttled and may retry far -// sooner. Either way attestation is per-connection (the binary cannot change -// without the process — and thus the WebSocket — restarting), so a single -// challenge per connection suffices, with bounded retries only on delivery -// failure. -// -// All maps are keyed by the Secure Enclave public key — the stable per-device -// identity that survives reconnects and process restarts. Three knobs: -// - reuseWindow: how long a successful attestation is honored for a NEW -// connection with the same device, version, APNs token, and exact process -// node key without re-pushing. Same-process verified continuity can also -// authorize a resume within codeAttestContinuityGap. Process-key changes -// only use the recent-proof approved-transition path or a new APNs push. -// Every resume still requires a live encrypted challenge. -// - push budget (backgroundPushCooldown / alertPushCooldown): minimum spacing -// between pushes to the same device — the hard rate-limit backstop, chosen by -// delivery mode. Background stays <= 3 pushes/hour/device; alert can be much -// shorter because it is not background-throttled. -// - retrySpacing (+jitter): the loop's poll/backoff cadence. SEPARATE from the -// push budget (W5b Fix 3) so a missed push is noticed and re-pushed promptly -// (within budget) instead of being pinned to the 20-minute background budget, -// and jitter de-synchronises fleet-wide reconnects (e.g. post-deploy). -type codeAttestThrottle struct { - mu sync.Mutex - attested map[string]codeAttestRecord // seKey -> last successful attestation (reuse cache) - lastPush map[string]time.Time // seKey -> last push (device-level rate limit) - lastBudgetClear map[string]time.Time // seKey -> last token-rotation budget reset (anti-DoS floor) - outstanding map[string][]codeAttestChallenge // seKey -> unexpired pushed, not-yet-verified challenges (alert mode can have several in flight) - resumeChallenges map[string]codeAttestResumeChallenge // nonce -> live WS/X25519 PoP - loopGeneration atomic.Uint64 - loopGenerations map[string]uint64 - loopTokens map[string]string - durableNextPush map[string]time.Time - novelTokenBlockedUntil map[string]time.Time - // novelPushFloor is the per-SE-key admission floor for NOVEL tokens: every - // admitted push raises it, so a device's first token pushes immediately but - // a reconnect churn of fabricated fresh tokens is paced at the same - // per-device budget as one token (Codex P1). Cleared only by an honored - // (budgetClearCooldown-throttled) genuine rotation. Mirrors the durable - // TokenHash=="" sentinel row so the floor survives restarts. - novelPushFloor map[string]time.Time - // budgetTokenOrder tracks per-SE-key token budget entries in recency order - // so lastPush/durableNextPush stay bounded under token churn (newest - // store.CodeAttestPushBudgetMaxTokenRows kept, matching the durable cap). - budgetTokenOrder map[string][]string - reservationLocks map[string]*codeAttestReservationLock - reuseWindow time.Duration - - // Push budget (the hard background-push rate-limit backstop) is mode-aware: - // allowPush picks the cooldown by delivery mode. - backgroundPushCooldown time.Duration - alertPushCooldown time.Duration - - // budgetClearCooldown is the minimum spacing between token-rotation budget - // resets per device (clearPushBudget). A provider can put any string in the - // heartbeat APNs-token field on every heartbeat; without this floor each - // "rotation" would reset the push budget and force an immediate push, letting a - // misbehaving provider spam APNs (and coordinator work) far beyond Apple's - // per-device budget. A GENUINE rotation is rare, so it still clears promptly; a - // flood is throttled back to the normal cooldown. - budgetClearCooldown time.Duration - - // retrySpacing is the loop's poll/backoff cadence, decoupled from the push - // budget; retryJitter de-synchronises a fleet-wide reconnect so pushes don't - // thunder against the per-device budget. - retrySpacing time.Duration - retryJitter time.Duration - - // challengeValidity bounds how long a pushed nonce is accepted by the read-loop - // delivery path. Kept consistent with the APNs apns-expiration window (W5b - // Fix 5): a reply is accepted for as long as the push could still have been - // delivered. - challengeValidity time.Duration - resumeTimeout time.Duration - - maxAttempts int - now func() time.Time - jitter func(max time.Duration) time.Duration - - // store persists the reuse cache across restarts/deploys (W5 Fix 2). nil - // until wired by Server.SeedCodeAttestCache at startup (and nil in unit tests - // that construct a bare throttle), so every persistence path is nil-safe — the - // in-memory reuse cache works identically with or without a store. - store codeAttestStore -} - -type codeAttestReservationLock struct { - mu sync.Mutex - users int -} - -type codeAttestRecord struct { - coveredUntil time.Time // observed verified same-process connection; never an APNs refresh - at time.Time - version string - token string // APNs device token the proof was bound to ("" = legacy row from before token-binding) - nodeKey string // registration X25519 process key ("" = legacy non-reusable row) - binaryHash string // SE-attested binary identity the proof was earned under ("" = legacy row; never authorizes a transition resume) -} - -// codeAttestChallenge is a pushed-but-not-yet-verified code-identity challenge. -// Keyed by SE key (not connection) so a reply that arrives on a reconnected -// WebSocket still matches the nonce the coordinator pushed (W5b Fix 1). -type codeAttestChallenge struct { - nonce string - token string - nodeKey string - at time.Time -} - -type codeAttestResumeChallenge struct { - providerID string - nodeKey string - seKey string - token string - expiresAt time.Time - done chan struct{} -} - -func newCodeAttestThrottle() *codeAttestThrottle { - return &codeAttestThrottle{ - attested: make(map[string]codeAttestRecord), - lastPush: make(map[string]time.Time), - lastBudgetClear: make(map[string]time.Time), - resumeChallenges: make(map[string]codeAttestResumeChallenge), - outstanding: make(map[string][]codeAttestChallenge), - loopGenerations: make(map[string]uint64), - loopTokens: make(map[string]string), - durableNextPush: make(map[string]time.Time), - novelTokenBlockedUntil: make(map[string]time.Time), - novelPushFloor: make(map[string]time.Time), - budgetTokenOrder: make(map[string][]string), - reservationLocks: make(map[string]*codeAttestReservationLock), - reuseWindow: 30 * time.Minute, - backgroundPushCooldown: 20 * time.Minute, // <= 3 pushes/hour/device (APNs background budget) - alertPushCooldown: 75 * time.Second, // alert is not background-throttled (Fix 3) - budgetClearCooldown: 20 * time.Minute, // a token rotation can reset the budget at most ~3x/hour/device - retrySpacing: 15 * time.Second, // poll/backoff cadence, separate from the budget - retryJitter: 15 * time.Second, // de-sync fleet retries -> retryDelay in [15s, 30s) - challengeValidity: CodeAttestResponseTimeout, - resumeTimeout: ChallengeResponseTimeout, - maxAttempts: 3, - now: time.Now, - jitter: defaultJitter, - } -} - -// defaultJitter returns a uniform random duration in [0, max). -func defaultJitter(max time.Duration) time.Duration { - if max <= 0 { - return 0 - } - return time.Duration(rand.Int64N(int64(max))) -} - -// reuseAttestation reports whether the device attested recently with the same -// binary version, exact current non-empty APNs token, and exact registration- -// bound process node key that decrypted E_K(nonce). Legacy token-less or -// process-key-less rows are never reusable authorization inputs; they must -// bootstrap a real push. Old proofs additionally require recorded same-process -// verified continuity within codeAttestContinuityGap. -func (t *codeAttestThrottle) reuseAttestation(seKey, version, token, nodeKey string) bool { - return t.reuseAttestationBasis(seKey, version, token, nodeKey) != "" -} - -func (t *codeAttestThrottle) reuseAttestationBasis(seKey, version, token, nodeKey string) string { - if seKey == "" || version == "" || token == "" || nodeKey == "" { - return "" - } - t.mu.Lock() - defer t.mu.Unlock() - r, ok := t.attested[seKey] - if !ok || r.version != version || r.token != token || r.nodeKey != nodeKey { - return "" - } - now := t.now() - if r.recent(now, t.reuseWindow) { - return "recent_apns" - } - if r.continuous(now) { - return "process_continuity" - } - return "" -} - -// reuseAttestationForTransition supplies the genuine Apple/APNs half of an -// approved release transition, returning the SE-attested binary identity the -// cached proof was earned under. Version may differ, and — unlike same-version -// reuseAttestation — the cached proof's process key may differ from the current -// one: the provider generates a fresh ephemeral NodeKeyPair on every process -// start, so requiring key equality here would push the whole fleet on every -// routine upgrade/restart and strand providers behind the durable APNs floor -// while queued requests expire. The proof must still be fresh, bound to the -// same SE identity and exact current non-empty token, must itself carry a -// process-key binding, and must record WHICH binary earned it (a legacy -// unbound or identity-less row never authorizes a transition). The CALLER -// (tryCrossVersionReuse) then decides whether that recorded identity — same -// binary, or an APPROVED active predecessor of the current release — may -// transition; a proof earned by a deactivated/unknown release falls through to -// a real APNs challenge (Codex 05:55Z P1). -// SECURITY: this only authorizes SENDING a live encrypted resume challenge to -// the CURRENT registration process key; possession of that new key is proven -// solely by decrypting E_K(nonce), and the SE signature over the recovered -// nonce is still verified — the cached record never grants trust by itself. -func (t *codeAttestThrottle) reuseAttestationForTransition( - seKey, token string, -) (string, bool) { - if seKey == "" || token == "" { - return "", false - } - t.mu.Lock() - defer t.mu.Unlock() - r, ok := t.attested[seKey] - if !ok || - r.token != token || - r.nodeKey == "" || - r.binaryHash == "" || - !r.recent(t.now(), t.reuseWindow) { - return "", false - } - return r.binaryHash, true -} - -// pushCooldown returns the per-device push budget for the active delivery mode. -func (t *codeAttestThrottle) pushCooldown(alert bool) time.Duration { - if alert { - return t.alertPushCooldown - } - return t.backgroundPushCooldown -} - -// allowPush reports whether the per-device push budget permits another push now, -// for the given delivery mode (alert is allowed to push far more often). -func (t *codeAttestThrottle) allowPush(seKey string, alert bool) bool { - if seKey == "" { - return true // no device identity to throttle on; fall back to the loop's cap - } - t.mu.Lock() - defer t.mu.Unlock() - last, ok := t.lastPush[seKey] - return !ok || t.now().Sub(last) >= t.pushCooldown(alert) -} - -// retryDelay is the loop's wait between wake-ups: a base spacing plus jitter. -// Decoupled from the push budget so attestation is noticed promptly (Fix 3). -func (t *codeAttestThrottle) retryDelay() time.Duration { - return t.retrySpacing + t.jitter(t.retryJitter) -} - -func (t *codeAttestThrottle) recordPush(seKey string) { - if seKey == "" { - return - } - t.mu.Lock() - t.lastPush[seKey] = t.now() - t.mu.Unlock() -} - -func codeAttestTokenHash(token string) string { - sum := sha256.Sum256([]byte(token)) - return hex.EncodeToString(sum[:]) -} - -func codeAttestPushBudgetKey(seKey, tokenHash string) string { - return seKey + "\x00" + tokenHash -} - -// beginLoop rotates exclusive loop ownership for one stable device identity. -// A registration loop and heartbeat rearm may overlap briefly, but only the -// latest generation can reserve a push. -func (t *codeAttestThrottle) beginLoop(seKey string) uint64 { - if seKey == "" { - return 0 - } - unlockReservation := t.lockPushReservation(seKey) - defer unlockReservation() - return t.beginLoopReservationHeld(seKey) -} - -func (t *codeAttestThrottle) beginLoopReservationHeld(seKey string) uint64 { - generation := t.loopGeneration.Add(1) - t.mu.Lock() - t.loopGenerations[seKey] = generation - delete(t.loopTokens, seKey) - t.mu.Unlock() - return generation -} - -// rotateLoopAndClearPushBudget makes token-rotation ownership and budget reset -// one per-device operation. An old loop cannot reserve the just-cleared budget -// between the generation change and the new loop taking ownership. An honored -// (unthrottled) reset also clears the durable novel-token admission floor so -// the rotated token is challenged promptly across restarts and peers. -func (t *codeAttestThrottle) rotateLoopAndClearPushBudget( - ctx context.Context, seKey string, -) uint64 { - if seKey == "" { - return 0 - } - unlockReservation := t.lockPushReservation(seKey) - defer unlockReservation() - generation := t.beginLoopReservationHeld(seKey) - t.clearPushBudgetReservationHeld(ctx, seKey) - return generation -} - -func (t *codeAttestThrottle) loopCurrent(seKey string, generation uint64) bool { - if seKey == "" || generation == 0 { - return false - } - t.mu.Lock() - defer t.mu.Unlock() - return t.loopGenerations[seKey] == generation -} - -func (t *codeAttestThrottle) endLoop(seKey string, generation uint64) { - if seKey == "" || generation == 0 { - return - } - t.mu.Lock() - if t.loopGenerations[seKey] == generation { - delete(t.loopGenerations, seKey) - delete(t.loopTokens, seKey) - } - t.mu.Unlock() -} - -func (t *codeAttestThrottle) loopCurrentForToken( - seKey, token string, - generation uint64, -) bool { - if seKey == "" || token == "" || generation == 0 { - return false - } - tokenHash := codeAttestTokenHash(token) - t.mu.Lock() - defer t.mu.Unlock() - return t.loopGenerations[seKey] == generation && - t.loopTokens[seKey] == tokenHash -} - -func (t *codeAttestThrottle) lockPushReservation(seKey string) func() { - t.mu.Lock() - lock := t.reservationLocks[seKey] - if lock == nil { - lock = &codeAttestReservationLock{} - t.reservationLocks[seKey] = lock - } - lock.users++ - t.mu.Unlock() - - lock.mu.Lock() - return func() { - lock.mu.Unlock() - t.mu.Lock() - lock.users-- - if lock.users == 0 && t.reservationLocks[seKey] == lock { - delete(t.reservationLocks, seKey) - } - t.mu.Unlock() - } -} - -// reservePush combines generation validation, local cooldown admission, and -// the durable cross-process compare-and-set. Its returned release function keeps -// the per-device lease held through identity recheck and push dispatch. -func (t *codeAttestThrottle) reservePush( - ctx context.Context, - seKey, token string, - alert bool, - generation uint64, -) (func(), bool) { - if seKey == "" || token == "" || generation == 0 { - return nil, false - } - unlockReservation := t.lockPushReservation(seKey) - - tokenHash := codeAttestTokenHash(token) - t.mu.Lock() - if t.loopGenerations[seKey] != generation { - t.mu.Unlock() - unlockReservation() - return nil, false - } - if currentToken := t.loopTokens[seKey]; currentToken != "" && - currentToken != tokenHash { - t.mu.Unlock() - unlockReservation() - return nil, false - } - t.loopTokens[seKey] = tokenHash - now := t.now() - cooldown := t.pushCooldown(alert) - budgetKey := codeAttestPushBudgetKey(seKey, tokenHash) - _, seenLastPush := t.lastPush[budgetKey] - _, seenDurablePush := t.durableNextPush[budgetKey] - novelToken := !seenLastPush && !seenDurablePush - if blockedUntil := t.novelTokenBlockedUntil[seKey]; blockedUntil.After(now) && novelToken { - t.mu.Unlock() - unlockReservation() - return nil, false - } else if !blockedUntil.IsZero() && !blockedUntil.After(now) { - delete(t.novelTokenBlockedUntil, seKey) - } - // Per-SE-key admission floor: a token this device never budgeted may only - // push once the floor from the LAST push (to any token) has elapsed. The - // first-ever token has no floor and admits immediately; a reconnect churn - // of fabricated fresh tokens is paced like a single token (Codex P1). - if floor, ok := t.novelPushFloor[seKey]; ok && novelToken { - if floor.After(now) { - t.mu.Unlock() - unlockReservation() - return nil, false - } - delete(t.novelPushFloor, seKey) - } - if last, ok := t.lastPush[budgetKey]; ok && - now.Sub(last) < cooldown { - t.mu.Unlock() - unlockReservation() - return nil, false - } - if next, ok := t.durableNextPush[budgetKey]; ok && - next.After(now) { - t.mu.Unlock() - unlockReservation() - return nil, false - } - reservationCooldown := max(cooldown, time.Nanosecond) - next := now.Add(reservationCooldown) - st, hasDurableBudget := store.As[codeAttestPushBudgetStore](t.store) - t.mu.Unlock() - - if hasDurableBudget { - admitted, err := st.ReserveCodeAttestPushBudget( - ctx, seKey, tokenHash, now, next, - ) - if err != nil || !admitted { - unlockReservation() - return nil, false - } - } - - t.mu.Lock() - if t.loopGenerations[seKey] != generation || - t.loopTokens[seKey] != tokenHash { - t.mu.Unlock() - unlockReservation() - return nil, false - } - t.lastPush[budgetKey] = now - t.durableNextPush[budgetKey] = next - if next.After(t.novelPushFloor[seKey]) { - t.novelPushFloor[seKey] = next - } - t.noteBudgetTokenReservationHeld(seKey, tokenHash) - t.mu.Unlock() - return unlockReservation, true -} - -// noteBudgetTokenReservationHeld (t.mu held) tracks per-SE-key token budget -// entries in recency order and evicts the oldest beyond the durable cap, so -// lastPush/durableNextPush cannot grow unboundedly under token churn. An -// evicted token that returns falls back to the admission floor. -func (t *codeAttestThrottle) noteBudgetTokenReservationHeld(seKey, tokenHash string) { - order := t.budgetTokenOrder[seKey] - if i := slices.Index(order, tokenHash); i >= 0 { - order = append(order[:i], order[i+1:]...) - } - order = append(order, tokenHash) - for len(order) > store.CodeAttestPushBudgetMaxTokenRows { - evictedKey := codeAttestPushBudgetKey(seKey, order[0]) - delete(t.lastPush, evictedKey) - delete(t.durableNextPush, evictedKey) - order = order[1:] - } - t.budgetTokenOrder[seKey] = order -} - -func (t *codeAttestThrottle) tryReservePush( - ctx context.Context, - seKey, token string, - alert bool, - generation uint64, -) bool { - release, ok := t.reservePush(ctx, seKey, token, alert, generation) - if release != nil { - release() - } - return ok -} - -// clearPushBudget drops the per-device push cooldown so the NEXT push is allowed -// immediately. Used on APNs token rotation: the cooldown tracks pushes to the OLD -// token, but Apple's push budget is per-token, so the freshly registered token has -// its own untouched budget. Without this, the rearm loop sets CodeAttested=false -// yet cannot challenge the new token until the old token's (up to 20-minute) -// background cooldown expires — derouting the provider for no reason (Codex #9). -// -// Anti-DoS: the reset is itself throttled to at most once per budgetClearCooldown -// per device, so a provider that floods token changes in heartbeats cannot reset -// the budget every time and spam APNs beyond the per-device budget. The cooldown -// is DURABLE (Codex 06:36Z P1): with a budget store wired, the clear is -// compare-and-set on the sentinel's persisted last-clear instant, so a -// coordinator restart (empty lastBudgetClear map) or a blue-green peer cannot -// grant one extra floor clear per deploy. Returns whether the budget was -// actually cleared (false = the reset was throttled). -func (t *codeAttestThrottle) clearPushBudget(ctx context.Context, seKey string) bool { - if seKey == "" { - return false - } - unlockReservation := t.lockPushReservation(seKey) - defer unlockReservation() - return t.clearPushBudgetReservationHeld(ctx, seKey) -} - -// clearPushBudgetReservationHeld runs the full throttled clear (reservation -// lock held, t.mu NOT held across the store call). Admission order: the cheap -// process-local cooldown first, then the durable compare-and-set — the durable -// verdict is authoritative and is mirrored locally either way, so a throttled -// peer's flood settles into the local fast path without further store traffic. -// Fail-closed: on store error nothing is cleared; the rotated token is only -// DELAYED until the floor elapses — the rate limit never weakens. -func (t *codeAttestThrottle) clearPushBudgetReservationHeld( - ctx context.Context, seKey string, -) bool { - t.mu.Lock() - now := t.now() - if last, ok := t.lastBudgetClear[seKey]; ok && - now.Sub(last) < t.budgetClearCooldown { - t.novelTokenBlockedUntil[seKey] = last.Add(t.budgetClearCooldown) - t.mu.Unlock() - return false - } - st, hasDurable := store.As[codeAttestPushBudgetStore](t.store) - cooldown := t.budgetClearCooldown - t.mu.Unlock() - - if hasDurable { - lastClear, cleared, err := st.ClearCodeAttestPushFloor( - ctx, seKey, now, cooldown, - ) - if err != nil { - return false - } - if !cleared { - // Another instance (or a pre-restart clear) already spent this - // window. Mirror the durable verdict locally so the next flood - // attempt short-circuits without a store round-trip. - t.mu.Lock() - if lastClear.After(t.lastBudgetClear[seKey]) { - t.lastBudgetClear[seKey] = lastClear - } - if blocked := lastClear.Add(cooldown); blocked.After(t.novelTokenBlockedUntil[seKey]) { - t.novelTokenBlockedUntil[seKey] = blocked - } - t.mu.Unlock() - return false - } - } - - t.mu.Lock() - t.lastBudgetClear[seKey] = now - delete(t.novelTokenBlockedUntil, seKey) - // An honored rotation lifts the novel-token admission floor: the freshly - // registered token must be challengeable immediately (Codex #9). The reset - // itself is budgetClearCooldown-throttled — durably when a store is wired — - // so floor lifting cannot be flooded into unbounded novel-token admissions. - delete(t.novelPushFloor, seKey) - // Composite (SE, token-hash) entries intentionally survive rotation. They - // preserve A-B-A cooldowns; a genuinely new token has no composite entry and - // therefore receives its independent budget. Only pre-composite legacy keys - // are safe to clear here. - delete(t.lastPush, seKey) - delete(t.durableNextPush, seKey) - t.mu.Unlock() - return true -} - -func (t *codeAttestThrottle) recordAttested(seKey, version, token string) { - if seKey == "" { - return - } - t.mu.Lock() - t.attested[seKey] = codeAttestRecord{at: t.now(), version: version, token: token} - t.mu.Unlock() -} - -func (t *codeAttestThrottle) recordAttestedForProcess( - seKey, version, token, nodeKey, binaryHash string, -) { - if seKey == "" { - return - } - t.mu.Lock() - t.attested[seKey] = codeAttestRecord{ - at: t.now().Truncate(time.Microsecond), version: version, token: token, nodeKey: nodeKey, - binaryHash: binaryHash, - } - t.mu.Unlock() -} - -// invalidateReuse drops any cached reuse record for a device so the NEXT -// code-identity attempt cannot be short-circuited by reuseAttestation and must -// run a real challenge round-trip. Used when a provider's APNs device token -// CHANGES mid-connection (W5 Fix 2): a changed token forces a re-challenge with -// no bypass. This drops only the IN-MEMORY record; the caller also deletes the -// PERSISTED row (Server.invalidatePersistedCodeAttestation) so a coordinator -// restart before the fresh challenge completes cannot reseed and reuse the -// pre-rotation proof (Codex #6). -func (t *codeAttestThrottle) invalidateReuse(seKey string) { - if seKey == "" { - return - } - t.mu.Lock() - delete(t.attested, seKey) - t.mu.Unlock() -} - -// seed loads persisted attestation records into the in-memory reuse cache at -// startup (W5 Fix 2). It applies the SAME freshness window used on read, so only -// rows that could still be reused are kept (an expired row would be ignored by -// reuseAttestation anyway). It never overwrites a fresher in-memory record (a -// device that reconnected and re-attested before seeding finished). Returns the -// number of rows seeded. SECURITY: seeding only populates the cache; -// reuseAttestation re-validates version, freshness, token, and exact process key -// on every read. A stale, mismatched, or legacy process-key-less row still -// forces a real challenge. -func (t *codeAttestThrottle) seed(rows []store.CodeAttestation) int { - t.mu.Lock() - defer t.mu.Unlock() - now := t.now() - n := 0 - for _, r := range rows { - if r.SEPubKey == "" { - continue - } - candidate := codeAttestRecord{at: r.AttestedAt, version: r.Version, token: r.APNsToken, nodeKey: r.NodePublicKey, binaryHash: r.BinaryHash, coveredUntil: coverageFromStore(r.ContinuousCoverageUntil)} - if !candidate.recent(now, t.reuseWindow) && !candidate.continuous(now) { - continue - } - if cur, ok := t.attested[r.SEPubKey]; ok && !r.AttestedAt.After(cur.at) { - continue // keep the fresher in-memory record - } - t.attested[r.SEPubKey] = candidate - n++ - } - return n -} - -// recordChallenge stores the nonce just pushed to a device so the read-loop -// delivery path can match the provider's reply — even one that lands on a -// different (re)connection from the same device (Fix 1). Overwrites any prior -// outstanding challenge for the device (only the latest push is honored). -func (t *codeAttestThrottle) recordChallenge(seKey, nonce string) { - if seKey == "" { - return - } - t.mu.Lock() - now := t.now() - // Keep EVERY still-unexpired nonce, not just the latest: in alert mode the push - // cooldown (75s) is shorter than the challenge validity (the APNs expiry window), - // so a second challenge can be pushed while the first is still deliverable. If we - // kept only the newest nonce, a delayed delivery of the first alert would make the - // device reply with a nonce we had already discarded, we'd reject a valid proof, - // and repeated delayed deliveries could strand attestation (Codex #8). Prune - // expired entries on the way in so the slice stays bounded by validity/cooldown. - old := t.outstanding[seKey] - kept := make([]codeAttestChallenge, 0, len(old)+1) - for _, ch := range old { - if now.Sub(ch.at) < t.challengeValidity { - kept = append(kept, ch) - } - } - t.outstanding[seKey] = append(kept, codeAttestChallenge{nonce: nonce, at: now}) - t.mu.Unlock() -} - -func (t *codeAttestThrottle) recordChallengeForIdentity( - seKey, nonce, token, nodeKey string, -) { - if seKey == "" { - return - } - t.mu.Lock() - now := t.now() - old := t.outstanding[seKey] - kept := old[:0] - for _, challenge := range old { - if now.Sub(challenge.at) < t.challengeValidity { - kept = append(kept, challenge) - } - } - t.outstanding[seKey] = append(kept, codeAttestChallenge{ - nonce: nonce, at: now, token: token, nodeKey: nodeKey, - }) - t.mu.Unlock() -} - -func (t *codeAttestThrottle) matchChallengeForIdentity( - seKey, nonce, token, nodeKey string, -) bool { - t.mu.Lock() - defer t.mu.Unlock() - now := t.now() - for _, challenge := range t.outstanding[seKey] { - if challenge.nonce == nonce && - now.Sub(challenge.at) < t.challengeValidity && - (challenge.token == "" || challenge.token == token) && - (challenge.nodeKey == "" || challenge.nodeKey == nodeKey) { - return true - } - } - return false -} - -func (t *codeAttestThrottle) consumeChallengeForIdentity( - seKey, nonce, token, nodeKey string, -) bool { - t.mu.Lock() - defer t.mu.Unlock() - now := t.now() - challenges := t.outstanding[seKey] - for i, challenge := range challenges { - if challenge.nonce == nonce && - now.Sub(challenge.at) < t.challengeValidity && - (challenge.token == "" || challenge.token == token) && - (challenge.nodeKey == "" || challenge.nodeKey == nodeKey) { - challenges = append(challenges[:i], challenges[i+1:]...) - if len(challenges) == 0 { - delete(t.outstanding, seKey) - } else { - t.outstanding[seKey] = challenges - } - return true - } - } - return false -} - -// outstandingChallenge reports whether the device has ANY still-valid pushed -// challenge, returning the most recent one. The delivery path matches a specific -// reply nonce via matchChallenge; this is the existence / most-recent view. -func (t *codeAttestThrottle) outstandingChallenge(seKey string) (codeAttestChallenge, bool) { - if seKey == "" { - return codeAttestChallenge{}, false - } - t.mu.Lock() - defer t.mu.Unlock() - now := t.now() - var best codeAttestChallenge - found := false - for _, ch := range t.outstanding[seKey] { - if now.Sub(ch.at) < t.challengeValidity && (!found || ch.at.After(best.at)) { - best = ch - found = true - } - } - return best, found -} - -// matchChallenge reports whether nonce equals ANY still-unexpired challenge pushed -// to this device. Accepting a reply to any in-flight challenge (not only the latest) -// is what prevents a delayed alert delivery from being rejected (Codex #8). -func (t *codeAttestThrottle) matchChallenge(seKey, nonce string) bool { - if seKey == "" || nonce == "" { - return false - } - t.mu.Lock() - defer t.mu.Unlock() - now := t.now() - for _, ch := range t.outstanding[seKey] { - if ch.nonce == nonce && now.Sub(ch.at) < t.challengeValidity { - return true - } - } - return false -} - -// clearChallengeIf removes the given nonce from the device's outstanding set (e.g. -// after it was answered or its push failed), leaving any other in-flight nonces -// intact so a concurrent challenge is never clobbered. -func (t *codeAttestThrottle) clearChallengeIf(seKey, nonce string) { - if seKey == "" { - return - } - t.mu.Lock() - if chs, ok := t.outstanding[seKey]; ok { - kept := chs[:0] - for _, ch := range chs { - if ch.nonce != nonce { - kept = append(kept, ch) - } - } - if len(kept) == 0 { - delete(t.outstanding, seKey) - } else { - t.outstanding[seKey] = kept - } - } - t.mu.Unlock() -} - -// clearChallenge unconditionally drops any outstanding challenge for a device. -// Used on APNs token rotation so a stale reply to the OLD-token challenge can -// never complete the forced re-challenge: if the fresh push is delayed or fails, -// there is simply no outstanding nonce to match (fail-closed), rather than the -// pre-rotation nonce remaining answerable. The subsequent fresh push records its -// own nonce, so this never clobbers the new challenge (it runs before the push). -func (t *codeAttestThrottle) clearChallenge(seKey string) { - if seKey == "" { - return - } - t.mu.Lock() - delete(t.outstanding, seKey) - t.mu.Unlock() -} - -// SeedCodeAttestCache wires the store into the code-identity reuse cache and -// seeds it from persisted records at startup (W5 Fix 2). This is what makes the -// reuse cache survive a coordinator restart / blue-green deploy, so a fresh -// instance does not re-push the entire fleet (against Apple's ~3/hour/device push -// budget). Safe to call once during server setup, AFTER the store is set and the -// attestor is wired; a nil store or nil throttle is a no-op. SECURITY: seeding -// only repopulates the cache that reuseAttestation re-validates (same version, -// freshness, token, and exact process key) on every read. A stale, mismatched, -// or legacy process-key-less row still falls through to a real challenge. -func (s *Server) SeedCodeAttestCache(ctx context.Context) { - if s == nil || s.codeAttestThrottle == nil || s.store == nil { - return - } - // Wire the write-through path so future successful round-trips are persisted. - s.codeAttestThrottle.store = s.store - - rows, err := s.store.ListCodeAttestations(ctx) - if err != nil { - s.logger.Warn("code-attest: failed to seed reuse cache from store", "error", err) - } else if n := s.codeAttestThrottle.seed(rows); n > 0 { - s.logger.Info("code-attest: seeded reuse cache from persisted records (survives deploys)", "records", n) - } - if st, ok := store.As[codeAttestPushBudgetStore](s.store); ok { - budgets, err := st.ListCodeAttestPushBudgets(ctx) - if err != nil { - s.logger.Warn("code-attest: failed to seed durable push budgets", "error", err) - } else { - th := s.codeAttestThrottle - th.mu.Lock() - for _, budget := range budgets { - if budget.SEPubKey == "" { - continue - } - if budget.TokenHash == "" { - // Sentinel row: the per-SE-key novel-token admission floor - // (also the shape of legacy pre-composite rows, whose - // per-SE budget means exactly this). Codex P1. Its - // LastClearAt seeds the rotation-clear cooldown, so a - // restart cannot re-grant a floor clear the previous - // instance already spent (Codex 06:36Z P1) — even when the - // floor itself has already elapsed. - if budget.LastClearAt.After(th.lastBudgetClear[budget.SEPubKey]) { - th.lastBudgetClear[budget.SEPubKey] = budget.LastClearAt - } - if budget.NextPushAt.After(th.now()) && - budget.NextPushAt.After(th.novelPushFloor[budget.SEPubKey]) { - th.novelPushFloor[budget.SEPubKey] = budget.NextPushAt - } - continue - } - if !budget.NextPushAt.After(th.now()) { - continue - } - key := codeAttestPushBudgetKey( - budget.SEPubKey, budget.TokenHash, - ) - th.durableNextPush[key] = budget.NextPushAt - th.noteBudgetTokenReservationHeld( - budget.SEPubKey, budget.TokenHash, - ) - } - th.mu.Unlock() - } - } -} - -// recordResumeChallenge stores a one-time, connection-bound X25519 PoP nonce -// with the exact resume deadline. APNs challenges intentionally use the longer -// challengeValidity window; live-connection resume proofs do not. -func (t *codeAttestThrottle) recordResumeChallenge( - nonce, providerID, nodeKey, seKey, token string, -) <-chan struct{} { - t.mu.Lock() - done := make(chan struct{}) - t.resumeChallenges[nonce] = codeAttestResumeChallenge{ - providerID: providerID, nodeKey: nodeKey, seKey: seKey, - token: token, expiresAt: t.now().Add(t.resumeTimeout), done: done, - } - t.mu.Unlock() - return done -} - -func (t *codeAttestThrottle) clearResumeChallenges(providerID string) { - t.mu.Lock() - for nonce, challenge := range t.resumeChallenges { - if challenge.providerID == providerID { - close(challenge.done) - delete(t.resumeChallenges, nonce) - } - } - t.mu.Unlock() -} - -func resumeChallengeMatches( - challenge codeAttestResumeChallenge, - providerID, nodeKey, seKey, token string, -) bool { - return challenge.providerID == providerID && - challenge.nodeKey == nodeKey && - challenge.seKey == seKey && - challenge.token == token -} - -func (t *codeAttestThrottle) resumeChallengeExpiry( - nonce, providerID, nodeKey, seKey, token string, -) (time.Time, bool) { - t.mu.Lock() - defer t.mu.Unlock() - challenge, ok := t.resumeChallenges[nonce] - if !ok || !resumeChallengeMatches( - challenge, providerID, nodeKey, seKey, token, - ) { - return time.Time{}, false - } - return challenge.expiresAt, true -} - -func (t *codeAttestThrottle) matchResumeChallenge( - nonce, providerID, nodeKey, seKey, token string, -) bool { - t.mu.Lock() - defer t.mu.Unlock() - challenge, ok := t.resumeChallenges[nonce] - return ok && - t.now().Before(challenge.expiresAt) && - resumeChallengeMatches(challenge, providerID, nodeKey, seKey, token) -} - -func (t *codeAttestThrottle) consumeResumeChallenge( - nonce, providerID, nodeKey, seKey, token string, -) bool { - t.mu.Lock() - defer t.mu.Unlock() - challenge, ok := t.resumeChallenges[nonce] - if !ok || - !t.now().Before(challenge.expiresAt) || - !resumeChallengeMatches(challenge, providerID, nodeKey, seKey, token) { - return false - } - delete(t.resumeChallenges, nonce) - close(challenge.done) - return true -} - -// expireResumeChallenge atomically lets only the deadline path claim a resume -// nonce. A response racing the timer either consumes the still-live nonce first -// or loses to this removal; neither path can both grant proof and start APNs. -func (t *codeAttestThrottle) expireResumeChallenge( - nonce, providerID, nodeKey, seKey, token string, -) bool { - t.mu.Lock() - defer t.mu.Unlock() - challenge, ok := t.resumeChallenges[nonce] - if !ok || - t.now().Before(challenge.expiresAt) || - !resumeChallengeMatches(challenge, providerID, nodeKey, seKey, token) { - return false - } - delete(t.resumeChallenges, nonce) - close(challenge.done) - return true -} - -// persistCodeAttestation best-effort writes a successful code-identity round-trip -// to the store so it survives a coordinator restart/deploy (W5 Fix 2). It mirrors -// the in-memory recordAttested and is called from the same event -// (handleCodeAttestationResponse). Behind the store seam (no-op until -// SeedCodeAttestCache wires a store): prod runs the Postgres store, so this makes -// reuse durable across blue-green deploys (avoiding a fleet-wide re-push storm). -// Runs off the read loop (saferun.Go) so the DB write never stalls WebSocket -// reads. SECURITY: writes only AFTER the full nonce-match + SE-signature -// verification — never from an unverified heartbeat token. -func (s *Server) persistCodeAttestation(seKey, version, token, nodeKey, binaryHash string) { - if s == nil || s.codeAttestThrottle == nil || seKey == "" { - return - } - st := s.codeAttestThrottle.store - if st == nil { - return - } - t := s.codeAttestThrottle - t.mu.Lock() - record, ok := t.attested[seKey] - t.mu.Unlock() - if !ok || record.version != version || record.token != token || record.nodeKey != nodeKey || record.binaryHash != binaryHash { - return - } - proof := record.persisted(seKey) - proof.ContinuousCoverageUntil = nil // only a verified observation can advance coverage - saferun.Go(s.logger, "persistCodeAttest", func() { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if err := st.UpsertCodeAttestation(ctx, proof); err != nil { - s.logger.Warn("code-attest: failed to persist reuse record", "error", err) - } - }) -} - -// invalidatePersistedCodeAttestation deletes a device's PERSISTED reuse row off -// the read loop. Called alongside the in-memory invalidateReuse when a provider's -// APNs token CHANGES, so a coordinator restart before the forced re-challenge -// completes cannot reseed and reuse the pre-rotation proof (Codex #6). No-op when -// no store is wired. The persisted row is only a re-push optimization — never a -// grant of CodeAttested — so deleting it can never weaken fail-closed identity. -func (s *Server) invalidatePersistedCodeAttestation(seKey string) { - if s == nil || s.codeAttestThrottle == nil || seKey == "" { - return - } - st := s.codeAttestThrottle.store - if st == nil { - return - } - saferun.Go(s.logger, "invalidatePersistedCodeAttest", func() { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if err := st.DeleteCodeAttestation(ctx, seKey); err != nil { - s.logger.Warn("code-attest: failed to delete persisted reuse record on token change", "error", err) - } - }) -} diff --git a/coordinator/api/code_attest_throttle_test.go b/coordinator/api/code_attest_throttle_test.go deleted file mode 100644 index 56478e0b1f..0000000000 --- a/coordinator/api/code_attest_throttle_test.go +++ /dev/null @@ -1,484 +0,0 @@ -package api - -import ( - "context" - "testing" - "time" - - "github.com/eigeninference/d-inference/coordinator/store" -) - -// TestCodeAttestThrottleBudgetAndReuse covers the per-device push budget + reuse -// cache with a fake clock: background pushes are blocked within the cooldown, and a -// recent attestation is reused only within the window and only for the same binary -// version. -func TestCodeAttestThrottleBudgetAndReuse(t *testing.T) { - cur := time.Unix(1_700_000_000, 0) - th := newCodeAttestThrottle() - th.now = func() time.Time { return cur } - const se, nodeKey = "se-key-1", "node-key-1" - - if !th.allowPush(se, false) { - t.Fatal("first push should be allowed") - } - if th.reuseAttestation(se, "0.6.0", "token", nodeKey) { - t.Fatal("no attestation yet → no reuse") - } - th.recordPush(se) - - cur = cur.Add(th.backgroundPushCooldown - time.Minute) // still inside the cooldown - if th.allowPush(se, false) { - t.Fatal("a background push within the cooldown must be blocked (background-push budget)") - } - cur = cur.Add(2 * time.Minute) // now just past the cooldown - if !th.allowPush(se, false) { - t.Fatal("a background push after the cooldown should be allowed") - } - - th.recordAttestedForProcess(se, "0.6.0", "token", nodeKey, "hash-a") - if !th.reuseAttestation(se, "0.6.0", "token", nodeKey) { - t.Fatal("should reuse a fresh proof bound to the same version, token, and process key") - } - if th.reuseAttestation(se, "0.6.1", "token", nodeKey) { - t.Fatal("must NOT reuse across a binary version change") - } - cur = cur.Add(th.reuseWindow) // window elapsed - if th.reuseAttestation(se, "0.6.0", "token", nodeKey) { - t.Fatal("reuse must expire after the window") - } -} - -// TestCodeAttestThrottleTokenBinding proves a reusable proof is bound to the -// exact current non-empty APNs token and process key; rotated, empty, and legacy -// identity inputs require a real bootstrap challenge. -func TestCodeAttestThrottleTokenBinding(t *testing.T) { - cur := time.Unix(1_700_000_000, 0) - th := newCodeAttestThrottle() - th.now = func() time.Time { return cur } - const se, nodeKey = "se-key-1", "node-key-1" - - th.recordAttestedForProcess(se, "0.6.0", "tokA", nodeKey, "hash-a") - if !th.reuseAttestation(se, "0.6.0", "tokA", nodeKey) { - t.Fatal("same token and process key must reuse") - } - if th.reuseAttestation(se, "0.6.0", "tokB", nodeKey) { - t.Fatal("a rotated (different) token must NOT reuse — it must force a real challenge") - } - if th.reuseAttestation(se, "0.6.0", "tokA", "node-key-2") { - t.Fatal("a different process key reused another process's proof") - } - if th.reuseAttestation(se, "0.6.0", "tokA", "") { - t.Fatal("an empty current process key reused a process-bound proof") - } - - // Legacy records missing either identity binding cannot satisfy current - // registration inputs and must bootstrap a genuine push. - th.seed([]store.CodeAttestation{{SEPubKey: "se-legacy-token", Version: "0.6.0", AttestedAt: cur}}) - if th.reuseAttestation("se-legacy-token", "0.6.0", "any-token", nodeKey) { - t.Fatal("a legacy token-less record bypassed current-token binding") - } - legacyNodeLess := newCodeAttestThrottle() - legacyNodeLess.recordAttested("se-legacy-node", "0.6.0", "tokA") - if legacyNodeLess.reuseAttestation("se-legacy-node", "0.6.0", "tokA", nodeKey) { - t.Fatal("a legacy process-key-less record bypassed current process-key binding") - } -} - -func TestCodeAttestThrottleProcessKeyBinding(t *testing.T) { - th := newCodeAttestThrottle() - th.recordAttestedForProcess("se", "0.8.17", "token", "node-key-A", "hash-a") - if !th.reuseAttestation( - "se", "0.8.17", "token", "node-key-A", - ) { - t.Fatal("same-process reconnect should reuse exact process-key proof") - } - if th.reuseAttestation( - "se", "0.8.17", "token", "node-key-B", - ) { - t.Fatal("new process key replayed prior code proof") - } - if th.reuseAttestation( - "se", "0.8.18", "token", "node-key-A", - ) { - t.Fatal("cross-version process proof reused") - } - if th.reuseAttestation( - "se", "0.8.17", "rotated-token", "node-key-A", - ) { - t.Fatal("rotated token reused process proof") - } - - seeded := newCodeAttestThrottle() - seeded.seed([]store.CodeAttestation{{ - SEPubKey: "se", Version: "0.8.17", AttestedAt: time.Now(), - APNsToken: "token", NodePublicKey: "node-key-A", - }}) - if !seeded.reuseAttestation( - "se", "0.8.17", "token", "node-key-A", - ) { - t.Fatal("persisted process-key binding did not survive seed") - } -} - -// TestCodeAttestThrottleTransitionProcessKeyBinding: a transition proof is -// bound to the SE identity, exact APNs token, and the binary identity that -// earned it — NOT to the current process key, which rotates on every provider -// restart. Possession of the new key is proven by decrypting the resume -// challenge, not by this cache lookup. A rotated token, empty inputs, or a -// legacy record without a process-key or binary-identity binding still refuse. -func TestCodeAttestThrottleTransitionProcessKeyBinding(t *testing.T) { - th := newCodeAttestThrottle() - th.recordAttestedForProcess("se", "0.8.17", "token", "node-key-A", "hash-a") - - if hash, ok := th.reuseAttestationForTransition("se", "token"); !ok || hash != "hash-a" { - t.Fatalf("same SE identity + token should authorize a transition resume challenge with the earned identity, got %q ok=%v", hash, ok) - } - if _, ok := th.reuseAttestationForTransition("se", "rotated-token"); ok { - t.Fatal("rotated token reused a transition APNs proof") - } - if _, ok := th.reuseAttestationForTransition("se", ""); ok { - t.Fatal("empty token reused a transition APNs proof") - } - if _, ok := th.reuseAttestationForTransition("", "token"); ok { - t.Fatal("empty SE key reused a transition APNs proof") - } - - legacy := newCodeAttestThrottle() - legacy.recordAttested("se", "0.8.17", "token") - if _, ok := legacy.reuseAttestationForTransition("se", "token"); ok { - t.Fatal("proof without a cached process-key binding reused for a transition") - } - - // A legacy identity-less record (process-key bound, but earned before - // binary-identity binding — e.g. seeded from a pre-migration durable row) - // never authorizes a transition resume; it must fall through to a real - // APNs challenge (Codex 05:55Z P1). - identityless := newCodeAttestThrottle() - identityless.recordAttestedForProcess("se", "0.8.17", "token", "node-key-A", "") - if _, ok := identityless.reuseAttestationForTransition("se", "token"); ok { - t.Fatal("identity-less cached proof authorized a transition resume") - } - seeded := newCodeAttestThrottle() - seeded.seed([]store.CodeAttestation{{ - SEPubKey: "se", Version: "0.8.17", AttestedAt: time.Now(), - APNsToken: "token", NodePublicKey: "node-key-A", - }}) - if _, ok := seeded.reuseAttestationForTransition("se", "token"); ok { - t.Fatal("seeded pre-migration row without a binary identity authorized a transition resume") - } - seededWithHash := newCodeAttestThrottle() - seededWithHash.seed([]store.CodeAttestation{{ - SEPubKey: "se", Version: "0.8.17", AttestedAt: time.Now(), - APNsToken: "token", NodePublicKey: "node-key-A", BinaryHash: "hash-a", - }}) - if hash, ok := seededWithHash.reuseAttestationForTransition("se", "token"); !ok || hash != "hash-a" { - t.Fatalf("persisted binary identity did not survive seed: %q ok=%v", hash, ok) - } -} - -func TestCodeAttestResumeChallengeUsesExactResumeDeadline(t *testing.T) { - const ( - nonce = "nonce" - providerID = "provider" - nodeKey = "node" - seKey = "se" - token = "token" - ) - newThrottle := func(now *time.Time) *codeAttestThrottle { - th := newCodeAttestThrottle() - th.now = func() time.Time { return *now } - th.recordResumeChallenge(nonce, providerID, nodeKey, seKey, token) - return th - } - - t.Run("29.9 seconds accepted", func(t *testing.T) { - now := time.Unix(1_700_000_000, 0) - th := newThrottle(&now) - expiresAt, ok := th.resumeChallengeExpiry( - nonce, providerID, nodeKey, seKey, token, - ) - if !ok || !expiresAt.Equal(now.Add(30*time.Second)) { - t.Fatalf("resume expiry = %v, ok=%v; want exactly 30s", expiresAt, ok) - } - now = now.Add(29*time.Second + 900*time.Millisecond) - if !th.matchResumeChallenge(nonce, providerID, nodeKey, seKey, token) || - !th.consumeResumeChallenge(nonce, providerID, nodeKey, seKey, token) { - t.Fatal("resume proof inside the 30s window was rejected") - } - if th.consumeResumeChallenge(nonce, providerID, nodeKey, seKey, token) { - t.Fatal("resume proof replayed") - } - }) - - t.Run("exact deadline rejected and timeout claims nonce", func(t *testing.T) { - now := time.Unix(1_700_000_000, 0) - th := newThrottle(&now) - now = now.Add(30 * time.Second) - if th.matchResumeChallenge(nonce, providerID, nodeKey, seKey, token) || - th.consumeResumeChallenge(nonce, providerID, nodeKey, seKey, token) { - t.Fatal("resume proof at the exact 30s deadline was accepted") - } - if !th.expireResumeChallenge(nonce, providerID, nodeKey, seKey, token) { - t.Fatal("timeout could not atomically claim nonce at the exact deadline") - } - }) - - t.Run("after deadline rejected and timeout claims nonce", func(t *testing.T) { - now := time.Unix(1_700_000_000, 0) - th := newThrottle(&now) - now = now.Add(30*time.Second + time.Nanosecond) - if th.consumeResumeChallenge(nonce, providerID, nodeKey, seKey, token) { - t.Fatal("resume proof after the 30s deadline was accepted") - } - if !th.expireResumeChallenge(nonce, providerID, nodeKey, seKey, token) { - t.Fatal("timeout could not claim nonce after the deadline") - } - }) - - t.Run("response and timeout race has one winner", func(t *testing.T) { - now := time.Unix(1_700_000_000, 0) - th := newThrottle(&now) - done, ok := th.resumeChallenges[nonce] - if !ok { - t.Fatal("recorded resume challenge missing") - } - now = now.Add(30 * time.Second) - - responseResult := make(chan bool, 1) - timeoutResult := make(chan bool, 1) - go func() { - responseResult <- th.consumeResumeChallenge( - nonce, providerID, nodeKey, seKey, token) - }() - go func() { - timeoutResult <- th.expireResumeChallenge( - nonce, providerID, nodeKey, seKey, token) - }() - - if <-responseResult { - t.Fatal("response racing at the exact deadline was accepted") - } - if !<-timeoutResult { - t.Fatal("timeout did not win the exact-deadline race") - } - select { - case <-done.done: - default: - t.Fatal("winning timeout did not close the challenge") - } - }) -} - -func TestCodeAttestAPNsChallengeBindsTokenAndProcessKey(t *testing.T) { - th := newCodeAttestThrottle() - th.recordChallengeForIdentity("se", "nonce", "token", "K1") - if th.matchChallengeForIdentity("se", "nonce", "token", "K2") || - th.consumeChallengeForIdentity("se", "nonce", "token", "K2") { - t.Fatal("K2 matched APNs challenge encrypted to K1") - } - if !th.matchChallengeForIdentity("se", "nonce", "token", "K1") || - !th.consumeChallengeForIdentity("se", "nonce", "token", "K1") { - t.Fatal("K1 could not consume its own APNs challenge") - } - if th.consumeChallengeForIdentity("se", "nonce", "token", "K1") { - t.Fatal("APNs challenge replayed") - } -} - -// TestCodeAttestThrottleModeAwareBudget proves Fix 3: alert pushes use a far -// shorter per-device budget than background pushes, so a missed alert push retries -// promptly instead of being pinned to the long background budget. -func TestCodeAttestThrottleModeAwareBudget(t *testing.T) { - cur := time.Unix(1_700_000_000, 0) - th := newCodeAttestThrottle() - th.now = func() time.Time { return cur } - const se = "se-key-1" - - if th.alertPushCooldown >= th.backgroundPushCooldown { - t.Fatalf("alert cooldown (%s) must be shorter than background (%s)", - th.alertPushCooldown, th.backgroundPushCooldown) - } - - th.recordPush(se) - // Just past the (short) alert cooldown but well inside the background cooldown. - cur = cur.Add(th.alertPushCooldown + time.Second) - if !th.allowPush(se, true) { - t.Fatal("alert push should be allowed once the short alert cooldown elapses") - } - if th.allowPush(se, false) { - t.Fatal("background push must still be blocked inside the long background cooldown") - } -} - -// TestCodeAttestThrottleClearPushBudget proves Codex #9: clearing the push budget -// (done on APNs token rotation) lets the next push proceed immediately even though -// the OLD token's cooldown has not elapsed, so a rotated token is not derouted -// while it waits out a cooldown that was spent on a different token. -func TestCodeAttestThrottleClearPushBudget(t *testing.T) { - cur := time.Unix(1_700_000_000, 0) - th := newCodeAttestThrottle() - th.now = func() time.Time { return cur } - const se = "se-key-1" - - th.recordPush(se) - cur = cur.Add(time.Minute) // deep inside both cooldowns - if th.allowPush(se, false) { - t.Fatal("precondition: a push within the cooldown must be blocked") - } - if !th.clearPushBudget(context.Background(), se) { - t.Fatal("the first budget reset must be honored") - } - if !th.allowPush(se, false) { - t.Fatal("clearPushBudget must let the next push proceed immediately (rotated token has its own budget)") - } - - // Anti-DoS (threat-model): a second reset within budgetClearCooldown must be - // throttled, so a provider flooding token changes can't spam APNs. - th.recordPush(se) // consume the budget again - cur = cur.Add(time.Minute) // still within budgetClearCooldown - if th.clearPushBudget(context.Background(), se) { - t.Fatal("a second budget reset within budgetClearCooldown must be throttled") - } - if th.allowPush(se, false) { - t.Fatal("a throttled reset must NOT clear the cooldown (flood protection)") - } - - // Once budgetClearCooldown elapses, a reset is honored again. - cur = cur.Add(th.budgetClearCooldown) - if !th.clearPushBudget(context.Background(), se) { - t.Fatal("a reset after budgetClearCooldown must be honored") - } - if !th.allowPush(se, false) { - t.Fatal("an honored reset must clear the cooldown") - } -} - -// TestCodeAttestThrottleOutstandingChallenge covers the per-device pushed-nonce -// tracking that lets the read-loop delivery path verify a reply on ANY connection -// (Fix 1), bounded by a validity window consistent with the APNs expiry (Fix 5). -func TestCodeAttestThrottleOutstandingChallenge(t *testing.T) { - cur := time.Unix(1_700_000_000, 0) - th := newCodeAttestThrottle() - th.now = func() time.Time { return cur } - const se = "se-key-1" - - if _, ok := th.outstandingChallenge(se); ok { - t.Fatal("no challenge recorded yet") - } - th.recordChallenge(se, "nonce-A") - - // Within the validity window: matchable. - cur = cur.Add(th.challengeValidity - time.Second) - ch, ok := th.outstandingChallenge(se) - if !ok || ch.nonce != "nonce-A" { - t.Fatalf("challenge should still be valid within the window, got %q ok=%v", ch.nonce, ok) - } - - // A non-matching clear must NOT drop it; a matching clear must. - th.clearChallengeIf(se, "nonce-WRONG") - if _, ok := th.outstandingChallenge(se); !ok { - t.Fatal("clearChallengeIf with a non-matching nonce must not drop the challenge") - } - th.clearChallengeIf(se, "nonce-A") - if _, ok := th.outstandingChallenge(se); ok { - t.Fatal("clearChallengeIf with the matching nonce must drop the challenge") - } - - // Re-record then let it expire past the validity window (fail-closed staleness). - th.recordChallenge(se, "nonce-B") - cur = cur.Add(th.challengeValidity) - if _, ok := th.outstandingChallenge(se); ok { - t.Fatal("challenge must expire after the validity window") - } -} - -// TestCodeAttestThrottleMultipleInFlightNonces proves Codex #8: when more than one -// challenge is pushed within the validity window (alert mode, where the push -// cooldown is shorter than the validity), a reply to EITHER in-flight nonce is -// accepted — a delayed first-alert delivery is not rejected just because a second -// nonce was pushed after it. -func TestCodeAttestThrottleMultipleInFlightNonces(t *testing.T) { - cur := time.Unix(1_700_000_000, 0) - th := newCodeAttestThrottle() - th.now = func() time.Time { return cur } - const se = "se-key-1" - - th.recordChallenge(se, "nonce-A") - cur = cur.Add(th.alertPushCooldown + time.Second) // second push, first still valid - th.recordChallenge(se, "nonce-B") - - if !th.matchChallenge(se, "nonce-A") { - t.Fatal("a reply to the FIRST (still-valid) nonce must be accepted, not clobbered by the second") - } - if !th.matchChallenge(se, "nonce-B") { - t.Fatal("a reply to the second nonce must be accepted") - } - if th.matchChallenge(se, "nonce-UNKNOWN") { - t.Fatal("an unknown nonce must never match") - } - - // Answering one nonce leaves the other in flight. - th.clearChallengeIf(se, "nonce-A") - if th.matchChallenge(se, "nonce-A") { - t.Fatal("a cleared nonce must no longer match") - } - if !th.matchChallenge(se, "nonce-B") { - t.Fatal("clearing one nonce must not drop the other") - } - - // Both expire past the validity window (fail-closed staleness). - cur = cur.Add(th.challengeValidity) - if th.matchChallenge(se, "nonce-B") { - t.Fatal("a nonce must stop matching after the validity window") - } -} - -// TestCodeAttestThrottleRetryDelayJitter proves the retry cadence is the base -// spacing plus injected jitter, and is decoupled from (and much shorter than) the -// push budget (Fix 3). -func TestCodeAttestThrottleRetryDelayJitter(t *testing.T) { - th := newCodeAttestThrottle() - th.retrySpacing = 10 * time.Second - th.retryJitter = 4 * time.Second - - th.jitter = func(time.Duration) time.Duration { return 0 } - if got := th.retryDelay(); got != 10*time.Second { - t.Fatalf("retryDelay with zero jitter = %s, want 10s", got) - } - th.jitter = func(max time.Duration) time.Duration { return max - 1 } - if got, want := th.retryDelay(), 10*time.Second+(4*time.Second-1); got != want { - t.Fatalf("retryDelay with max jitter = %s, want %s", got, want) - } - if th.retryDelay() >= th.backgroundPushCooldown { - t.Fatal("retry cadence must be decoupled from (and shorter than) the push budget") - } -} - -// TestCodeAttestThrottleDefaultsConsistent pins the cross-knob invariants: -// live resume PoP expires at 30s, APNs replies remain valid for 300s, and the -// alert budget is short while the background budget stays long. -func TestCodeAttestThrottleDefaultsConsistent(t *testing.T) { - th := newCodeAttestThrottle() - if ChallengeResponseTimeout != 30*time.Second { - t.Fatalf("ChallengeResponseTimeout = %s, want exact 30s", - ChallengeResponseTimeout) - } - if th.resumeTimeout != ChallengeResponseTimeout { - t.Fatalf("resumeTimeout = %s, want ChallengeResponseTimeout %s", - th.resumeTimeout, ChallengeResponseTimeout) - } - if CodeAttestResponseTimeout != 300*time.Second { - t.Fatalf("CodeAttestResponseTimeout = %s, want exact 300s", - CodeAttestResponseTimeout) - } - if th.challengeValidity != CodeAttestResponseTimeout { - t.Fatalf("APNs challengeValidity = %s, want CodeAttestResponseTimeout %s", - th.challengeValidity, CodeAttestResponseTimeout) - } - if th.retrySpacing >= th.backgroundPushCooldown { - t.Fatal("retry spacing must be shorter than the background push budget") - } - if th.alertPushCooldown >= th.backgroundPushCooldown { - t.Fatal("alert budget must be shorter than the background budget") - } -} diff --git a/coordinator/api/code_attestation_integration_test.go b/coordinator/api/code_attestation_integration_test.go index 799988a394..5a13776267 100644 --- a/coordinator/api/code_attestation_integration_test.go +++ b/coordinator/api/code_attestation_integration_test.go @@ -9,18 +9,13 @@ import ( "encoding/asn1" "encoding/base64" "encoding/json" - "errors" - "math/big" - "sync/atomic" - "testing" - "time" - "github.com/eigeninference/d-inference/coordinator/apns" "github.com/eigeninference/d-inference/coordinator/attestation" "github.com/eigeninference/d-inference/coordinator/internal/e2e" "github.com/eigeninference/d-inference/coordinator/protocol" "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" + "math/big" + "testing" ) // fakeCodeAttestor simulates APNs in-process — no real Apple push. onSend is @@ -161,675 +156,3 @@ func completeResumeRoundTrip( ) return nil } - -// TestCodeIdentityRoundTripEndToEnd is the correctness gate: the full crypto -// round-trip — coordinator generates a nonce → real E_K(nonce) encrypt → genuine- -// provider decrypt with K → Sign_SE over the recovered nonce → WS reply verified -// in the read-loop delivery path → CodeAttested flips true. -func TestCodeIdentityRoundTripEndToEnd(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - - kPubB64, kPriv, seKey, sePubB64 := providerKeyMaterial(t) - provider := newCodeAttestProvider(kPubB64, sePubB64) - - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, pubKeyB64, nonceB64 string) error { - return completeRoundTrip(t, srv, provider, "p1", kPriv, seKey, pubKeyB64, nonceB64) - }}) - - srv.sendCodeIdentityChallenge(context.Background(), "p1", provider) - - if !provider.GetCodeAttested() { - t.Fatal("expected CodeAttested=true after a valid end-to-end round-trip") - } -} - -// TestCodeIdentityRejectsWrongSEKey proves fail-closed: a response whose nonce -// decrypts correctly (proving K) but is signed by a DIFFERENT SE key (not the one -// bound at registration) must NOT attest — defending against a fork that received -// a relayed challenge but holds its own SE key. -func TestCodeIdentityRejectsWrongSEKey(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - - kPubB64, kPriv, _, sePubB64 := providerKeyMaterial(t) - wrongSE, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatalf("gen wrong SE: %v", err) - } - provider := newCodeAttestProvider(kPubB64, sePubB64) // bound to the REAL SE key - - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, pubKeyB64, nonceB64 string) error { - // Decrypts fine (proves K), but signs with the WRONG SE key. - return completeRoundTrip(t, srv, provider, "p1", kPriv, wrongSE, pubKeyB64, nonceB64) - }}) - - srv.sendCodeIdentityChallenge(context.Background(), "p1", provider) - - if provider.GetCodeAttested() { - t.Fatal("CodeAttested must stay false when the SE signature is from the wrong key") - } -} - -// TestCodeAttestLoopHealsDroppedPushWithBoundedRetry proves a single dropped push -// doesn't strand a capable provider: the first push fails and the loop retries. -func TestCodeAttestLoopHealsDroppedPushWithBoundedRetry(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - srv.codeAttestThrottle.backgroundPushCooldown = time.Millisecond // fast budget for the test - srv.codeAttestThrottle.retrySpacing = time.Millisecond // fast poll cadence - srv.codeAttestThrottle.retryJitter = 0 - - kPubB64, kPriv, seKey, sePubB64 := providerKeyMaterial(t) - provider := newCodeAttestProvider(kPubB64, sePubB64) - - var pushes int32 - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, pubKeyB64, nonceB64 string) error { - if atomic.AddInt32(&pushes, 1) == 1 { - return errors.New("transient push send failure") // first push fails - } - return completeRoundTrip(t, srv, provider, "p1", kPriv, seKey, pubKeyB64, nonceB64) - }}) - - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() - srv.codeAttestLoop(ctx, "p1", provider) - - if !provider.GetCodeAttested() { - t.Fatal("expected CodeAttested=true after a bounded retry healed the dropped first push") - } - if got := atomic.LoadInt32(&pushes); got < 2 || got > int32(srv.codeAttestThrottle.maxAttempts) { - t.Fatalf("expected 2..%d pushes, got %d", srv.codeAttestThrottle.maxAttempts, got) - } -} - -// TestCodeAttestLoopReusesRecentAttestation proves same-version reuse is limited -// to the exact process key that completed the prior proof: a same-key reconnect -// spends no APNs push, while K2 gets no code trust until one fresh challenge. -func TestCodeAttestLoopReusesRecentAttestation(t *testing.T) { - logger := quietLogger() - st := store.NewMemory(store.Config{}) - srv := NewServer(registry.New(logger), st, ServerConfig{}, logger) - srv.codeAttestThrottle.retrySpacing = time.Millisecond - srv.codeAttestThrottle.retryJitter = 0 - - kPubB64, kPriv, seKey, sePubB64 := providerKeyMaterial(t) - - var pushes int32 - expectUntrustedAtFreshProcessPush := false - // onSend completes the round-trip for whichever provider is currently attesting. - var current *registry.Provider - currentPriv := kPriv - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, pubKeyB64, nonceB64 string) error { - if expectUntrustedAtFreshProcessPush && - (current.GetCodeAttested() || current.GetFreshCodeAttested()) { - t.Fatal("K2 inherited K1 code trust before its fresh APNs proof") - } - atomic.AddInt32(&pushes, 1) - return completeRoundTrip(t, srv, current, "p1", currentPriv, seKey, pubKeyB64, nonceB64) - }}) - srv.codeResumeSender = func( - _ string, - message protocol.CodeAttestationResumeChallenge, - ) error { - if current.GetCodeAttested() || current.GetFreshCodeAttested() { - t.Fatal("cached APNs evidence granted code trust before live process-key proof") - } - recovered, err := e2e.DecryptWithPrivateKey( - &e2e.EncryptedPayload{ - EphemeralPublicKey: message.CodeChallenge.EphemeralPublicKey, - Ciphertext: message.CodeChallenge.Ciphertext, - }, - currentPriv, - ) - if err != nil { - return err - } - nonce := string(recovered) - srv.handleCodeAttestationResponse( - "p1", - current, - &protocol.CodeAttestationResponseMessage{ - Type: protocol.TypeCodeAttestationResponse, - Nonce: nonce, - Signature: signSEOverString(t, seKey, nonce), - }, - ) - return nil - } - - // Connection 1: a real round-trip → exactly one push, attested. - p1 := newCodeAttestProvider(kPubB64, sePubB64) - p1.Version = "0.6.0" - current = p1 - srv.codeAttestLoop(context.Background(), "p1", p1) - if !p1.GetCodeAttested() { - t.Fatal("connection 1 should attest") - } - if got := atomic.LoadInt32(&pushes); got != 1 { - t.Fatalf("connection 1 should send exactly 1 push, got %d", got) - } - - // Connection 2: same device + version, fresh Provider (CodeAttested=false). It - // must REUSE the recent attestation — attested without another push. - p2 := newCodeAttestProvider(kPubB64, sePubB64) - p2.Version = "0.6.0" - current = p2 - srv.codeAttestLoop(context.Background(), "p1", p2) - if !p2.GetCodeAttested() { - t.Fatal("connection 2 should inherit the recent attestation (reuse)") - } - if got := atomic.LoadInt32(&pushes); got != 1 { - t.Fatalf("connection 2 must NOT send another push (reuse); total pushes=%d", got) - } - - // Connection 3 advertises protected runtime capabilities but retains the - // exact process X25519 key. It reuses the process-bound proof without - // spending another throttled push. - p3 := newCodeAttestProvider(kPubB64, sePubB64) - p3.Version = "0.6.0" - p3.ReportedRuntimeCapabilities = []string{ - registry.ProviderCapabilityAppleM5, - registry.ProviderCapabilityMLXNAX, - } - current = p3 - srv.codeAttestLoop(context.Background(), "p1", p3) - if !p3.GetCodeAttested() || !p3.GetFreshCodeAttested() { - t.Fatal("same-process protected reconnect should reuse bound proof") - } - if got := atomic.LoadInt32(&pushes); got != 1 { - t.Fatalf("same-process reconnect unexpectedly pushed; total=%d", got) - } - kPubB64New, kPrivNew, _, _ := providerKeyMaterial(t) - copiedPublic := newCodeAttestProvider(kPubB64, sePubB64) - copiedPublic.Version = "0.6.0" - copiedPublic.ReportedRuntimeCapabilities = p3.ReportedRuntimeCapabilities - current, currentPriv = copiedPublic, kPrivNew - if srv.sendCodeIdentityResumeChallenge( - context.Background(), "p1", copiedPublic, kPubB64, sePubB64, - copiedPublic.APNsDeviceToken, - ) || copiedPublic.GetFreshCodeAttested() { - t.Fatal("copied public key without old X25519 private key passed resume PoP") - } - - // Same-version K2 on the same SE device/token cannot reuse K1's proof. It - // remains untrusted until exactly one fresh E_K2(nonce)+SE challenge completes. - p4 := newCodeAttestProvider(kPubB64New, sePubB64) - p4.Version = "0.6.0" - p4.ReportedRuntimeCapabilities = p3.ReportedRuntimeCapabilities - current, currentPriv = p4, kPrivNew - srv.codeAttestThrottle.backgroundPushCooldown = 0 - // Simulate expiry of Apple's existing per-token push window without - // weakening production A-B-A cooldown retention. - budgetKey := codeAttestPushBudgetKey( - sePubB64, codeAttestTokenHash(p4.APNsDeviceToken), - ) - srv.codeAttestThrottle.mu.Lock() - delete(srv.codeAttestThrottle.lastPush, budgetKey) - delete(srv.codeAttestThrottle.durableNextPush, budgetKey) - delete(srv.codeAttestThrottle.novelPushFloor, sePubB64) - srv.codeAttestThrottle.mu.Unlock() - if err := st.DeleteCodeAttestPushBudget( - context.Background(), sePubB64, - ); err != nil { - t.Fatalf("fresh process test could not expire durable cooldown: %v", err) - } - expectUntrustedAtFreshProcessPush = true - srv.codeAttestLoop(context.Background(), "p1", p4) - expectUntrustedAtFreshProcessPush = false - if !p4.GetCodeAttested() || !p4.GetFreshCodeAttested() { - t.Fatal("K2 should complete code trust only after its fresh proof") - } - if got := atomic.LoadInt32(&pushes); got != 2 { - t.Fatalf("K2 should force exactly one fresh APNs challenge; total pushes=%d", got) - } - - // Same-process resume that gets no reply falls back to APNs on this live - // connection after the bounded timeout. A late resume reply cannot replay. - var timedOutResumeNonce string - srv.codeAttestThrottle.resumeTimeout = time.Millisecond - srv.codeAttestThrottle.retrySpacing = time.Millisecond - srv.codeResumeSender = func( - _ string, message protocol.CodeAttestationResumeChallenge, - ) error { - recovered, err := e2e.DecryptWithPrivateKey( - &e2e.EncryptedPayload{ - EphemeralPublicKey: message.CodeChallenge.EphemeralPublicKey, - Ciphertext: message.CodeChallenge.Ciphertext, - }, - kPrivNew, - ) - timedOutResumeNonce = string(recovered) - return err - } - p5 := newCodeAttestProvider(kPubB64New, sePubB64) - p5.Version = "0.6.0" - p5.ReportedRuntimeCapabilities = p3.ReportedRuntimeCapabilities - current, currentPriv = p5, kPrivNew - srv.codeAttestLoop(context.Background(), "p1", p5) - deadline := time.Now().Add(time.Second) - for !p5.GetFreshCodeAttested() && time.Now().Before(deadline) { - time.Sleep(time.Millisecond) - } - if !p5.GetFreshCodeAttested() || atomic.LoadInt32(&pushes) != 3 { - t.Fatalf("resume timeout did not APNs-fallback: fresh=%v pushes=%d", - p5.GetFreshCodeAttested(), atomic.LoadInt32(&pushes)) - } - srv.handleCodeAttestationResponse("p1", p5, &protocol.CodeAttestationResponseMessage{ - Type: protocol.TypeCodeAttestationResponse, - Nonce: timedOutResumeNonce, - Signature: signSEOverString(t, seKey, timedOutResumeNonce), - }) - if got := atomic.LoadInt32(&pushes); got != 3 { - t.Fatalf("late resume reply changed fallback state: pushes=%d", got) - } - - // A resume transport failure falls through to APNs immediately. - srv.codeResumeSender = func( - string, protocol.CodeAttestationResumeChallenge, - ) error { - return errors.New("resume send failed") - } - p6 := newCodeAttestProvider(kPubB64New, sePubB64) - p6.Version = "0.6.0" - p6.ReportedRuntimeCapabilities = p3.ReportedRuntimeCapabilities - current, currentPriv = p6, kPrivNew - srv.codeAttestLoop(context.Background(), "p1", p6) - if !p6.GetFreshCodeAttested() || atomic.LoadInt32(&pushes) != 4 { - t.Fatalf("resume send failure did not immediately fall back: fresh=%v pushes=%d", - p6.GetFreshCodeAttested(), atomic.LoadInt32(&pushes)) - } - - // Cancellation after the timer consumes the resume nonce but before fallback - // must not send or charge APNs on behalf of a dead connection. - srv.codeResumeSender = func( - string, protocol.CodeAttestationResumeChallenge, - ) error { - return nil // no response; let the resume timer win - } - resumeCtx, cancelResume := context.WithCancel(context.Background()) - fallbackReached := make(chan struct{}) - srv.codeResumeFallbackBeforeAPNs = func() { - cancelResume() - close(fallbackReached) - } - srv.codeAttestThrottle.mu.Lock() - lastPushBefore := srv.codeAttestThrottle.lastPush[sePubB64] - srv.codeAttestThrottle.mu.Unlock() - p7 := newCodeAttestProvider(kPubB64New, sePubB64) - p7.Version = "0.6.0" - p7.ReportedRuntimeCapabilities = p3.ReportedRuntimeCapabilities - current, currentPriv = p7, kPrivNew - srv.codeAttestLoop(resumeCtx, "p1", p7) - select { - case <-fallbackReached: - case <-time.After(time.Second): - t.Fatal("resume timeout did not reach cancellation seam") - } - time.Sleep(10 * time.Millisecond) - srv.codeAttestThrottle.mu.Lock() - lastPushAfter := srv.codeAttestThrottle.lastPush[sePubB64] - srv.codeAttestThrottle.mu.Unlock() - if got := atomic.LoadInt32(&pushes); got != 4 || - !lastPushAfter.Equal(lastPushBefore) || - p7.GetFreshCodeAttested() { - t.Fatalf("canceled fallback spent APNs budget: pushes=%d before=%v after=%v fresh=%v", - got, lastPushBefore, lastPushAfter, p7.GetFreshCodeAttested()) - } - - // Cancellation inside the resume write failure must also stop before APNs. - srv.codeResumeFallbackBeforeAPNs = nil - writeCtx, cancelWrite := context.WithCancel(context.Background()) - srv.codeResumeSender = func( - string, protocol.CodeAttestationResumeChallenge, - ) error { - cancelWrite() - return errors.New("connection canceled during resume write") - } - p8 := newCodeAttestProvider(kPubB64New, sePubB64) - p8.Version = "0.6.0" - p8.ReportedRuntimeCapabilities = p3.ReportedRuntimeCapabilities - current, currentPriv = p8, kPrivNew - srv.codeAttestLoop(writeCtx, "p1", p8) - srv.codeAttestThrottle.mu.Lock() - lastPushAfterWriteCancel := srv.codeAttestThrottle.lastPush[sePubB64] - srv.codeAttestThrottle.mu.Unlock() - if got := atomic.LoadInt32(&pushes); got != 4 || - !lastPushAfterWriteCancel.Equal(lastPushBefore) || - p8.GetFreshCodeAttested() { - t.Fatalf("canceled resume write spent APNs budget: pushes=%d before=%v after=%v fresh=%v", - got, lastPushBefore, lastPushAfterWriteCancel, - p8.GetFreshCodeAttested()) - } - - // Token rotation after cache match but before resume creation invalidates the - // captured loop; the heartbeat rearm's fresh loop earns a new APNs proof. - p9 := newCodeAttestProvider(kPubB64New, sePubB64) - p9.Version = "0.6.0" - p9.ReportedRuntimeCapabilities = p3.ReportedRuntimeCapabilities - current, currentPriv = p9, kPrivNew - srv.codeResumeBeforeIdentityCheck = func() { - p9.Mu().Lock() - p9.APNsDeviceToken = "rotated-token" - p9.Mu().Unlock() - // Production token rotation synchronously supersedes the old loop before - // launching its replacement. - srv.codeAttestThrottle.beginLoop(sePubB64) - srv.codeResumeBeforeIdentityCheck = nil - } - srv.codeResumeSender = func( - string, protocol.CodeAttestationResumeChallenge, - ) error { - return errors.New("resume sender must not run after identity rotation") - } - srv.codeAttestLoop(context.Background(), "p1", p9) - srv.codeAttestLoop(context.Background(), "p1", p9) - if !p9.GetFreshCodeAttested() || atomic.LoadInt32(&pushes) != 5 { - t.Fatalf("pre-record token rotation did not APNs-fallback: fresh=%v pushes=%d", - p9.GetFreshCodeAttested(), atomic.LoadInt32(&pushes)) - } - - // Rotation after the resume was sent clears that one-time proof and arms a - // fresh APNs loop; the late old-token response cannot grant it. - p10 := newCodeAttestProvider(kPubB64New, sePubB64) - p10.Version = "0.6.0" - p10.APNsDeviceToken = "rotated-token" - p10.ReportedRuntimeCapabilities = p3.ReportedRuntimeCapabilities - current, currentPriv = p10, kPrivNew - srv.codeResumeSender = func( - _ string, message protocol.CodeAttestationResumeChallenge, - ) error { - recovered, err := e2e.DecryptWithPrivateKey( - &e2e.EncryptedPayload{ - EphemeralPublicKey: message.CodeChallenge.EphemeralPublicKey, - Ciphertext: message.CodeChallenge.Ciphertext, - }, - kPrivNew, - ) - if err != nil { - return err - } - srv.maybeRearmCodeAttest( - context.Background(), "p1", p10, - &protocol.HeartbeatMessage{APNsDeviceToken: "rotated-again"}, - ) - nonce := string(recovered) - srv.handleCodeAttestationResponse( - "p1", p10, &protocol.CodeAttestationResponseMessage{ - Type: protocol.TypeCodeAttestationResponse, - Nonce: nonce, - Signature: signSEOverString(t, seKey, nonce), - }, - ) - return nil - } - srv.codeAttestLoop(context.Background(), "p1", p10) - deadline = time.Now().Add(time.Second) - for !p10.GetFreshCodeAttested() && time.Now().Before(deadline) { - time.Sleep(time.Millisecond) - } - if !p10.GetFreshCodeAttested() || atomic.LoadInt32(&pushes) != 6 { - t.Fatalf("pre-response token rotation did not APNs-fallback: fresh=%v pushes=%d", - p10.GetFreshCodeAttested(), atomic.LoadInt32(&pushes)) - } - - // A malformed SE signature does not consume/cancel the resume challenge; - // its timer remains armed and falls back to fresh APNs. - p11 := newCodeAttestProvider(kPubB64New, sePubB64) - p11.Version = "0.6.0" - p11.APNsDeviceToken = "rotated-again" - p11.ReportedRuntimeCapabilities = p3.ReportedRuntimeCapabilities - current, currentPriv = p11, kPrivNew - srv.codeResumeSender = func( - _ string, message protocol.CodeAttestationResumeChallenge, - ) error { - recovered, err := e2e.DecryptWithPrivateKey( - &e2e.EncryptedPayload{ - EphemeralPublicKey: message.CodeChallenge.EphemeralPublicKey, - Ciphertext: message.CodeChallenge.Ciphertext, - }, - kPrivNew, - ) - if err != nil { - return err - } - srv.handleCodeAttestationResponse( - "p1", p11, &protocol.CodeAttestationResponseMessage{ - Type: protocol.TypeCodeAttestationResponse, - Nonce: string(recovered), - Signature: base64.StdEncoding.EncodeToString([]byte("bad")), - }, - ) - return nil - } - srv.codeAttestLoop(context.Background(), "p1", p11) - deadline = time.Now().Add(time.Second) - for !p11.GetFreshCodeAttested() && time.Now().Before(deadline) { - time.Sleep(time.Millisecond) - } - if !p11.GetFreshCodeAttested() || atomic.LoadInt32(&pushes) != 7 { - t.Fatalf("invalid resume signature did not APNs-fallback: fresh=%v pushes=%d", - p11.GetFreshCodeAttested(), atomic.LoadInt32(&pushes)) - } -} - -// TestCodeAttestLateReplyOnLiveConnectionStillAttests proves Fix 1 + Fix 5: a -// reply arriving long after the old 90s blocking wait — but on a live connection -// and within the (widened) challenge validity window — still attests, because -// verification now happens in the read-loop delivery path rather than a goroutine -// that times out at 90s. The complementary case proves the validity bound stays -// fail-closed: a reply past the window is rejected. -func TestCodeAttestLateReplyOnLiveConnectionStillAttests(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - - cur := time.Unix(1_700_000_000, 0) - srv.codeAttestThrottle.now = func() time.Time { return cur } - - kPubB64, _, seKey, sePubB64 := providerKeyMaterial(t) - - // Capture the pushed nonce; do NOT deliver during the push (model a sleepy - // device that answers later). - var pushedNonce string - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, _, nonceB64 string) error { - pushedNonce = nonceB64 - return nil - }}) - - // Case A: reply 91s later (was > the old 90s wait) but inside the 300s window. - provider := newCodeAttestProvider(kPubB64, sePubB64) - srv.sendCodeIdentityChallenge(context.Background(), "p1", provider) - if provider.GetCodeAttested() { - t.Fatal("must not attest before any reply arrives") - } - cur = cur.Add(91 * time.Second) - srv.handleCodeAttestationResponse("p1", provider, &protocol.CodeAttestationResponseMessage{ - Type: protocol.TypeCodeAttestationResponse, - Nonce: pushedNonce, - Signature: signSEOverString(t, seKey, pushedNonce), - }) - if !provider.GetCodeAttested() { - t.Fatal("a reply 91s later on a live connection must still attest (Fix 1 + Fix 5)") - } - - // Case B: a reply past the validity window must be rejected (fail-closed). - cur = cur.Add(time.Hour) - late := newCodeAttestProvider(kPubB64, sePubB64) - srv.sendCodeIdentityChallenge(context.Background(), "p1", late) - cur = cur.Add(srv.codeAttestThrottle.challengeValidity + time.Second) - srv.handleCodeAttestationResponse("p1", late, &protocol.CodeAttestationResponseMessage{ - Type: protocol.TypeCodeAttestationResponse, - Nonce: pushedNonce, - Signature: signSEOverString(t, seKey, pushedNonce), - }) - if late.GetCodeAttested() { - t.Fatal("a reply past the challenge validity window must not attest (fail-closed staleness)") - } -} - -// TestCodeAttestReconnectMidFlightDoesNotStrand proves Fix 1 kills the connection- -// scoped strand: a challenge pushed on connection 1 is verified when its reply -// lands on connection 2 (a reconnect from the SAME device), with NO second push — -// because the pushed nonce is tracked per-device (by SE key), not per-connection. -func TestCodeAttestReconnectMidFlightDoesNotStrand(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - - kPubB64, _, seKey, sePubB64 := providerKeyMaterial(t) - - var pushes int32 - var pushedNonce string - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, _, nonceB64 string) error { - atomic.AddInt32(&pushes, 1) - pushedNonce = nonceB64 // push goes out, but conn 1 drops before replying - return nil - }}) - - // Connection 1 pushes a challenge, then "drops" before the reply. - conn1 := newCodeAttestProvider(kPubB64, sePubB64) - srv.sendCodeIdentityChallenge(context.Background(), "conn1", conn1) - if conn1.GetCodeAttested() { - t.Fatal("conn1 must not be attested (it dropped before replying)") - } - - // A different process key K2 on the same SE device/token cannot consume K1's - // challenge or inherit its proof. - kPubB64New, _, _, _ := providerKeyMaterial(t) - wrongProcess := newCodeAttestProvider(kPubB64New, sePubB64) - srv.handleCodeAttestationResponse( - "conn2-wrong", - wrongProcess, - &protocol.CodeAttestationResponseMessage{ - Type: protocol.TypeCodeAttestationResponse, - Nonce: pushedNonce, - Signature: signSEOverString(t, seKey, pushedNonce), - }, - ) - if wrongProcess.GetCodeAttested() { - t.Fatal("K2 consumed an APNs challenge encrypted to K1") - } - - // Connection 2 is a fresh connection from the SAME device (same SE key). The - // provider's reply to conn1's challenge now lands here. - conn2 := newCodeAttestProvider(kPubB64, sePubB64) - srv.handleCodeAttestationResponse("conn2", conn2, &protocol.CodeAttestationResponseMessage{ - Type: protocol.TypeCodeAttestationResponse, - Nonce: pushedNonce, - Signature: signSEOverString(t, seKey, pushedNonce), - }) - - if !conn2.GetCodeAttested() { - t.Fatal("a reply on a reconnected socket must attest the live connection (no strand)") - } - if got := atomic.LoadInt32(&pushes); got != 1 { - t.Fatalf("reconnect must NOT burn another push; pushes=%d", got) - } - - // K2 becomes eligible only after its own freshly encrypted APNs challenge. - srv.sendCodeIdentityChallenge(context.Background(), "conn2-wrong", wrongProcess) - srv.handleCodeAttestationResponse( - "conn2-wrong", - wrongProcess, - &protocol.CodeAttestationResponseMessage{ - Type: protocol.TypeCodeAttestationResponse, - Nonce: pushedNonce, - Signature: signSEOverString(t, seKey, pushedNonce), - }, - ) - if !wrongProcess.GetCodeAttested() { - t.Fatal("K2 did not attest after its own fresh APNs challenge") - } - if got := atomic.LoadInt32(&pushes); got != 2 { - t.Fatalf("fresh K2 challenge push count=%d, want 2", got) - } -} - -// TestCodeAttestNoTokenNeverAttests is the fail-closed gate for a provider with no -// APNs device token (legacy/headless): the loop exits immediately, never pushes, -// and the connection never attests. -func TestCodeAttestNoTokenNeverAttests(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - - kPubB64, _, _, sePubB64 := providerKeyMaterial(t) - provider := newCodeAttestProvider(kPubB64, sePubB64) - provider.APNsDeviceToken = "" // no token → cannot be challenged - - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, _, _ string) error { - t.Fatal("must not push when the provider has no APNs token") - return nil - }}) - - srv.codeAttestLoop(context.Background(), "p1", provider) - if provider.GetCodeAttested() { - t.Fatal("a provider with no APNs token must never attest (fail-closed)") - } -} - -// TestCodeAttestTimeoutNeverAttests is the fail-closed gate for a delivered push -// that is never answered: the loop pushes up to maxAttempts and gives up without -// attesting. -func TestCodeAttestTimeoutNeverAttests(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - srv.codeAttestThrottle.maxAttempts = 2 - srv.codeAttestThrottle.backgroundPushCooldown = time.Millisecond - srv.codeAttestThrottle.retrySpacing = time.Millisecond - srv.codeAttestThrottle.retryJitter = 0 - - kPubB64, _, _, sePubB64 := providerKeyMaterial(t) - provider := newCodeAttestProvider(kPubB64, sePubB64) - - var pushes int32 - srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, _, _ string) error { - atomic.AddInt32(&pushes, 1) // push accepted, but the provider never replies - return nil - }}) - - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() - srv.codeAttestLoop(ctx, "p1", provider) - - if provider.GetCodeAttested() { - t.Fatal("an unanswered challenge must never attest (fail-closed)") - } - if got := atomic.LoadInt32(&pushes); got != int32(srv.codeAttestThrottle.maxAttempts) { - t.Fatalf("expected exactly maxAttempts=%d pushes, got %d", srv.codeAttestThrottle.maxAttempts, got) - } -} - -// TestCodeAttestLoopAlertModeUsesShortBudget proves Fix 3: in alert mode the loop -// retries on the (short) alert push budget, not the (long) background budget. The -// background budget is set to an hour and the alert budget to ~nothing; if the loop -// used the background budget it could never heal the dropped first push within the -// test deadline. -func TestCodeAttestLoopAlertModeUsesShortBudget(t *testing.T) { - logger := quietLogger() - srv := NewServer(registry.New(logger), store.NewMemory(store.Config{}), ServerConfig{}, logger) - srv.codeAttestThrottle.alertPushCooldown = time.Millisecond - srv.codeAttestThrottle.backgroundPushCooldown = time.Hour // would strand if used - srv.codeAttestThrottle.retrySpacing = time.Millisecond - srv.codeAttestThrottle.retryJitter = 0 - - kPubB64, kPriv, seKey, sePubB64 := providerKeyMaterial(t) - provider := newCodeAttestProvider(kPubB64, sePubB64) - - var pushes int32 - srv.SetCodeAttestor(&fakeCodeAttestor{ - mode: apns.ModeAlert, - onSend: func(_, _, pubKeyB64, nonceB64 string) error { - if atomic.AddInt32(&pushes, 1) == 1 { - return errors.New("transient push send failure") // first push fails - } - return completeRoundTrip(t, srv, provider, "p1", kPriv, seKey, pubKeyB64, nonceB64) - }, - }) - - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() - srv.codeAttestLoop(ctx, "p1", provider) - - if !provider.GetCodeAttested() { - t.Fatal("alert mode must retry on the short alert budget and heal within the deadline") - } -} diff --git a/coordinator/api/code_identity_disabled_test.go b/coordinator/api/code_identity_disabled_test.go new file mode 100644 index 0000000000..602f4b6e9c --- /dev/null +++ b/coordinator/api/code_identity_disabled_test.go @@ -0,0 +1,41 @@ +package api + +import ( + "context" + "testing" + + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" +) + +func TestCodeIdentityDisabledServerEntryPoints(t *testing.T) { + for _, tc := range []struct { + name string + run func(*Server, *registry.Provider) + }{ + {"loop", func(s *Server, p *registry.Provider) { + s.codeAttestLoop(context.Background(), p.ID, p) + }}, + {"heartbeat_rearm", func(s *Server, p *registry.Provider) { + s.maybeRearmCodeAttest(context.Background(), p.ID, p, &protocol.HeartbeatMessage{ + APNsDeviceToken: "replacement-token", APNsEnvironment: "development", + }) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + // Direct construction has no configured attestor or state owner. + s := &Server{} + p := ®istry.Provider{ + ID: "disabled-code-identity", APNsDeviceToken: "original-token", + APNsEnvironment: "production", CodeAttested: true, FreshCodeAttested: true, + } + tc.run(s, p) + p.Mu().Lock() + defer p.Mu().Unlock() + if p.APNsDeviceToken != "original-token" || p.APNsEnvironment != "production" || + !p.CodeAttested || !p.FreshCodeAttested { + t.Fatalf("disabled code identity changed token/environment/proof flags: %+v", p) + } + }) + } +} diff --git a/coordinator/api/code_identity_owner_test.go b/coordinator/api/code_identity_owner_test.go new file mode 100644 index 0000000000..6c71fb6b9f --- /dev/null +++ b/coordinator/api/code_identity_owner_test.go @@ -0,0 +1,96 @@ +package api + +import ( + "context" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Proofs and push budgets bind at startup; connection coverage intentionally +// discovers the current store. Exercise those bindings through a real encrypted +// nonce/signature round trip and the ordinary coverage sweep. +func TestCodeIdentityKeepsStartupProofAndLiveCoverageStores(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + initial := store.NewMemory(store.Config{}) + srv := NewServer(registry.New(quietLogger()), initial, ServerConfig{}, quietLogger()) + defer srv.Close() + fastBudgets(srv) + srv.SeedCodeAttestCache(ctx) + replacement := store.NewMemory(store.Config{}) + srv.store = replacement + + pub, priv, signer, se := providerKeyMaterial(t) + p := srv.registry.Register("code-store-binding", nil, &protocol.RegisterMessage{ + Type: protocol.TypeRegister, Backend: "mlx-swift", PublicKey: pub, + Models: []protocol.ModelInfo{{ID: "m", ModelType: "chat", Quantization: "4bit"}}, + }) + identity := newCodeAttestProvider(pub, se) + p.Mu().Lock() + p.AttestationResult = identity.AttestationResult + p.AttestationResult.BinaryHash = trHashA + p.Version, p.APNsDeviceToken = "0.9.0", identity.APNsDeviceToken + p.Status, p.TrustLevel = registry.StatusOnline, registry.TrustHardware + p.Mu().Unlock() + p.SignalApplicationProofSettled() + srv.SetCodeAttestor(&fakeCodeAttestor{onSend: func(_, _, target, nonce string) error { + return completeRoundTrip(t, srv, p, p.ID, priv, signer, target, nonce) + }}) + srv.codeAttestLoop(ctx, p.ID, p) + if !p.GetCodeAttested() || !p.GetFreshCodeAttested() { + t.Fatal("the encrypted nonce/signature round trip did not grant the live process proof") + } + var proof store.CodeAttestation + if !waitForCond(2*time.Second, func() bool { + rows, err := initial.ListCodeAttestations(ctx) + if err != nil || len(rows) != 1 { + return false + } + proof = rows[0] + return proof.SEPubKey == se && proof.NodePublicKey == pub && proof.BinaryHash == trHashA + }) { + t.Fatal("the startup store did not receive the verified proof") + } + if rows, err := replacement.ListCodeAttestations(ctx); err != nil || len(rows) != 0 { + t.Fatalf("the replacement store received a startup-bound proof: rows=%+v err=%v", rows, err) + } + if budgets, err := initial.ListCodeAttestPushBudgets(ctx); err != nil || len(budgets) == 0 { + t.Fatalf("the startup store did not reserve the push budget: rows=%+v err=%v", budgets, err) + } + if budgets, err := replacement.ListCodeAttestPushBudgets(ctx); err != nil || len(budgets) != 0 { + t.Fatalf("the replacement store received a startup-bound push budget: rows=%+v err=%v", budgets, err) + } + if proof.ContinuousCoverageUntil != nil { + t.Fatal("a new APNs proof manufactured a continuity watermark") + } + if err := replacement.UpsertCodeAttestation(ctx, proof); err != nil { + t.Fatal(err) + } + srv.sweepCodeAttestCoverage() + rows, err := replacement.ListCodeAttestations(ctx) + if err != nil || len(rows) != 1 || rows[0].ContinuousCoverageUntil == nil || rows[0].ContinuousCoverageUntil.Before(proof.AttestedAt) { + t.Fatalf("the current store did not receive verified connection coverage: rows=%+v err=%v", rows, err) + } + rows, err = initial.ListCodeAttestations(ctx) + if err != nil || len(rows) != 1 || rows[0].ContinuousCoverageUntil != nil { + t.Fatalf("coverage was redirected to the startup proof store: rows=%+v err=%v", rows, err) + } +} + +func TestCodeIdentityAbsentReleasePolicyCannotResume(t *testing.T) { + srv := NewServer(registry.New(quietLogger()), store.NewMemory(store.Config{}), ServerConfig{}, quietLogger()) + defer srv.Close() + fastBudgets(srv) + pub, _, _, se := providerKeyMaterial(t) + p := crossVersionProvider(pub, se, "0.9.0") + seedFreshProcessAttestation(t, srv, se, "0.8.0", p.APNsDeviceToken, pub, trHashB) + armCrossVersionApplicationEvidence(t, srv, p, se) + resetReleasePolicyForTest(srv) + if srv.tryCrossVersionReuse(context.Background(), p.ID, p) || p.GetCodeAttested() || p.GetFreshCodeAttested() { + t.Fatal("absent release policy authorized a resume or granted code trust") + } +} diff --git a/coordinator/api/cold_dispatch.go b/coordinator/api/cold_dispatch.go deleted file mode 100644 index 119d9e3a93..0000000000 --- a/coordinator/api/cold_dispatch.go +++ /dev/null @@ -1,97 +0,0 @@ -package api - -import ( - "os" - "strings" - - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/saferun" -) - -// Routing v2 — W3: cold-dispatch spill + queue-before-shed wiring. -// -// Both behaviours are default-ON and reversible without a rebuild via env flags. -// They are read here (not on the Server struct) so this workstream stays -// confined to its owned files — server.go / main.go are owned by parallel -// workstreams. The flags are read per call: a feature-flag lookup is negligible -// next to the JSON-parse + crypto + DB work each request already does, and -// reading live env keeps the flags overridable in tests (t.Setenv). -// -// - EIGENINFERENCE_QUEUE_BEFORE_SHED (default true): when the preflight would -// 429 `machine_busy` (providers exist for the model but all are at capacity), -// route the request into the normal dispatch+queue path instead, so a slot -// freeing — or a cold load completing — within the queue window serves it. -// The dispatch/queue path still returns a 429 when the queue is full or the -// wait times out (true saturation). -// - EIGENINFERENCE_COLD_DISPATCH (default true): (1) when the preflight would -// 503 `no_provider` but an idle on-disk provider could load the model, spill -// the request into the queue instead of shedding; and (2) on every queue -// enqueue, proactively kick the model-swap machinery so a cold provider is -// warmed for the queued demand without waiting for the next heartbeat. - -const ( - envQueueBeforeShed = "EIGENINFERENCE_QUEUE_BEFORE_SHED" - envColdDispatch = "EIGENINFERENCE_COLD_DISPATCH" -) - -// envEnabledDefaultTrue parses a boolean env var that defaults to TRUE when -// unset. Only an explicit falsey value ("0"/"false"/"no"/"off", -// case-insensitive) disables the flag; anything else (including malformed input) -// leaves the default-safe behaviour enabled. -func envEnabledDefaultTrue(name string) bool { - switch strings.ToLower(strings.TrimSpace(os.Getenv(name))) { - case "0", "false", "no", "off": - return false - default: - return true - } -} - -// queueBeforeShedEnabled reports whether capacity-rejected preflight requests -// are queued instead of immediately 429'd. Default true. -func (s *Server) queueBeforeShedEnabled() bool { - return envEnabledDefaultTrue(envQueueBeforeShed) -} - -// coldDispatchEnabled reports whether the coordinator spills "no eligible -// provider" requests into the queue when an idle on-disk provider could be -// warmed, and proactively triggers cold loads for queued demand. Default true. -func (s *Server) coldDispatchEnabled() bool { - return envEnabledDefaultTrue(envColdDispatch) -} - -// coldSpillAvailable reports whether at least one idle on-disk provider could be -// warmed to serve `model` for a public request with these traits. Used by the -// preflight to turn an otherwise-immediate 503 `no_provider` into a queued -// cold-dispatch when warming can actually help. -func (s *Server) coldSpillAvailable(model string, traits registry.RequestTraits, requiresVision bool, allowedSerials []string) bool { - if s == nil || s.registry == nil { - return false - } - return s.registry.ColdSpillProviders(model, traits, requiresVision, allowedSerials...) > 0 -} - -// kickColdDispatch proactively triggers the model-swap machinery so a cold -// provider is warmed for a freshly-queued model without waiting for the next -// heartbeat. It is a no-op when cold-dispatch is disabled. Safe to call on every -// enqueue: TriggerModelSwaps only loads models that have queued demand and no -// warm provider, and de-dups in-flight loads. -// -// It deliberately does NOT emit RecordWarmPoolColdDispatch: the queued request is -// already counted via the warm-pool queue-depth signal, and the cold-dispatch -// counter is recorded once at the actual cold reserve (registry/scheduler.go), so -// emitting here too would double-count the autoscaler's demand signal. -// -// The swap is dispatched on a recovered goroutine so the request hot path never -// blocks on registry locking. -func (s *Server) kickColdDispatch(model string) { - if s == nil || s.registry == nil || model == "" { - return - } - if !s.coldDispatchEnabled() { - return - } - saferun.Go(s.logger, "api.coldDispatchSwap", func() { - s.registry.TriggerModelSwaps() - }) -} diff --git a/coordinator/api/concrete_model_entries.go b/coordinator/api/concrete_model_entries.go deleted file mode 100644 index 3c04e0b6ed..0000000000 --- a/coordinator/api/concrete_model_entries.go +++ /dev/null @@ -1,157 +0,0 @@ -package api - -import ( - "github.com/eigeninference/d-inference/coordinator/api/types" - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" -) - -// modelEntryForConcrete builds the consumer catalog representation of one -// provider-advertised concrete model. Callers decide whether the entry is hidden -// behind a standard rollout alias; OpenRouter-only aliases never hide it. -func (s *Server) modelEntryForConcrete( - model registry.AggregateModel, - capacity *registry.ModelCapacity, - catalogModel store.SupportedModel, - inCatalog bool, - registryEntry store.ModelRegistryEntry, - hasRegistryEntry bool, -) types.ModelEntry { - metadata := types.ModelMetadata{ - ModelType: model.ModelType, - Quantization: model.Quantization, - ProviderCount: model.Providers, - AttestedProviders: model.AttestedProviders, - TrustLevel: string(model.TrustLevel), - } - if capacity != nil { - metadata.RoutableProviders = capacity.RoutableProviders - metadata.WarmProviders = capacity.WarmProviders - metadata.CanAccept = capacity.CanAccept - } - if model.Attestation != nil { - metadata.Attestation = &types.ModelAttestation{ - SecureEnclave: model.Attestation.SecureEnclave, - SIPEnabled: model.Attestation.SIPEnabled, - SecureBoot: model.Attestation.SecureBoot, - } - } - if inCatalog && catalogModel.DisplayName != "" { - metadata.DisplayName = catalogModel.DisplayName - } - - entry := types.ModelEntry{ - ID: model.ID, - Object: "model", - OwnedBy: "eigeninference", - Name: metadata.DisplayName, - HuggingFaceID: huggingFaceIDForModel(model.ID, registryEntry.Metadata), - Metadata: metadata, - } - s.openRouterModelFieldsFor(model.ID, model.Quantization, registryEntry, hasRegistryEntry).applyToModelEntry(&entry) - - var capabilities []string - if hasRegistryEntry { - capabilities = registryEntry.Capabilities - } - entry.InputModalities, entry.OutputModalities = deriveModalities(model.ModelType, capabilities) - return entry -} - -// modelEntryForCatalogConcrete builds exact-retrieval metadata for an active -// concrete model even when no provider is connected. Live counts remain zero; -// the durable registry supplies identity, limits, pricing, and capabilities. -func (s *Server) modelEntryForCatalogConcrete( - modelID string, - catalogByID map[string]store.SupportedModel, - registryByID map[string]store.ModelRegistryEntry, -) (types.ModelEntry, bool) { - catalogModel, ok := catalogByID[modelID] - if !ok { - return types.ModelEntry{}, false - } - registryEntry, hasRegistryEntry := registryByID[modelID] - entry := s.modelEntryForConcrete( - registry.AggregateModel{ - ID: modelID, - ModelType: catalogModel.ModelType, - Quantization: registryEntry.Quantization, - }, - nil, - catalogModel, - true, - registryEntry, - hasRegistryEntry, - ) - return entry, true -} - -func (s *Server) openRouterAggregateTypeByID() map[string]string { - typesByID := make(map[string]string) - for _, model := range s.registry.ListModels() { - if model.ModelType != "" { - typesByID[model.ID] = model.ModelType - } - } - return typesByID -} - -func concreteModelEligibleForOpenRouterFeed( - modelID string, - catalogByID map[string]store.SupportedModel, - aggregateTypeByID map[string]string, -) bool { - catalogModel, ok := catalogByID[modelID] - if !ok { - return false - } - modelType := catalogModel.ModelType - if aggregateType, found := aggregateTypeByID[modelID]; found { - modelType = aggregateType - } - return !isNonTextModelType(modelType) -} - -// openRouterEntryForConcrete builds the dedicated provider-feed representation -// of one active concrete catalog model. It remains independently listed when an -// OpenRouter-only alias clones it. -func (s *Server) openRouterEntryForConcrete( - modelID string, - catalogByID map[string]store.SupportedModel, - registryByID map[string]store.ModelRegistryEntry, - aggregateTypeByID map[string]string, -) (types.OpenRouterModel, bool) { - catalogModel, ok := catalogByID[modelID] - if !ok || !concreteModelEligibleForOpenRouterFeed(modelID, catalogByID, aggregateTypeByID) { - return types.OpenRouterModel{}, false - } - - registryEntry, hasRegistryEntry := registryByID[modelID] - modelType := catalogModel.ModelType - if aggregateType, found := aggregateTypeByID[modelID]; found { - modelType = aggregateType - } - var capabilities []string - if hasRegistryEntry { - capabilities = registryEntry.Capabilities - } - inputModalities, outputModalities := deriveModalities(modelType, capabilities) - entry := types.OpenRouterModel{ - ID: modelID, - HuggingFaceID: huggingFaceIDForModel(modelID, registryEntry.Metadata), - Name: openRouterModelName(catalogModel, registryEntry, hasRegistryEntry, modelID), - InputModalities: inputModalities, - OutputModalities: outputModalities, - SupportedFeatures: []string{}, - IsReady: true, - } - s.openRouterModelFieldsFor(modelID, registryEntry.Quantization, registryEntry, hasRegistryEntry).applyToFeed(&entry) - if hasRegistryEntry { - entry.IsReady = openRouterIsReady(registryEntry.Metadata) - entry.OpenRouter = &types.OpenRouterSlug{Slug: openRouterSlug(modelID, registryEntry.Metadata)} - } else { - entry.OpenRouter = &types.OpenRouterSlug{Slug: openRouterSlug(modelID, nil)} - } - entry.Datacenters = s.modelDatacenters(modelID) - return entry, true -} diff --git a/coordinator/api/consumer.go b/coordinator/api/consumer.go deleted file mode 100644 index da16c39956..0000000000 --- a/coordinator/api/consumer.go +++ /dev/null @@ -1,3003 +0,0 @@ -package api - -// Consumer-facing API handlers for the Darkbloom coordinator. -// -// This file implements the OpenAI-compatible HTTP endpoints that consumers -// use to send inference requests. The coordinator acts as a trusted routing -// layer between consumers and providers. -// -// Trust model: -// The coordinator runs in a Confidential VM, providing hardware-encrypted -// memory. Consumers may additionally sender-seal requests to the -// coordinator's X25519 key. The coordinator decrypts for routing purposes -// but never logs prompt content, then re-encrypts each request to the -// selected provider's X25519 public key before forwarding over the -// WebSocket. Providers are attested via Secure Enclave challenge-response. - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "math" - "net/http" - "strconv" - "strings" - "time" - - "github.com/eigeninference/d-inference/coordinator/api/types" - "github.com/eigeninference/d-inference/coordinator/auth" - "github.com/eigeninference/d-inference/coordinator/internal/e2e" - "github.com/eigeninference/d-inference/coordinator/modelpolicy" - "github.com/eigeninference/d-inference/coordinator/payments" - "github.com/eigeninference/d-inference/coordinator/promptcontract" - "github.com/eigeninference/d-inference/coordinator/protocol" - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" - "github.com/google/uuid" -) - -const ( - // inferenceTimeout is the maximum time to wait between chunks (streaming) - // or for the full response (non-streaming). For streaming, the deadline - // resets on each received chunk so long-running generations don't time out. - // 10 minutes allows 32k tokens at ~55 tok/s on slower hardware. - inferenceTimeout = 600 * time.Second - - // defaultFirstContentDeadlineBase preserves the ordinary coordinator and - // unit-test budget. Production overrides it to 9s through validated startup - // configuration; exact model overrides live in modelpolicy and every request - // adds 1ms per estimated prompt token. - defaultFirstContentDeadlineBase = 5 * time.Second - - // preambleContentTimeout is the relative cap from the first boilerplate - // chunk to the first CONTENT chunk. A provider that produced only preamble - // (role delta / Responses lifecycle) has written ZERO bytes to the client, - // so a role-then-stall zombie must fail over instead of pinning the request - // for the full inferenceTimeout. 90s covers the measured pre-content tail - // (vision prefill is 6-30s). When ReceivedAt is stamped this cap cannot - // exceed leftover request-absolute first-token budget: AcceptedCh is not a - // completion token and must not reset that clock. - preambleContentTimeout = 90 * time.Second - - // chunkBufferSize is the channel buffer size for SSE chunks flowing from - // the provider to the consumer. A larger buffer prevents dropped chunks - // when the consumer reads slowly. - chunkBufferSize = 256 - - // maxDispatchAttempts is a SAFETY CEILING on per-request provider failover, - // not the normal stopping point. A request keeps failing over to fresh - // healthy providers until one succeeds, OR candidates are exhausted (every - // failed provider is excluded from re-selection, so dispatchPrimary returns - // outcomeFailFast on the next attempt once no eligible provider remains), OR - // the request's deadline/context fires (run() checks r.Context() each - // attempt). This ceiling only guards against a pathological retry path that - // fails to exclude a provider (an unbounded hot loop); it is set well above - // any realistic per-request fault count. Retries never re-queue — only the - // first attempt may wait for capacity — so failover stays fast, walking the - // immediately-available healthy providers rather than waiting on busy ones. - maxDispatchAttempts = 64 - - // maxCapacityClassRetries bounds failover specifically for TRANSIENT-capacity - // rejections (this provider's live KV budget, a full queue, an update drain). - // Such a shortage MAY clear on another provider, so we fail over — but only a - // few times, so a fleet-wide transient (or an oversized request the determinism - // check didn't tag) cannot walk all maxDispatchAttempts providers and 503 each - // (the prod storm: median 22, max 63 attempts, ~8.7 min, 0% eventual success). - // A DETERMINISTIC-context rejection (prompt > model context, identical on every - // provider) stops on the FIRST attempt regardless — see classifyRejection. - maxCapacityClassRetries = 3 - - // maxFirstChunkTimeoutRetries bounds failover for coordinator-synthesized - // first-chunk TIMEOUTS (the untyped 504 the exhausted ladder reclassifies - // to a retryable 429 with reason "first_chunk_timeout"). Unlike capacity - // rejections these carried NO cap: every retry re-ran a full fleet - // reservation scan (~1,260 providers, registry.ReserveProviderEx), and in - // the 2026-09-01 congestion collapse retry-amplified inbound (~100 req/s - // of retryable 429 traffic from OpenRouter) times per-request fleet scans - // saturated every coordinator CPU — attempt-0 route p50 went 40ms → 4.6s, - // success ~40%, 429s were delivered after 11s, inbound ~6k/min vs served - // ~550/min. The request-absolute first-content budget already bounds WALL - // time per request; this bounds CPU: after this many timed-out attempts - // (each on a distinct provider — a timed-out provider is excluded from - // re-selection) the ladder exhausts immediately into the existing - // synthetic-timeout → 429 reclassification (classifyExhaustedStatus). - maxFirstChunkTimeoutRetries = 3 - - // speculativeTimerRatio is the fraction of the TTFT deadline at which - // the coordinator launches a speculative backup dispatch. The primary - // provider gets this fraction of the deadline before the backup is - // started, and then both race until one produces the first chunk. - speculativeTimerRatio = 0.5 - - // maxHeldBoilerplate bounds how many pre-content boilerplate chunks the - // dispatch loop holds per provider before committing anyway. Real - // preambles are one chunk (chat role delta) or two (Responses - // created/in_progress), so the cap exists only to stop a misbehaving - // provider from growing the held buffer for the whole inference window. - // Excess boilerplate is dropped while the first-content clock continues; - // it must never be mistaken for content and commit a bad provider. - maxHeldBoilerplate = 8 - - // cancelWriteTimeout bounds how long a cancel write to the provider can - // block. Using context.Background() unbounded here risks hanging the HTTP - // handler goroutine when a WebSocket is half-dead. - cancelWriteTimeout = 2 * time.Second -) - -// FirstContentDeadline returns this server's request-absolute first-content -// budget for a concrete model. The ordinary base is instance-owned so -// production-like E2E servers can use the production value without mutating -// concurrent unit tests. Exact-model overrides and the fixed 1ms/token slope -// are centralized in modelpolicy. -func (s *Server) FirstContentDeadline(model string, estimatedPromptTokens int) time.Duration { - base := s.firstContentDeadlineBase - if base <= 0 { - base = defaultFirstContentDeadlineBase - } - return modelpolicy.CoordinatorFirstContentDeadline(model, estimatedPromptTokens, base) -} - -// shedIfModelRejected answers a public/prefer-owner request with 429 + -// Retry-After when its requested alias or resolved build is in the operator -// reject set (EIGENINFERENCE_REJECT_MODELS). This is a deterministic -// per-model circuit breaker: it takes an unhealthy model out of rotation before -// rate-limit, reservation, or routing work, so aggregators see rate limiting -// rather than dropped/cancelled streams. Exclusive self-route bypasses the shed -// because it never falls back to the public fleet. -func (s *Server) shedIfModelRejected(w http.ResponseWriter, r *http.Request, parsed map[string]any, policy selfRoutePolicy, publicModel, model string, stream bool, estimatedPromptTokens, requestedMaxTokens int, requiresVision, hasTools bool) bool { - if policy.enabled || !s.modelShed(model, publicModel) { - return false - } - retryAfter := s.estimateRetryAfter(model) - if retryAfter <= 0 { - retryAfter = 30 - } - s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:model_shed"}) - s.recordRejection(rejectionInfo{ - r: r, - stage: "model_shed", - reasonCode: "model_shed", - httpStatus: http.StatusTooManyRequests, - keyID: keyIDFromContext(r.Context()), - consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), - requestedModel: publicModel, - resolvedModel: model, - stream: stream, - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - requiresVision: requiresVision, - hasTools: hasTools, - selfRouteOnly: policy.enabled, - preferOwner: policy.prefer, - retryAfterMs: retryAfter * 1000, - params: rejectionSamplingParams(parsed), - }) - w.Header().Set("Retry-After", strconv.Itoa(retryAfter)) - writeJSON(w, http.StatusTooManyRequests, errorResponse("rate_limit_exceeded", - fmt.Sprintf("model %q is temporarily rate-limited — retry after %ds", publicModel, retryAfter), - withCode("rate_limit_exceeded"))) - return true -} - -// sendProviderCancel sends a Cancel message for the given request to the -// provider with a bounded timeout so a half-dead WebSocket doesn't hang the -// caller. It reports whether the frame was handed to the writer. Failures are -// logged at debug level because a disconnect race is the expected case — the -// provider may already be gone — but every one is metered -// (inference.cancel_send_failed{reason}) since a dropped cancel is the only -// silent-loss path on the coordinator side of cancel delivery. -// -// This is the raw primitive. Abandon paths that may leave the provider -// generating go through sendAbandonCancel / cancelDispatch so the cancel is -// recorded for terminal correlation and zombie re-sends. -func (s *Server) sendProviderCancel(provider *registry.Provider, requestID string) bool { - if provider == nil || provider.Conn == nil { - return false - } - cancelMsg := protocol.CancelMessage{Type: protocol.TypeCancel, RequestID: requestID} - cancelData, err := json.Marshal(cancelMsg) - if err != nil { - s.logger.Error("failed to marshal cancel message", "request_id", requestID, "error", err) - return false - } - ctx, cancel := context.WithTimeout(context.Background(), cancelWriteTimeout) - defer cancel() - if err := provider.EnqueueText(ctx, cancelData); err != nil { - s.ddIncr(metricCancelSendFailed, []string{"reason:" + cancelSendFailureReason(err)}) - s.logger.Debug("failed to send cancel (provider may have disconnected)", - "request_id", requestID, "error", err) - return false - } - return true -} - -func writeProviderInferenceRequestDeferred( - ctx context.Context, - provider *registry.Provider, - builder registry.TextFrameBuilder, - onHandoff registry.TextFrameHandoff, -) (registry.TextFrameWriteMetadata, error) { - if provider == nil || provider.Conn == nil { - return registry.TextFrameWriteMetadata{}, errors.New("provider websocket is not connected") - } - return provider.WriteTextDeferred(ctx, builder, onHandoff) -} - -// cancelDispatch abandons a dispatch attempt that may still be generating -// (hedge loser, client gone before content): removes the pending request, -// marks the provider idle, sends a cancel over WebSocket so the provider stops, -// and refunds this attempt's provider-specific reservation top-up. cause is -// the bounded cancel cause recorded for terminal correlation. -// -// The cancel is sent only when THIS call removed a live pending record and no -// clean terminal has been ingressed for it. A missing record means a provider -// terminal already claimed the attempt (handleInferenceError removes pending -// before publishing on ErrorCh); a completion parked on the speculative -// empty-completion decision leaves the record but marks completion ingress. -// In both cases nothing is running provider-side, and cancelling would only -// cost the provider a no-op frame per request. Attempts whose terminal was -// observed by the caller use cancelDispatchAfterTerminal instead. -// -// The top-up refund only runs if THIS call actually removed the pending request -// (RemovePending returned non-nil). If settlement (handleComplete) already -// claimed it via its own RemovePending, we must not also refund — that would -// double-credit the consumer. -func (s *Server) cancelDispatch(provider *registry.Provider, pr *registry.PendingRequest, cause string) { - if provider == nil || pr == nil { - return - } - pr.ResolveSpeculativeEmptyCompletion(false) - now := time.Now() - // Record before RemovePending: a terminal racing this cleanup looks the - // id up only after its own RemovePending returns nil, and must find the - // entry rather than log the terminal as unknown. - created, expired := s.zombieCanceller.record(pr.RequestID, pr.Model, cause, now) - s.emitExpiredCancelEntries(expired) - removed := provider.RemovePending(pr.RequestID) - s.registry.SetProviderIdle(provider.ID) - if removed != nil && !pr.HasCompletionIngress() { - pr.Profile.Mark(registry.StampCancelSent) - s.sendRecordedCancel(provider, pr.RequestID, pr.Model, cause) - } else if created { - s.zombieCanceller.forget(pr.RequestID) - } - if removed != nil { - s.refundProviderExtra(pr) - } -} - -// cancelDispatchAfterTerminal is cancelDispatch for an attempt whose provider -// terminal the caller has already observed (ErrorCh value / ChunkCh closed). -// The terminal handler removed the pending record before publishing it, so -// nothing is running provider-side and no cancel frame is sent — only the -// speculative arbitration, idle transition and top-up refund remain. -func (s *Server) cancelDispatchAfterTerminal(provider *registry.Provider, pr *registry.PendingRequest) { - if provider == nil || pr == nil { - return - } - pr.ResolveSpeculativeEmptyCompletion(false) - removed := provider.RemovePending(pr.RequestID) - s.registry.SetProviderIdle(provider.ID) - if removed != nil { - s.refundProviderExtra(pr) - } -} - -// cancelDispatchForFirstContentTimeout atomically arbitrates timeout cleanup -// against provider ingress. false means an on-time event or another terminal -// already owns the request, so the wait loop must keep draining its channels. -func (s *Server) cancelDispatchForFirstContentTimeout( - provider *registry.Provider, - pr *registry.PendingRequest, -) bool { - if provider == nil || pr == nil { - return false - } - now := time.Now() - created, expired := s.zombieCanceller.record(pr.RequestID, pr.Model, cancelCauseFirstChunkTimeout, now) - s.emitExpiredCancelEntries(expired) - removed, deferred := provider.RemovePendingForFirstContentTimeout(pr.RequestID) - if deferred || removed == nil { - if created { - s.zombieCanceller.forget(pr.RequestID) - } - return false - } - pr.ResolveSpeculativeEmptyCompletion(false) - s.registry.SetProviderIdle(provider.ID) - pr.Profile.Mark(registry.StampCancelSent) - s.sendRecordedCancel(provider, pr.RequestID, pr.Model, cancelCauseFirstChunkTimeout) - s.refundProviderExtra(pr) - return true -} - -// refundProviderExtra refunds the provider-specific surcharge charged on top of -// the shared base reservation when an attempt is abandoned. It is idempotent: -// after refunding it resets ReservedMicroUSD to the base so a second call (or a -// later settlement) cannot double-refund. The shared base is never refunded -// here — that is handled once by refundReservation (full failure) or by the -// winning attempt's settlement. -func (s *Server) refundProviderExtra(pr *registry.PendingRequest) { - if pr == nil { - return - } - extra := pr.ReservedMicroUSD - pr.BaseReservedMicroUSD - if extra <= 0 { - return - } - _ = s.store.Credit(pr.ConsumerKey, extra, store.LedgerRefund, "reservation_extra_refund:"+pr.RequestID) - pr.ReservedMicroUSD = pr.BaseReservedMicroUSD - s.ddIncr("billing.reservation_extra_refunds", []string{"model:" + pr.Model}) -} - -// writeGenericProviderError writes the terminal HTTP body for a provider error -// on paths WITHOUT a failover ladder or in-band SSE error framing: the generic -// inference handlers (/v1/messages, /v1/completions) and the non-streaming -// chat response assembly. Deterministic non-provider-fault reasons surface the -// SAME curated bodies as the chat dispatch ladder — a jinja_* template-render -// failure becomes the 422 model_capability invalid_request_error (the raw -// template backtrace never reaches a client), gated by the ladder's -// EIGENINFERENCE_JINJA_TERMINAL_REJECT kill switch; tool_noncompliance keeps -// its provider-typed 422 message (already curated and content-free) but in the -// invalid_request_error/model_capability envelope instead of provider_error. -// Every other error is mapped from the closed failure_code vocabulary. Raw -// provider prose is never passed through. -func (s *Server) writeGenericProviderError(w http.ResponseWriter, errMsg protocol.InferenceErrorMessage) { - errMsg = normalizeInferenceErrorForInternalUse(errMsg) - if jinjaTerminalRejectEnabled() && isJinjaTemplateErrorReason(errMsg.ErrorReason) { - writeJSON(w, http.StatusUnprocessableEntity, - errorResponse("invalid_request_error", jinjaTerminalRejectMessage, withCode("model_capability"))) - return - } - if normalizeInferenceErrorReason(errMsg.ErrorReason) == errorReasonToolNoncompliance { - writeJSON(w, http.StatusUnprocessableEntity, - errorResponse("invalid_request_error", clientSafeInferenceErrorMessage(errMsg), withCode("model_capability"))) - return - } - statusCode := errMsg.StatusCode - if statusCode == 0 { - statusCode = http.StatusBadGateway - } - writeJSON(w, statusCode, errorResponse("provider_error", clientSafeInferenceErrorMessage(errMsg))) -} - -// noteInferenceError feeds the circuit breakers for a provider-side error -// received on a pending request's ErrorCh (any phase, pre- or post-commit): -// - the shape-keyed inference-error breaker (counts only sickness-shaped -// 500/502/504 for the (provider, model, shape) triple), -// - the per-provider node-health breaker, which also counts fault-shaped -// 503s (errStr classifies capacity-503 vs fault-503), -// - the stable-identity ejection breaker (survives reconnect churn), and -// - the capacity-reject cooldown (the ONLY consumer of capacity-class -// rejections, which every breaker above deliberately ignores). -// -// It emits the cool-down metric on the inference-error transition and the -// provider_breaker_open metric on the node-health transition into quarantine. -// errStr is the provider's error message and errReason its structured -// InferenceErrorMessage.ErrorReason ("" for synthetic timeouts and legacy -// providers) — the reason feeds the gray-box request-shape classification the -// same way the dispatch failover trusts it (classifyRejection P1). -// terminalCause is the provider's typed InferenceErrorMessage.TerminalCause -// ("" for synthetic terminals and legacy providers): a typed NEUTRAL cause -// (safety_deadline / backpressure_timeout / cancelled — platform policy or -// consumer behavior) feeds NOTHING here, strike or clear; a typed CAPACITY -// cause (admission_timeout — healthy but busy) feeds only the black-hole -// capacity cooldown. Absent/engine_error/unknown causes keep the legacy -// status/string funnels bit-for-bit (see api/terminal_cause.go). -func (s *Server) noteInferenceError(providerID string, pr *registry.PendingRequest, statusCode int, errStr, errReason, terminalCause string, causes ...protocol.CoordinatorInferenceErrorCause) { - if providerID == "" || pr == nil { - return - } - // Structured health-neutral outcomes (isProviderHealthNeutralErrorReason: - // jinja_* template-render failures, tool_noncompliance, and the - // request-clock-specific deadline_unreachable refusal) never feed provider - // health or capacity trackers. Gating HERE (the single breaker chokepoint) - // mirrors the dispatch-funnel gate - // (dispatchState.noteProviderError) and the reputation exemption - // (handleInferenceError), and closes the generic-inference path - // (/v1/messages, /v1/completions), which calls noteInferenceError directly on - // pre-commit provider errors. Capacity-class rejections never carry these - // reasons except deadline_unreachable, whose exclusion is intentional. - if isProviderHealthNeutralErrorReason(errReason) { - return - } - // Typed drain refusal (R2, registry/drain_state.go): the provider is - // restarting, not sick and not dishonest about capacity. It feeds NO - // breaker and NO gray-box capacity state (no cooldown strike, no rate - // derate, no budget clamp). Ingress marks draining before releasing the - // pending slot, so its queue drain already skips this provider. Do not - // repeat that mutation here: an idle/serving heartbeat may have cleared - // the mark while this consumer was waiting to process its error channel. - if isDrainingErrorReason(errReason) { - return - } - // Typed terminal-cause gate (the deadline-incident fix): the provider told - // us WHY the attempt died, so the status/string heuristics below must not - // misread a platform-policy terminal as sickness. Neutral causes touch no - // tracker at all — strictly neutral, never a success/clear either. - // admission_timeout records exactly one capacity-signal strike (the - // black-hole cooldown, whose zero-interleaved-accepts discriminator keeps - // serving boxes safe) and skips every fault breaker. All other causes — - // absent (legacy/synthetic), engine_error, the fault causes - // (prefill_stall / decode_stall / watchdog), and unknown drift values — - // fall through to the unchanged legacy funnels. - switch class, _ := classifyTerminalCause(terminalCause); class { - case causeClassNeutral: - return - case causeClassCapacity: - if s.registry.RecordCapacityRejectBusy(providerID, pr.Model) { - s.ddIncr(metricCapacityCooldownTripped, []string{"provider_id:" + providerID, "model:" + pr.Model}) - s.logger.Warn("capacity-reject cooldown tripped: provider+model admission-timing-out with zero interleaved accepts — routing will skip the pair until the cooldown expires", - "provider_id", providerID, - "model", pr.Model, - "status_code", statusCode, - "terminal_cause", terminalCause, - ) - } - return - } - // Late disconnect-flush strike (registry/version_reset.go): the session this - // 502 was flushed from was dropped at or before its identity's version- - // changed reset, so the reset already accounted for it. The flush is - // recorded HERE, by the request goroutine, not by Disconnect — and - // registration evicts a same-serial predecessor and stores the new version - // on one goroutine, ahead of these consumers — so without the check the - // new binary would be quarantined for the old one's death. - if s.registry.IsSupersededDisconnectFlush(providerID, statusCode, causes...) { - return - } - if s.registry.RecordInferenceError(providerID, pr.Model, statusCode, pr.Traits.CooldownShape(), causes...) { - s.ddIncr("routing.cooldown_entered", []string{"model:" + pr.Model}) - } - // Feed EVERY provider terminal into the per-provider node-health breaker (not - // just the shape-keyed 5xx the inference-error breaker counts) so a node - // fault-503ing ~all of its requests gets quarantined fleet-wide. errStr lets - // the breaker tell a capacity-503 (ignored) from a fault-503 (counted). Both - // breakers coexist. - if opened, _ := s.registry.RecordProviderOutcome(providerID, false, statusCode, errStr, causes...); opened { - s.ddIncr("routing.provider_breaker_open", []string{"model:" + pr.Model}) - } - // Feed the STABLE-IDENTITY ejection breaker too (survives reconnect churn, so a - // zombie that fault-loops while constantly disconnecting still accumulates). - if ejected, _ := s.registry.RecordProviderSessionServeOutcome(providerID, false, statusCode, errStr, causes...); ejected { - s.ddIncr("routing.provider_ejected", []string{"model:" + pr.Model}) - } - // Feed the capacity-reject cooldown. Capacity-class rejections are - // DELIBERATELY invisible to reputation and to ALL the breakers above (a - // busy box must never be punished for shedding) — which turns a box that - // capacity-rejects EVERYTHING into a routing black hole: its idle-looking - // heartbeats keep winning the cost scheduler while every dispatch bounces - // (2026-07 incident: 7 boxes, ~9k "token_budget_exhausted" rejections in - // 30 min, zero successes). Strikes accumulate per (provider, model); any - // accept (first content chunk or clean completion) resets the streak, so - // transient fullness on a serving box can never trip. Gated to 429/404/5xx - // so a client-shape 4xx that happens to carry a capacity-looking string - // never strikes; explicit context-overflow rejections are excluded by - // isCapacityRejectStrike (they indict the request, not the provider). - // - // 404 is included WITH CARE for the cold "model not loaded" miss: a lazy - // load on first touch makes a 404-then-load-then-serve sequence NORMAL - // lifecycle, so the zero-interleaved-accepts discriminator remains the - // safety — the first accept after the load clears the streak, and only a - // box that 404s FOREVER (never loads, zero accepts) trips. A 404 whose - // message is not capacity-class (e.g. "model not found" for an unknown - // model id — a request-shape error) never strikes, because - // isCapacityRejectStrike only matches the capacity vocabulary - // ("not loaded" / "no model loaded"). - if (statusCode == http.StatusTooManyRequests || statusCode == http.StatusNotFound || - statusCode >= http.StatusInternalServerError) && - isCapacityRejectStrike(errStr) { - // A cold "model not loaded" miss is benign warm-up lifecycle, not - // capacity dishonesty. It still feeds the black-hole cooldown (a box - // that 404s forever with zero accepts is a black hole), but it must NOT - // derate the pair's gray-box capacity-503 RATE (capacity_rate.go) — that - // window has no accept-reset, so counting a healthy box's normal reloads - // would penalize it. A "batch token budget" reject that classifyRejection - // proves REQUEST-deterministic (provider budget not below the model - // context ⇒ the binding term was the fleet-wide context) indicts the - // request, not the provider: it counts a cooldown strike only — arming - // the one-shot clamp or the no-reset rate window off a single oversized - // prompt would gate/derate a healthy pair. Genuine capacity/token-budget - // 503s feed everything. - var tripped bool - switch { - case isColdModelMissRejection(errStr): - tripped = s.registry.RecordCapacityRejectLifecycle(providerID, pr.Model) - case s.isRequestShapeBatchBudgetReject(providerID, pr.Model, errStr, errReason): - tripped = s.registry.RecordCapacityRejectRequestShape(providerID, pr.Model) - default: - tripped = s.registry.RecordCapacityReject(providerID, pr.Model) - } - if tripped { - s.ddIncr(metricCapacityCooldownTripped, []string{"provider_id:" + providerID, "model:" + pr.Model}) - s.logger.Warn("capacity-reject cooldown tripped: provider+model capacity-rejecting with zero interleaved accepts — routing will skip the pair until the cooldown expires", - "provider_id", providerID, - "model", pr.Model, - "status_code", statusCode, - ) - } - } -} - -// metricCapacityCooldownTripped counts transitions of a (provider, model) pair -// into the capacity-reject routing cooldown (registry/capacity_cooldown.go), -// tagged provider_id + model. Distinct from routing.cooldown_entered (the 5xx -// inference-error breaker) and routing.provider_breaker_open (node health) so -// black-hole trips are independently alertable. -const metricCapacityCooldownTripped = "routing.capacity_cooldown_tripped" - -// isRequestShapeBatchBudgetReject reports whether a capacity-class rejection -// is PROVEN request-deterministic by classifyRejection: a "batch token budget" -// reject from a provider whose reported token budget is not below the model's -// context window (the admission cap min(context, budget) was the CONTEXT — the -// prompt is too big fleet-wide), or an explicit request_exceeds_context -// structured reason. Such a reject must arm neither the one-shot budget clamp -// nor the no-reset capacity-503 rate window -// (RecordCapacityRejectRequestShape). When the reported budget IS below the -// context, the binding term may have been this node's memory-pressured KV -// budget — a genuine provider-specific capacity signal — and the reject feeds -// the full gray-box state (same discrimination the dispatch failover uses: -// classifyRejection in inference_failure_class.go, DAR-347). -// -// Inputs mirror the dispatch path exactly: the structured errReason -// (InferenceErrorMessage.ErrorReason — a provider that says -// request_exceeds_node_budget / capacity_busy is TRUSTED over the stale -// heartbeat-budget heuristic, so a stale snapshot that still reads >= context -// cannot misroute a genuine node-capacity failure away from the gray-box -// trackers), providerBudget from the provider's last heartbeat -// (ReportedTokenBudgetMaxForModel), and modelContext from the model registry -// record. Called only inside the isCapacityRejectStrike branch, so explicit -// context-overflow STRINGS never reach it (they never strike at all). The -// cheap gate keeps the two lookups off every other rejection. -func (s *Server) isRequestShapeBatchBudgetReject(providerID, model, errStr, errReason string) bool { - e := strings.ToLower(strings.TrimSpace(errStr)) - e = strings.ReplaceAll(e, "’", "'") - reason := strings.ToLower(strings.TrimSpace(errReason)) - if !strings.Contains(e, "batch token budget") && reason != "request_exceeds_context" { - return false - } - var providerBudget int64 - if p := s.registry.GetProvider(providerID); p != nil { - providerBudget = p.ReportedTokenBudgetMaxForModel(model) - } - modelContext := 0 - if rec, err := s.store.GetModelRegistryRecord(model); err == nil && rec != nil { - modelContext = rec.MaxContextLength - } - // No typed CapacityRejectionReason threads into the strike funnel - // (noteInferenceError carries only the string vocabulary), so this stays - // the legacy string+heartbeat heuristic — enriched typed reasons already - // reach it mapped onto error_reason by the sanitizer. - return classifyRejection(errReason, errStr, providerBudget, modelContext, "") == rejectionDeterministicUnservable -} - -// noteInferenceSuccess clears the inference-error strike state for the serving -// provider-model pair on a clean completion (streaming relay ended without a -// provider error; non-streaming response assembled OK). -func (s *Server) noteInferenceSuccess(pr *registry.PendingRequest) { - if pr == nil || pr.ProviderID == "" { - return - } - s.registry.RecordInferenceSuccess(pr.ProviderID, pr.Model, pr.Traits.CooldownShape()) - // A clean completion is an ACCEPT for the capacity-reject cooldown: clear - // the pair's reject streak, any active capacity cooldown, and the re-trip - // backoff. Belt-and-braces with the commit-time accept (commitFirstContent) - // and the only accept signal on paths that never stream content. For the - // capacity-503 RATE window (capacity_rate.go) one served request must - // count exactly ONE outcome, so this completion-time accept re-offers the - // outcome only when the commit-time accept did not actually RECORD one - // (RateOutcomeCountedSafe — stamped from RecordCapacityAccept's return at - // every commit site). With rate tracking enabled, commit-time accepts are - // retained even before the first reject; paths that never commit content - // record their sole outcome here instead. - s.registry.RecordCapacityAcceptOutcome(pr.ProviderID, pr.Model, !pr.RateOutcomeCountedSafe()) - // A clean completion proves the node is healthy — close its node-health - // breaker (and reset the exponential backoff) if it had tripped. - if _, closed := s.registry.RecordProviderOutcome(pr.ProviderID, true, 200, ""); closed { - s.ddIncr("routing.provider_breaker_closed", []string{"model:" + pr.Model}) - } - // A clean completion is a success for the stable-identity ejection breaker too - // — closes it (half-open recovery) if this identity had been ejected. - if sid := s.registry.GetProviderStableIdentity(pr.ProviderID); sid != "" { - if _, recovered := s.registry.RecordProviderServeOutcome(sid, true, 200, ""); recovered { - s.ddIncr("routing.provider_ejection_recovered", []string{"model:" + pr.Model}) - } - } -} - -// noteDispatchProviderError records a provider error received while the -// dispatch loop had NOT yet committed to that provider: it feeds the -// inference-error breaker, refunds the failed attempt's provider-specific -// reservation top-up, and, when boilerplate chunks from that provider were -// being held (deferred commit), discards them and emits the pre-content -// failover counter — the invisible-retry signal that replaces what used to be -// an in-band SSE error after a premature commit. Returns true when held -// chunks were discarded so callers skip their generic retry counter. -// -// The refund lives here because both ErrorCh senders (handleInferenceError and -// registry.Disconnect's pending flush) remove the pending request BEFORE -// pushing the error, so the arm's cancelDispatch sees RemovePending()==nil and -// skips its own refund — without this the custom-price surcharge reserved by -// reserveAdditionalForProvider would be stranded for the failed attempt. -// refundProviderExtra is idempotent (it resets ReservedMicroUSD to the base), -// so arms where cancelDispatch did refund are safe, and a failed pre-commit -// attempt never reaches settlement (its channels are closed and it is neither -// pending nor parked), so this can never double-credit against a settle. -func (s *Server) noteDispatchProviderError(provider *registry.Provider, pr *registry.PendingRequest, statusCode int, errStr, errReason, terminalCause string, held *[]string, causes ...protocol.CoordinatorInferenceErrorCause) (discardedHeld bool) { - if provider != nil { - s.noteInferenceError(provider.ID, pr, statusCode, errStr, errReason, terminalCause, causes...) - } - s.refundProviderExtra(pr) - if held == nil || len(*held) == 0 { - return false - } - *held = nil - s.ddIncr("inference.dispatches", []string{"status:retry_precontent"}) - return true -} - -// failedProviderVersion reads a provider's reported binary version under its -// lock (mirroring the policy.prefer owner reads). Captured when an attempt -// fails so the next attempt's Traits.AvoidVersion can steer the retry to a -// different build — a deterministic per-version bug must not burn every retry -// on identical binaries. -func failedProviderVersion(p *registry.Provider) string { - if p == nil { - return "" - } - p.Mu().Lock() - defer p.Mu().Unlock() - return p.Version -} - -// errModelTooLarge is the dispatch error returned when providers serve the -// requested model but none of them has enough total memory to ever load it. -// Distinct from "no provider available" so the caller rejects fast instead of -// queuing for 120s — queueing can't help a model that will never fit. -const errModelTooLarge = "model too large for any available provider" - -// errTTFTTooSlow is the dispatch error returned when providers are available -// but all of them exceed the per-request TTFT ceiling. Distinct from -// "no provider available" so the caller returns a retryable 429 instead of -// queueing for a provider that would miss the OpenRouter SLA target. -const errTTFTTooSlow = "all available providers exceed the TTFT target" - -// errFirstContentDeadlineExpired is returned when the request-absolute -// first-content clock runs out before an inference_request reaches the provider -// wire. No provider work was started, so callers surface a deadline 429 without -// charging provider health. -const errFirstContentDeadlineExpired = "first-content deadline expired before provider dispatch" - -// errRoutingScanSaturated is returned when no provider-selection scan slot -// (Server.routingScanSem) freed up within the request's remaining -// first-content budget: the coordinator itself is the bottleneck (the -// 2026-09-01 congestion collapse). No provider was scanned or contacted, so -// callers shed ONE capacity-shaped retryable 429 — never a 5xx, never more -// scans. -const errRoutingScanSaturated = "routing scan capacity saturated — coordinator busy" - -// errClientGoneBeforeScan is returned when the caller's context fired while -// the dispatch goroutine was parked for a provider-selection scan slot. No -// provider was scanned or contacted; the dispatch loop takes its ordinary -// client-gone terminal (cancelled route outcome, refund, no response body) — -// never the routing_saturated 429 or a rejection-ledger row. -const errClientGoneBeforeScan = "client disconnected before provider selection" - -// attempt0RouteAnchor returns the instant the attempt-0 route-latency EWMA -// sample is measured from — the SAME anchor applyTimingDecomposition uses for -// route_ms (MediaFetchedAt when a remote-media fetch happened, else -// ReservedAt) — so download or parse time can never fake routing distress. -// Zero when the request never stamped a reservation (bare test fixtures): -// the caller then records no sample. -func attempt0RouteAnchor(t *registry.RequestTiming) time.Time { - if t == nil { - return time.Time{} - } - if !t.MediaFetchedAt.IsZero() { - return t.MediaFetchedAt - } - return t.ReservedAt -} - -// consumerModel returns the model name to echo back to the consumer: the public -// alias they requested when set, otherwise the concrete build id (raw-id -// requests and any internal caller that didn't populate PublicModel). -func consumerModel(pr *registry.PendingRequest) string { - if pr.PublicModel != "" { - return pr.PublicModel - } - return pr.Model -} - -// rewriteChunkModel replaces the concrete build id in a streamed SSE chunk's -// "model" field with the public alias the consumer requested, so streaming -// responses never expose the underlying build/quant. No-op when the request -// used a raw build id (PublicModel == Model) or no alias was set. Uses a -// precise key+value string replace (both compact and spaced JSON forms) to -// avoid parsing every chunk on the hot path. -func rewriteChunkModel(chunk string, pr *registry.PendingRequest) string { - if pr.PublicModel == "" || pr.PublicModel == pr.Model { - return chunk - } - chunk = strings.ReplaceAll(chunk, `"model":"`+pr.Model+`"`, `"model":"`+pr.PublicModel+`"`) - chunk = strings.ReplaceAll(chunk, `"model": "`+pr.Model+`"`, `"model": "`+pr.PublicModel+`"`) - return chunk -} - -// resolveRequestedModel maps the consumer-requested model — which may be a -// public alias like "gemma-4-26b" — to the concrete build id used for routing, -// billing, and serving, returning the public name to echo back to the consumer. -// When the request used an alias it rewrites parsed["model"] and returns an -// updated rawBody so the provider receives the concrete build. Raw build ids -// pass through unchanged (publicModel == buildModel). ok=false means the alias -// currently has no usable build; the caller should surface a model_unavailable -// error. -func (s *Server) resolveRequestedModel( - parsed map[string]any, - rawBody []byte, - requested string, - allowedProviderSerials []string, - policy selfRoutePolicy, - traits registry.RequestTraits, -) (buildModel, publicModel string, newRawBody []byte, ok bool) { - buildID, isAlias, resolved := s.registry.ResolveModelConstrainedWithTraits( - requested, allowedProviderSerials, policy.ownerAccountID, - policy.enabled, policy.prefer, traits) - if !resolved { - return "", requested, rawBody, false - } - if !isAlias { - return requested, requested, rawBody, true - } - parsed["model"] = buildID - rb, err := marshalForwardBody(parsed) - if err != nil { - rb = rawBody - } - return buildID, requested, rb, true -} - -// aliasFallbackMode selects the failure policy for maybeFallbackAlias. -type aliasFallbackMode int - -const ( - // aliasFallbackCapacity routes to Previous whenever it has any free capacity. - aliasFallbackCapacity aliasFallbackMode = iota - // aliasFallbackTTFT additionally rejects Previous when its best TTFT estimate - // would miss the per-request ceiling (ttftThreshold). - aliasFallbackTTFT -) - -// maybeFallbackAlias keeps public aliases available during a desired-build -// saturation event. Alias resolution intentionally prefers Desired when it is -// routable, but if every desired provider is transiently full (aliasFallbackCapacity) -// or too slow to hit the TTFT ceiling (aliasFallbackTTFT) and Previous can serve, -// route this request to Previous instead of returning a fast 429 / slow stream. -// Hard constraints and permanent model-too-large failures are handled by the -// caller and do not use this fallback. The TTFT estimate for Previous is also -// returned so the caller does not need to recompute it. ttftThreshold is the -// request-local deadline pinned before admission and is only consulted in -// aliasFallbackTTFT mode. -func (s *Server) maybeFallbackAlias(parsed map[string]any, mode aliasFallbackMode, publicModel, currentModel string, estimatedPromptTokens, requestedMaxTokens int, ttftThreshold time.Duration, traits registry.RequestTraits, requiresVision bool, allowedProviderSerials []string) (string, int, int, int, time.Duration, bool, bool) { - if publicModel == "" || publicModel == currentModel { - return currentModel, 0, 0, 0, 0, false, false - } - target, ok := s.registry.AliasTarget(publicModel) - if !ok || target.Desired != currentModel || target.Previous == "" { - return currentModel, 0, 0, 0, 0, false, false - } - // Previous must be a real, non-shed catalog build before we probe it. - if s.modelShed(target.Previous, publicModel) || !s.registry.IsModelInCatalog(target.Previous) { - return currentModel, 0, 0, 0, 0, false, false - } - // A SINGLE Previous-build probe drives both modes; the mode only decides - // whether the probe's TTFT estimate also gates the fallback. - candidates, rejections, tooLarge, bestTTFT, hasTTFT := s.registry.QuickCapacityCheckWithTTFTForRequest(target.Previous, estimatedPromptTokens, requestedMaxTokens, traits, requiresVision, allowedProviderSerials...) - enforceTTFT := mode == aliasFallbackTTFT - if candidates <= 0 || (enforceTTFT && ttftTooSlow(bestTTFT, hasTTFT, ttftThreshold)) { - // No fallback. TTFT mode reports the probed Previous build (the caller - // uses it as the alternate TTFT estimate); capacity mode discards the - // model, so keep the unchanged current build. - failModel := currentModel - if enforceTTFT { - failModel = target.Previous - } - return failModel, candidates, rejections, tooLarge, bestTTFT, hasTTFT, false - } - parsed["model"] = target.Previous - return target.Previous, candidates, rejections, tooLarge, bestTTFT, hasTTFT, true -} - -func ttftTooSlow(bestTTFT time.Duration, hasTTFT bool, threshold time.Duration) bool { - return hasTTFT && bestTTFT > threshold -} - -// hardTTFTGateApplies reports whether the scheduler's token-prefill estimate is -// authoritative enough to reject this request before dispatch. Media requests -// run CPU decode plus a separate vision tower before text prefill; neither cost -// exists in estimatedTTFTFromSnapshot, so treating that partial estimate as a -// hard ceiling rejects healthy video/image requests on a number that cannot -// predict their TTFT. They still use the best-available provider and remain -// bounded by the same request-absolute first-content deadline. -func (s *Server) hardTTFTGateApplies(requiresVision bool) bool { - return s.ttftHardReject && !requiresVision -} - -func fasterTTFTEstimate(primaryModel string, primary time.Duration, alternateModel string, alternate time.Duration, alternateOK bool) (string, time.Duration) { - if alternateOK && alternate < primary { - return alternateModel, alternate - } - return primaryModel, primary -} - -func (s *Server) estimateTTFTRetryAfter(model string, bestTTFT, threshold time.Duration) int { - overage := bestTTFT - threshold - seconds := int(math.Ceil(overage.Seconds())) - if base := s.estimateRetryAfter(model); seconds < base { - seconds = base - } - if seconds < 2 { - seconds = 2 - } - if seconds > 30 { - seconds = 30 - } - return seconds -} - -func (s *Server) writeTTFTTooSlow(w http.ResponseWriter, model, publicModel string, bestTTFT, threshold time.Duration) { - retryAfter := s.estimateTTFTRetryAfter(model, bestTTFT, threshold) - w.Header().Set("Retry-After", strconv.Itoa(retryAfter)) - s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:ttft_429"}) - writeJSON(w, http.StatusTooManyRequests, errorResponse("rate_limit_exceeded", - ttftTooSlowMessage(publicModel, bestTTFT, threshold, retryAfter), - withCode("rate_limit_exceeded"))) -} - -// ttftTooSlowMessage is the single wording for a fleet-wide TTFT rejection. -func ttftTooSlowMessage(publicModel string, bestTTFT, threshold time.Duration, retryAfter int) string { - return fmt.Sprintf( - "all providers for model %q are above the %ds TTFT target (best estimate %.1fs); retry after %ds", - publicModel, int(math.Ceil(threshold.Seconds())), bestTTFT.Seconds(), retryAfter) -} - -func (s *Server) triggerWarmPool() { - if s == nil || s.registry == nil { - return - } - s.registry.RequestWarmPoolTrigger() -} - -func (s *Server) recordWarmPoolQueueState(model string) { - if s == nil || s.registry == nil || s.registry.Queue() == nil { - return - } - depth, oldest := s.registry.Queue().QueueStats(model) - if depth <= 0 { - s.registry.RecordWarmPoolQueueCleared(model) - return - } - s.registry.RecordWarmPoolQueueEnqueued(model, depth, oldest) - s.triggerWarmPool() -} - -// ttftMsForRejection converts a pre-flight TTFT estimate to milliseconds for the -// rejection ledger, returning 0 when the pre-flight produced no estimate. -func ttftMsForRejection(bestTTFT time.Duration, hasTTFT bool) float64 { - if !hasTTFT { - return 0 - } - return float64(bestTTFT.Milliseconds()) -} - -// rejectionSamplingParams captures only the non-content sampling knobs already -// parsed from an inbound request body for the rejection ledger. It never -// includes prompt/message/input content. Returns nil when none are present. -func rejectionSamplingParams(parsed map[string]any) json.RawMessage { - if parsed == nil { - return nil - } - knobs := make(map[string]any, 4) - for _, k := range []string{"temperature", "top_p", "presence_penalty", "frequency_penalty"} { - if v, ok := parsed[k]; ok { - knobs[k] = v - } - } - if len(knobs) == 0 { - return nil - } - b, err := json.Marshal(knobs) - if err != nil { - return nil - } - return b -} - -type routeDecisionRecorder func(*registry.Provider, *registry.PendingRequest, registry.RoutingDecision) - -// dispatchReserver selects and atomically reserves a provider for an -// already-constructed PendingRequest. It is the ONE seam between provider -// SELECTION and the single prepare/encrypt/write funnel in -// dispatchWithReserver: wave-2 callers plug in the retained-plan variants -// (ReserveNextFromPlan / RefreshDispatchPlan) without forking the funnel. -// The returned plan is non-nil only for scan-backed reservers that retain -// alternates. -type dispatchReserver func(pr *registry.PendingRequest, excludeIDs []string) (*registry.Provider, registry.RoutingDecision, *registry.DispatchPlan) - -// dispatchOneProvider encrypts and sends an inference request to a single -// provider selected by a fresh full scan. It returns the pending request and -// provider on success, or an error string on failure, plus the bounded -// DispatchPlan of provisional alternates retained from the SAME scan (nil -// whenever no provider was reserved) so retries and speculative backups can -// consume retained identities instead of rescanning the fleet (Routing v2 -// Phase 3). The excludeProviders set is updated on failure. selfRoutePolicy -// and its resolvers live in self_route.go. -func (s *Server) dispatchOneProvider( - r *http.Request, - model string, - publicModel string, - rawBody []byte, - consumerKey string, - consumerLocation *store.ProviderLocation, - reservedMicroUSD int64, - estimatedPromptTokens int, - requestDeadline time.Duration, - requestedMaxTokens int, - tokenAdmission registry.TokenAdmission, - requiresVision bool, - traits registry.RequestTraits, - allowedProviderSerials []string, - isResponsesAPI bool, - policy selfRoutePolicy, - timing *registry.RequestTiming, - serviceReservation bool, - cachePlan registry.CachePlan, - excludeProviders map[string]struct{}, - attempt int, - rp *registry.RequestProfile, - backupOf string, - recordRoute routeDecisionRecorder, - onDispatched func(), -) ( - provider *registry.Provider, - pr *registry.PendingRequest, - decision registry.RoutingDecision, - plan *registry.DispatchPlan, - lastErr string, - lastErrCode int, -) { - return s.dispatchWithReserver( - r, model, publicModel, rawBody, consumerKey, consumerLocation, - reservedMicroUSD, estimatedPromptTokens, requestDeadline, - requestedMaxTokens, tokenAdmission, requiresVision, traits, - allowedProviderSerials, isResponsesAPI, policy, timing, - serviceReservation, cachePlan, excludeProviders, attempt, rp, backupOf, - recordRoute, onDispatched, - true, // ReserveProviderWithPlan is the O(fleet) full scan - func(pr *registry.PendingRequest, excludeIDs []string) (*registry.Provider, registry.RoutingDecision, *registry.DispatchPlan) { - return s.registry.ReserveProviderWithPlan(model, pr, excludeIDs...) - }, - ) -} - -// dispatchWithReserver is the single prepare/encrypt/write funnel behind every -// provider dispatch: pending construction and admission stamps, the pluggable -// reservation, the billing surcharge, E2E encryption, and the -// deadline-bounded provider write, with releaseUnsentDispatch cleanup on every -// failure path. onDispatched (nil-safe) fires inside the write handoff -// callback — the same instant Timing.DispatchedAt is stamped — so -// providerDispatches counts frames that actually reached a provider, never -// loop attempts. -func (s *Server) dispatchWithReserver( - r *http.Request, - model string, - publicModel string, - rawBody []byte, - consumerKey string, - consumerLocation *store.ProviderLocation, - reservedMicroUSD int64, - estimatedPromptTokens int, - requestDeadline time.Duration, - requestedMaxTokens int, - tokenAdmission registry.TokenAdmission, - requiresVision bool, - traits registry.RequestTraits, - allowedProviderSerials []string, - isResponsesAPI bool, - policy selfRoutePolicy, - timing *registry.RequestTiming, - serviceReservation bool, - cachePlan registry.CachePlan, - excludeProviders map[string]struct{}, - attempt int, - rp *registry.RequestProfile, - backupOf string, - recordRoute routeDecisionRecorder, - onDispatched func(), - fullScan bool, - reserve dispatchReserver, -) ( - provider *registry.Provider, - pr *registry.PendingRequest, - decision registry.RoutingDecision, - plan *registry.DispatchPlan, - lastErr string, - lastErrCode int, -) { - receivedAt := timingReceivedAt(timing) - _, dispatchable := firstContentBudgetMillis(receivedAt, requestDeadline) - if !dispatchable { - return nil, nil, decision, nil, errFirstContentDeadlineExpired, http.StatusGatewayTimeout - } - - requestID := uuid.New().String() - ap := rp.NewAttempt(requestID, attempt, backupOf) - s.recordPredictivePolicy(ap, policy, requiresVision) - ap.Mark(registry.StampAttemptStart) - // Any failure return closes the attempt as not dispatched (terminal half; the handler half lands in finalizeProfile); - // a dispatched attempt is left for the provider terminal / relay to close. - defer func() { - if provider == nil { - closeUndispatchedAttempt(ap, lastErr, lastErrCode) - } - }() - pr = ®istry.PendingRequest{ - RequestID: requestID, - Profile: ap, - // Attempt is stamped at construction — BEFORE the request is encrypted - // and sent to the provider — so a fast provider that returns - // inference_complete immediately is correlated to the right route row. - // Setting it after the send (on the dispatch goroutine) would race the - // provider WS reader goroutine's handleComplete read of pr.Attempt. - Attempt: attempt, - Model: model, - PublicModel: publicModel, - ConsumerKey: consumerKey, - KeyID: keyIDFromContext(r.Context()), - KeyLimitMicroUSD: keyLimitMicroFromContext(r.Context()), - KeyLimitReset: keyLimitResetFromContext(r.Context()), - ConsumerLocation: consumerLocation, - IsResponsesAPI: isResponsesAPI, - EstimatedPromptTokens: estimatedPromptTokens, - RequiresVision: requiresVision, - Traits: traits, - RequestedMaxTokens: requestedMaxTokens, - TokenAdmission: tokenAdmission, - CachePlan: cachePlan, - ReservedMicroUSD: reservedMicroUSD, - BaseReservedMicroUSD: reservedMicroUSD, - ServiceReservation: serviceReservation, - AllowedProviderSerials: allowedProviderSerials, - SelfRouteOnly: policy.enabled, - PreferOwner: policy.prefer, - OwnerAccountID: policy.ownerAccountID, - FreeSelfRoute: policy.enabled, - MetadataDetails: metadataDetailsFromRequest(r), - AcceptedCh: make(chan struct{}, 1), - ChunkCh: make(chan registry.ProviderChunk, chunkBufferSize), - CompleteCh: make(chan protocol.UsageInfo, 1), - ErrorCh: make(chan protocol.InferenceErrorMessage, 1), - Timing: timing, - } - if !receivedAt.IsZero() { - pr.FirstContentDeadline = receivedAt.Add(requestDeadline) - } - - // Public inference routes (not self-route / prefer-owner) enforce the - // OpenRouter TTFT ceiling inside the scheduler. This makes the preflight - // check authoritative: the router cannot select a provider whose estimated - // TTFT is above the threshold. - // Routing v2 (P1 fix): only enforce the TTFT ceiling inside the scheduler when - // the HARD gate is on. In soft mode (default) MaxTTFTMs stays 0 so the primary - // dispatch serves the best-available provider instead of re-rejecting an - // over-threshold request the preflight already chose to soft-serve. (Mirrors - // queueMaxTTFTMs, which already returns 0 in soft mode.) - if !policy.enabled && !policy.prefer && s.hardTTFTGateApplies(requiresVision) { - pr.MaxTTFTMs = float64(requestDeadline.Milliseconds()) - } - // Refresh immediately before reservation: every retry spends the same - // absolute clock, so the scheduler must never see the original ceiling. - if !pr.RefreshFirstContentBudget(time.Now()) { - return nil, nil, decision, nil, errFirstContentDeadlineExpired, http.StatusGatewayTimeout - } - // Routing v2 W2: soft per-request decode floor (0 = off). Applies to all - // routes; it only ranks providers, never rejects. - pr.MinDecodeTPS = s.minDecodeTPS - - excludeList := func() []string { - ids := make([]string, 0, len(excludeProviders)) - for id := range excludeProviders { - ids = append(ids, id) - } - return ids - } - - // noteSelectionSample feeds the attempt-0 route-latency distress EWMA - // behind estimateRetryAfter (2026-09-01: route p50 40ms → 4.6s while the - // empty-queue heuristic kept answering "retry in 2s"). Anchored exactly - // where applyTimingDecomposition anchors route_ms (MediaFetchedAt when - // set, else ReservedAt) so a multi-second media download or slow body - // parse can never masquerade as routing distress. Called on BOTH the - // successful reservation (at the RoutedAt stamp) and every failed - // attempt-0 selection (semaphore acquisition timeout, scan that yields no - // provider): under TOTAL overload no selection ever succeeds, and an - // EWMA fed only by successes would sit at 0 — keeping Retry-After at the - // legacy 2s exactly when distress scaling matters most. - noteSelectionSample := func() { - if attempt != 0 { - return - } - if anchor := attempt0RouteAnchor(timing); !anchor.IsZero() { - s.noteAttempt0RouteLatency(time.Since(anchor)) - } - } - - // Bound concurrent provider-selection scans (2026-09-01 congestion - // collapse: retry-amplified inbound × a fresh full fleet scan per attempt - // saturated every coordinator CPU). Only O(fleet) reservers take a slot — - // the full scan, the plan REFRESH (itself a full re-scan), and the - // speculative-backup scan. A retained-plan step (ReserveNextFromPlan) - // revalidates at most the plan's bounded entries, so it bypasses the - // semaphore: a held slot must never starve the cheap retry path that - // exists precisely to avoid rescans. The wait is bounded by the request's - // remaining first-content budget: a goroutine parks cheaply on the channel - // and either scans as soon as a slot frees or sheds capacity-shaped - // (errRoutingScanSaturated → one retryable 429) once the budget is gone. - if fullScan { - switch s.acquireRoutingScanSlot( - firstTokenRemainingSince(receivedAt, requestDeadline), - r.Context().Done(), - ) { - case scanSlotClientGone: - // The caller vanished while parked for a slot: this is the - // ordinary client-gone terminal, never the routing_saturated - // 429/rejection row (and no distress sample — a vanished caller - // proves nothing about selection latency). - return nil, nil, decision, nil, errClientGoneBeforeScan, 0 - case scanSlotTimeout: - noteSelectionSample() - return nil, nil, decision, nil, errRoutingScanSaturated, http.StatusTooManyRequests - } - } - provider, decision, plan = reserve(pr, excludeList()) - ap.SetReservationTTFTCeiling(pr.MaxTTFTMs) - ap.Mark(registry.StampReserveDone) - ap.SetDecision(decision) - if fullScan { - s.releaseRoutingScanSlot() - } - if provider == nil { - noteSelectionSample() - // Providers serve this model but none can physically fit it: don't make - // the caller queue/retry for something that will never load. - if decision.CandidateCount == 0 && decision.CapacityRejections == 0 && decision.ModelTooLargeRejections > 0 { - return nil, nil, decision, plan, errModelTooLarge, http.StatusServiceUnavailable - } - // Providers are available but all exceed the TTFT ceiling. Fail fast - // with a retryable 429 rather than queueing or routing to a slow - // provider. - if decision.TTFTRejections > 0 { - return nil, nil, decision, plan, errTTFTTooSlow, http.StatusTooManyRequests - } - return nil, nil, decision, plan, "no provider available", http.StatusServiceUnavailable - } - pendingCleanup := true - cleanupPending := func() { - if pendingCleanup { - s.releaseUnsentDispatch(provider, pr) - pendingCleanup = false - } - } - defer cleanupPending() - if pr.Timing != nil { - pr.Timing.RoutedAt = time.Now() - } - noteSelectionSample() - if ap != nil { - ap.ProviderID = provider.ID - provider.Mu().Lock() - ap.ProviderVersion = provider.Version - ap.ChipFamily = provider.Hardware.ChipFamily - provider.Mu().Unlock() - ap.KVBackend, _ = provider.SlotKVBackendTags(model) - } - if recordRoute != nil { - recordRoute(provider, pr, decision) - } - - // A request settles FREE when it's served by a machine the caller owns: - // exclusive self-route (policy.enabled) always, OR a prefer request whose - // SELECTED provider is the caller's own machine (settlement refunds it to - // zero). In that case there is no payout and no reservation to top up — and - // applying a provider custom price above the platform rate would wrongly 429 - // the free owned route, so skip both the payout warning and the top-up. - settlesFree := policy.enabled - if !settlesFree && policy.prefer { - provider.Mu().Lock() - settlesFree = policy.ownerAccountID != "" && provider.AccountID == policy.ownerAccountID - provider.Mu().Unlock() - } - - if s.billing != nil && !settlesFree && !providerHasPayoutDestination(provider) { - s.logger.Warn("provider missing payout destination, crediting to internal ledger", - "provider_id", provider.ID) - } - - // Free (owned) requests are settled at zero cost (handleComplete), so there - // is no reservation to top up for a provider's custom price. - if s.billing != nil && !settlesFree { - _, err := s.reserveAdditionalForProvider(pr, provider) - if err != nil { - cleanupPending() - excludeProviders[provider.ID] = struct{}{} - if errors.Is(err, store.ErrInsufficientBalance) { - return nil, nil, decision, plan, "insufficient funds for provider price", http.StatusPaymentRequired - } - s.logger.Error("provider reservation failed (DB error)", "provider_id", provider.ID, "error", err) - return nil, nil, decision, plan, "service temporarily unavailable — please retry", http.StatusServiceUnavailable - } - } - ap.Mark(registry.StampTopupDone) - // refundExtra credits back the provider-specific surcharge that - // reserveAdditionalForProvider may have added. The caller's - // refundReservation only covers the base reservation. - refundExtra := func() { - extra := pr.ReservedMicroUSD - reservedMicroUSD - if extra > 0 { - start := time.Now() - _ = s.store.Credit(consumerKey, extra, store.LedgerRefund, "reservation_extra_refund:"+requestID) - s.ddIncr("billing.reservation_extra_refunds", []string{"model:" + model}) - s.ddHistogram("store.credit.latency_ms", float64(time.Since(start).Milliseconds()), []string{"op:reservation_extra_refund"}) - pr.ReservedMicroUSD = reservedMicroUSD - } - } - - // E2E encryption - if provider.PublicKey == "" { - refundExtra() - cleanupPending() - excludeProviders[provider.ID] = struct{}{} - return nil, nil, decision, plan, "no provider with E2E encryption", http.StatusServiceUnavailable - } - - providerPubKey, err := e2e.ParsePublicKey(provider.PublicKey) - if err != nil { - refundExtra() - cleanupPending() - excludeProviders[provider.ID] = struct{}{} - return nil, nil, decision, plan, "provider public key invalid", http.StatusServiceUnavailable - } - - sessionKeys, err := e2e.GenerateSessionKeys() - if err != nil { - refundExtra() - cleanupPending() - return nil, nil, decision, plan, "failed to generate session keys", http.StatusInternalServerError - } - - if err := s.registry.PrepareCacheAttempt(pr, provider); err != nil { - s.registry.ForgetCacheAttempt(pr) - refundExtra() - cleanupPending() - return nil, nil, decision, plan, "failed to prepare cache-safe request", http.StatusInternalServerError - } - // Pre-fix providers crash on a vision request carrying sampling penalties; - // strip them for those providers only. Protocol-0 providers additionally get - // a coordinator-authored prompt_cache_key only inside this sealed body. - sealedBody, err := bodyForCacheAttempt(rawBody, requiresVision, provider, pr) - if err != nil { - s.registry.ForgetCacheAttempt(pr) - refundExtra() - cleanupPending() - if errors.Is(err, errProviderBodyTooLarge) { - excludeProviders[provider.ID] = struct{}{} - return nil, nil, decision, plan, err.Error(), http.StatusRequestEntityTooLarge - } - return nil, nil, decision, plan, "failed to prepare provider request", http.StatusInternalServerError - } - encrypted, err := e2e.Encrypt(sealedBody, providerPubKey, sessionKeys) - if err != nil { - s.registry.ForgetCacheAttempt(pr) - refundExtra() - cleanupPending() - return nil, nil, decision, plan, "failed to encrypt request", http.StatusInternalServerError - } - if pr.Timing != nil { - pr.Timing.EncryptedAt = time.Now() - } - ap.Mark(registry.StampEncrypted) - pr.SessionPrivKey = &sessionKeys.PrivateKey - // pr.ReservedMicroUSD was already set in the struct literal and may have - // been increased by reserveAdditionalForProvider above. Don't overwrite. - - // Bound the provider write by the request-absolute first-token clock (see - // firstTokenWriteContext): a congested write lane must not silently eat - // the budget while the aggregator's cancel clock keeps running. - writeCtx, cancelWrite := firstTokenWriteContext( - r.Context(), receivedAt, requestDeadline) - ap.Mark(registry.StampWriteSubmitted) - _, writeErr := writeProviderInferenceRequestDeferred( - writeCtx, - provider, - providerInferenceFrameBuilder( - requestID, encrypted.EphemeralPublicKey, encrypted.Ciphertext, pr), - func(metadata registry.TextFrameWriteMetadata) { - if pr.Timing != nil { - pr.Timing.DispatchedAt = metadata.DequeuedAt - } - if onDispatched != nil { - onDispatched() - } - ap.MarkAt(registry.StampWriteDequeued, metadata.DequeuedAt) - }, - ) - cancelWrite() - if writeErr == nil { - ap.Mark(registry.StampWriteDone) - } - if writeErr != nil { - s.registry.ForgetCacheAttempt(pr) - refundExtra() - cleanupPending() - excludeProviders[provider.ID] = struct{}{} - if errors.Is(writeErr, context.DeadlineExceeded) || - errors.Is(writeErr, errFirstContentDeadlineAtWriter) { - // The writer either discarded the frame before handoff or aborted - // its connection during an in-flight write. Cancel defensively in - // case the provider decoded the final bytes before disconnect. - ap.Mark(registry.StampCancelSent) - s.sendProviderCancel(provider, requestID) - return nil, nil, decision, plan, errFirstContentDeadlineExpired, http.StatusGatewayTimeout - } - return nil, nil, decision, plan, "failed to send request to provider", http.StatusBadGateway - } - pendingCleanup = false - - return provider, pr, decision, plan, "", 0 -} - -// releaseUnsentDispatch returns a reservation after frame construction or -// socket handoff fails. Resolving speculative completion arbitration first -// guarantees a provider completion already waiting off the read loop cannot -// remain stranded after pending state is removed. -func (s *Server) releaseUnsentDispatch( - provider *registry.Provider, - pr *registry.PendingRequest, -) { - if provider == nil || pr == nil { - return - } - pr.ResolveSpeculativeEmptyCompletion(false) - provider.RemovePending(pr.RequestID) - s.registry.SetProviderIdle(provider.ID) -} - -// penaltySafeProviderVersion is the first provider release whose VLM penalty -// path handles repetition/presence/frequency penalties without crashing (the -// TokenRing 2D-prompt fix). Providers below it crash on a vision request that -// carries any of these fields, so the coordinator strips them before sealing -// for such a provider. Keep in sync with the release that ships the fix. -const penaltySafeProviderVersion = "0.6.7" - -// visionPenaltyFields crash the pre-fix VLM penalty path on image requests. -var visionPenaltyFields = []string{"repetition_penalty", "presence_penalty", "frequency_penalty"} - -// bodyForProvider returns the request body to seal for `provider`. It equals -// rawBody, except a vision request routed to a pre-fix provider has the -// crash-inducing penalty fields stripped. Fixed providers receive the penalties -// unchanged. Per-provider (not pre-routing) so a retry on a fixed provider keeps -// them. Remove once MIN_PROVIDER_VERSION clears all pre-fix builds. -func bodyForProvider(rawBody []byte, requiresVision bool, provider *registry.Provider) []byte { - if !requiresVision { - return rawBody - } - if provider.Version != "" && !semverLess(provider.Version, penaltySafeProviderVersion) { - return rawBody // fixed provider — pass penalties through - } - // A body carrying none of the penalty fields at its top level is returned - // unchanged without decoding it — the same outcome the decode path reaches - // through changed=false, minus a full-body parse per sizing probe. - if has, ok := topLevelObjectHasAnyKey(rawBody, visionPenaltyFields); ok && !has { - return rawBody - } - parsed, err := decodeInferenceJSONObject(rawBody) - if err != nil { - return rawBody - } - changed := false - for _, key := range visionPenaltyFields { - if _, ok := parsed[key]; ok { - delete(parsed, key) - changed = true - } - } - if !changed { - return rawBody - } - if stripped, err := marshalForwardBody(parsed); err == nil { - return stripped - } - return rawBody -} - -var errProviderBodyTooLarge = errors.New("provider request body too large") - -type providerBodyTooLargeError struct { - size int -} - -func (e *providerBodyTooLargeError) Error() string { - return fmt.Sprintf("%s: %d bytes exceeds the %d-byte limit after cache isolation", - errProviderBodyTooLarge, e.size, maxInferenceBodyBytes) -} - -func (e *providerBodyTooLargeError) Unwrap() error { - return errProviderBodyTooLarge -} - -func oversizedProviderBodyBytes(err error) int { - var sizeErr *providerBodyTooLargeError - if errors.As(err, &sizeErr) { - return sizeErr.size - } - return 0 -} - -func legacyCacheBustBodyBytes( - rawBody []byte, - requiresVision bool, - provider *registry.Provider, -) (int, error) { - if provider == nil { - return 0, nil - } - return cacheAttemptSizeError( - bodyForProvider(rawBody, requiresVision, provider), - strings.Repeat("x", registry.LegacyCacheBustKeyLength)) -} - -func providerBodySizeError( - rawBody []byte, - requiresVision bool, - provider *registry.Provider, -) (int, error) { - if provider == nil { - return 0, nil - } - provider.Mu().Lock() - usesLegacyCacheBust := provider.PrefixCacheProtocol < 1 - provider.Mu().Unlock() - legacyKey := "" - if usesLegacyCacheBust { - legacyKey = strings.Repeat("x", registry.LegacyCacheBustKeyLength) - } - return cacheAttemptSizeError( - bodyForProvider(rawBody, requiresVision, provider), legacyKey) -} - -func minimumLegacyCacheBustOverflow(rawBody []byte, requiresVision bool) (int, error) { - // An empty-version provider exercises the only provider-specific shrinking - // transform: legacy vision penalty removal. Raise a fleet-wide protocol floor - // only when even that smallest valid protocol-0 body exceeds the cap. - return legacyCacheBustBodyBytes(rawBody, requiresVision, ®istry.Provider{}) -} - -func routingTraitsForProviderBody( - hasTools bool, - providerBody []byte, - requiresVision bool, -) (registry.RequestTraits, error) { - traits := registry.RequestTraits{HasTools: hasTools} - _, err := minimumLegacyCacheBustOverflow(providerBody, requiresVision) - if errors.Is(err, errProviderBodyTooLarge) { - traits.MinPrefixCacheProtocol = 1 - } - return traits, err -} - -// bodyForCacheAttempt returns the body to seal for one dispatch attempt: the -// provider-specific body (bodyForProvider) with the protocol-0 cache-bust key -// added as prompt_cache_key when the attempt carries one, size-checked -// against the sealed-frame cap. -func bodyForCacheAttempt(rawBody []byte, requiresVision bool, provider *registry.Provider, pr *registry.PendingRequest) ([]byte, error) { - body := bodyForProvider(rawBody, requiresVision, provider) - if pr == nil || pr.LegacyCacheBustKey == "" { - if len(body) > maxInferenceBodyBytes { - return nil, &providerBodyTooLargeError{size: len(body)} - } - return body, nil - } - keyJSON, err := json.Marshal(pr.LegacyCacheBustKey) - if err != nil { - return nil, err - } - sealed, ok := spliceTopLevelMember(body, legacyCacheBustField, keyJSON) - if !ok { - if sealed, err = sealLegacyCacheBust(body, keyJSON); err != nil { - return nil, err - } - } - if len(sealed) > maxInferenceBodyBytes { - return nil, &providerBodyTooLargeError{size: len(sealed)} - } - return sealed, nil -} - -// defaultMaxOutputTokens is the ceiling injected into requests that don't set -// max_tokens. It bounds the worst-case cost of a single inference so the -// pre-flight balance reservation covers the entire generation; without this -// cap a consumer could stream output exceeding their reservation and the -// post-inference charge would fail silently (see GitHub issue #33). Consumers -// who need longer generations must set max_tokens explicitly and carry the -// balance to cover it. -const defaultMaxOutputTokens = 8192 - -// explicitMaxTokens returns the consumer-specified max output tokens from any -// of the recognized field names, or 0 if none were set. -func explicitMaxTokens(parsed map[string]any) int { - for _, key := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens"} { - if n, ok := intFromRequestValue(parsed[key]); ok && n > 0 { - return n - } - } - return 0 -} - -// reservationCost is the pre-flight worst-case cost for a text inference -// request. It mirrors the platform-price branch of handleComplete's billing -// so the reservation covers any platform-level custom price for the model; -// without this, a platform override above the built-in default would leave -// the reservation short and the post-inference clamp would silently -// undercharge. Provider-specific custom prices are not known until dispatch -// commits to a provider, so a provider that sets a custom price above the -// platform rate accepts revenue capped at the reservation. -func (s *Server) reservationCost(model string, promptTokens, maxTokens int) int64 { - customIn, customOut, hasCustom := s.store.GetModelPrice("platform", model) - return payments.CalculateCostWithOverrides(model, promptTokens, maxTokens, customIn, customOut, hasCustom) -} - -func (s *Server) refundReservedBalance(pr *registry.PendingRequest, reference string) bool { - if pr == nil || pr.ReservedMicroUSD <= 0 { - return false - } - if reference == "" { - reference = "reservation_refund:" + pr.RequestID - } - start := time.Now() - finalized, err := pr.FinalizeReservation(func() error { - if pr.ServiceReservation { - s.releaseServiceReservation(pr, "refund") - return nil - } - return s.store.Credit(pr.ConsumerKey, pr.ReservedMicroUSD, store.LedgerRefund, reference) - }) - if err != nil { - s.logger.Error("failed to refund reservation", - "request_id", pr.RequestID, - "consumer_key", pr.ConsumerKey, - "reserved_micro_usd", pr.ReservedMicroUSD, - "error", err, - ) - return false - } - if !finalized { - return false - } - tags := []string{"model:" + pr.Model, "mode:" + reservationMetricMode(pr.ServiceReservation)} - s.ddIncr("billing.reservation_refunds", tags) - if !pr.ServiceReservation { - s.ddIncr("billing.reservation_releases", append(tags, "reason:refund")) - s.ddHistogram("store.credit.latency_ms", float64(time.Since(start).Milliseconds()), []string{"op:reservation_refund"}) - } - return true -} - -// routeLatencyEWMAAlpha weights the newest attempt-0 route-latency sample in -// the distress EWMA: ~10 healthy requests pull a degraded average back under -// the threshold once the collapse clears. -const routeLatencyEWMAAlpha = 0.2 - -// degradedRouteEWMAThresholdMs is the attempt-0 route-latency EWMA above which -// estimateRetryAfter switches from the queue-depth heuristic to distress -// scaling. Healthy routing runs ~40ms; anything over a second means the -// coordinator itself is the bottleneck. -const degradedRouteEWMAThresholdMs = 1000.0 - -// maxDistressRetryAfter caps the distress-scaled Retry-After (seconds). -const maxDistressRetryAfter = 60 - -// noteAttempt0RouteLatency folds one attempt-0 route latency (ReceivedAt → -// RoutedAt) into the distress EWMA. Called from dispatchWithReserver where -// RoutedAt is stamped; negative samples (clock skew) are dropped. -func (s *Server) noteAttempt0RouteLatency(d time.Duration) { - ms := float64(d) / float64(time.Millisecond) - if ms < 0 { - return - } - s.routeLatencyMu.Lock() - if s.routeLatencyEWMAMs == 0 { - s.routeLatencyEWMAMs = ms - } else { - s.routeLatencyEWMAMs = routeLatencyEWMAAlpha*ms + - (1-routeLatencyEWMAAlpha)*s.routeLatencyEWMAMs - } - s.routeLatencyMu.Unlock() -} - -// attempt0RouteEWMAMs reads the current attempt-0 route-latency EWMA (ms). -func (s *Server) attempt0RouteEWMAMs() float64 { - s.routeLatencyMu.Lock() - defer s.routeLatencyMu.Unlock() - return s.routeLatencyEWMAMs -} - -// estimateRetryAfter returns a suggested wait time in seconds before retrying -// a request for the given model. Based on queue depth as a rough proxy for -// fleet backlog. OpenRouter uses the Retry-After header to schedule retries. -// -// Distress scaling (2026-09-01 congestion collapse): queue depth alone was a -// LIAR under CPU saturation — the queue was empty (nothing could even reach -// it), so every 429 carried "Retry-After: 2" and upstream obligingly hammered -// the coordinator every 2s, sustaining the death loop. When the attempt-0 -// route-latency EWMA shows routing itself is degraded (> 1s), the answer -// scales with the observed degradation — max(base, ceil(EWMA seconds)×5), -// capped at 60s — so upstream backoff actually relieves pressure. Queue-depth -// behavior is unchanged while routing is healthy. -func (s *Server) estimateRetryAfter(model string) int { - estimate := 2 // Light load, retry soon - if queueDepth := s.registry.Queue().QueueSize(model); queueDepth > 0 { - // Rough estimate: each queued request takes ~3 seconds to drain. - estimate = queueDepth * 3 - if estimate < 2 { - estimate = 2 - } - if estimate > 30 { - estimate = 30 - } - } - if ewmaMs := s.attempt0RouteEWMAMs(); ewmaMs > degradedRouteEWMAThresholdMs { - scaled := int(math.Ceil(ewmaMs/1000)) * 5 - if scaled > maxDistressRetryAfter { - scaled = maxDistressRetryAfter - } - if scaled > estimate { - estimate = scaled - } - } - return estimate -} - -// writeServiceUnavailable writes a retryable 503 with a Retry-After header so -// clients (and OpenRouter) can schedule the retry instead of blind backoff. -func (s *Server) writeServiceUnavailable(w http.ResponseWriter, model string) { - w.Header().Set("Retry-After", strconv.Itoa(s.estimateRetryAfter(model))) - writeJSON(w, http.StatusServiceUnavailable, errorResponse("service_unavailable", - "service temporarily unavailable — please retry")) -} - -func providerHasPayoutDestination(provider *registry.Provider) bool { - if provider == nil { - return false - } - provider.Mu().Lock() - defer provider.Mu().Unlock() - return provider.AccountID != "" -} - -func providerPricingKeys(provider *registry.Provider) string { - if provider == nil { - return "" - } - provider.Mu().Lock() - defer provider.Mu().Unlock() - return provider.AccountID -} - -func (s *Server) providerReservationCost(provider *registry.Provider, model string, promptTokens, maxTokens int) int64 { - accountID := providerPricingKeys(provider) - if accountID != "" { - customIn, customOut, hasCustom := s.store.GetModelPrice(accountID, model) - if hasCustom { - return payments.CalculateCostWithOverrides(model, promptTokens, maxTokens, customIn, customOut, true) - } - } - return s.reservationCost(model, promptTokens, maxTokens) -} - -// isServiceConsumer reports whether the account is a service/wholesale account -// (e.g. OpenRouter). Such accounts are billed at the advertised platform price, -// so the provider-price reservation top-up and provider custom pricing are -// skipped for them. A failed lookup falls back to false (normal consumer). -func (s *Server) isServiceConsumer(accountID string) bool { - if accountID == "" { - return false - } - if u, err := s.store.GetUserByAccountID(accountID); err == nil && u != nil { - return u.Role == store.RoleService - } - return false -} - -func (s *Server) reserveAdditionalForProvider(pr *registry.PendingRequest, provider *registry.Provider) (int64, error) { - if pr == nil { - return 0, fmt.Errorf("pending request is required") - } - // Service/wholesale consumers are billed at the platform price at - // settlement, so don't top the reservation up to a provider's higher custom - // price — the base platform reservation already covers the actual charge. - if s.isServiceConsumer(pr.ConsumerKey) { - return pr.ReservedMicroUSD, nil - } - required := s.providerReservationCost(provider, pr.Model, pr.EstimatedPromptTokens, pr.RequestedMaxTokens) - if required <= pr.ReservedMicroUSD { - return pr.ReservedMicroUSD, nil - } - // Per-key spend cap re-check against the provider-specific total: the - // initial cap check only saw the platform reservation, so a provider whose - // custom price exceeds it could otherwise push a capped key over its limit - // in a single request. Treat a cap breach like insufficient funds so the - // caller excludes this provider (a cheaper one may still fit) and, if none - // fit, the request fails with 402. Checked BEFORE charging the top-up. - if pr.KeyID != "" && pr.KeyLimitMicroUSD != nil { - since := store.KeySpendWindowStart(pr.KeyLimitReset, time.Now()) - if s.store.KeySpendSince(pr.KeyID, since)+required > *pr.KeyLimitMicroUSD { - return pr.ReservedMicroUSD, store.ErrInsufficientBalance - } - } - extra := required - pr.ReservedMicroUSD - if err := s.ledger.Charge(pr.ConsumerKey, extra, "reserve:"+pr.ConsumerKey); err != nil { - return pr.ReservedMicroUSD, err - } - pr.ReservedMicroUSD = required - s.ddHistogram("billing.reserved_micro_usd", float64(required), []string{"model:" + pr.Model}) - return required, nil -} - -// ensureMaxTokensBound injects a max-tokens bound into parsed when the -// consumer didn't specify any max-tokens field, so the outgoing request to -// the provider is bounded by the amount we reserve upfront. The bound is -// the model's max_output_length from the registry (or defaultMaxOutputTokens -// as fallback). The injected field name depends on the API flavor: Responses -// API uses max_output_tokens, everything else uses max_tokens. Returns true -// when an injection occurred, so the caller can re-marshal the outgoing body -// if needed. -func ensureMaxTokensBound(parsed map[string]any, isResponsesAPI bool, bound int) bool { - if n := explicitMaxTokens(parsed); n > 0 { - // Normalize alias fields the provider engine doesn't read: a chat - // request bounded only via max_completion_tokens (the OpenAI-preferred - // spelling) must still reach the provider as max_tokens, or the bound - // is silently ignored. - if !isResponsesAPI { - if cur, ok := intFromRequestValue(parsed["max_tokens"]); !ok || cur <= 0 { - parsed["max_tokens"] = n - return true - } - } - return false - } - if isResponsesAPI { - parsed["max_output_tokens"] = bound - } else { - parsed["max_tokens"] = bound - } - return true -} - -// handleChatCompletions handles POST /v1/chat/completions. -// -// This is the main inference endpoint. It validates the request, finds an -// available provider for the requested model, forwards the request via -// WebSocket, and either streams SSE chunks or assembles a complete response. -// -// Chat-completions bodies are passed through to the provider, preserving all -// OpenAI-compatible fields. Responses API bodies are lowered into that same -// provider-facing chat shape while their original parsed form remains the -// source for accounting and consumer-facing response conversion. -func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { - timing := ®istry.RequestTiming{ReceivedAt: time.Now()} - rp := s.newRequestProfile(r, "", "", false) - - // Shared prelude: read body, normalize tool schemas, parse, require a model, - // enforce the per-key model allowlist. (See parseInferencePrelude.) - prelude, ok := s.parseInferencePrelude(w, r) - if !ok { - return - } - // body is the provider-bound request: every rewrite below mutates - // body.parsed (== parsed) and marks it dirty; the bytes are serialized ONCE, - // at the single serialization point ahead of the first consumer of the - // provider body. originalRawBody stays the caller's untouched input. - body := &prelude.body - originalRawBody := prelude.originalRawBody - parsed := prelude.parsed - model := prelude.model - runtimeDefaults := newModelRuntimeDefaults(parsed) - _, reasoningProvided := parsed["reasoning"] - - // Accept either chat completions format (messages) or Responses API format - // (input). Responses requests are lowered before the provider body is sealed. - messages, _ := parsed["messages"].([]any) - input := parsed["input"] - if len(messages) == 0 && input == nil { - s.recordRejection(rejectionInfo{ - r: r, - stage: "validation", - reasonCode: "messages_required", - httpStatus: http.StatusBadRequest, - keyID: keyIDFromContext(r.Context()), - consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), - requestedModel: model, - params: rejectionSamplingParams(parsed), - }) - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "messages or input is required")) - return - } - - // Multiple choices per request are not supported — fail loudly instead of - // silently returning a single choice the consumer didn't ask for. - if copies, ok := intFromRequestValue(parsed["n"]); ok && copies > 1 { - s.recordRejection(rejectionInfo{ - r: r, - stage: "validation", - reasonCode: "bad_param", - httpStatus: http.StatusBadRequest, - keyID: keyIDFromContext(r.Context()), - consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), - requestedModel: model, - n: copies, - params: rejectionSamplingParams(parsed), - }) - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", - "n > 1 is not supported", withParam("n"))) - return - } - - var allowedProviderSerials []string - if stripProviderRoutingFields(parsed) { - body.markDirty() - } - if applyMetadataDetailsRequest(r, parsed) { - body.markDirty() - } - - // "Use my own machine, for free" opt-in. The signal is the - // X-Darkbloom-Route header (OpenAI-client-safe: invisible to the body - // schema) OR a per-key hard ceiling. The header can only *request* - // self-routing; it cannot name a machine — ownership is matched on the - // coordinator-stamped provider AccountID, so nothing here is forgeable. - policy := s.resolveSelfRoutePolicy(r) - - isResponsesAPI := input != nil && len(messages) == 0 - // Tool-constraint validation must judge the PRE-normalization tools (a - // normalization marker in the caller's body is forged). On the chat surface - // that is the parsed map with the caller's original tools restored; the - // Responses surface needs the input→chat lowering, which works on bytes, so - // the untouched input is lowered and parsed once. - var validatedPolicy validatedToolConstraintPolicy - var validationErr error - if isResponsesAPI { - loweredConstraintBody, err := promptcontract.LowerProviderBody( - promptcontract.EndpointResponses, originalRawBody) - if err != nil { - writeJSON(w, http.StatusBadRequest, errorResponse( - "invalid_request_error", err.Error())) - return - } - validatedPolicy, validationErr = validateToolConstraintPolicy(loweredConstraintBody) - } else { - validatedPolicy, validationErr = validateParsedToolConstraintPolicy( - constraintView(parsed, prelude.originalTools)) - } - if validationErr != nil { - s.recordToolConstraintMetric(validatedPolicy.mode, "compile_rejection") - writeToolConstraintValidationError(w, validationErr) - return - } - // Derive request-shape traits before alias resolution. During a - // mixed-version rollout Desired may have ordinary providers while Previous - // has the only provider capable of enforcing this exact tool policy. One - // walk of the message tree yields the media count, the tools flag, and the - // routing/billing token estimates (consumed below, after the rewrites). It - // runs after constraint validation so a rejected tool policy on a large - // body never pays the walk. - shape := introspectRequest(parsed) - requiresVision := shape.requiresVision() - hasTools := shape.hasTools - validatedMode := validatedPolicy.mode - toolChoiceName := validatedPolicy.name - parallelToolCalls := validatedPolicy.parallel - s.recordToolConstraintMetric(validatedMode, "requested") - requiresToolConstraint := validatedMode.requiresInferenceConstraint() - if requiresToolConstraint && requiresVision { - writeJSON(w, http.StatusBadRequest, errorResponse( - "invalid_request_error", - "inference-enforced tool_choice is not supported for multimodal requests", - withParam("tool_choice"))) - return - } - aliasTraits := registry.RequestTraits{ - HasTools: hasTools, - RequiresToolConstraint: requiresToolConstraint, - ToolChoiceMode: string(validatedMode), - ToolChoiceName: toolChoiceName, - ParallelToolCalls: parallelToolCalls, - } - - // Resolve a public alias (e.g. "gemma-4-26b") to a concrete build id, now - // that coordinator routing constraints and self-route policy are known so - // the pick only considers builds the constrained provider set can actually - // serve. From here on `model` is the build (routing/billing/serving) while - // `publicModel` is echoed back so the consumer never sees the quant. - buildModel, publicModel, modelRewritten, ok := s.resolveRequestedBuild( - parsed, model, allowedProviderSerials, policy, aliasTraits) - if !ok { - s.recordRejection(rejectionInfo{ - r: r, - stage: "model_resolution", - reasonCode: "model_unavailable", - httpStatus: http.StatusServiceUnavailable, - keyID: keyIDFromContext(r.Context()), - consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), - requestedModel: model, - params: rejectionSamplingParams(parsed), - }) - writeJSON(w, http.StatusServiceUnavailable, errorResponse("model_unavailable", - fmt.Sprintf("model %q has no available build right now", model), withParam("model"))) - return - } - model = buildModel - if modelRewritten { - body.markDirty() - } - user := auth.UserFromContext(r.Context()) - serviceChatConsumer := r.URL.Path == "/v1/chat/completions" && - user != nil && user.Role == store.RoleService - if applyResolvedModelReasoningPolicy(parsed, model, serviceChatConsumer, reasoningProvided) { - body.markDirty() - } - - // Shared media/tools fail-fast. Chat completions additionally rejects media - // sent via the Responses API surface (input-without-messages), because the - // Responses→chat lowering doesn't carry image/video parts through. - if s.visionToolsFailFast(w, model, publicModel, requiresVision, hasTools, - requiresToolConstraint, string(validatedMode), - input != nil && len(messages) == 0, policy, allowedProviderSerials) { - return - } - // Remote media URL gate (phase 1, pre-billing). With the media resolver - // enabled (default), remote http(s) image_url/video_url links are fetched - // and inlined as data: URIs AFTER the balance reservation (resolveRemoteMedia - // below); here we fail fast only the cases that must never fetch: sealed - // requests, remote refs in shapes the resolver doesn't handle, and the - // resolver-disabled fallback (the legacy one-clean-400, the provider VLM - // path being data:-only). - if s.gateRemoteMediaPreDispatch(w, r, parsed, model, publicModel, requiresVision, hasTools) { - return - } - - // Inject model-specific request defaults from the registry, then apply the - // model's max_tokens bound. Single DB lookup (cached for platform prices). - maxOutputBound := defaultMaxOutputTokens - // modelMaxContext is the model's max context window (0 = unknown), used by the - // servability gate. Lifted out of the record block so it is in scope at the - // preflight below. - modelMaxContext := 0 - registryReadStart := time.Now() - var resolvedRuntimeParameters map[string]any - if rec, err := s.store.GetModelRegistryRecord(model); err == nil { - profileDBCall(rp, registryReadStart) - resolvedRuntimeParameters = rec.RuntimeParameters - if runtimeDefaults.apply(parsed, rec.RuntimeParameters) { - body.markDirty() - } - // Use the registry's max_output_length as the default max_tokens - // bound instead of the hardcoded 8192. This lets models like - // GPT-OSS 20B (32K output) generate longer responses when the - // consumer omits max_tokens. - if rec.MaxOutputLength > 0 { - maxOutputBound = rec.MaxOutputLength - } - modelMaxContext = rec.MaxContextLength - } - if err := validateResolvedToolConstraintParser( - parsed, validatedMode, model, s.registry.ModelType(model), - resolvedRuntimeParameters, - ); err != nil { - s.recordToolConstraintMetric(validatedMode, "compile_rejection") - writeToolConstraintValidationError(w, err) - return - } - - // Bound the generation so the pre-flight reservation covers it. If the - // consumer didn't set max_tokens, inject the model's max_output_length - // (or defaultMaxOutputTokens as fallback). Without this bound the - // provider could return more tokens than we reserved for, and the - // silent post-inference charge failure would hand the consumer free - // inference (GitHub issue #33). - if ensureMaxTokensBound(parsed, isResponsesAPI, maxOutputBound) { - body.markDirty() - } - - stream, _ := parsed["stream"].(bool) - estimatedPromptTokens := shape.routingPromptTokens(parsed) - billingPromptTokens := shape.billingPromptTokens(parsed) - requestedMaxTokens := estimateRequestedMaxTokens(parsed) - deadline := s.FirstContentDeadline(model, estimatedPromptTokens) - timing.ParsedAt = time.Now() - rp.Mark(registry.StampReqParsed) - if s.shedIfModelRejected(w, r, parsed, policy, publicModel, model, stream, estimatedPromptTokens, requestedMaxTokens, requiresVision, hasTools) { - return - } - - // Single serialization point: every rewrite above (stop, stripped fields, - // alias, reasoning policy, runtime defaults, max_tokens) landed in parsed; - // serialize once here — or hand the caller's exact bytes through when - // nothing changed. - rawBody, err := body.current() - if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse( - "server_error", "failed to prepare inference request")) - return - } - providerBody := rawBody - if isResponsesAPI { - loweredProviderBody, err := promptcontract.LowerProviderBody(promptcontract.EndpointResponses, rawBody) - if err != nil { - s.recordRejection(rejectionInfo{ - r: r, - stage: "validation", - reasonCode: "bad_param", - httpStatus: http.StatusBadRequest, - keyID: keyIDFromContext(r.Context()), - consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), - requestedModel: publicModel, - resolvedModel: model, - stream: stream, - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - requiresVision: requiresVision, - hasTools: hasTools, - params: rejectionSamplingParams(parsed), - }) - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", err.Error())) - return - } - providerBody = loweredProviderBody - } - // Candidate provider bodies (the resolved build, the alias fallback build - // the preflight probes) and the routing verdicts derived from them are - // memoized per request: traits, the protocol-0 size verdict, and dispatch - // all reuse one serialization per candidate. When the body above is the - // coordinator's own serialization, the resolved build is seeded with it — - // parsed is fully reconciled for that build, so a rebuild would produce the - // same bytes. A verbatim caller body is NOT a substitute (its whitespace, - // key order and escapes differ from the serialized form the size verdicts - // have always measured), so that rare case builds its candidate as before. - bodies := newProviderBodyMemo(func(candidateModel string) ([]byte, error) { - return s.candidateProviderBody(parsed, runtimeDefaults, candidateModel, - serviceChatConsumer, reasoningProvided, isResponsesAPI) - }, hasTools, requiresVision) - if body.serialized { - bodies.seed(model, providerBody) - } - routingTraitsForModel := func(candidateModel string) registry.RequestTraits { - traits, ok := bodies.traits(candidateModel) - if !ok { - traits = registry.RequestTraits{HasTools: hasTools} - } - traits.RequiresToolConstraint = requiresToolConstraint - traits.ToolChoiceMode = string(validatedMode) - traits.ToolChoiceName = toolChoiceName - traits.ParallelToolCalls = parallelToolCalls - return traits - } - providerBodyErrorForModel := bodies.sizeError - routingTraits := routingTraitsForModel(model) - - // Per-account token rate limiting (ITPM/OTPM) — the industry-standard - // token throttle alongside RPM. Charged upfront from the input estimate - // and the bounded max_tokens (OpenAI-style). Runs before the balance - // reservation so a throttled request never touches billing. - tokenAdmission, ok := s.applyTokenRateLimitWithAdmission(w, r, estimatedPromptTokens, requestedMaxTokens) - if !ok { - return - } - - // Pre-flight balance reservation + per-key spend cap (see - // reserveInferenceBalance). Self-route and a nil billing backend are free. - reservedMicroUSD, serviceReservation, reserveHandled := s.reserveInferenceBalance(w, r, parsed, balanceReservationParams{ - model: model, - publicModel: publicModel, - billingPromptTokens: billingPromptTokens, - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - stream: stream, - requiresVision: requiresVision, - hasTools: hasTools, - policy: policy, - }) - if reserveHandled { - return - } - timing.ReservedAt = time.Now() - rp.Mark(registry.StampReqReserved) - - // Refund reservation on early errors (before inference starts). - refundReservation := func() { - if reservedMicroUSD > 0 { - s.releaseInitialReservation(consumerKeyFromContext(r.Context()), model, reservedMicroUSD, serviceReservation) - } - } - - // Reject requests for models not in the catalog. - if !policy.enabled && !s.registry.IsModelInCatalog(model) { - refundReservation() - s.recordRejection(rejectionInfo{ - r: r, - stage: "model_resolution", - reasonCode: "model_not_found", - httpStatus: http.StatusNotFound, - keyID: keyIDFromContext(r.Context()), - consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), - requestedModel: publicModel, - resolvedModel: model, - stream: stream, - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - requiresVision: requiresVision, - hasTools: hasTools, - params: rejectionSamplingParams(parsed), - }) - writeJSON(w, http.StatusNotFound, errorResponse("model_not_found", - fmt.Sprintf("model %q is not available — see /v1/models for supported models", publicModel), withParam("model"))) - return - } - - // Resolve remote http(s) image_url/video_url links into inline base64 data: - // URIs (phase 2 — see media_resolve.go) — AFTER token admission, the balance - // reservation, and the catalog check, so network I/O is gated behind the - // cost gates: an authenticated but unfunded/over-quota request (or one for a - // nonexistent model) can never drive coordinator-side fetches. The token & - // routing estimates above count media parts flatly (300/1500 per part), so - // they don't need the inlined bytes. The billing reservation is refunded on - // any failure, and topped up below on success — it was taken while the media - // was still a ~100-byte URL. parsed is mutated in place, so every view - // derived from the pre-inline body is refreshed via refreshForwardBody. - var mediaInlined bool - rawBody, mediaInlined, ok = s.resolveRemoteMedia(w, r, rawBody, parsed, timing, mediaResolveMeta{ - model: model, - publicModel: publicModel, - stream: stream, - estimatedPromptTokens: estimatedPromptTokens, - firstContentDeadline: deadline, - requestedMaxTokens: requestedMaxTokens, - hasTools: hasTools, - requiresVision: requiresVision, - selfRoute: policy.enabled, - ownerAccountID: policy.ownerAccountID, - traits: routingTraits, - }) - if !ok { - refundReservation() - // Token-rate admission is intentionally NOT refunded: this matches every - // other post-admission validation failure and makes blocked/invalid URL - // probes consume the caller's input/output token quota. - return - } - - // refreshForwardBody re-derives every view of the provider-bound request from - // a freshly marshaled `parsed`: the threaded rawBody, the body actually - // forwarded to the provider (re-lowered input→chat on the Responses surface, - // which can itself fail with a 400), the memoized candidate bodies (every - // earlier candidate described a parsed that no longer exists), and the - // routing traits computed from it. Any in-place mutation of `parsed` MUST go - // through it — an alias fallback rewriting the model, or remote media being - // inlined as data: URIs. Returns false after writing a terminal response. - refreshForwardBody := func(forwardBytes []byte, forModel string) bool { - rawBody = forwardBytes - body.replace(forwardBytes) - bodies.reset() - if !isResponsesAPI { - providerBody = rawBody - bodies.seed(forModel, providerBody) - routingTraits = routingTraitsForModel(forModel) - return true - } - var err error - providerBody, err = promptcontract.LowerProviderBody(promptcontract.EndpointResponses, rawBody) - if err != nil { - refundReservation() - s.recordRejection(rejectionInfo{ - r: r, - stage: "validation", - reasonCode: "bad_param", - httpStatus: http.StatusBadRequest, - keyID: keyIDFromContext(r.Context()), - consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), - requestedModel: publicModel, - resolvedModel: forModel, - stream: stream, - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - requiresVision: requiresVision, - hasTools: hasTools, - params: rejectionSamplingParams(parsed), - }) - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", err.Error())) - return false - } - bodies.seed(forModel, providerBody) - routingTraits = routingTraitsForModel(forModel) - return true - } - - // Remote media was fetched and inlined into `parsed` above, so `providerBody` - // (captured before the resolve) and the routing traits derived from it now - // describe a body that no longer exists. Without this refresh the coordinator - // pays for the fetch and then seals and dispatches the ORIGINAL body still - // carrying the http(s) URL, which the provider's data:-only guard rejects. - if mediaInlined { - if !refreshForwardBody(rawBody, model) { - return - } - // The reservation was taken against a body where the image was a short - // URL, so estimateBillingPromptTokens — the guaranteed len(bytes) >= tokens - // upper bound the settlement path relies on — was computed over ~100 bytes - // of URL instead of the inlined media. Re-reserve against the real body - // before dispatch; otherwise settlement's 2x-reservation overage clamp - // silently absorbs the difference and underpays the provider. - var topUpHandled bool - reservedMicroUSD, topUpHandled = s.topUpReservationForInlinedMedia(w, r, parsed, balanceReservationParams{ - model: model, - publicModel: publicModel, - billingPromptTokens: estimateBillingPromptTokens(parsed), - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - stream: stream, - requiresVision: requiresVision, - hasTools: hasTools, - policy: policy, - }, reservedMicroUSD) - if topUpHandled { - refundReservation() - return - } - } - - // Shared routing/capacity admission preflight (self-route / prefer / public - // capacity+TTFT gate — see runInferenceAdmission). On the chat path an alias - // fallback must refresh the threaded rawBody; thread that as the - // onModelFallback callback. resolvedModel uses the new build to match the - // pre-extraction behavior. - onModelFallback := func(newModel string) bool { - var runtimeParameters map[string]any - if rec, err := s.store.GetModelRegistryRecord(newModel); err == nil { - runtimeParameters = rec.RuntimeParameters - runtimeDefaults.apply(parsed, runtimeParameters) - } else { - runtimeDefaults.apply(parsed, nil) - } - if err := validateResolvedToolConstraintParser( - parsed, validatedMode, newModel, s.registry.ModelType(newModel), - runtimeParameters, - ); err != nil { - s.recordToolConstraintMetric(validatedMode, "compile_rejection") - writeToolConstraintValidationError(w, err) - refundReservation() - return false - } - applyResolvedModelReasoningPolicy(parsed, newModel, serviceChatConsumer, reasoningProvided) - // maybeFallbackAlias rewrote parsed["model"]; the defaults and reasoning - // policy above may have moved more. One serialization covers all of it. - body.markDirty() - forwardBytes, err := body.current() - if err != nil { - refundReservation() - writeJSON(w, http.StatusInternalServerError, errorResponse( - "server_error", "failed to prepare inference request")) - return false - } - return refreshForwardBody(forwardBytes, newModel) - } - var preflightHandled bool - preflightStart := time.Now() - model, preflightHandled = s.runInferenceAdmission(w, r, parsed, inferenceAdmissionParams{ - model: model, - publicModel: publicModel, - stream: stream, - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - requiresVision: requiresVision, - hasTools: hasTools, - traits: &routingTraits, - traitsForModel: routingTraitsForModel, - providerBodyErrorForModel: providerBodyErrorForModel, - modelMaxContext: modelMaxContext, - allowedProviderSerials: allowedProviderSerials, - deadline: deadline, - policy: policy, - refundReservation: refundReservation, - onModelFallback: onModelFallback, - }) - if rp != nil { - rp.PreflightUS = time.Since(preflightStart).Microseconds() - rp.Mark(registry.StampReqPreflightDone) - if preflightHandled { - rp.PreflightOutcome = "handled" - } else { - rp.PreflightOutcome = "passed" - } - } - if preflightHandled { - return - } - - // Dispatch to a provider with speculative TTFT-aware dispatch. On the - // first attempt we dispatch to the best provider (primary), and start a - // speculative timer at 50% of the TTFT deadline. If the primary hasn't - // produced a first chunk by the speculative timer, a backup provider is - // dispatched in parallel and both race. If the primary fails outright - // (error before the speculative timer), up to maxDispatchAttempts - // sequential retries are performed without speculation. - // - // No HTTP response is written until a provider starts generating, so - // retries and speculative dispatch are invisible to the consumer. - // Dispatch is driven by the per-request state machine in dispatch.go: it - // picks a provider (or queues), runs the speculative TTFT-aware first-chunk - // wait with an invisible backup race + failover up to maxDispatchAttempts, - // commits exactly once, then writes attestation/timing headers and streams. - consumerKey := consumerKeyFromContext(r.Context()) - consumerLocation := s.requestLocation(r) - - // model may have been rewritten by a capacity- or TTFT-fallback above - // (maybeFallbackAlias), so refresh the context - // window for the FINAL build before handing it to the dispatch loop — otherwise - // shouldStopFailover/classifyRejection would compare a provider's budget against - // the originally-resolved model's context. Overwrite only on a successful lookup - // (fallback builds of the same alias normally share a context window; a build - // absent from the store keeps the prior value, matching the initial read). - registryReadStart2 := time.Now() - if rec, err := s.store.GetModelRegistryRecord(model); err == nil { - modelMaxContext = rec.MaxContextLength - } - profileDBCall(rp, registryReadStart2) - cachePlan := s.planCacheRoute( - r.Context(), consumerKey, model, providerBody, requiresVision) - rp.Mark(registry.StampReqPlanDone) - if rp != nil { - rp.Model, rp.PublicModel, rp.Stream = model, publicModel, stream - rp.FirstContentBudgetMs = int(deadline.Milliseconds()) - rp.EstimatedPromptTokens, rp.RequestedMaxTokens = estimatedPromptTokens, requestedMaxTokens - rp.RequiresVision, rp.HasTools = requiresVision, hasTools - rp.BodyBytes = len(rawBody) - if mediaInlined { - rp.Mark(registry.StampReqMediaFetched) - } - } - - d := &dispatchState{ - s: s, - w: w, - r: r, - model: model, - publicModel: publicModel, - rawBody: providerBody, - consumerKey: consumerKey, - consumerLocation: consumerLocation, - reservedMicroUSD: reservedMicroUSD, - tokenAdmission: tokenAdmission, - serviceReservation: serviceReservation, - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - requiresVision: requiresVision, - visionImageCount: shape.mediaParts, - hasTools: hasTools, - requiresToolConstraint: requiresToolConstraint, - toolChoiceMode: string(validatedMode), - toolChoiceName: toolChoiceName, - parallelToolCalls: parallelToolCalls, - isResponsesAPI: isResponsesAPI, - stream: stream, - metadataDetails: metadataDetailsFromRequest(r), - policy: policy, - allowedProviderSerials: allowedProviderSerials, - cachePlan: cachePlan, - timing: timing, - profile: rp, - deadline: deadline, - speculativeAt: time.Duration(float64(deadline) * speculativeTimerRatio), - modelMaxContext: modelMaxContext, - refundReservation: refundReservation, - // Track providers that failed during retry so we don't dispatch to them again. - excludeProviders: make(map[string]struct{}), - } - d.run() -} - -// createAPIKeyRequest is the POST /v1/keys (and rotate inherit) body. Money is -// supplied in USD; the wire never sees the secret after the create response. -type createAPIKeyRequest struct { - Name string `json:"name"` - LimitUSD *float64 `json:"limit_usd"` - LimitReset string `json:"limit_reset"` - RPMLimit *int64 `json:"rpm_limit"` - ITPMLimit *int64 `json:"itpm_limit"` - OTPMLimit *int64 `json:"otpm_limit"` - AllowedModels []string `json:"allowed_models"` - SelfRouteOnly bool `json:"self_route_only"` - ExpiresAt *time.Time `json:"expires_at"` -} - -// usdToMicro converts a USD dollar amount to micro-USD (rounded). -func usdToMicro(usd float64) int64 { return int64(math.Round(usd * 1_000_000)) } - -// microToUSD converts micro-USD to a USD float. -func microToUSD(micro int64) float64 { return float64(micro) / 1_000_000 } - -// handleHealth handles GET /health. -// Returns the coordinator's status and the number of connected providers. -// This endpoint does not require authentication. -// -// /health is a LIVENESS probe: it returns 200 whenever the process is up, INCLUDING -// while draining. This is deliberate. The production host Caddy health-checks its -// single coordinator upstream on /health with health_status 200, so returning 503 here -// would mark the only backend down and make the admin/rollback endpoints -// (POST /v1/admin/drain {"draining":false}) and /readyz unreachable through the -// public URL — you could not undo a drain remotely. Drain/readiness lives on -// /readyz (handleReadyz, 503 while draining), which the deploy script and -// multi-backend load balancers consult to shift traffic. The body still reports -// draining=true for observability, but the status code stays 200. -func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, types.HealthResponse{ - Status: "ok", - Draining: s.IsDraining(), - Providers: s.registry.ProviderCount(), - Version: BuildVersion, - BuildCommit: BuildCommit, - BuildDate: BuildDate, - }) -} - -// handleVersion returns the latest provider CLI version and download URL. -// Providers call GET /api/version to check if they need to update. -// If a release is registered in the store, uses that. Otherwise falls back -// to the hardcoded LatestProviderVersion. -func (s *Server) handleVersion(w http.ResponseWriter, r *http.Request) { - if cached, ok := s.readCache.Get(apiVersionCacheKey); ok { - writeCachedJSON(w, cached) - return - } - - var resp types.VersionResponse - // Try release table first. - if release := s.store.GetLatestRelease(defaultReleasePlatform); release != nil { - resp = types.VersionResponse{ - Version: release.Version, - Platform: release.Platform, - Backend: release.Backend, - DownloadURL: release.URL, - BinaryHash: release.BinaryHash, - BundleHash: release.BundleHash, - MetallibHash: release.MetallibHash, - Changelog: release.Changelog, - } - } else { - // Fallback to hardcoded version + coordinator download. - scheme := "https" - if r.TLS == nil && !strings.Contains(r.Host, "darkbloom.dev") { - scheme = "http" - } - downloadURL := fmt.Sprintf("%s://%s/dl/eigeninference-bundle-macos-arm64.tar.gz", scheme, r.Host) - resp = types.VersionResponse{ - Version: LatestProviderVersion, - DownloadURL: downloadURL, - } - } - body, err := json.Marshal(resp) - if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to encode version")) - return - } - s.readCache.Set(apiVersionCacheKey, body, time.Minute) - writeCachedJSON(w, body) -} - -// --- payment handlers --- - -// handleBalance handles GET /v1/payments/balance. -// Returns the consumer's current balance in both micro-USD and USD. -func (s *Server) handleBalance(w http.ResponseWriter, r *http.Request) { - consumerKey := consumerKeyFromContext(r.Context()) - balance := s.ledger.Balance(consumerKey) - withdrawable := s.store.GetWithdrawableBalance(consumerKey) - - writeJSON(w, http.StatusOK, types.BalanceResponse{ - BalanceMicroUSD: balance, - BalanceUSD: fmt.Sprintf("%.6f", float64(balance)/1_000_000), - WithdrawableMicroUSD: withdrawable, - WithdrawableUSD: fmt.Sprintf("%.6f", float64(withdrawable)/1_000_000), - }) -} - -// handleUsage handles GET /v1/payments/usage. -// Returns the consumer's inference usage history with per-request costs. -// Tries in-memory ledger first (has full detail), falls back to store -// ledger history (persists across restarts but has less detail). -func (s *Server) handleUsage(w http.ResponseWriter, r *http.Request) { - consumerKey := consumerKeyFromContext(r.Context()) - entries := s.ledger.Usage(consumerKey) - - // If in-memory usage is empty (coordinator restarted), build from - // the persisted usage table which has full request details. - if len(entries) == 0 { - usageRecords := s.store.UsageByConsumer(consumerKey) - for _, u := range usageRecords { - jobID := u.RequestID - if jobID == "" { - jobID = u.ProviderID - } - model := u.Model - if u.PublicModel != "" { - model = u.PublicModel - } - entries = append(entries, payments.UsageEntry{ - JobID: jobID, - Model: model, - PromptTokens: u.PromptTokens, - CompletionTokens: u.CompletionTokens, - CostMicroUSD: u.CostMicroUSD, - Timestamp: u.CreatedAt, - }) - } - } - - writeJSON(w, http.StatusOK, types.UsageResponse{ - Usage: entries, - }) -} - -// handleProviderEarnings handles GET /v1/provider/earnings?wallet=0x... -// -// Returns the provider's balance and payout history. -// No API key auth required — providers identify by provider address. -func (s *Server) handleProviderEarnings(w http.ResponseWriter, r *http.Request) { - wallet := r.URL.Query().Get("wallet") - if wallet == "" { - wallet = r.Header.Get("X-Provider-Wallet") - } - if wallet == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "wallet address required (query param ?wallet=0x... or X-Provider-Wallet header)")) - return - } - - // Look up balance by provider address - balance := s.ledger.Balance(wallet) - history := s.ledger.LedgerHistory(wallet) - payouts := s.ledger.AllPayouts() - - // Filter payouts to this wallet - var walletPayouts []payments.Payout - var totalEarned int64 - var totalJobs int - for _, p := range payouts { - if p.ProviderAddress == wallet { - walletPayouts = append(walletPayouts, p) - totalEarned += p.AmountMicroUSD - totalJobs++ - } - } - - // If no explicit payout records exist (for example, legacy rows created - // before provider_payouts was introduced), reconstruct from persisted - // ledger entries with payout type and the wallet as account ID. - if len(walletPayouts) == 0 { - ledgerEntries := s.store.LedgerHistory(wallet) - for _, le := range ledgerEntries { - if le.Type == store.LedgerPayout && le.Reference != "" { - walletPayouts = append(walletPayouts, payments.Payout{ - ProviderAddress: wallet, - AmountMicroUSD: le.AmountMicroUSD, - JobID: le.Reference, - Timestamp: le.CreatedAt, - Settled: true, - }) - totalEarned += le.AmountMicroUSD - totalJobs++ - } - } - } - - if walletPayouts == nil { - walletPayouts = []payments.Payout{} - } - - writeJSON(w, http.StatusOK, types.ProviderEarningsResponse{ - BalanceMicroUSD: balance, - BalanceUSD: fmt.Sprintf("%.6f", float64(balance)/1_000_000), - TotalEarnedMicroUSD: totalEarned, - TotalEarnedUSD: fmt.Sprintf("%.6f", float64(totalEarned)/1_000_000), - TotalJobs: totalJobs, - Payouts: walletPayouts, - Ledger: history, - }) -} - -// --- helpers --- - -// handleCompletions handles POST /v1/completions. -// Proxies OpenAI-compatible text completions to the selected provider over the -// E2E-encrypted WebSocket relay (MLX-Swift in-process backend). -func (s *Server) handleCompletions(w http.ResponseWriter, r *http.Request) { - s.handleGenericInference(w, r, "/v1/completions") -} - -// handleAnthropicMessages handles POST /v1/messages. -// Proxies the Anthropic-compatible messages API to the selected provider over -// the E2E-encrypted WebSocket relay (MLX-Swift in-process backend). -func (s *Server) handleAnthropicMessages(w http.ResponseWriter, r *http.Request) { - s.handleGenericInference(w, r, "/v1/messages") -} - -// handleGenericInference is the shared dispatch for completions and Anthropic endpoints. -// It reads the endpoint-native body, preserves it for accounting, lowers the -// final provider body to OpenAI chat format, and reuses the same E2E encryption -// and provider routing as chat completions. -func (s *Server) handleGenericInference(w http.ResponseWriter, r *http.Request, endpoint string) { - timing := ®istry.RequestTiming{ReceivedAt: time.Now()} - rp := s.newRequestProfile(r, "", "", false) - - // Shared prelude: read body, normalize tool schemas (Anthropic /v1/messages - // bodies carry a top-level "tools" array too; the provider body is rebuilt - // from parsed below, so normalizing before the unmarshal covers it), parse, - // require a model, enforce the per-key model allowlist. - prelude, ok := s.parseInferencePrelude(w, r) - if !ok { - return - } - // This handler rebuilds its provider body from `parsed` (inferenceBody - // below); the prelude's forward bytes are only threaded into - // resolveRequestedModel, which never uses them here. - rawBody := prelude.originalRawBody - originalRawBody := prelude.originalRawBody - parsed := prelude.parsed - model := prelude.model - runtimeDefaults := newModelRuntimeDefaults(parsed) - endpointKind := promptcontract.EndpointCompletions - if endpoint == "/v1/messages" { - endpointKind = promptcontract.EndpointMessages - } - - var allowedProviderSerials []string - stripProviderRoutingFields(parsed) - applyMetadataDetailsRequest(r, parsed) - - // "Use my own machine, for free" opt-in (see handleChatCompletions). - policy := s.resolveSelfRoutePolicy(r) - - // Constraint validation needs the lowered chat shape. Endpoint-native - // shapes the contract lowering cannot express — multi-prompt completions, - // media-bearing messages — have always been forwarded verbatim (see the - // inferenceBody fallback below), so a lowering failure is only terminal - // for requests that actually carry tool policy to validate; tool-less - // unsupported shapes keep the pre-existing native-forward behavior with - // the neutral auto defaults. - validatedPolicy := validatedToolConstraintPolicy{ - mode: toolChoiceAuto, parallel: true, - } - constraintBody, constraintLowerErr := promptcontract.LowerProviderBody( - endpointKind, originalRawBody) - if constraintLowerErr == nil { - var validationErr error - validatedPolicy, validationErr = validateToolConstraintPolicy(constraintBody) - if validationErr != nil { - s.recordToolConstraintMetric(validatedPolicy.mode, "compile_rejection") - writeToolConstraintValidationError(w, validationErr) - return - } - } else if _, hasToolChoice := parsed["tool_choice"]; hasToolChoice || requestHasTools(parsed) { - s.recordToolConstraintMetric(validatedPolicy.mode, "compile_rejection") - writeJSON(w, http.StatusBadRequest, errorResponse( - "invalid_request_error", constraintLowerErr.Error())) - return - } - validatedMode := validatedPolicy.mode - toolChoiceName := validatedPolicy.name - parallelToolCalls := validatedPolicy.parallel - s.recordToolConstraintMetric(validatedMode, "requested") - requiresToolConstraint := validatedMode.requiresInferenceConstraint() - requiresVision := detectMediaRequirement(parsed) - hasTools := requestHasTools(parsed) - aliasTraits := registry.RequestTraits{ - HasTools: hasTools, - RequiresToolConstraint: requiresToolConstraint, - ToolChoiceMode: string(validatedMode), - ToolChoiceName: toolChoiceName, - ParallelToolCalls: parallelToolCalls, - } - - // Resolve a public alias to a concrete build id, constraint-aware (after - // allowlist/self-route are known). resolveRequestedModel rewrites - // parsed["model"] to the build; this handler builds the provider body fresh - // from `parsed` (inferenceBody below), so rawBody isn't threaded here. - buildModel, publicModel, _, ok := s.resolveRequestedModel( - parsed, rawBody, model, allowedProviderSerials, policy, aliasTraits) - if !ok { - s.recordRejection(rejectionInfo{ - r: r, - stage: "model_resolution", - reasonCode: "model_unavailable", - httpStatus: http.StatusServiceUnavailable, - keyID: keyIDFromContext(r.Context()), - consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), - requestedModel: model, - params: rejectionSamplingParams(parsed), - }) - writeJSON(w, http.StatusServiceUnavailable, errorResponse("model_unavailable", - fmt.Sprintf("model %q has no available build right now", model), withParam("model"))) - return - } - model = buildModel - - if !policy.enabled && !s.registry.IsModelInCatalog(model) { - s.recordRejection(rejectionInfo{ - r: r, - stage: "model_resolution", - reasonCode: "model_not_found", - httpStatus: http.StatusNotFound, - keyID: keyIDFromContext(r.Context()), - consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), - requestedModel: publicModel, - resolvedModel: model, - params: rejectionSamplingParams(parsed), - }) - writeJSON(w, http.StatusNotFound, errorResponse("model_not_found", - fmt.Sprintf("model %q is not available — see /v1/models for supported models", publicModel), withParam("model"))) - return - } - // Shared media/tools fail-fast (see visionToolsFailFast). Completions and - // Anthropic bodies share the top-level "tools" field; neither has the - // Responses-API media surface, so rejectResponsesMedia is false here. - if s.visionToolsFailFast(w, model, publicModel, requiresVision, hasTools, - requiresToolConstraint, string(validatedMode), - false, policy, allowedProviderSerials) { - return - } - if s.rejectRemoteMediaURLs(w, r, parsed, model, publicModel, requiresVision, hasTools) { - return - } - - // Completions and Anthropic messages both use the max_tokens field (never - // max_output_tokens, which is Responses API only). Inject a default if - // unset so the pre-flight reservation bounds the generation. - genericMaxOutput := defaultMaxOutputTokens - modelMaxContext := 0 - if rec, err := s.store.GetModelRegistryRecord(model); err == nil { - // Keep generic endpoints aligned with chat completions: parser defaults - // are catalog-owned request semantics, not provider inference guesses. - runtimeDefaults.apply(parsed, rec.RuntimeParameters) - if rec.MaxOutputLength > 0 { - genericMaxOutput = rec.MaxOutputLength - } - modelMaxContext = rec.MaxContextLength - } - ensureMaxTokensBound(parsed, false, genericMaxOutput) - - stream, _ := parsed["stream"].(bool) - estimatedPromptTokens := estimatePromptTokens(parsed) - billingPromptTokens := estimateBillingPromptTokens(parsed) - requestedMaxTokens := estimateRequestedMaxTokens(parsed) - genericDeadline := s.FirstContentDeadline(model, estimatedPromptTokens) - timing.ParsedAt = time.Now() - rp.Mark(registry.StampReqParsed) - if s.shedIfModelRejected(w, r, parsed, policy, publicModel, model, stream, estimatedPromptTokens, requestedMaxTokens, requiresVision, hasTools) { - return - } - - // Bind the endpoint to the cache-planning input. Successful lowering removes - // it from the final OpenAI chat body before that body is sealed. - parsed["endpoint"] = endpoint - - // Per-account token rate limiting (ITPM/OTPM), before the reservation. - tokenAdmission, ok := s.applyTokenRateLimitWithAdmission(w, r, estimatedPromptTokens, requestedMaxTokens) - if !ok { - return - } - - // Pre-flight balance reservation + per-key spend cap (see - // reserveInferenceBalance). Self-route and a nil billing backend are free. - consumerKey := consumerKeyFromContext(r.Context()) - consumerLocation := s.requestLocation(r) - reservedMicroUSD, serviceReservation, reserveHandled := s.reserveInferenceBalance(w, r, parsed, balanceReservationParams{ - model: model, - publicModel: publicModel, - billingPromptTokens: billingPromptTokens, - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - stream: stream, - requiresVision: requiresVision, - hasTools: hasTools, - policy: policy, - }) - if reserveHandled { - return - } - refundReservation := func() { - if reservedMicroUSD > 0 { - s.releaseInitialReservation(consumerKey, model, reservedMicroUSD, serviceReservation) - } - } - timing.ReservedAt = time.Now() - rp.Mark(registry.StampReqReserved) - - lowerGenericBodyForModel := func(candidateModel string) ([]byte, []byte, error) { - candidateParsed := make(map[string]any, len(parsed)) - for key, value := range parsed { - candidateParsed[key] = value - } - candidateParsed["model"] = candidateModel - candidateDefaults := runtimeDefaults - if rec, err := s.store.GetModelRegistryRecord(candidateModel); err == nil { - candidateDefaults.apply(candidateParsed, rec.RuntimeParameters) - } else { - candidateDefaults.apply(candidateParsed, nil) - } - endpointBody, _ := marshalForwardBody(candidateParsed) - inferenceBody, loweringErr := promptcontract.LowerProviderBody( - endpointKind, endpointBody) - if loweringErr != nil { - inferenceBody = endpointBody - } - return endpointBody, inferenceBody, loweringErr - } - routingTraitsForModel := func(candidateModel string) registry.RequestTraits { - _, candidateBody, _ := lowerGenericBodyForModel(candidateModel) - traits, _ := routingTraitsForProviderBody( - hasTools, candidateBody, requiresVision) - traits.RequiresToolConstraint = requiresToolConstraint - traits.ToolChoiceMode = string(validatedMode) - traits.ToolChoiceName = toolChoiceName - traits.ParallelToolCalls = parallelToolCalls - return traits - } - providerBodyErrorForModel := func(candidateModel string) error { - _, candidateBody, _ := lowerGenericBodyForModel(candidateModel) - _, sizeErr := routingTraitsForProviderBody( - hasTools, candidateBody, requiresVision) - return sizeErr - } - var endpointBody, inferenceBody []byte - var loweringErr error - routingTraits := routingTraitsForModel(model) - refreshGenericBody := func(newModel string) bool { - var runtimeParameters map[string]any - if rec, err := s.store.GetModelRegistryRecord(newModel); err == nil { - runtimeParameters = rec.RuntimeParameters - runtimeDefaults.apply(parsed, runtimeParameters) - } else { - runtimeDefaults.apply(parsed, nil) - } - if err := validateResolvedToolConstraintParser( - parsed, validatedMode, newModel, s.registry.ModelType(newModel), - runtimeParameters, - ); err != nil { - s.recordToolConstraintMetric(validatedMode, "compile_rejection") - writeToolConstraintValidationError(w, err) - refundReservation() - return false - } - endpointBody, inferenceBody, loweringErr = lowerGenericBodyForModel(newModel) - routingTraits, _ = routingTraitsForProviderBody( - hasTools, inferenceBody, requiresVision) - routingTraits.RequiresToolConstraint = requiresToolConstraint - routingTraits.ToolChoiceMode = string(validatedMode) - routingTraits.ToolChoiceName = toolChoiceName - routingTraits.ParallelToolCalls = parallelToolCalls - return true - } - if !refreshGenericBody(model) { - return - } - - // Shared routing/capacity admission preflight (self-route / prefer / public - // capacity+TTFT gate — see runInferenceAdmission). - var preflightHandled bool - preflightStart := time.Now() - model, preflightHandled = s.runInferenceAdmission(w, r, parsed, inferenceAdmissionParams{ - model: model, - publicModel: publicModel, - stream: stream, - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - requiresVision: requiresVision, - hasTools: hasTools, - traits: &routingTraits, - traitsForModel: routingTraitsForModel, - providerBodyErrorForModel: providerBodyErrorForModel, - modelMaxContext: modelMaxContext, - allowedProviderSerials: allowedProviderSerials, - deadline: genericDeadline, - policy: policy, - refundReservation: refundReservation, - onModelFallback: refreshGenericBody, - }) - if rp != nil { - rp.PreflightUS = time.Since(preflightStart).Microseconds() - rp.Mark(registry.StampReqPreflightDone) - if preflightHandled { - rp.PreflightOutcome = "handled" - } else { - rp.PreflightOutcome = "passed" - } - } - if preflightHandled { - return - } - cachePlan := registry.CachePlan{} - // Response framing is determined by the caller-facing endpoint, never by - // whether its request shape could be lowered for cache participation. - consumerEndpoint, requestedStopSequences := genericResponseMetadata(endpoint, parsed) - if loweringErr == nil { - cachePlan = s.planCacheRoute( - r.Context(), consumerKey, model, inferenceBody, requiresVision) - } else { - // Endpoint lowering is a cache-routing eligibility boundary, not a new - // inference rejection. Preserve the existing generic endpoint behavior - // for unsupported shapes while declining cache participation. - inferenceBody = endpointBody - } - - // Generic endpoints use the same dispatch state machine as chat. This keeps - // queue deadlines, speculative failover, pre-content boilerplate handling, - // typed deadline refusals, and terminal 429 semantics identical. - genericRegistryReadStart := time.Now() - if rec, err := s.store.GetModelRegistryRecord(model); err == nil { - modelMaxContext = rec.MaxContextLength - } - profileDBCall(rp, genericRegistryReadStart) - rp.Mark(registry.StampReqPlanDone) - if rp != nil { - rp.Model, rp.PublicModel, rp.Stream = model, publicModel, stream - rp.FirstContentBudgetMs = int(genericDeadline.Milliseconds()) - rp.EstimatedPromptTokens, rp.RequestedMaxTokens = estimatedPromptTokens, requestedMaxTokens - rp.RequiresVision, rp.HasTools = requiresVision, hasTools - rp.BodyBytes = len(rawBody) - } - d := &dispatchState{ - s: s, - w: w, - r: r, - model: model, - publicModel: publicModel, - rawBody: inferenceBody, - consumerKey: consumerKey, - consumerLocation: consumerLocation, - reservedMicroUSD: reservedMicroUSD, - tokenAdmission: tokenAdmission, - serviceReservation: serviceReservation, - estimatedPromptTokens: estimatedPromptTokens, - requestedMaxTokens: requestedMaxTokens, - requiresVision: requiresVision, - visionImageCount: countMediaParts(parsed), - hasTools: hasTools, - requiresToolConstraint: requiresToolConstraint, - toolChoiceMode: string(validatedMode), - toolChoiceName: toolChoiceName, - parallelToolCalls: parallelToolCalls, - consumerEndpoint: consumerEndpoint, - requestedStopSequences: requestedStopSequences, - stream: stream, - metadataDetails: metadataDetailsFromRequest(r), - policy: policy, - allowedProviderSerials: allowedProviderSerials, - cachePlan: cachePlan, - timing: timing, - profile: rp, - deadline: genericDeadline, - speculativeAt: time.Duration(float64(genericDeadline) * speculativeTimerRatio), - modelMaxContext: modelMaxContext, - refundReservation: refundReservation, - excludeProviders: make(map[string]struct{}), - } - d.run() -} diff --git a/coordinator/api/consumer_estimation_test.go b/coordinator/api/consumer_estimation_test.go deleted file mode 100644 index 984cf6f3a2..0000000000 --- a/coordinator/api/consumer_estimation_test.go +++ /dev/null @@ -1,414 +0,0 @@ -package api - -import ( - "bytes" - "encoding/json" - "strings" - "testing" - - "github.com/eigeninference/d-inference/coordinator/protocol" - "github.com/eigeninference/d-inference/coordinator/registry" -) - -// TestApproximateTokenCount verifies the len/4 routing heuristic. -func TestApproximateTokenCount(t *testing.T) { - tests := []struct { - name string - input any - want int - }{ - {"nil", nil, 0}, - {"empty string", "", 0}, - {"single char", "a", 1}, - {"short ASCII", "hello", 1}, // 5/4 = 1 - {"english prose", "The quick brown fox jumps.", 6}, // 26/4 = 6 - {"16 bytes", "0123456789abcdef", 4}, // 16/4 = 4 - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := approximateTokenCount(tt.input) - if got != tt.want { - t.Errorf("approximateTokenCount(%v) = %d, want %d", tt.input, got, tt.want) - } - }) - } -} - -// TestApproximateTokenCountUpperBound verifies that the billing upper bound -// returns len(text) — guaranteed >= actual BPE tokens for any tokenizer. -func TestApproximateTokenCountUpperBound(t *testing.T) { - tests := []struct { - name string - input any - want int - }{ - {"nil", nil, 0}, - {"empty string", "", 0}, - {"single char", "a", 1}, - {"short ASCII", "hello", 5}, - {"english prose", "The quick brown fox jumps over the lazy dog.", 44}, - {"code snippet", "func main() { fmt.Println(\"hello\") }", 36}, - {"multibyte UTF-8", "こんにちは世界", 21}, // 7 chars × 3 bytes each - {"emoji", "👋🌍", 8}, // 2 emoji × 4 bytes each - {"chat template tags", "<|im_start|>system\nYou are helpful.<|im_end|>", 45}, - {"json object", map[string]string{"role": "user", "content": "hi"}, len(`{"content":"hi","role":"user"}`)}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := approximateTokenCountUpperBound(tt.input) - if got != tt.want { - t.Errorf("approximateTokenCountUpperBound(%v) = %d, want %d", tt.input, got, tt.want) - } - }) - } -} - -// TestBillingEstimateAlwaysGERoutingEstimate confirms that the billing -// upper bound is always >= the routing heuristic for the same input. -func TestBillingEstimateAlwaysGERoutingEstimate(t *testing.T) { - inputs := []string{ - "Hello, world!", - "def fibonacci(n):\n if n <= 1:\n return n\n return fibonacci(n-1) + fibonacci(n-2)", - "SELECT u.id, u.name FROM users u WHERE u.active = true ORDER BY u.created_at DESC LIMIT 10;", - "これはテストです。日本語のテキストはトークン数が多くなります。", - strings.Repeat("a", 1000), - } - for _, input := range inputs { - routing := approximateTokenCount(input) - billing := approximateTokenCountUpperBound(input) - if billing < routing { - t.Errorf("billing(%d) < routing(%d) for %q", billing, routing, input[:min(20, len(input))]) - } - } -} - -// TestEstimatePromptTokens verifies the routing estimate for different -// request field layouts. -func TestEstimatePromptTokens(t *testing.T) { - tests := []struct { - name string - input map[string]any - want int - }{ - { - name: "messages field", - input: map[string]any{"messages": []any{map[string]any{"role": "user", "content": "hello"}}}, - want: 5, // 4 framing + 5/4 text tokens. - }, - { - name: "prompt field", - input: map[string]any{"prompt": "Tell me a story"}, - want: 3, - }, - { - name: "input field", - input: map[string]any{"input": "Translate this"}, - want: 3, - }, - { - name: "responses structured input", - input: map[string]any{"input": []any{map[string]any{"role": "user", "content": []any{ - map[string]any{"type": "input_text", "text": "hello"}, - }}}}, - want: 5, // 4 framing + 5/4 text tokens; do not count JSON wrapper bytes. - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - routing := estimatePromptTokens(tt.input) - billing := estimateBillingPromptTokens(tt.input) - if routing != tt.want { - t.Errorf("estimatePromptTokens() = %d, want %d", routing, tt.want) - } - if billing < routing { - t.Errorf("billing(%d) < routing(%d)", billing, routing) - } - }) - } -} - -// TestResolveReasoningTokens covers the precedence between the provider's -// tokenizer-accurate count and the legacy completion-tokens fallback. -func TestResolveReasoningTokens(t *testing.T) { - cases := []struct { - name string - usage protocol.UsageInfo - reasoning string - want uint64 - }{ - { - name: "accurate count preferred", - usage: protocol.UsageInfo{CompletionTokens: 100, ReasoningTokens: 42}, - reasoning: "thinking...", - want: 42, - }, - { - name: "fallback to completion tokens for legacy provider", - usage: protocol.UsageInfo{CompletionTokens: 100, ReasoningTokens: 0}, - reasoning: "thinking...", - want: 100, - }, - { - name: "no reasoning content yields zero", - usage: protocol.UsageInfo{CompletionTokens: 100, ReasoningTokens: 0}, - reasoning: "", - want: 0, - }, - { - name: "accurate count wins even without reasoning text", - usage: protocol.UsageInfo{CompletionTokens: 100, ReasoningTokens: 7}, - reasoning: "", - want: 7, - }, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - if got := resolveReasoningTokens(tc.usage, tc.reasoning); got != tc.want { - t.Errorf("resolveReasoningTokens = %d, want %d", got, tc.want) - } - }) - } -} - -// TestBuildNonStreamingResponseReasoningDetails verifies the chat -// completion usage object carries completion_tokens_details.reasoning_tokens -// only when there is a reasoning count to report. -func TestBuildNonStreamingResponseReasoningDetails(t *testing.T) { - msg := extractedMessage{Content: "4", Reasoning: "2+2"} - usage := protocol.UsageInfo{PromptTokens: 10, CompletionTokens: 20, ReasoningTokens: 8} - - resp := buildNonStreamingResponse("req-1", "gpt-oss-20b", msg, usage, 0, "", "") - if resp.Usage.CompletionTokensDetails == nil { - t.Fatalf("expected completion_tokens_details, got nil") - } - if resp.Usage.CompletionTokensDetails.ReasoningTokens != 8 { - t.Errorf("reasoning_tokens = %d, want 8", resp.Usage.CompletionTokensDetails.ReasoningTokens) - } - - // Wire format must include the nested detail. - b, err := json.Marshal(resp) - if err != nil { - t.Fatalf("marshal: %v", err) - } - if !strings.Contains(string(b), `"completion_tokens_details":{"reasoning_tokens":8}`) { - t.Errorf("wire missing reasoning detail: %s", b) - } - - // No reasoning content => no details object (omitempty). - plain := buildNonStreamingResponse("req-2", "gpt-oss-20b", - extractedMessage{Content: "hi"}, - protocol.UsageInfo{PromptTokens: 3, CompletionTokens: 1}, 0, "", "") - if plain.Usage.CompletionTokensDetails != nil { - t.Errorf("expected no details for non-reasoning response, got %#v", plain.Usage.CompletionTokensDetails) - } - pb, _ := json.Marshal(plain) - if strings.Contains(string(pb), "completion_tokens_details") { - t.Errorf("non-reasoning wire should omit details: %s", pb) - } -} - -// TestBuildResponsesResponseReasoningTokens verifies the Responses API -// uses the accurate count when the provider supplies it. -func TestBuildResponsesResponseReasoningTokens(t *testing.T) { - msg := extractedMessage{Content: "4", Reasoning: "2+2"} - usage := protocol.UsageInfo{PromptTokens: 10, CompletionTokens: 20, ReasoningTokens: 8} - - resp := buildResponsesResponse("req-1", "gpt-oss-20b", msg, usage, 0, "", "") - if resp.Usage.OutputTokensDetail.ReasoningTokens != 8 { - t.Errorf("reasoning_tokens = %d, want 8 (accurate count, not %d completion)", - resp.Usage.OutputTokensDetail.ReasoningTokens, usage.CompletionTokens) - } -} - -// TestInjectReasoningDetailIntoRawUsage covers the passthrough path: a -// provider-reported accurate reasoning count is spliced into the raw -// chat.completion usage object, without overriding an existing value. -func TestInjectReasoningDetailIntoRawUsage(t *testing.T) { - // Adds detail when absent. - obj := map[string]any{ - "object": "chat.completion", - "usage": map[string]any{ - "prompt_tokens": float64(10), - "completion_tokens": float64(30), - }, - } - injectReasoningDetailIntoRawUsage(obj, protocol.UsageInfo{CompletionTokens: 30, ReasoningTokens: 12}) - details := obj["usage"].(map[string]any)["completion_tokens_details"].(map[string]any) - if details["reasoning_tokens"] != 12 { - t.Errorf("reasoning_tokens = %v, want 12", details["reasoning_tokens"]) - } - - // No-op when the provider reported no reasoning count. - plain := map[string]any{"usage": map[string]any{"completion_tokens": float64(5)}} - injectReasoningDetailIntoRawUsage(plain, protocol.UsageInfo{CompletionTokens: 5, ReasoningTokens: 0}) - if _, ok := plain["usage"].(map[string]any)["completion_tokens_details"]; ok { - t.Errorf("expected no details injected for zero reasoning count") - } - - // Never overrides an existing detail. - existing := map[string]any{ - "usage": map[string]any{ - "completion_tokens_details": map[string]any{"reasoning_tokens": float64(99)}, - }, - } - injectReasoningDetailIntoRawUsage(existing, protocol.UsageInfo{ReasoningTokens: 5}) - got := existing["usage"].(map[string]any)["completion_tokens_details"].(map[string]any)["reasoning_tokens"] - if got != float64(99) { - t.Errorf("reasoning_tokens = %v, want 99 (must not override)", got) - } - - // No-op when there is no usage object at all. - noUsage := map[string]any{"object": "chat.completion"} - injectReasoningDetailIntoRawUsage(noUsage, protocol.UsageInfo{ReasoningTokens: 7}) - if _, ok := noUsage["usage"]; ok { - t.Errorf("did not expect a usage object to be created") - } -} - -// TestDetectMediaRequirementAndTokenEstimate verifies media detection and that -// the media-aware estimator counts an image as a flat cost rather than its -// inflated base64 length (which would distort routing admission and billing). -func TestDetectMediaRequirementAndTokenEstimate(t *testing.T) { - bigImage := "data:image/png;base64," + strings.Repeat("A", 200_000) - parsed := map[string]any{ - "messages": []any{ - map[string]any{"role": "user", "content": []any{ - map[string]any{"type": "text", "text": "what is in this image?"}, - map[string]any{"type": "image_url", "image_url": map[string]any{"url": bigImage}}, - }}, - }, - } - if !detectMediaRequirement(parsed) { - t.Fatal("expected media requirement detected for an image_url content part") - } - got := estimatePromptTokens(parsed) - if got > 1000 { - t.Fatalf("media-aware ROUTING estimate must ignore base64 length; got %d tokens for a 200KB image", got) - } - if got < imagePromptTokenCost { - t.Fatalf("routing estimate should include the flat per-image cost (%d); got %d", imagePromptTokenCost, got) - } - // Billing intentionally stays a guaranteed UPPER bound (still counts the - // base64 bytes) so it can never under-reserve; over-reservation is refunded - // after inference. It must therefore exceed the small routing estimate here. - if b := estimateBillingPromptTokens(parsed); b <= got { - t.Fatalf("billing upper bound (%d) should exceed the routing estimate (%d) for a base64 image", b, got) - } - - textParsed := map[string]any{ - "messages": []any{ - map[string]any{"role": "user", "content": "hello world"}, - }, - } - if detectMediaRequirement(textParsed) { - t.Fatal("a text-only request must not be flagged as requiring vision") - } -} - -// TestDetectMediaRequirementResponsesInput verifies the Responses API surface -// (input[].content parts) is gated too, so a media request there fails fast -// rather than being silently routed text-blind. -func TestDetectMediaRequirementResponsesInput(t *testing.T) { - bigImage := "data:image/png;base64," + strings.Repeat("A", 200_000) - withImage := map[string]any{ - "input": []any{ - map[string]any{"role": "user", "content": []any{ - map[string]any{"type": "input_text", "text": "describe"}, - map[string]any{"type": "input_image", "image_url": bigImage}, - }}, - }, - } - if !detectMediaRequirement(withImage) { - t.Fatal("expected media detected in Responses API input parts") - } - got := estimatePromptTokens(withImage) - if got > 1000 { - t.Fatalf("Responses input estimate must ignore base64 length; got %d tokens for a 200KB image", got) - } - if got < imagePromptTokenCost { - t.Fatalf("Responses input estimate should include flat image cost (%d); got %d", imagePromptTokenCost, got) - } - textOnly := map[string]any{"input": "just a string prompt"} - if detectMediaRequirement(textOnly) { - t.Fatal("a string Responses input must not be flagged as media") - } -} - -// TestDetectMediaRequirementAnthropicImageBlock verifies Anthropic /v1/messages -// image content blocks ({"type":"image","source":...}) are detected for the -// vision routing gate, not just OpenAI-style image_url parts. -func TestDetectMediaRequirementAnthropicImageBlock(t *testing.T) { - parsed := map[string]any{ - "messages": []any{ - map[string]any{"role": "user", "content": []any{ - map[string]any{"type": "text", "text": "what is this?"}, - map[string]any{"type": "image", "source": map[string]any{ - "type": "base64", "media_type": "image/png", "data": "AAAA", - }}, - }}, - }, - } - if !detectMediaRequirement(parsed) { - t.Fatal("expected Anthropic image content block to be detected as media") - } -} - -// TestBodyForProviderPenaltyGating verifies the coordinator strips the penalty -// fields that crash the pre-fix VLM path, but ONLY for vision requests routed to -// a provider below penaltySafeProviderVersion. Fixed providers and text requests -// keep their penalties. See bodyForProvider. -func TestBodyForProviderPenaltyGating(t *testing.T) { - visionBody := []byte(`{"model":"gemma-4-26b","temperature":1.0,"precision_probe":9007199254740993,"repetition_penalty":1.0,` + - `"presence_penalty":0.0,"frequency_penalty":0.0,"messages":[{"role":"user","content":[` + - `{"type":"text","text":"what is this?"},` + - `{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]}]}`) - textBody := []byte(`{"model":"gemma-4-26b","repetition_penalty":1.3,` + - `"messages":[{"role":"user","content":"hello"}]}`) - - has := func(body []byte, key string) bool { - var m map[string]any - if err := json.Unmarshal(body, &m); err != nil { - t.Fatalf("unmarshal: %v", err) - } - _, ok := m[key] - return ok - } - penalties := []string{"repetition_penalty", "presence_penalty", "frequency_penalty"} - - // Vision + pre-fix provider → penalties stripped, other fields kept. - out := bodyForProvider(visionBody, true, ®istry.Provider{Version: "0.6.6"}) - for _, k := range penalties { - if has(out, k) { - t.Fatalf("pre-fix vision provider: expected %q stripped", k) - } - } - if !has(out, "temperature") || !has(out, "messages") { - t.Fatal("pre-fix vision provider: non-penalty fields must be preserved") - } - if !bytes.Contains(out, []byte("9007199254740993")) { - t.Fatalf("pre-fix vision provider: field stripping rounded an exact numeric literal: %s", out) - } - - // Vision + provider with unknown version → stripped (conservative). - if has(bodyForProvider(visionBody, true, ®istry.Provider{Version: ""}), "repetition_penalty") { - t.Fatal("unknown-version vision provider: expected penalties stripped") - } - - // Vision + fixed provider (== and > floor) → penalties preserved. - for _, v := range []string{"0.6.7", "0.7.0"} { - if !has(bodyForProvider(visionBody, true, ®istry.Provider{Version: v}), "repetition_penalty") { - t.Fatalf("fixed provider %s: penalties must pass through", v) - } - } - - // Text request (any provider) → penalties preserved. - if !has(bodyForProvider(textBody, false, ®istry.Provider{Version: "0.6.6"}), "repetition_penalty") { - t.Fatal("text request: penalties must pass through") - } - - // Vision + pre-fix provider but no penalty fields → returns rawBody unchanged. - clean := []byte(`{"model":"gemma-4-26b","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]}]}`) - if out := bodyForProvider(clean, true, ®istry.Provider{Version: "0.6.6"}); string(out) != string(clean) { - t.Fatal("no-penalty vision body should be returned unchanged") - } -} diff --git a/coordinator/api/consumer_media_url_test.go b/coordinator/api/consumer_media_url_test.go deleted file mode 100644 index a9a9c88a23..0000000000 --- a/coordinator/api/consumer_media_url_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package api - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" - "unicode/utf8" -) - -// C4: media parts carrying a remote/non-data: URL must be detected so the -// coordinator can reject them pre-dispatch (the provider VLM path is data:-only). - -func TestMediaPartURLString_AllShapes(t *testing.T) { - cases := []struct { - name string - part map[string]any - wantRef string - wantMed bool - }{ - {"image_url object remote", map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://x/a.png"}}, "https://x/a.png", true}, - {"image_url bare string", map[string]any{"type": "image_url", "image_url": "https://x/b.png"}, "https://x/b.png", true}, - {"image_url data uri", map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,AAAA"}}, "data:image/png;base64,AAAA", true}, - {"input_image string", map[string]any{"type": "input_image", "image_url": "https://x/c.png"}, "https://x/c.png", true}, - {"video_url object", map[string]any{"type": "video_url", "video_url": map[string]any{"url": "https://x/v.mp4"}}, "https://x/v.mp4", true}, - {"anthropic image url", map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": "https://x/d.png"}}, "https://x/d.png", true}, - {"anthropic image base64 inline", map[string]any{"type": "image", "source": map[string]any{"type": "base64", "data": "AAAA"}}, "data:anthropic-inline-base64", true}, - {"text part not media", map[string]any{"type": "text", "text": "hi"}, "", false}, - } - for _, c := range cases { - ref, isMedia := mediaPartURLString(c.part) - if isMedia != c.wantMed || ref != c.wantRef { - t.Errorf("%s: got (%q,%v) want (%q,%v)", c.name, ref, isMedia, c.wantRef, c.wantMed) - } - } -} - -func msg(content any) map[string]any { return map[string]any{"role": "user", "content": content} } - -func TestValidateMediaParts_RejectsRemote(t *testing.T) { - remote := []any{map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://example.com/x.png"}}} - dataURI := []any{map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,AAAA"}}} - mixed := []any{ - map[string]any{"type": "text", "text": "describe"}, - map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,AAAA"}}, - map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://example.com/y.png"}}, - } - - if ref, ok := validateMediaParts(map[string]any{"messages": []any{msg(remote)}}); ok || ref == "" { - t.Errorf("remote URL must be rejected; got ref=%q ok=%v", ref, ok) - } - if _, ok := validateMediaParts(map[string]any{"messages": []any{msg(dataURI)}}); !ok { - t.Error("data: URI must pass") - } - if ref, ok := validateMediaParts(map[string]any{"messages": []any{msg(mixed)}}); ok || ref != "https://example.com/y.png" { - t.Errorf("mixed body must return the first remote URL; got ref=%q ok=%v", ref, ok) - } - // Responses API input[] surface. - if _, ok := validateMediaParts(map[string]any{"input": []any{map[string]any{"content": remote}}}); ok { - t.Error("remote URL in Responses input[] must be rejected") - } - // Text-only body passes. - if _, ok := validateMediaParts(map[string]any{"messages": []any{msg("just text")}}); !ok { - t.Error("text-only body must pass") - } - // Anthropic inline base64 passes (not a remote URL). - anth := []any{map[string]any{"type": "image", "source": map[string]any{"type": "base64", "data": "AAAA"}}} - if _, ok := validateMediaParts(map[string]any{"messages": []any{msg(anth)}}); !ok { - t.Error("anthropic inline base64 must pass (only remote refs are rejected in v1)") - } -} - -// TestRejectRemoteMediaURLsIsUnconditional pins the gate as unconditional on -// every surface. The generic (completions + Anthropic) surface never fetches, -// so forwarding a remote URL there can only end in a provider-side 400 — the -// retired DARKBLOOM_VISION_REJECT_REMOTE_URLS switch must never re-enable it. -func TestRejectRemoteMediaURLsIsUnconditional(t *testing.T) { - s := &Server{logger: quietLogger()} - remotePart := map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://example.com/x.png"}} - remote := map[string]any{"messages": []any{msg([]any{remotePart})}} - - // The retired flag is read nowhere: no value of it may disable the gate. - for _, flag := range []string{"", "false", "0", "true"} { - t.Setenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS", flag) - w := httptest.NewRecorder() - if !s.rejectRemoteMediaURLs(w, plainReq(), remote, "test", "test", true, false) { - t.Fatalf("flag=%q: a remote media URL must always be rejected pre-dispatch", flag) - } - if w.Code != http.StatusBadRequest { - t.Errorf("flag=%q: status = %d, want 400", flag, w.Code) - } - } - - // Unconditional on the flag, still conditional on the request: non-vision - // bodies and inline data: URIs pass untouched. - if s.rejectRemoteMediaURLs(httptest.NewRecorder(), plainReq(), remote, "test", "test", false, false) { - t.Error("non-vision requests must never be gated") - } - inline := map[string]any{"messages": []any{msg([]any{ - map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,AAAA"}}, - })}} - if s.rejectRemoteMediaURLs(httptest.NewRecorder(), plainReq(), inline, "test", "test", true, false) { - t.Error("inline data: URI must pass") - } -} - -func TestTruncateMediaRef(t *testing.T) { - // "é" is 2 bytes; placed at offset 199 it straddles the 200-byte cut, so a - // naive ref[:200] ends on a partial rune that encoding/json renders U+FFFD. - straddling := strings.Repeat("a", 199) + "é" + strings.Repeat("b", 50) - cases := []struct { - name string - ref string - want string - }{ - {"short ref verbatim", "https://example.com/a.png", "https://example.com/a.png"}, - {"exactly at the cap verbatim", strings.Repeat("a", 200), strings.Repeat("a", 200)}, - {"ascii over the cap", strings.Repeat("a", 201), strings.Repeat("a", 200) + "…"}, - {"multibyte rune straddling the cut is dropped", straddling, strings.Repeat("a", 199) + "…"}, - } - for _, c := range cases { - got := truncateMediaRef(c.ref) - if got != c.want { - t.Errorf("%s: truncateMediaRef() = %q, want %q", c.name, got, c.want) - } - if !utf8.ValidString(got) { - t.Errorf("%s: truncateMediaRef() emitted invalid UTF-8: %q", c.name, got) - } - } -} diff --git a/coordinator/api/consumer_metadata_details_test.go b/coordinator/api/consumer_metadata_details_test.go index c4eac364c3..491e5b2509 100644 --- a/coordinator/api/consumer_metadata_details_test.go +++ b/coordinator/api/consumer_metadata_details_test.go @@ -365,28 +365,6 @@ func TestStreamingChatSwallowsDecoratedProviderDone(t *testing.T) { } } -func TestStripSSEDoneEventsPreservesSiblingEvents(t *testing.T) { - t.Parallel() - input := "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n" + - "event: done\nid: provider-terminal\ndata: [DONE]\n\n" - - got, removed := stripSSEDoneEvents(input) - if !removed { - t.Fatal("expected provider terminator to be removed") - } - if strings.Contains(got, "[DONE]") || strings.Contains(got, "provider-terminal") { - t.Fatalf("provider terminator survived: %s", got) - } - if !strings.Contains(got, `"content":"hi"`) { - t.Fatalf("sibling content event was removed: %s", got) - } - - got, removed = stripSSEDoneEvents("\uFEFFdata: [DONE]\n\n") - if !removed || strings.TrimSpace(got) != "" { - t.Fatalf("BOM-prefixed provider terminator survived: %q", got) - } -} - func startChatMetadataTestServer(t *testing.T, model string) (*httptest.Server, *websocket.Conn, string) { t.Helper() logger := quietLogger() diff --git a/coordinator/api/consumer_normalize_test.go b/coordinator/api/consumer_normalize_test.go deleted file mode 100644 index e8fc799646..0000000000 --- a/coordinator/api/consumer_normalize_test.go +++ /dev/null @@ -1,758 +0,0 @@ -package api - -import ( - "encoding/json" - "math" - "reflect" - "strconv" - "strings" - "testing" - - "github.com/eigeninference/d-inference/coordinator/api/types" - "github.com/eigeninference/d-inference/coordinator/protocol" -) - -func TestExtractMessage(t *testing.T) { - chunks := []string{ - "data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n", - "data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"delta\":{\"content\":\" world\"}}]}\n\n", - } - - msg := extractMessage(chunks) - if msg.Content != "Hello world" { - t.Errorf("content = %q, want %q", msg.Content, "Hello world") - } - if len(msg.ToolCalls) != 0 { - t.Errorf("tool_calls = %v, want empty", msg.ToolCalls) - } -} - -func TestExtractMessageEmpty(t *testing.T) { - msg := extractMessage(nil) - if msg.Content != "" { - t.Errorf("content = %q, want empty", msg.Content) - } -} - -func TestExtractMessageWithToolCalls(t *testing.T) { - chunks := []string{ - `data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_abc","type":"function","function":{"name":"get_weather","arguments":""}}]}}]}`, - `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"lo"}}]}}]}`, - `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"cation\":"}}]}}]}`, - `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"SF\"}"}}]}}]}`, - } - - msg := extractMessage(chunks) - if msg.Content != "" { - t.Errorf("content = %q, want empty", msg.Content) - } - if len(msg.ToolCalls) != 1 { - t.Fatalf("tool_calls length = %d, want 1", len(msg.ToolCalls)) - } - tc := msg.ToolCalls[0] - if tc["id"] != "call_abc" { - t.Errorf("tool_call id = %v, want call_abc", tc["id"]) - } - fn := tc["function"].(map[string]any) - if fn["name"] != "get_weather" { - t.Errorf("function name = %v, want get_weather", fn["name"]) - } - if fn["arguments"] != `{"location":"SF"}` { - t.Errorf("function arguments = %v, want {\"location\":\"SF\"}", fn["arguments"]) - } -} - -func TestNormalizeSSEChunk(t *testing.T) { - tests := []struct { - name string - input string - wantChecks func(t *testing.T, got string) - }{ - { - name: "null content becomes empty string", - input: `data: {"choices":[{"delta":{"content":null}}]}`, - wantChecks: func(t *testing.T, got string) { - if !strings.Contains(got, `"content":""`) { - t.Errorf("expected content to be empty string, got: %s", got) - } - }, - }, - { - name: "null tool_calls becomes empty array", - input: `data: {"choices":[{"delta":{"content":"hi","tool_calls":null}}]}`, - wantChecks: func(t *testing.T, got string) { - if !strings.Contains(got, `"tool_calls":[]`) { - t.Errorf("expected tool_calls to be empty array, got: %s", got) - } - }, - }, - { - name: "usage null is removed entirely", - input: `data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":null,"reasoning":null,"tool_calls":null,"reasoning_content":null},"finish_reason":null}],"usage":null}`, - wantChecks: func(t *testing.T, got string) { - if strings.Contains(got, `"usage"`) { - t.Errorf("expected usage to be removed, got: %s", got) - } - if !strings.Contains(got, `"content":""`) { - t.Errorf("expected content to be empty string, got: %s", got) - } - if !strings.Contains(got, `"reasoning":""`) { - t.Errorf("expected reasoning to be empty string, got: %s", got) - } - if !strings.Contains(got, `"tool_calls":[]`) { - t.Errorf("expected tool_calls to be empty array, got: %s", got) - } - // Both reasoning and reasoning_content should be present: - // reasoning_content for AI SDK compatibility, reasoning - // for ForgeCode and other clients. - if !strings.Contains(got, `"reasoning_content"`) { - t.Errorf("expected reasoning_content to be preserved for AI SDK, got: %s", got) - } - }, - }, - { - name: "no nulls returns unchanged", - input: `data: {"choices":[{"delta":{"content":"hello"}}]}`, - wantChecks: func(t *testing.T, got string) { - if got != `data: {"choices":[{"delta":{"content":"hello"}}]}` { - t.Errorf("expected unchanged, got: %s", got) - } - }, - }, - { - name: "valid usage object is preserved", - input: `data: {"id":"1","choices":[],"usage":{"prompt_tokens":5,"completion_tokens":3,"total_tokens":8}}`, - wantChecks: func(t *testing.T, got string) { - if !strings.Contains(got, `"prompt_tokens"`) { - t.Errorf("expected usage to be preserved, got: %s", got) - } - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := normalizeSSEChunk(tt.input) - tt.wantChecks(t, got) - }) - } -} - -func TestNormalizeCompleteChatResponse(t *testing.T) { - resp := map[string]any{ - "id": "chatcmpl-1", - "object": "chat.completion", - "model": "/Users/provider/.cache/huggingface/hub/models--mlx-community--MiniMax-M2.5-8bit/snapshots/main", - "choices": []any{ - map[string]any{ - "index": 0, - "message": map[string]any{ - "role": "assistant", - "content": "work through it\n\n4", - "reasoning_content": "existing reasoning", - "tool_calls": nil, - }, - }, - }, - "system_fingerprint": nil, - } - - normalizeCompleteChatResponse(resp, "mlx-community/MiniMax-M2.5-8bit") - - if resp["model"] != "mlx-community/MiniMax-M2.5-8bit" { - t.Fatalf("model = %v", resp["model"]) - } - if _, ok := resp["system_fingerprint"]; ok { - t.Fatalf("system_fingerprint should be removed: %#v", resp) - } - message := resp["choices"].([]any)[0].(map[string]any)["message"].(map[string]any) - if message["content"] != "4" { - t.Fatalf("content = %q, want 4", message["content"]) - } - reasoning := message["reasoning"].(string) - if message["reasoning_content"] != reasoning { - t.Fatalf("reasoning_content = %v, want synchronized reasoning %q", message["reasoning_content"], reasoning) - } - if _, ok := message["tool_calls"]; ok { - t.Fatalf("null tool_calls should be removed: %#v", message) - } - if !strings.Contains(reasoning, "existing reasoning") || !strings.Contains(reasoning, "work through it") { - t.Fatalf("reasoning was not merged correctly: %q", reasoning) - } - details := message["reasoning_details"].([]types.ReasoningDetail) - if len(details) != 1 || details[0].Text != reasoning || details[0].ID != "reasoning-text-0" { - t.Fatalf("reasoning_details = %#v, want full merged reasoning", details) - } -} - -func TestNormalizeCompleteChatResponseNullContent(t *testing.T) { - resp := map[string]any{ - "object": "chat.completion", - "choices": []any{ - map[string]any{ - "message": map[string]any{ - "role": "assistant", - "content": nil, - }, - }, - }, - } - - normalizeCompleteChatResponse(resp, "test-model") - - message := resp["choices"].([]any)[0].(map[string]any)["message"].(map[string]any) - if message["content"] != "" { - t.Fatalf("content = %v, want empty string", message["content"]) - } -} - -func TestNormalizeSSEChunkReasoningDetails(t *testing.T) { - parseDelta := func(t *testing.T, chunk string, choice int) map[string]any { - t.Helper() - var payload map[string]any - if err := json.Unmarshal([]byte(strings.TrimPrefix(normalizeSSEChunk(chunk), "data: ")), &payload); err != nil { - t.Fatalf("unmarshal normalized chunk: %v", err) - } - choices := payload["choices"].([]any) - return choices[choice].(map[string]any)["delta"].(map[string]any) - } - assertCanonical := func(t *testing.T, delta map[string]any, text, id string) { - t.Helper() - details, ok := delta["reasoning_details"].([]any) - if !ok || len(details) != 1 { - t.Fatalf("reasoning_details = %#v, want one detail", delta["reasoning_details"]) - } - detail := details[0].(map[string]any) - if detail["type"] != "reasoning.text" || detail["text"] != text || detail["id"] != id || detail["format"] != "unknown" || detail["index"] != float64(0) || detail["signature"] != nil { - t.Fatalf("reasoning detail = %#v", detail) - } - } - - t.Run("reasoning content alias gets canonical detail", func(t *testing.T) { - delta := parseDelta(t, `data: {"choices":[{"index":3,"delta":{"reasoning_content":"thinking"}}]}`, 0) - if delta["reasoning"] != "thinking" || delta["reasoning_content"] != "thinking" { - t.Fatalf("reasoning aliases not synchronized: %#v", delta) - } - assertCanonical(t, delta, "thinking", "reasoning-text-3") - }) - - t.Run("reasoning content wins conflicting aliases", func(t *testing.T) { - delta := parseDelta(t, `data: {"choices":[{"index":5,"delta":{"reasoning":"legacy","reasoning_content":"canonical"}}]}`, 0) - if delta["reasoning"] != "canonical" || delta["reasoning_content"] != "canonical" { - t.Fatalf("reasoning_content did not win alias conflict: %#v", delta) - } - assertCanonical(t, delta, "canonical", "reasoning-text-5") - }) - - t.Run("malformed aliases are forced to raw equality", func(t *testing.T) { - delta := parseDelta(t, `data: {"choices":[{"index":0,"delta":{"reasoning":{"unexpected":true},"reasoning_content":["opaque"]}}]}`, 0) - reasoning, err := json.Marshal(delta["reasoning"]) - if err != nil { - t.Fatalf("marshal reasoning alias: %v", err) - } - reasoningContent, err := json.Marshal(delta["reasoning_content"]) - if err != nil { - t.Fatalf("marshal reasoning_content alias: %v", err) - } - if string(reasoning) != string(reasoningContent) || string(reasoning) != `["opaque"]` { - t.Fatalf("malformed aliases differ: reasoning=%s reasoning_content=%s", reasoning, reasoningContent) - } - if _, ok := delta["reasoning_details"]; ok { - t.Fatalf("malformed reasoning created details: %#v", delta) - } - }) - - t.Run("invalid indexes fall back to distinct choice positions", func(t *testing.T) { - chunk := `data: {"choices":[{"index":-1,"delta":{"reasoning":"a"}},{"index":"9","delta":{"reasoning":"b"}},{"index":1.5,"delta":{"reasoning":"c"}}]}` - for choice, wantID := range []string{"reasoning-text-0", "reasoning-text-1", "reasoning-text-2"} { - delta := parseDelta(t, chunk, choice) - assertCanonical(t, delta, string(rune('a'+choice)), wantID) - } - }) - - t.Run("stable IDs across chunks and choices", func(t *testing.T) { - first := parseDelta(t, `data: {"choices":[{"index":2,"delta":{"reasoning":"a"}},{"index":7,"delta":{"reasoning":"b"}}]}`, 0) - second := parseDelta(t, `data: {"choices":[{"index":2,"delta":{"reasoning":"c"}},{"index":7,"delta":{"reasoning":"d"}}]}`, 0) - other := parseDelta(t, `data: {"choices":[{"index":2,"delta":{"reasoning":"a"}},{"index":7,"delta":{"reasoning":"b"}}]}`, 1) - assertCanonical(t, first, "a", "reasoning-text-2") - assertCanonical(t, second, "c", "reasoning-text-2") - assertCanonical(t, other, "b", "reasoning-text-7") - }) - - t.Run("existing details are preserved", func(t *testing.T) { - delta := parseDelta(t, `data: {"choices":[{"index":0,"delta":{"reasoning":"thinking","reasoning_details":[{"type":"provider.custom","data":{"opaque":true}}]}}]}`, 0) - details := delta["reasoning_details"].([]any) - detail := details[0].(map[string]any) - if len(details) != 1 || detail["type"] != "provider.custom" || detail["data"].(map[string]any)["opaque"] != true { - t.Fatalf("existing reasoning_details changed: %#v", details) - } - }) - - t.Run("empty reasoning synchronizes aliases without details", func(t *testing.T) { - for _, chunk := range []string{ - `data: {"choices":[{"index":0,"delta":{"reasoning":""}}]}`, - `data: {"choices":[{"index":0,"delta":{"reasoning_content":null}}]}`, - } { - delta := parseDelta(t, chunk, 0) - if delta["reasoning"] != "" || delta["reasoning_content"] != "" { - t.Fatalf("empty reasoning aliases not synchronized: %#v", delta) - } - if _, ok := delta["reasoning_details"]; ok { - t.Fatalf("empty reasoning added details: %#v", delta) - } - } - }) -} - -func TestNormalizeCompleteChatResponseReasoningDetails(t *testing.T) { - existingDetails := []any{map[string]any{"type": "provider.custom", "opaque": "value"}} - resp := map[string]any{ - "object": "chat.completion", - "choices": []any{ - map[string]any{"index": float64(4), "message": map[string]any{"content": "answer", "reasoning": "full thought"}}, - map[string]any{"index": float64(9), "message": map[string]any{"content": "answer", "reasoning_content": "provider thought", "reasoning_details": existingDetails}}, - map[string]any{"index": float64(11), "message": map[string]any{"content": "answer", "reasoning": ""}}, - map[string]any{"index": float64(12), "message": map[string]any{"content": "answer", "reasoning": "legacy", "reasoning_content": "canonical"}}, - }, - } - - normalizeCompleteChatResponse(resp, "test-model") - choices := resp["choices"].([]any) - first := choices[0].(map[string]any)["message"].(map[string]any) - if first["reasoning_content"] != "full thought" { - t.Fatalf("reasoning aliases not synchronized: %#v", first) - } - firstDetail := first["reasoning_details"].([]types.ReasoningDetail) - if len(firstDetail) != 1 || firstDetail[0].Text != "full thought" || firstDetail[0].ID != "reasoning-text-4" || firstDetail[0].Signature != nil { - t.Fatalf("canonical reasoning_details = %#v", firstDetail) - } - second := choices[1].(map[string]any)["message"].(map[string]any) - if second["reasoning"] != "provider thought" || second["reasoning_content"] != "provider thought" { - t.Fatalf("reasoning aliases not synchronized: %#v", second) - } - preserved := second["reasoning_details"].([]any) - if len(preserved) != 1 || preserved[0].(map[string]any)["type"] != "provider.custom" || preserved[0].(map[string]any)["opaque"] != "value" { - t.Fatalf("existing reasoning_details changed: %#v", preserved) - } - third := choices[2].(map[string]any)["message"].(map[string]any) - if _, ok := third["reasoning_details"]; ok { - t.Fatalf("empty reasoning added details: %#v", third) - } - fourth := choices[3].(map[string]any)["message"].(map[string]any) - merged := "legacy\n\ncanonical" - if fourth["reasoning"] != merged || fourth["reasoning_content"] != merged { - t.Fatalf("complete aliases did not retain both values: %#v", fourth) - } - fourthDetail := fourth["reasoning_details"].([]types.ReasoningDetail) - if len(fourthDetail) != 1 || fourthDetail[0].Text != merged || fourthDetail[0].ID != "reasoning-text-12" { - t.Fatalf("conflicting alias details = %#v", fourthDetail) - } -} - -func TestNormalizeCompleteChatResponseInvalidChoiceIndexes(t *testing.T) { - resp := map[string]any{ - "object": "chat.completion", - "choices": []any{ - map[string]any{"index": float64(-1), "message": map[string]any{"reasoning": "a"}}, - map[string]any{"index": 1.5, "message": map[string]any{"reasoning": "b"}}, - map[string]any{"index": math.NaN(), "message": map[string]any{"reasoning": "c"}}, - map[string]any{"index": math.Inf(1), "message": map[string]any{"reasoning": "d"}}, - map[string]any{"index": int64(-2), "message": map[string]any{"reasoning": "e"}}, - }, - } - - normalizeCompleteChatResponse(resp, "test-model") - for position, rawChoice := range resp["choices"].([]any) { - message := rawChoice.(map[string]any)["message"].(map[string]any) - detail := message["reasoning_details"].([]types.ReasoningDetail)[0] - wantID := "reasoning-text-" + strconv.Itoa(position) - if detail.ID != wantID { - t.Fatalf("choice %d detail ID = %q, want %q", position, detail.ID, wantID) - } - } -} - -func TestNormalizeCompleteChatResponseConflictPreservesResponsesReasoning(t *testing.T) { - resp := map[string]any{ - "id": "chatcmpl-conflict", - "object": "chat.completion", - "created": float64(123), - "choices": []any{map[string]any{ - "index": float64(0), - "message": map[string]any{ - "content": "answer", - "reasoning": "legacy", - "reasoning_content": "canonical", - }, - "finish_reason": "stop", - }}, - "usage": map[string]any{}, - } - normalizeCompleteChatResponse(resp, "test-model") - - wire, err := json.Marshal(resp) - if err != nil { - t.Fatalf("marshal normalized chat response: %v", err) - } - var chat types.ChatCompletionResponse - if err := json.Unmarshal(wire, &chat); err != nil { - t.Fatalf("decode normalized chat response: %v", err) - } - converted := chatCompletionToResponses(chat, "test-model", "", "") - reasoningItem := converted.Output[0].(map[string]any) - summary := reasoningItem["summary"].([]map[string]any) - if summary[0]["text"] != "legacy\n\ncanonical" { - t.Fatalf("Responses reasoning = %q, want old merged value", summary[0]["text"]) - } - convertedWire, err := json.Marshal(converted) - if err != nil { - t.Fatalf("marshal Responses conversion: %v", err) - } - if strings.Contains(string(convertedWire), "reasoning_details") || strings.Contains(string(convertedWire), "reasoning_content") { - t.Fatalf("chat aliases leaked into Responses API wire: %s", convertedWire) - } -} - -func TestBuildNonStreamingResponseReasoningDetailsWire(t *testing.T) { - chat := buildNonStreamingResponse( - "req-reasoning", - "test-model", - extractedMessage{Content: "answer", Reasoning: "full thought"}, - protocol.UsageInfo{PromptTokens: 2, CompletionTokens: 3}, - 16, - "", - "", - ) - - wire, err := json.Marshal(chat) - if err != nil { - t.Fatalf("marshal reconstructed chat response: %v", err) - } - var decoded map[string]any - if err := json.Unmarshal(wire, &decoded); err != nil { - t.Fatalf("unmarshal reconstructed chat response: %v", err) - } - message := decoded["choices"].([]any)[0].(map[string]any)["message"].(map[string]any) - if message["reasoning"] != "full thought" || message["reasoning_content"] != "full thought" { - t.Fatalf("reconstructed reasoning aliases = %#v", message) - } - detail := message["reasoning_details"].([]any)[0].(map[string]any) - if detail["type"] != "reasoning.text" || detail["text"] != "full thought" || detail["id"] != "reasoning-text-0" || detail["format"] != "unknown" || detail["index"] != float64(0) || detail["signature"] != nil { - t.Fatalf("reconstructed reasoning detail = %#v", detail) - } - - responsesWire, err := json.Marshal(chatCompletionToResponses(chat, "test-model", "", "")) - if err != nil { - t.Fatalf("marshal converted Responses API result: %v", err) - } - if strings.Contains(string(responsesWire), "reasoning_details") || strings.Contains(string(responsesWire), "reasoning_content") { - t.Fatalf("chat aliases leaked into Responses API wire: %s", responsesWire) - } -} - -func TestBuildNonStreamingResponsePreservesUpstreamReasoningDetails(t *testing.T) { - msg := extractMessageWithReasoningPolicy([]string{ - `data: {"choices":[{"delta":{"reasoning":"legacy","reasoning_content":"canonical","reasoning_details":[{"type":"provider.custom","data":"first"}]}}]}`, - `data: {"choices":[{"message":{"reasoning_content":"next","reasoning_details":[{"type":"reasoning.encrypted","data":"second"}]}}]}`, - }, true) - if msg.Reasoning != "canonicalnext" { - t.Fatalf("reconstructed reasoning = %q, want reasoning_content precedence", msg.Reasoning) - } - chat := buildNonStreamingResponse("req-upstream-details", "test-model", msg, protocol.UsageInfo{}, 16, "", "") - wire, err := json.Marshal(chat) - if err != nil { - t.Fatalf("marshal reconstructed response: %v", err) - } - var decoded map[string]any - if err := json.Unmarshal(wire, &decoded); err != nil { - t.Fatalf("decode reconstructed response: %v", err) - } - message := decoded["choices"].([]any)[0].(map[string]any)["message"].(map[string]any) - details := message["reasoning_details"].([]any) - if len(details) != 2 || details[0].(map[string]any)["type"] != "provider.custom" || details[1].(map[string]any)["type"] != "reasoning.encrypted" { - t.Fatalf("upstream reasoning_details not preserved in order: %#v", details) - } - if details[0].(map[string]any)["data"] != "first" || details[1].(map[string]any)["data"] != "second" { - t.Fatalf("upstream reasoning_details values changed: %#v", details) - } -} - -func TestExtractMessageReasoningDetailsNullPlaceholder(t *testing.T) { - t.Run("later arrays supersede null and accumulate", func(t *testing.T) { - msg := extractMessageWithReasoningPolicy([]string{ - `data: {"choices":[{"delta":{"reasoning":"a","reasoning_details":null}}]}`, - `data: {"choices":[{"delta":{"reasoning":"b","reasoning_details":[{"type":"first"}]}}]}`, - `data: {"choices":[{"delta":{"reasoning":"c","reasoning_details":[{"type":"second"}]}}]}`, - }, true) - details, ok := msg.ReasoningDetails.([]json.RawMessage) - if !ok || len(details) != 2 { - t.Fatalf("accumulated reasoning_details = %#v, want two array items", msg.ReasoningDetails) - } - var first, second map[string]any - if err := json.Unmarshal(details[0], &first); err != nil { - t.Fatalf("decode first reasoning detail: %v", err) - } - if err := json.Unmarshal(details[1], &second); err != nil { - t.Fatalf("decode second reasoning detail: %v", err) - } - if first["type"] != "first" || second["type"] != "second" { - t.Fatalf("reasoning detail order changed: %#v %#v", first, second) - } - }) - - t.Run("lone null survives malformed later chunk", func(t *testing.T) { - msg := extractMessage([]string{ - `data: {"choices":[{"delta":{"reasoning":"a","reasoning_details":null}}]}`, - `data: {"choices":[{"delta":{"reasoning":"b","reasoning_details":[}}]}`, - }) - raw, ok := msg.ReasoningDetails.(json.RawMessage) - if !ok || string(raw) != "null" { - t.Fatalf("lone null reasoning_details = %#v", msg.ReasoningDetails) - } - chat := buildNonStreamingResponse("req-null", "test-model", msg, protocol.UsageInfo{}, 16, "", "") - wire, err := json.Marshal(chat) - if err != nil { - t.Fatalf("marshal null reasoning_details: %v", err) - } - var decoded map[string]any - if err := json.Unmarshal(wire, &decoded); err != nil { - t.Fatalf("decode null reasoning_details response: %v", err) - } - message := decoded["choices"].([]any)[0].(map[string]any)["message"].(map[string]any) - value, exists := message["reasoning_details"] - if !exists || value != nil { - t.Fatalf("null reasoning_details not preserved: %#v", message) - } - }) -} - -func TestExtractMessageReasoningPolicyByEndpoint(t *testing.T) { - chunks := []string{`data: {"choices":[{"delta":{"content":"answer","reasoning":"legacy","reasoning_content":"canonical"}}]}`} - responsesMessage := extractMessage(chunks) - chatMessage := extractMessageWithReasoningPolicy(chunks, true) - if responsesMessage.Reasoning != "legacy" { - t.Fatalf("Responses fallback reasoning = %q, want historical reasoning alias", responsesMessage.Reasoning) - } - if chatMessage.Reasoning != "canonical" { - t.Fatalf("chat fallback reasoning = %q, want reasoning_content", chatMessage.Reasoning) - } - - responses := buildResponsesResponse("req-policy", "test-model", responsesMessage, protocol.UsageInfo{}, 16, "", "") - responsesWire, err := json.Marshal(responses) - if err != nil { - t.Fatalf("marshal Responses fallback: %v", err) - } - if strings.Contains(string(responsesWire), "reasoning_content") || strings.Contains(string(responsesWire), "reasoning_details") { - t.Fatalf("chat fields leaked into Responses fallback: %s", responsesWire) - } - chat := buildNonStreamingResponse("req-policy", "test-model", chatMessage, protocol.UsageInfo{}, 16, "", "") - chatWire, err := json.Marshal(chat) - if err != nil { - t.Fatalf("marshal chat fallback: %v", err) - } - if !strings.Contains(string(chatWire), `"reasoning_content":"canonical"`) || !strings.Contains(string(chatWire), `"reasoning_details"`) { - t.Fatalf("chat fallback missing canonical reasoning fields: %s", chatWire) - } -} - -func TestBuildNonStreamingResponsePreservesNonArrayReasoningDetails(t *testing.T) { - for _, tt := range []struct { - name string - raw string - }{ - {name: "null", raw: `null`}, - {name: "object", raw: `{"type":"provider.custom","opaque":true}`}, - {name: "scalar", raw: `"encrypted-token"`}, - } { - t.Run(tt.name, func(t *testing.T) { - chunk := `data: {"choices":[{"delta":{"reasoning":"thought","reasoning_details":` + tt.raw + `}}]}` - msg := extractMessage([]string{chunk}) - if !msg.ReasoningDetailsPresent { - t.Fatal("reasoning_details key presence was lost") - } - chat := buildNonStreamingResponse("req-non-array", "test-model", msg, protocol.UsageInfo{}, 16, "", "") - wire, err := json.Marshal(chat) - if err != nil { - t.Fatalf("marshal reconstructed response: %v", err) - } - var decoded map[string]any - if err := json.Unmarshal(wire, &decoded); err != nil { - t.Fatalf("decode reconstructed response: %v", err) - } - message := decoded["choices"].([]any)[0].(map[string]any)["message"].(map[string]any) - value, ok := message["reasoning_details"] - if !ok { - t.Fatalf("reasoning_details missing from wire: %s", wire) - } - if tt.name == "object" { - var want any - if err := json.Unmarshal([]byte(tt.raw), &want); err != nil { - t.Fatalf("decode expected reasoning_details: %v", err) - } - if !reflect.DeepEqual(value, want) { - t.Fatalf("reasoning_details = %#v, want %#v", value, want) - } - } else { - got, err := json.Marshal(value) - if err != nil { - t.Fatalf("marshal preserved reasoning_details: %v", err) - } - if string(got) != tt.raw { - t.Fatalf("reasoning_details = %s, want %s", got, tt.raw) - } - } - }) - } -} - -func TestChatCompletionToResponses(t *testing.T) { - chat := types.ChatCompletionResponse{ - ID: "chatcmpl-test", - Object: "chat.completion", - Created: 123, - Model: "local-path", - Choices: []types.ChatCompletionChoice{{ - FinishReason: "tool_calls", - Message: types.ChatCompletionMessage{ - Role: "assistant", - Content: "", - Reasoning: "need weather", - ToolCalls: []map[string]any{ - { - "id": "call_123", - "type": "function", - "function": map[string]any{ - "name": "get_current_weather", - "arguments": `{"city":"Paris"}`, - }, - }, - }, - }, - }}, - Usage: types.ChatCompletionUsage{ - PromptTokens: 10, - CompletionTokens: 5, - TotalTokens: 15, - }, - } - - got := chatCompletionToResponses(chat, "mlx-community/gemma-4-26b-a4b-it-8bit", "", "") - if got.Object != "response" || got.Model != "mlx-community/gemma-4-26b-a4b-it-8bit" { - t.Fatalf("response metadata = %#v", got) - } - output := got.Output - if output[0].(map[string]any)["type"] != "reasoning" { - t.Fatalf("first output = %#v", output[0]) - } - call := output[1].(map[string]any) - if call["type"] != "function_call" || call["call_id"] != "call_123" { - t.Fatalf("function call output = %#v", call) - } - usage := got.Usage - if usage.InputTokens != 10 || usage.OutputTokens != 5 { - t.Fatalf("usage = %#v", usage) - } - - // Verify wire format preserves zero-valued fields. - b, err := json.Marshal(got) - if err != nil { - t.Fatalf("marshal: %v", err) - } - wire := string(b) - if !strings.Contains(wire, `"incomplete_details"`) { - t.Errorf("wire output missing incomplete_details field: %s", wire) - } - if !strings.Contains(wire, `"cached_tokens"`) { - t.Errorf("wire output missing cached_tokens in usage details: %s", wire) - } - if !strings.Contains(wire, `"reasoning_tokens"`) { - t.Errorf("wire output missing reasoning_tokens in usage details: %s", wire) - } -} - -func TestExtractMessageWithNullFields(t *testing.T) { - // Simulates real vllm-mlx chunks where the first chunk has null content - // and subsequent chunks have actual content. - chunks := []string{ - `data: {"id":"chatcmpl-1","choices":[{"index":0,"delta":{"role":"assistant","content":null},"finish_reason":null}]}`, - `data: {"id":"chatcmpl-1","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}`, - `data: {"id":"chatcmpl-1","choices":[{"index":0,"delta":{"content":" world"},"finish_reason":"stop"}]}`, - } - - msg := extractMessage(chunks) - if msg.Content != "Hello world" { - t.Errorf("content = %q, want %q", msg.Content, "Hello world") - } -} - -func TestExtractMessageWithReasoningContentAndThinkTags(t *testing.T) { - chunks := []string{ - `data: {"choices":[{"delta":{"reasoning_content":"hidden"}}]}`, - `data: {"choices":[{"delta":{"content":"more hidden\n\n4"}}]}`, - } - - msg := extractMessage(chunks) - if msg.Content != "4" { - t.Fatalf("content = %q, want 4", msg.Content) - } - if !strings.Contains(msg.Reasoning, "hidden") || !strings.Contains(msg.Reasoning, "more hidden") { - t.Fatalf("reasoning not preserved: %q", msg.Reasoning) - } -} - -func BenchmarkNormalizeSSEChunk_NoNulls(b *testing.B) { - b.ReportAllocs() - // Fast path: no null fields, function should return early. - chunk := `data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1700000000,"model":"qwen3.5-27b","choices":[{"index":0,"delta":{"content":"Hello world"},"finish_reason":null}]}` - - b.ResetTimer() - for range b.N { - _ = normalizeSSEChunk(chunk) - } -} - -func BenchmarkNormalizeSSEChunk_WithNulls(b *testing.B) { - b.ReportAllocs() - // Slow path: has null content, tool_calls, reasoning_content that need fixing. - chunk := `data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1700000000,"model":"qwen3.5-27b","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":null,"reasoning_content":null},"finish_reason":null}],"usage":null,"system_fingerprint":null}` - - b.ResetTimer() - for range b.N { - _ = normalizeSSEChunk(chunk) - } -} - -func BenchmarkNormalizeSSEChunk_Usage(b *testing.B) { - b.ReportAllocs() - // Final chunk with usage object (should be preserved, not removed). - chunk := `data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1700000000,"model":"qwen3.5-27b","choices":[],"usage":{"prompt_tokens":150,"completion_tokens":83,"total_tokens":233}}` - - b.ResetTimer() - for range b.N { - _ = normalizeSSEChunk(chunk) - } -} - -func BenchmarkNormalizeSSEChunk_ReasoningDelta(b *testing.B) { - b.ReportAllocs() - // Slow path: a reasoning delta must be mirrored across both aliases and - // gain reasoning_details (the gate is not what makes this case expensive). - chunk := `data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1700000000,"model":"qwen3.5-27b","choices":[{"index":0,"delta":{"reasoning_content":"Let me think about this"},"finish_reason":null}]}` - - b.ResetTimer() - for range b.N { - _ = normalizeSSEChunk(chunk) - } -} - -func BenchmarkNormalizeSSEChunk_ReasoningDetailsPassthrough(b *testing.B) { - b.ReportAllocs() - // Fast path: reasoning_details without either reasoning alias (and the - // usual finish_reason:null) must be forwarded without a round-trip. - chunk := `data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1700000000,"model":"qwen3.5-27b","choices":[{"index":0,"delta":{"content":"Hello","reasoning_details":[{"type":"reasoning.text","text":"t","index":0}]},"finish_reason":null}]}` - - b.ResetTimer() - for range b.N { - _ = normalizeSSEChunk(chunk) - } -} diff --git a/coordinator/api/consumer_response.go b/coordinator/api/consumer_response.go deleted file mode 100644 index 83255e5e91..0000000000 --- a/coordinator/api/consumer_response.go +++ /dev/null @@ -1,218 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "errors" - "log" - "net/http" - "strings" - - "github.com/eigeninference/d-inference/coordinator/api/types" - "github.com/eigeninference/d-inference/coordinator/protocol" - "github.com/eigeninference/d-inference/coordinator/registry" -) - -func (s *Server) handleNonStreamingResponseWithFirstChunkAndError( - w http.ResponseWriter, - r *http.Request, - pr *registry.PendingRequest, - firstChunks []string, - initialError *protocol.InferenceErrorMessage, -) { - ctx, cancel := context.WithTimeout(r.Context(), inferenceTimeout) - defer cancel() - - var chunks []string - for _, firstChunk := range firstChunks { - if firstChunk != "" { - chunks = append(chunks, firstChunk) - } - } - if initialError != nil { - s.refundReservedBalance(pr, "provider_error:"+pr.RequestID) - s.noteInferenceError(pr.ProviderID, pr, initialError.StatusCode, initialError.Error, initialError.ErrorReason, initialError.TerminalCause, initialError.CoordinatorCause) - s.updateInferenceRouteOutcomeForPending(pr, preResponseProviderErrorOutcome(pr, *initialError)) - s.writeGenericProviderError(w, *initialError) - return - } - - for { - select { - case providerChunk, ok := <-pr.ChunkCh: - if !ok { - select { - case errMsg, ok := <-pr.ErrorCh: - if ok && errMsg.Error != "" { - s.refundReservedBalance(pr, "provider_error:"+pr.RequestID) - s.noteInferenceError(pr.ProviderID, pr, errMsg.StatusCode, errMsg.Error, errMsg.ErrorReason, errMsg.TerminalCause, errMsg.CoordinatorCause) - s.updateInferenceRouteOutcomeForPending(pr, preResponseProviderErrorOutcome(pr, errMsg)) - s.writeGenericProviderError(w, errMsg) - return - } - default: - } - // The provider forwards the raw backend response as a single - // chunk. Detect complete responses (object=chat.completion - // or object=response) and pass through directly — this is - // format-agnostic and works for chat completions, Responses - // API, or any future endpoint without parsing. - if len(chunks) == 1 { - raw := strings.TrimPrefix(chunks[0], "data: ") - var obj map[string]any - if err := json.Unmarshal([]byte(raw), &obj); err == nil { - objType, _ := obj["object"].(string) - // Complete responses have object=chat.completion or - // object=response. Delta chunks have object=chat.completion.chunk. - if objType == "chat.completion" || objType == "response" { - completeUsage, ok := s.awaitNonStreamUsage(ctx, w, pr) - if !ok { - return - } - if objType == "chat.completion" { - normalizeCompleteChatResponse(obj, consumerModel(pr)) - // The provider engine reports "stop" even when generation - // hit the max-tokens bound — correct it from the - // authoritative token counts. - rewriteRawFinishReason(obj, completeUsage, pr.RequestedMaxTokens) - // Keep the passthrough path consistent with the - // SSE-reconstruction path: surface the provider's - // accurate reasoning-token count if its raw usage - // object didn't already carry one. - injectReasoningDetailIntoRawUsage(obj, completeUsage) - injectCacheDetailIntoRawUsage(obj, completeUsage) - if pr.ConsumerEndpoint == completionsEndpoint || - pr.ConsumerEndpoint == messagesEndpoint { - encoded, err := json.Marshal(obj) - if err != nil { - writeJSON(w, http.StatusBadGateway, errorResponse("provider_error", "invalid provider response")) - return - } - msg := extractMessage([]string{"data: " + string(encoded)}) - resp := buildGenericEndpointResponse(pr, msg, completeUsage) - s.noteInferenceSuccess(pr) - writeNonStreamBody(w, pr.Profile.Parent(), resp) - return - } - if pr.IsResponsesAPI { - var chatResp types.ChatCompletionResponse - b, err := json.Marshal(obj) - if err != nil { - log.Printf("WARN: failed to marshal chat response for Responses API conversion: %v", err) - writeJSON(w, http.StatusBadGateway, errorResponse("provider_error", "invalid provider response")) - return - } - if err := json.Unmarshal(b, &chatResp); err != nil { - log.Printf("WARN: failed to unmarshal chat response into typed struct: %v", err) - writeJSON(w, http.StatusBadGateway, errorResponse("provider_error", "invalid provider response")) - return - } - respObj := chatCompletionToResponses( - chatResp, consumerModel(pr), pr.SESignature, - pr.ResponseHash, pr.Traits) - s.noteInferenceSuccess(pr) - writeNonStreamBody(w, pr.Profile.Parent(), respObj) - return - } - } else { - // Native passthrough (object=="response"): the provider - // echoed the concrete build id; rewrite it to the public - // alias so the consumer never sees the quant/build. - sanitizeCacheDetailIntoRawResponsesUsage(obj, completeUsage) - if pr.PublicModel != "" { - obj["model"] = consumerModel(pr) - } - } - if pr.SESignature != "" { - obj["se_signature"] = pr.SESignature - obj["response_hash"] = pr.ResponseHash - } - if isChatCompletionsConsumer(pr) { - attachChatCompletionMetadata(obj, pr) - } - s.noteInferenceSuccess(pr) - writeNonStreamBody(w, pr.Profile.Parent(), obj) - return - } - } - } - - // Only reconstructed chat-completions use provider-canonical - // reasoning_content precedence. Responses and generic endpoints keep - // the historical reasoning-first extraction contract. - preferReasoningContent := !pr.IsResponsesAPI && - pr.ConsumerEndpoint != completionsEndpoint && - pr.ConsumerEndpoint != messagesEndpoint - msg := extractMessageWithReasoningPolicy(chunks, preferReasoningContent) - usage, ok := s.awaitNonStreamUsage(ctx, w, pr) - if !ok { - return - } - var resp any - if pr.IsResponsesAPI { - resp = buildResponsesResponse( - pr.RequestID, consumerModel(pr), msg, usage, - pr.RequestedMaxTokens, pr.SESignature, pr.ResponseHash, - pr.Traits) - } else if pr.ConsumerEndpoint == completionsEndpoint || - pr.ConsumerEndpoint == messagesEndpoint { - resp = buildGenericEndpointResponse(pr, msg, usage) - } else { - chatResp := buildNonStreamingResponse(pr.RequestID, consumerModel(pr), msg, usage, pr.RequestedMaxTokens, pr.SESignature, pr.ResponseHash) - applyChatCompletionMetadataToResponse(&chatResp, pr) - resp = chatResp - } - s.noteInferenceSuccess(pr) - writeNonStreamBody(w, pr.Profile.Parent(), resp) - return - } - chunk := providerChunk.Data - chunks = append(chunks, chunk) - - case errMsg, ok := <-pr.ErrorCh: - if !ok { - continue - } - s.refundReservedBalance(pr, "provider_error:"+pr.RequestID) - s.noteInferenceError(pr.ProviderID, pr, errMsg.StatusCode, errMsg.Error, errMsg.ErrorReason, errMsg.TerminalCause, errMsg.CoordinatorCause) - s.updateInferenceRouteOutcomeForPending(pr, preResponseProviderErrorOutcome(pr, errMsg)) - s.writeGenericProviderError(w, errMsg) - return - - case <-ctx.Done(): - if errors.Is(ctx.Err(), context.DeadlineExceeded) { - s.refundReservedBalance(pr, "provider_timeout:"+pr.RequestID) - s.updateInferenceRouteOutcomeForPending(pr, preResponseTimeoutOutcome(pr, "response_timeout_before_response")) - writeJSON(w, http.StatusGatewayTimeout, errorResponse("timeout", "request timed out")) - } else { - s.refundReservedBalance(pr, "client_gone:"+pr.RequestID) - s.updateInferenceRouteOutcomeForPending(pr, clientGoneBeforeResponseOutcome(pr)) - } - return - } - } -} - -// awaitNonStreamUsage applies the shared completion contract after raw-body -// detection or delta reconstruction. A body alone cannot establish completion. -func (s *Server) awaitNonStreamUsage(ctx context.Context, w http.ResponseWriter, pr *registry.PendingRequest) (protocol.UsageInfo, bool) { - select { - case usage, ok := <-pr.CompleteCh: - if ok { - return usage, true - } - s.refundReservedBalance(pr, "provider_incomplete:"+pr.RequestID) - s.updateInferenceRouteOutcomeForPending(pr, preResponseProviderIncompleteOutcome(pr)) - writeJSON(w, http.StatusBadGateway, errorResponse("provider_error", "provider ended without completion")) - case <-ctx.Done(): - if errors.Is(ctx.Err(), context.DeadlineExceeded) { - s.refundReservedBalance(pr, "provider_timeout:"+pr.RequestID) - s.updateInferenceRouteOutcomeForPending(pr, preResponseTimeoutOutcome(pr, "usage_timeout_before_response")) - writeJSON(w, http.StatusGatewayTimeout, errorResponse("timeout", "timed out waiting for usage info")) - } else { - s.refundReservedBalance(pr, "client_gone:"+pr.RequestID) - s.updateInferenceRouteOutcomeForPending(pr, clientGoneBeforeResponseOutcome(pr)) - } - } - return protocol.UsageInfo{}, false -} diff --git a/coordinator/api/consumer_stream.go b/coordinator/api/consumer_stream.go deleted file mode 100644 index 17d1008112..0000000000 --- a/coordinator/api/consumer_stream.go +++ /dev/null @@ -1,359 +0,0 @@ -package api - -import ( - "encoding/json" - "net/http" - "strings" - "time" - - "github.com/eigeninference/d-inference/coordinator/protocol" - "github.com/eigeninference/d-inference/coordinator/registry" -) - -func (s *Server) handleStreamingResponseWithFirstChunkAndError( - w http.ResponseWriter, - r *http.Request, - pr *registry.PendingRequest, - firstChunks []string, - initialError *protocol.InferenceErrorMessage, -) { - if pr.ConsumerEndpoint == completionsEndpoint || pr.ConsumerEndpoint == messagesEndpoint { - s.handleGenericEndpointStreamingResponseWithError( - w, r, pr, firstChunks, initialError) - return - } - if pr.IsResponsesAPI { - s.handleResponsesStreamingResponseWithFirstChunk( - w, r, pr, firstChunks, initialError) - return - } - - flusher, ok := w.(http.Flusher) - if !ok { - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "streaming not supported")) - return - } - - writeSSEResponseHeader(w, pr.RequestID) - flusher.Flush() - rs := newRelayStamps(pr.Profile.Parent()) - - // Per-request relay state: the Responses-format latch, the held terminal - // usage/finish frames, and the batch buffer. Every chunk — the ones already - // consumed during dispatch and the ones relayed below — goes through the - // same relay.handleChunk pipeline (see chat_stream_relay.go). - relay := newChatStreamRelay(pr, w, flusher, rs) - - // Write the chunks that were already consumed during dispatch (held - // preamble first, then the committing content chunk). - for _, firstChunk := range firstChunks { - if firstChunk == "" { - continue - } - relay.handleChunk(firstChunk) - } - relay.flush() - if initialError != nil { - s.writeChatStreamProviderError(w, flusher, pr, *initialError) - return - } - - // Use a timer that resets on each chunk so long-running generations - // (e.g. chain-of-thought models) don't hit a global timeout. - timer := time.NewTimer(inferenceTimeout) - defer timer.Stop() - - // finishStream runs once ChunkCh is observed closed — on the blocking - // receive or while draining already-queued chunks (after those were - // flushed): surface a trailing provider error, refund an incomplete stream, - // or emit the held finish/usage frames and the single [DONE]. - finishStream := func() { - select { - case errMsg, ok := <-pr.ErrorCh: - if ok && errMsg.Error != "" { - s.writeChatStreamProviderError(w, flusher, pr, errMsg) - return - } - default: - } - if s.refundReservedBalance(pr, "provider_incomplete:"+pr.RequestID) { - s.ddIncr("inference.in_band_error", []string{"model:" + pr.Model, "reason:provider_incomplete"}) - s.updateInferenceRouteOutcomeForPending(pr, postCommitProviderIncompleteOutcome(pr)) - s.writeChatStreamTerminalError( - w, flusher, pr, "provider_error", "provider ended without completion") - return - } - // Channel closed — inference complete. - s.noteInferenceSuccess(pr) - // For Responses API streams, the provider already sent - // "response.completed" as the terminal event. Adding - // extra chunks would break SDK parsers. - if relay.sawResponsesAPI { - return - } - // Emit the held finish/usage chunks with the authoritative token - // counts (CompleteCh) spliced in: the finish chunk gets its - // finish_reason corrected to "length" when generation hit the - // max-tokens bound, and the usage chunk gets the reasoning - // breakdown. This select runs once, at stream end: the provider's - // inferenceComplete (which populates CompleteCh) is what ends the - // stream, so it is effectively already buffered — the timeout is a - // fallback, not a hot-path wait. - var usage protocol.UsageInfo - if relay.pendingUsage != nil || relay.pendingFinish != nil { - select { - case u, uok := <-pr.CompleteCh: - if uok { - usage = u - } - case <-time.After(2 * time.Second): - case <-r.Context().Done(): - } - } - if relay.pendingFinish != nil { - if out := finalizeFinishChunk(relay.pendingFinish, usage, pr); out != "" { - relay.writeFrame(out) - } - } - if relay.pendingUsage != nil { - // Ride the SE signature on the held usage chunk (a complete, - // well-formed chat.completion.chunk) instead of emitting a - // separate bare event that strict SDK parsers reject. - if pr.SESignature != "" { - relay.pendingUsage["se_signature"] = pr.SESignature - relay.pendingUsage["response_hash"] = pr.ResponseHash - } - attachChatCompletionMetadata(relay.pendingUsage, pr) - if out := finalizeUsageChunk(relay.pendingUsage, usage, pr); out != "" { - relay.writeFrame(out) - } - } else if pr.SESignature != "" || hasChatCompletionMetadata(pr) { - // No held usage chunk to ride on: emit the signature and/or - // opt-in metadata as a fully-shaped chat.completion.chunk - // (id/object/created/model/choices) so strict decoders parse - // it; the extra fields are additive. It precedes the single - // [DONE] below. - event := newChatCompletionExtrasEvent(pr) - if pr.SESignature != "" { - event["se_signature"] = pr.SESignature - event["response_hash"] = pr.ResponseHash - } - attachChatCompletionMetadata(event, pr) - sigEvent, _ := json.Marshal(event) - relay.writeFrame("data: " + string(sigEvent)) - } - // Exactly one terminator, after every coordinator-appended event. The - // terminal frames normally reach the wire together in one flush (the - // relay splits a batch only at maxCoalescedBatchBytes). - relay.writeFrame("data: [DONE]") - relay.flush() - rs.done() - } - - // relayChunk forwards one provider chunk. Every chunk is a liveness - // signal — re-arm the idle timeout up front, before deciding whether to - // forward or hold it, so holding the terminal usage chunk still resets - // the window that bounds the wait for the provider's inference_complete - // (which closes ChunkCh after billing). - relayChunk := func(chunk registry.ProviderChunk) { - resetIdleTimer(timer, inferenceTimeout) - relay.handleChunk(chunk.Data) - } - - for { - select { - case providerChunk, ok := <-pr.ChunkCh: - if !ok { - finishStream() - return - } - relayChunk(providerChunk) - // Fold in whatever the provider already queued behind this chunk - // (never waiting for more), then flush the batch once. A close - // observed mid-drain is handled exactly like the blocking-receive - // close — after the drained chunks are on the wire. - closed := drainQueuedChunks(pr.ChunkCh, maxCoalescedChunks-1, relayChunk) - relay.flush() - if closed { - finishStream() - return - } - - case errMsg, ok := <-pr.ErrorCh: - if !ok { - continue - } - // The provider error is delivered before ChunkCh is closed, so - // chunks that arrived ahead of it may still be queued: forward them - // (never waiting) before the terminal error so a late failure never - // truncates content the provider already produced. - drainQueuedChunks(pr.ChunkCh, cap(pr.ChunkCh), relayChunk) - relay.flush() - s.writeChatStreamProviderError(w, flusher, pr, errMsg) - return - - case <-timer.C: - s.refundReservedBalance(pr, "provider_timeout:"+pr.RequestID) - s.ddIncr("inference.in_band_error", []string{"model:" + pr.Model, "reason:timeout"}) - s.updateInferenceRouteOutcomeForPending(pr, postCommitStreamTimeoutOutcome(pr)) - s.writeChatStreamTerminalError(w, flusher, pr, "timeout", "request timed out") - return - - case <-r.Context().Done(): - profileClientGone(pr, phaseAfterCommit) - return - } - } -} - -func (s *Server) writeChatStreamProviderError( - w http.ResponseWriter, - flusher http.Flusher, - pr *registry.PendingRequest, - errMsg protocol.InferenceErrorMessage, -) { - s.refundReservedBalance(pr, "provider_error:"+pr.RequestID) - s.noteInferenceError(pr.ProviderID, pr, errMsg.StatusCode, errMsg.Error, errMsg.ErrorReason, errMsg.TerminalCause, errMsg.CoordinatorCause) - s.ddIncr("inference.in_band_error", []string{"model:" + pr.Model, "reason:provider_error"}) - s.updateInferenceRouteOutcomeForPending(pr, postCommitProviderErrorOutcome(pr, errMsg)) - s.writeChatStreamTerminalError( - w, flusher, pr, "provider_error", clientSafeInferenceErrorMessage(errMsg)) -} - -func (s *Server) handleResponsesStreamingResponseWithFirstChunk( - w http.ResponseWriter, - r *http.Request, - pr *registry.PendingRequest, - firstChunks []string, - initialError *protocol.InferenceErrorMessage, -) { - flusher, ok := w.(http.Flusher) - if !ok { - writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "streaming not supported")) - return - } - - writeSSEResponseHeader(w, pr.RequestID) - - // The emitter flushes after every event; defer those flushes so a burst of - // already-queued provider chunks reaches the wire in one Flush. Every - // return path performs the owed flush. - deferred := newDeferredFlusher(flusher) - defer deferred.flushNow() - - responseID := "resp_" + strings.ReplaceAll(pr.RequestID, "-", "") - createdAt := time.Now().Unix() - emitter := newResponsesStreamEmitter(w, deferred, pr, responseID, createdAt) - emitter.start() - - for _, firstChunk := range firstChunks { - if firstChunk != "" { - emitter.handleChunk(sanitizeStreamCacheDetails(firstChunk)) - } - } - if initialError != nil { - s.refundReservedBalance(pr, "provider_error:"+pr.RequestID) - s.noteInferenceError(pr.ProviderID, pr, initialError.StatusCode, initialError.Error, initialError.ErrorReason, initialError.TerminalCause, initialError.CoordinatorCause) - s.ddIncr("inference.in_band_error", []string{"model:" + pr.Model, "reason:provider_error"}) - s.updateInferenceRouteOutcomeForPending(pr, postCommitProviderErrorOutcome(pr, *initialError)) - emitter.emitError("provider_error", clientSafeInferenceErrorMessage(*initialError)) - return - } - // The preamble (lifecycle events + dispatch-time chunks) goes on the wire - // before blocking on the provider. - deferred.flushNow() - - timer := time.NewTimer(inferenceTimeout) - defer timer.Stop() - - // emitProviderError settles and reports an in-band provider error. - emitProviderError := func(errMsg protocol.InferenceErrorMessage) { - s.refundReservedBalance(pr, "provider_error:"+pr.RequestID) - s.noteInferenceError(pr.ProviderID, pr, errMsg.StatusCode, errMsg.Error, errMsg.ErrorReason, errMsg.TerminalCause, errMsg.CoordinatorCause) - s.ddIncr("inference.in_band_error", []string{"model:" + pr.Model, "reason:provider_error"}) - s.updateInferenceRouteOutcomeForPending(pr, postCommitProviderErrorOutcome(pr, errMsg)) - emitter.emitError("provider_error", clientSafeInferenceErrorMessage(errMsg)) - } - - // finishStream runs once ChunkCh is observed closed — on the blocking - // receive or while draining already-queued chunks (after those were - // flushed). A provider error is delivered on ErrorCh just before the - // channels close, so it is checked first: a close must never turn a real - // provider error into "incomplete" (or, with nothing reserved, success). - finishStream := func() { - select { - case errMsg, ok := <-pr.ErrorCh: - if ok && errMsg.Error != "" { - emitProviderError(errMsg) - return - } - default: - } - var usage protocol.UsageInfo - completed := false - select { - case u, ok := <-pr.CompleteCh: - if ok { - usage = u - completed = true - } - case <-time.After(2 * time.Second): - } - if !completed && s.refundReservedBalance(pr, "provider_incomplete:"+pr.RequestID) { - s.ddIncr("inference.in_band_error", []string{"model:" + pr.Model, "reason:provider_incomplete"}) - s.updateInferenceRouteOutcomeForPending(pr, postCommitProviderIncompleteOutcome(pr)) - emitter.emitError("provider_error", "provider ended without completion") - return - } - s.noteInferenceSuccess(pr) - emitter.finish(usage) - } - - relayChunk := func(chunk registry.ProviderChunk) { - emitter.handleChunk(sanitizeStreamCacheDetails(chunk.Data)) - resetIdleTimer(timer, inferenceTimeout) - } - - for { - select { - case providerChunk, ok := <-pr.ChunkCh: - if !ok { - finishStream() - return - } - relayChunk(providerChunk) - // Fold in whatever the provider already queued behind this chunk - // (never waiting for more), then flush the batch once. A close - // observed mid-drain is handled exactly like the blocking-receive - // close — after the drained chunks are on the wire. - closed := drainQueuedChunks(pr.ChunkCh, maxCoalescedChunks-1, relayChunk) - deferred.flushNow() - if closed { - finishStream() - return - } - - case errMsg, ok := <-pr.ErrorCh: - if !ok { - continue - } - // Forward chunks queued ahead of the error before the terminal - // event (see the chat relay for the rationale). - drainQueuedChunks(pr.ChunkCh, cap(pr.ChunkCh), relayChunk) - deferred.flushNow() - emitProviderError(errMsg) - return - - case <-timer.C: - s.refundReservedBalance(pr, "provider_timeout:"+pr.RequestID) - s.ddIncr("inference.in_band_error", []string{"model:" + pr.Model, "reason:timeout"}) - s.updateInferenceRouteOutcomeForPending(pr, postCommitStreamTimeoutOutcome(pr)) - emitter.emitError("timeout", "request timed out") - return - - case <-r.Context().Done(): - profileClientGone(pr, phaseAfterCommit) - return - } - } -} diff --git a/coordinator/api/consumer_streaming_usage_test.go b/coordinator/api/consumer_streaming_usage_test.go index 9c0337e090..9c77c0d28d 100644 --- a/coordinator/api/consumer_streaming_usage_test.go +++ b/coordinator/api/consumer_streaming_usage_test.go @@ -12,43 +12,6 @@ import ( "github.com/eigeninference/d-inference/coordinator/store" ) -// TestUsageChunkParseAndFinalize covers the parse-once + finalize helpers. -func TestUsageChunkParseAndFinalize(t *testing.T) { - usageChunk := `data: {"object":"chat.completion.chunk","model":"gpt-oss-20b","choices":[],"usage":{"prompt_tokens":10,"completion_tokens":50,"total_tokens":60}}` - pr := ®istry.PendingRequest{Model: "gpt-oss-20b"} - - obj, ok := parseUsageOnlyStreamChunk(usageChunk) - if !ok { - t.Fatal("expected the usage-only chunk to be detected + parsed") - } - out := finalizeUsageChunk(obj, protocol.UsageInfo{CompletionTokens: 50, ReasoningTokens: 8}, pr) - if !strings.Contains(out, `"reasoning_tokens":8`) { - t.Fatalf("expected reasoning_tokens spliced into usage; got %s", out) - } - - // A content delta and a usage:null chunk are NOT usage-only chunks. - if _, ok := parseUsageOnlyStreamChunk(`data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"x"}}]}`); ok { - t.Fatal("a content delta must NOT be treated as a usage-only chunk") - } - if _, ok := parseUsageOnlyStreamChunk(`data: {"object":"chat.completion.chunk","choices":[],"usage":null}`); ok { - t.Fatal("a usage:null chunk must NOT be treated as a usage-only chunk") - } - - // No reasoning → no completion_tokens_details added. - obj2, _ := parseUsageOnlyStreamChunk(usageChunk) - if plain := finalizeUsageChunk(obj2, protocol.UsageInfo{CompletionTokens: 50}, pr); strings.Contains(plain, "completion_tokens_details") { - t.Fatalf("expected no reasoning detail when ReasoningTokens=0; got %s", plain) - } - - // Build id rewritten to the public alias. - obj3, _ := parseUsageOnlyStreamChunk(usageChunk) - prAlias := ®istry.PendingRequest{Model: "gpt-oss-20b", PublicModel: "gpt-oss"} - aliased := finalizeUsageChunk(obj3, protocol.UsageInfo{CompletionTokens: 50, ReasoningTokens: 8}, prAlias) - if !strings.Contains(aliased, `"model":"gpt-oss"`) || strings.Contains(aliased, `"model":"gpt-oss-20b"`) { - t.Fatalf("expected build id rewritten to the public alias; got %s", aliased) - } -} - // TestStreamingChatReasoningTokensInUsage proves chat-completions STREAMING now // reports the reasoning breakdown in the terminal usage chunk (the bug: reasoning // was lumped into completion with no completion_tokens_details). @@ -127,52 +90,6 @@ func TestStreamingFramesCannotForwardUnvalidatedCachedTokens(t *testing.T) { } } -func TestSanitizeNestedResponsesStreamCacheDetails(t *testing.T) { - chunk := "event: response.completed\n" + - "id: response-7\n" + - ": retain this comment\n" + - `data: {"type":"response.completed","response":{"usage":{` + "\n" + - `data: "input_tokens_details":{"cached\u005ftokens":99,"audio_tokens":7}}}}` + "\n\n" - got := sanitizeStreamCacheDetails(chunk) - if strings.Contains(got, `"cached_tokens"`) || strings.Contains(got, `cached\u005ftokens`) || strings.Contains(got, "99") { - t.Fatalf("nested Responses cached_tokens survived: %s", got) - } - if !strings.Contains(got, `"audio_tokens":7`) || !strings.Contains(got, "event: response.completed") || - !strings.Contains(got, "id: response-7") || !strings.Contains(got, ": retain this comment") || strings.Count(got, "data:") != 1 { - t.Fatalf("nested Responses sanitization removed unrelated content: %s", got) - } -} - -func TestSanitizeSplitMultilineChatStreamCacheDetails(t *testing.T) { - for _, tc := range []struct { - name string - choices string - }{ - {name: "content", choices: `[{"delta":{"content":"hi"},"finish_reason":null}]`}, - {name: "finish", choices: `[{"delta":{},"finish_reason":"stop"}]`}, - } { - t.Run(tc.name, func(t *testing.T) { - chunk := "event: message\n" + - "id: chat-9\n" + - ": keepalive\n" + - `data: {"object":"chat.completion.chunk","choices":` + tc.choices + `,` + "\n" + - `data: "usage":{"prompt_tokens_details":{"cached\u005ftokens":123,"audio_tokens":6}}}` + "\n\n" - got := sanitizeStreamCacheDetails(chunk) - if strings.Contains(got, "123") || strings.Contains(got, `cached\u005ftokens`) || strings.Contains(got, `"cached_tokens"`) { - t.Fatalf("split %s frame retained cached_tokens: %s", tc.name, got) - } - for _, preserved := range []string{`"audio_tokens":6`, "event: message", "id: chat-9", ": keepalive"} { - if !strings.Contains(got, preserved) { - t.Fatalf("split %s frame lost %q: %s", tc.name, preserved, got) - } - } - if strings.Count(got, "data:") != 1 || !strings.HasSuffix(got, "\n\n") { - t.Fatalf("split %s frame was not re-emitted as one data line/event: %q", tc.name, got) - } - }) - } -} - // TestStreamingChatUsageOnlyFirstChunk covers the zero-delta case: a completion // that streams no content/reasoning deltas, so the include_usage frame is the very // FIRST chunk handed to the handler. It must still be held and have the reasoning diff --git a/coordinator/api/consumer_toolcall_cap_test.go b/coordinator/api/consumer_toolcall_cap_test.go deleted file mode 100644 index 203e77da28..0000000000 --- a/coordinator/api/consumer_toolcall_cap_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package api - -import ( - "fmt" - "testing" -) - -// T11/T10 (PR #548 review): chunks come from providers, which are only -// semi-trusted — a buggy or malicious provider can stream an unbounded -// number of distinct-id tool-call deltas into the non-streaming -// reconstruction. extractMessage caps LOGICAL tool calls at -// maxLogicalToolCalls: past the cap, deltas that would start a new logical -// call are dropped (counted + logged), while argument fragments for -// already-kept calls keep accumulating — kept calls are never truncated or -// corrupted, and huge/sparse wire indices cannot grow the tracking map past -// the cap either. - -// capCallID builds the distinct id for the i-th flood call. -func capCallID(i int) string { return fmt.Sprintf("c%d", i) } - -// A malicious all-index-0 stream of cap+1 distinct-id calls keeps exactly -// the first maxLogicalToolCalls calls, in arrival order, and drops the rest. -func TestExtractMessageCapsLogicalToolCalls(t *testing.T) { - var chunks []string - for i := 1; i <= maxLogicalToolCalls+1; i++ { - chunks = append(chunks, tcDelta(0, capCallID(i), "fn", fmt.Sprintf(`{"n":%d}`, i))) - } - - msg := extractMessage(chunks) - if len(msg.ToolCalls) != maxLogicalToolCalls { - t.Fatalf("tool_calls length = %d, want cap %d", len(msg.ToolCalls), maxLogicalToolCalls) - } - for i, tc := range msg.ToolCalls { - if wantID := capCallID(i + 1); tc["id"] != wantID { - t.Fatalf("call %d id = %v, want %s (arrival order must be stable under the cap)", i, tc["id"], wantID) - } - } - last := msg.ToolCalls[maxLogicalToolCalls-1] - fn := last["function"].(map[string]any) - if want := fmt.Sprintf(`{"n":%d}`, maxLogicalToolCalls); fn["arguments"] != want { - t.Errorf("last kept call arguments = %q, want %q (dropped call must not contaminate it)", fn["arguments"], want) - } -} - -// Past the cap, kept calls still accumulate their own argument fragments, -// and fragments belonging to a dropped call are swallowed — never merged -// onto a kept call at the same wire index. -func TestExtractMessageAtCapKeepsAccumulatingKeptCalls(t *testing.T) { - chunks := []string{ - // A long-running kept call on its own wire index. - tcDelta(5, "keeper", "keep_fn", `{"k":`), - } - // Fill the remaining cap slots with distinct-id calls at index 0. - for i := 1; i <= maxLogicalToolCalls-1; i++ { - chunks = append(chunks, tcDelta(0, capCallID(i), "fn", fmt.Sprintf(`{"n":%d}`, i))) - } - chunks = append(chunks, - // Cap is full: this new logical call must be dropped... - tcDelta(0, "overflow", "fn", `{"evil":true}`), - // ...and its id-less fragments swallowed, not merged onto the - // last kept index-0 call. - tcDelta(0, "", "", `LEAK`), - // The kept call keeps accumulating fragments as usual. - tcDelta(5, "", "", `1}`), - ) - - msg := extractMessage(chunks) - if len(msg.ToolCalls) != maxLogicalToolCalls { - t.Fatalf("tool_calls length = %d, want cap %d", len(msg.ToolCalls), maxLogicalToolCalls) - } - // Output is index-ordered: the index-0 group first, keeper (index 5) last. - keeper := msg.ToolCalls[maxLogicalToolCalls-1] - if keeper["id"] != "keeper" { - t.Fatalf("last call id = %v, want keeper (index 5 sorts after index 0)", keeper["id"]) - } - keeperFn := keeper["function"].(map[string]any) - if keeperFn["arguments"] != `{"k":1}` { - t.Errorf("keeper arguments = %q, want %q (kept calls must keep accumulating past the cap)", keeperFn["arguments"], `{"k":1}`) - } - lastKept := msg.ToolCalls[maxLogicalToolCalls-2] - if wantID := capCallID(maxLogicalToolCalls - 1); lastKept["id"] != wantID { - t.Fatalf("last index-0 call id = %v, want %s", lastKept["id"], wantID) - } - lastKeptFn := lastKept["function"].(map[string]any) - if want := fmt.Sprintf(`{"n":%d}`, maxLogicalToolCalls-1); lastKeptFn["arguments"] != want { - t.Errorf("last kept index-0 arguments = %q, want %q (dropped call's fragments must be swallowed, not merged)", lastKeptFn["arguments"], want) - } - for _, tc := range msg.ToolCalls { - if tc["id"] == "overflow" { - t.Errorf("dropped call id overflow must not appear in output: %v", tc) - } - } -} - -// Huge and sparse wire indices are fine for Go maps (no preallocation by -// key value), but each distinct index could otherwise add a tracking entry -// forever; the logical-call cap bounds that too. -func TestExtractMessageCapBoundsSparseHugeIndices(t *testing.T) { - var chunks []string - for i := 1; i <= maxLogicalToolCalls+10; i++ { - // Distinct sparse indices, including very large ones. - chunks = append(chunks, tcDelta(i*1000003, capCallID(i), "fn", `{}`)) - } - msg := extractMessage(chunks) - if len(msg.ToolCalls) != maxLogicalToolCalls { - t.Fatalf("tool_calls length = %d, want cap %d", len(msg.ToolCalls), maxLogicalToolCalls) - } -} diff --git a/coordinator/api/consumer_toolcall_reconstruction_test.go b/coordinator/api/consumer_toolcall_reconstruction_test.go deleted file mode 100644 index c0d78844e8..0000000000 --- a/coordinator/api/consumer_toolcall_reconstruction_test.go +++ /dev/null @@ -1,244 +0,0 @@ -package api - -import ( - "encoding/json" - "strings" - "testing" -) - -// Each call's builder must remain independent as the accumulator grows, IDs -// arrive after argument fragments, and sparse indices change output order. -func TestExtractMessageLongInterleavedToolArguments(t *testing.T) { - const fragments = 512 - fragmentA, fragmentB := strings.Repeat("a", 32), strings.Repeat("b", 32) - chunks := []string{ - tcDelta(8, "", "", `{"text":"`), - tcDelta(2, "call_b", "second", `{"text":"`), - } - for range fragments { - chunks = append(chunks, tcDelta(8, "", "", fragmentA), tcDelta(2, "", "", fragmentB)) - } - chunks = append(chunks, - tcDelta(8, "call_a", "first", `"}`), - tcDelta(2, "call_b", "", `"}`), - ) - msg := extractMessage(chunks) - if len(msg.ToolCalls) != 2 { - t.Fatalf("got %d calls, want 2", len(msg.ToolCalls)) - } - for i, want := range []struct{ id, name, text string }{ - {"call_b", "second", strings.Repeat(fragmentB, fragments)}, - {"call_a", "first", strings.Repeat(fragmentA, fragments)}, - } { - call := msg.ToolCalls[i] - function := call["function"].(map[string]any) - if call["id"] != want.id || function["name"] != want.name { - t.Fatalf("call %d metadata = %v", i, call) - } - var arguments struct{ Text string } - if err := json.Unmarshal([]byte(function["arguments"].(string)), &arguments); err != nil { - t.Fatal(err) - } - if arguments.Text != want.text { - t.Fatalf("call %d arguments were truncated or mixed", i) - } - if _, present := call["index"]; present { - t.Fatal("wire index leaked into reconstructed response") - } - } -} - -func TestExtractMessageToolCallOptionalFields(t *testing.T) { - msg := extractMessage([]string{ - `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{}},{"index":1,"id":"call_1","type":"function","function":{"name":"run"}}]}}]}`, - }) - encoded, err := json.Marshal(msg.ToolCalls) - if err != nil { - t.Fatal(err) - } - want := `[{"function":{"arguments":""}},{"function":{"arguments":"","name":"run"},"id":"call_1","type":"function"}]` - if string(encoded) != want { - t.Fatalf("optional fields changed:\n got: %s\nwant: %s", encoded, want) - } -} - -func TestExtractMessageMalformedToolDeltaDoesNotCorruptKeptCall(t *testing.T) { - for _, invalid := range []string{ - `{"index":"bad","function":{"arguments":"LEAK"}}`, - `{"index":0,"function":"bad"}`, - `{"index":0,"function":{"arguments":42}}`, - `{"index":0,"id":42,"function":{"arguments":"LEAK"}}`, - } { - msg := extractMessage([]string{ - tcDelta(0, "call_a", "run", `{"n":`), - `data: {"choices":[{"delta":{"tool_calls":[` + invalid + `]}}]}`, - tcDelta(0, "", "", `1}`), - }) - if len(msg.ToolCalls) != 1 { - t.Fatalf("invalid delta %s changed kept calls: %v", invalid, msg.ToolCalls) - } - function := msg.ToolCalls[0]["function"].(map[string]any) - if function["arguments"] != `{"n":1}` { - t.Fatalf("invalid delta %s corrupted arguments: %v", invalid, function) - } - } -} - -// E6 (2026-07-15 platform errors deep dive): the engine emits EVERY streamed -// parallel tool call with `index: 0`, and extractMessage keyed reconstruction -// by index — so a second call overwrote the first's id/name and concatenated -// both argument streams into one corrupted call. Defensively, a delta whose -// non-empty id DIFFERS from the current entry's non-empty id starts a NEW -// logical call (arrival order preserved); well-behaved indexed streams keep -// index-keyed accumulation. (The engine-side proper fix — unique indices in -// MLXOpenAIService — lives in the submodule and ships separately.) - -func tcDelta(index int, id, name, args string) string { - chunk := `data: {"choices":[{"delta":{"tool_calls":[{"index":` + itoa(index) - if id != "" { - chunk += `,"id":"` + id + `"` - } - chunk += `,"function":{` - sep := "" - if name != "" { - chunk += `"name":"` + name + `"` - sep = "," - } - chunk += sep + `"arguments":` + quoteJSON(args) + `}}]}}]}` - return chunk -} - -func itoa(n int) string { - if n == 0 { - return "0" - } - digits := "" - for n > 0 { - digits = string(rune('0'+n%10)) + digits - n /= 10 - } - return digits -} - -func quoteJSON(s string) string { - out := `"` - for _, r := range s { - switch r { - case '"': - out += `\"` - case '\\': - out += `\\` - default: - out += string(r) - } - } - return out + `"` -} - -// Two parallel calls both streamed at index 0 with distinct ids: the second -// id must START A NEW logical call — two calls out, each with its own -// id/name/arguments — instead of one merged call with concatenated args. -func TestExtractMessageTwoIndexZeroCallsWithDistinctIDs(t *testing.T) { - chunks := []string{ - tcDelta(0, "call_a", "get_weather", ""), - tcDelta(0, "", "", `{"city":`), - tcDelta(0, "", "", `"SF"}`), - tcDelta(0, "call_b", "get_time", ""), - tcDelta(0, "", "", `{"tz":"PST"}`), - } - - msg := extractMessage(chunks) - if len(msg.ToolCalls) != 2 { - t.Fatalf("tool_calls length = %d, want 2 (second index-0 id must not merge into the first call): %v", len(msg.ToolCalls), msg.ToolCalls) - } - first, second := msg.ToolCalls[0], msg.ToolCalls[1] - if first["id"] != "call_a" || second["id"] != "call_b" { - t.Fatalf("ids = %v, %v; want call_a then call_b (arrival order)", first["id"], second["id"]) - } - fn1 := first["function"].(map[string]any) - fn2 := second["function"].(map[string]any) - if fn1["name"] != "get_weather" || fn2["name"] != "get_time" { - t.Errorf("names = %v, %v; want get_weather / get_time", fn1["name"], fn2["name"]) - } - if fn1["arguments"] != `{"city":"SF"}` { - t.Errorf("first arguments = %q, want %q", fn1["arguments"], `{"city":"SF"}`) - } - if fn2["arguments"] != `{"tz":"PST"}` { - t.Errorf("second arguments = %q, want %q (must not contain the first call's fragments)", fn2["arguments"], `{"tz":"PST"}`) - } -} - -// The id being RE-SENT on later deltas of the same call (some engines repeat -// it on every frame) is a continuation, never a split. -func TestExtractMessageRepeatedSameIDDoesNotSplit(t *testing.T) { - chunks := []string{ - tcDelta(0, "call_a", "run", ""), - tcDelta(0, "call_a", "", `{"a":`), - tcDelta(0, "call_a", "", `1}`), - } - msg := extractMessage(chunks) - if len(msg.ToolCalls) != 1 { - t.Fatalf("tool_calls length = %d, want 1", len(msg.ToolCalls)) - } - fn := msg.ToolCalls[0]["function"].(map[string]any) - if fn["arguments"] != `{"a":1}` { - t.Errorf("arguments = %q, want %q", fn["arguments"], `{"a":1}`) - } -} - -// Well-behaved indexed streams (unique index per call, interleaved deltas) -// keep index-keyed accumulation and index-ordered output. -func TestExtractMessageWellBehavedIndexedStreamUnchanged(t *testing.T) { - chunks := []string{ - tcDelta(1, "call_b", "second", ""), - tcDelta(0, "call_a", "first", ""), - tcDelta(0, "", "", `{"x":1}`), - tcDelta(1, "", "", `{"y":2}`), - } - msg := extractMessage(chunks) - if len(msg.ToolCalls) != 2 { - t.Fatalf("tool_calls length = %d, want 2", len(msg.ToolCalls)) - } - if msg.ToolCalls[0]["id"] != "call_a" || msg.ToolCalls[1]["id"] != "call_b" { - t.Fatalf("output must be index-ordered: got %v, %v", msg.ToolCalls[0]["id"], msg.ToolCalls[1]["id"]) - } - fn1 := msg.ToolCalls[0]["function"].(map[string]any) - fn2 := msg.ToolCalls[1]["function"].(map[string]any) - if fn1["arguments"] != `{"x":1}` || fn2["arguments"] != `{"y":2}` { - t.Errorf("arguments = %q / %q, want index-keyed accumulation", fn1["arguments"], fn2["arguments"]) - } -} - -// Sparse wire indices (0 and 2) must both survive — the old dense 0..n-1 map -// walk silently dropped the call at index 2. -func TestExtractMessageSparseIndicesNotDropped(t *testing.T) { - chunks := []string{ - tcDelta(0, "call_a", "first", `{}`), - tcDelta(2, "call_c", "third", `{}`), - } - msg := extractMessage(chunks) - if len(msg.ToolCalls) != 2 { - t.Fatalf("tool_calls length = %d, want 2 (sparse index dropped)", len(msg.ToolCalls)) - } - if msg.ToolCalls[1]["id"] != "call_c" { - t.Errorf("second call id = %v, want call_c", msg.ToolCalls[1]["id"]) - } -} - -// Three calls all at index 0: arrival order is preserved across every split. -func TestExtractMessageThreeIndexZeroCalls(t *testing.T) { - chunks := []string{ - tcDelta(0, "c1", "f1", `{"n":1}`), - tcDelta(0, "c2", "f2", `{"n":2}`), - tcDelta(0, "c3", "f3", `{"n":3}`), - } - msg := extractMessage(chunks) - if len(msg.ToolCalls) != 3 { - t.Fatalf("tool_calls length = %d, want 3", len(msg.ToolCalls)) - } - for i, wantID := range []string{"c1", "c2", "c3"} { - if msg.ToolCalls[i]["id"] != wantID { - t.Errorf("call %d id = %v, want %s", i, msg.ToolCalls[i]["id"], wantID) - } - } -} diff --git a/coordinator/api/consumer_ttft_test.go b/coordinator/api/consumer_ttft_test.go index 4b32b1bc3b..6bf83a6808 100644 --- a/coordinator/api/consumer_ttft_test.go +++ b/coordinator/api/consumer_ttft_test.go @@ -13,33 +13,6 @@ import ( "github.com/eigeninference/d-inference/coordinator/registry" ) -func TestWriteServiceUnavailableSetsRetryAfter(t *testing.T) { - srv, _ := testServer(t) - w := httptest.NewRecorder() - srv.writeServiceUnavailable(w, "gpt-oss-20b") - - if w.Code != http.StatusServiceUnavailable { - t.Errorf("status = %d, want %d", w.Code, http.StatusServiceUnavailable) - } - if ra := w.Header().Get("Retry-After"); ra == "" { - t.Error("Retry-After header missing") - } else if n, err := strconv.Atoi(ra); err != nil || n < 1 { - t.Errorf("Retry-After = %q, want positive integer seconds", ra) - } - var body struct { - Error struct { - Code string `json:"code"` - Message string `json:"message"` - } `json:"error"` - } - if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal: %v", err) - } - if body.Error.Code != "service_unavailable" { - t.Errorf("code = %q, want service_unavailable", body.Error.Code) - } -} - func TestTTFTDeadlineExact(t *testing.T) { srv, _ := testServer(t) tests := []struct { @@ -89,9 +62,6 @@ func TestWriteTTFTTooSlowSets429RetryAfter(t *testing.T) { if threshold != 5*time.Second { t.Fatalf("FirstContentDeadline(0) = %v, want 5s", threshold) } - if got := srv.estimateTTFTRetryAfter("no-queue", 8*time.Second, threshold); got != 3 { - t.Fatalf("Retry-After without queue = %d, want 3s over target", got) - } model := "slow-ttft-model" for i := 0; i < 5; i++ { @@ -101,7 +71,7 @@ func TestWriteTTFTTooSlowSets429RetryAfter(t *testing.T) { } w := httptest.NewRecorder() - srv.writeTTFTTooSlow(w, model, model, 6*time.Second, threshold) + srv.inferenceDispatch().WriteTTFTTooSlow(w, model, model, 6*time.Second, threshold) if w.Code != http.StatusTooManyRequests { t.Fatalf("status = %d, want %d", w.Code, http.StatusTooManyRequests) @@ -293,125 +263,3 @@ func TestTTFTHardGateDoesNotRejectMediaOnTextOnlyEstimate(t *testing.T) { t.Fatal("warm-pool snapshot missing media model") } } - -func TestMaybeFallbackAliasTTFTSwitchesToPrevious(t *testing.T) { - srv, _ := testServer(t) - publicModel := "public-ttft-alias" - desired := "desired-ttft-build" - previous := "previous-ttft-build" - srv.registry.SetModelCatalog([]registry.CatalogEntry{ - {ID: desired, SizeGB: 1, MinRAMGB: 24}, - {ID: previous, SizeGB: 1, MinRAMGB: 24}, - }) - srv.registry.SetModelAliases(map[string]registry.AliasTarget{ - publicModel: {Desired: desired, Previous: previous}, - }) - - desiredProvider := registerBuildsProvider(srv, "desired-slow", desired) - desiredProvider.Mu().Lock() - desiredProvider.DecodeTPS = 100 - desiredProvider.PrefillTPS = 400 - desiredProvider.BackendCapacity.Slots[0].State = "idle_shutdown" - desiredProvider.Mu().Unlock() - - previousProvider := registerBuildsProvider(srv, "previous-fast", previous) - previousProvider.Mu().Lock() - previousProvider.DecodeTPS = 100 - previousProvider.PrefillTPS = 400 - previousProvider.Mu().Unlock() - - parsed := map[string]any{"model": desired} - fallbackModel, candidates, rejections, tooLarge, bestTTFT, hasTTFT, switched := srv.maybeFallbackAlias( - parsed, - aliasFallbackTTFT, - publicModel, - desired, - 100, - 128, - srv.FirstContentDeadline(desired, 100), - registry.RequestTraits{}, - false, - nil, - ) - - if !switched { - t.Fatalf("switched = false, candidates=%d rejections=%d tooLarge=%d bestTTFT=%v has=%v", candidates, rejections, tooLarge, bestTTFT, hasTTFT) - } - if fallbackModel != previous || parsed["model"] != previous { - t.Fatalf("fallback model = %q parsed=%v, want previous %q", fallbackModel, parsed["model"], previous) - } - if candidates != 1 || rejections != 0 || tooLarge != 0 { - t.Fatalf("capacity = (%d,%d,%d), want (1,0,0)", candidates, rejections, tooLarge) - } - if !hasTTFT || bestTTFT > srv.FirstContentDeadline(desired, 100) { - t.Fatalf("bestTTFT = %v has=%v, want within threshold", bestTTFT, hasTTFT) - } - - // Alias fallback must consume the logical request's pinned deadline rather - // than recomputing a fresh full duration for Previous. A deliberately tiny - // pinned budget therefore blocks the same otherwise-healthy fallback. - parsed["model"] = desired - fallbackModel, _, _, _, _, _, switched = srv.maybeFallbackAlias( - parsed, - aliasFallbackTTFT, - publicModel, - desired, - 100, - 128, - time.Nanosecond, - registry.RequestTraits{}, - false, - nil, - ) - if switched || fallbackModel != previous || parsed["model"] != desired { - t.Fatalf("expired pinned deadline restarted on Previous: switched=%v fallback=%q parsed=%v", switched, fallbackModel, parsed) - } -} - -func TestMaybeFallbackAliasTTFTSkipsRejectedPrevious(t *testing.T) { - srv, _ := testServer(t) - publicModel := "public-ttft-shed-alias" - desired := "desired-ttft-shed-build" - previous := "previous-ttft-shed-build" - srv.SetRejectModels(map[string]bool{previous: true}) - srv.registry.SetModelCatalog([]registry.CatalogEntry{ - {ID: desired, SizeGB: 1, MinRAMGB: 24}, - {ID: previous, SizeGB: 1, MinRAMGB: 24}, - }) - srv.registry.SetModelAliases(map[string]registry.AliasTarget{ - publicModel: {Desired: desired, Previous: previous}, - }) - registerBuildsProvider(srv, "previous-fast-shed", previous) - parsed := map[string]any{"model": desired} - - fallbackModel, _, _, _, _, _, switched := srv.maybeFallbackAlias( - parsed, aliasFallbackTTFT, publicModel, desired, 100, 128, srv.FirstContentDeadline(desired, 100), registry.RequestTraits{}, false, nil) - - if switched || fallbackModel != desired || parsed["model"] != desired { - t.Fatalf("fallback switched to rejected previous: switched=%v fallback=%q parsed=%v", switched, fallbackModel, parsed) - } -} - -func TestMaybeFallbackAliasCapacitySkipsRejectedPrevious(t *testing.T) { - srv, _ := testServer(t) - publicModel := "public-capacity-shed-alias" - desired := "desired-capacity-shed-build" - previous := "previous-capacity-shed-build" - srv.SetRejectModels(map[string]bool{previous: true}) - srv.registry.SetModelCatalog([]registry.CatalogEntry{ - {ID: desired, SizeGB: 1, MinRAMGB: 24}, - {ID: previous, SizeGB: 1, MinRAMGB: 24}, - }) - srv.registry.SetModelAliases(map[string]registry.AliasTarget{ - publicModel: {Desired: desired, Previous: previous}, - }) - registerBuildsProvider(srv, "previous-capacity-shed", previous) - parsed := map[string]any{"model": desired} - - fallbackModel, _, _, _, _, _, switched := srv.maybeFallbackAlias( - parsed, aliasFallbackCapacity, publicModel, desired, 100, 128, 0, registry.RequestTraits{}, false, nil) - - if switched || fallbackModel != desired || parsed["model"] != desired { - t.Fatalf("capacity fallback switched to rejected previous: switched=%v fallback=%q parsed=%v", switched, fallbackModel, parsed) - } -} diff --git a/coordinator/api/deadline_unreachable_integration_test.go b/coordinator/api/deadline_unreachable_integration_test.go index 0d51ebfd39..ff3f341420 100644 --- a/coordinator/api/deadline_unreachable_integration_test.go +++ b/coordinator/api/deadline_unreachable_integration_test.go @@ -12,6 +12,9 @@ import ( "testing" "time" + "github.com/eigeninference/d-inference/coordinator/inference/attempt" + "github.com/eigeninference/d-inference/coordinator/inference/dispatch" + "github.com/eigeninference/d-inference/coordinator/internal/inferencefixture" "github.com/eigeninference/d-inference/coordinator/modelpolicy" "github.com/eigeninference/d-inference/coordinator/protocol" "github.com/eigeninference/d-inference/coordinator/registry" @@ -194,7 +197,7 @@ func TestDeadlineUnreachableFailoverCarriesDecreasingBudgets(t *testing.T) { ctx, req, protocol.FailureCodeCapacity, - errorReasonDeadlineUnreachable, + attempt.ErrorReasonDeadlineUnreachable, http.StatusServiceUnavailable, ) return @@ -249,7 +252,7 @@ func TestDeadlineUnreachableFailoverCarriesDecreasingBudgets(t *testing.T) { routes, _ := waitForDeadlineTelemetryWhere(t, st, 2, 0, func(routes []store.InferenceRouteRecord) bool { for _, route := range routes { - if route.ErrorReason == errorReasonDeadlineUnreachable { + if route.ErrorReason == attempt.ErrorReasonDeadlineUnreachable { return true } } @@ -257,12 +260,12 @@ func TestDeadlineUnreachableFailoverCarriesDecreasingBudgets(t *testing.T) { }) deadlineRoutes := 0 for _, route := range routes { - if route.ErrorReason != errorReasonDeadlineUnreachable { + if route.ErrorReason != attempt.ErrorReasonDeadlineUnreachable { continue } deadlineRoutes++ - if route.ErrorClass != errorClassDeadlineUnreachable { - t.Errorf("deadline route class = %q, want %q", route.ErrorClass, errorClassDeadlineUnreachable) + if route.ErrorClass != attempt.ErrorClassDeadlineUnreachable { + t.Errorf("deadline route class = %q, want %q", route.ErrorClass, attempt.ErrorClassDeadlineUnreachable) } if route.AdmittedButFailed { t.Error("pre-content deadline refusal must not be admitted-but-failed") @@ -318,7 +321,7 @@ func TestModelSpecificFirstContentDeadlineReachesProviderWire(t *testing.T) { t.Fatalf("parse request body: %v", err) } expected := srv.FirstContentDeadline( - tt.model, estimatePromptTokens(parsed), + tt.model, inferencefixture.PromptTokens(parsed), ).Milliseconds() if expected < tt.wantBase.Milliseconds() || expected >= tt.wantBase.Milliseconds()+time.Second.Milliseconds() { @@ -368,43 +371,21 @@ func TestDispatchOneProviderUsesPinnedExpiredClockWithoutRecomputing(t *testing. "/v1/chat/completions", strings.NewReader(buildChatBody(t, model, false, nil)), ) - selected, pending, _, _, dispatchErr, dispatchErrCode := srv.dispatchOneProvider( - req, - model, - model, - []byte(buildChatBody(t, model, false, nil)), - "test-key", - nil, - 0, - 8, - 10*time.Millisecond, - 64, - registry.TokenAdmission{}, - false, - registry.RequestTraits{}, - nil, - false, - selfRoutePolicy{}, - // The pinned 10ms request clock is expired, while recomputing this - // ordinary model from the server's 5s default would still allow a send. - ®istry.RequestTiming{ReceivedAt: time.Now().Add(-50 * time.Millisecond)}, - false, - registry.CachePlan{}, - map[string]struct{}{}, - 0, - nil, - "", - nil, - nil, - ) - if selected != nil || pending != nil { - t.Fatalf("expired dispatch selected provider=%v pending=%v", selected, pending) + recorder := httptest.NewRecorder() + srv.inferenceDispatch().Run(recorder, req, dispatch.Request{ + Model: model, PublicModel: model, + RawBody: []byte(buildChatBody(t, model, false, nil)), + ConsumerKey: "test-key", EstimatedPromptTokens: 8, RequestedMaxTokens: 64, + Deadline: 10 * time.Millisecond, + // This pinned clock is expired; the ordinary 5s model default is not. + Timing: ®istry.RequestTiming{ReceivedAt: time.Now().Add(-50 * time.Millisecond)}, + RefundReservation: func() {}, + }) + if recorder.Code != http.StatusTooManyRequests || !strings.Contains(recorder.Body.String(), "timeout waiting for first response") { + t.Fatalf("expired dispatch HTTP = %d %s, want deadline 429", recorder.Code, recorder.Body.String()) } - if dispatchErr != errFirstContentDeadlineExpired || - dispatchErrCode != http.StatusGatewayTimeout { - t.Fatalf( - "expired dispatch = (%q,%d), want (%q,504)", - dispatchErr, dispatchErrCode, errFirstContentDeadlineExpired) + if p := reg.GetProvider(provider.registryID); p == nil || p.PendingCount() != 0 { + t.Fatalf("expired dispatch retained a provider reservation: %v", p) } time.Sleep(50 * time.Millisecond) if got := provider.dispatchCount(); got != 0 { @@ -434,7 +415,7 @@ func TestDeadlineUnreachableAllProvidersReturnSingle429(t *testing.T) { ctx, req, protocol.FailureCodeCapacity, - errorReasonDeadlineUnreachable, + attempt.ErrorReasonDeadlineUnreachable, http.StatusServiceUnavailable, ) } @@ -494,7 +475,7 @@ func TestDeadlineUnreachableAllProvidersReturnSingle429(t *testing.T) { deadlineRoutes := 0 for _, route := range routes { - if route.ErrorReason == errorReasonDeadlineUnreachable { + if route.ErrorReason == attempt.ErrorReasonDeadlineUnreachable { deadlineRoutes++ } } @@ -609,7 +590,7 @@ func TestDeadlineRefusalDoesNotMaskLaterProvider500(t *testing.T) { if attempts.capture(t, reg, fp, req) == 1 { fp.sendTypedInferenceError( ctx, req, protocol.FailureCodeCapacity, - errorReasonDeadlineUnreachable, http.StatusServiceUnavailable) + attempt.ErrorReasonDeadlineUnreachable, http.StatusServiceUnavailable) return } fp.sendInferenceError( @@ -735,7 +716,7 @@ func TestGenericEndpointsShareDeadlineFailover(t *testing.T) { time.Sleep(40 * time.Millisecond) fp.sendTypedInferenceError( ctx, req, protocol.FailureCodeCapacity, - errorReasonDeadlineUnreachable, + attempt.ErrorReasonDeadlineUnreachable, http.StatusServiceUnavailable) return } @@ -781,7 +762,7 @@ func TestGenericDeadlineExhaustionReturnsSingle429(t *testing.T) { ) { fp.sendTypedInferenceError( ctx, req, protocol.FailureCodeCapacity, - errorReasonDeadlineUnreachable, http.StatusServiceUnavailable) + attempt.ErrorReasonDeadlineUnreachable, http.StatusServiceUnavailable) } for i := 0; i < 2; i++ { startFailoverProvider(t, ctx, ts, reg, failoverProviderConfig{ diff --git a/coordinator/api/deferred_commit_test.go b/coordinator/api/deferred_commit_test.go index 0c427c9271..160f12ea22 100644 --- a/coordinator/api/deferred_commit_test.go +++ b/coordinator/api/deferred_commit_test.go @@ -1,11 +1,5 @@ package api -// Deferred-commit tests: the dispatch loop must not commit to a provider on -// boilerplate preamble chunks (role delta / Responses lifecycle events), so a -// provider that dies after its preamble — but before any real output — is -// retried invisibly instead of surfacing an in-band SSE error to a consumer -// that never received a byte. - import ( "context" "encoding/json" @@ -23,200 +17,6 @@ import ( "nhooyr.io/websocket" ) -func TestIsBoilerplateChunk(t *testing.T) { - cases := []struct { - name string - chunk string - want bool - }{ - { - name: "role-only delta with data prefix", - chunk: `data: {"id":"chatcmpl-1","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}`, - want: true, - }, - { - name: "role-only delta without data prefix", - chunk: `{"id":"chatcmpl-1","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}`, - want: true, - }, - { - name: "role-only delta with trailing newlines", - chunk: "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\"},\"finish_reason\":null}]}\n\n", - want: true, - }, - { - name: "role with empty content rides along", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}`, - want: true, - }, - { - name: "role with null content rides along", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":null},"finish_reason":null}]}`, - want: true, - }, - { - name: "role with empty tool_calls array rides along", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[]},"finish_reason":null}]}`, - want: true, - }, - { - name: "role plus real content commits", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello"},"finish_reason":null}]}`, - want: false, - }, - { - name: "content-only delta commits", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}`, - want: false, - }, - { - name: "role plus reasoning_content commits", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"thinking"},"finish_reason":null}]}`, - want: false, - }, - { - name: "tool_calls delta commits", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"f","arguments":""}}]},"finish_reason":null}]}`, - want: false, - }, - { - name: "finish chunk commits", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":"stop"}]}`, - want: false, - }, - { - name: "usage-only chunk commits", - chunk: `data: {"object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}`, - want: false, - }, - { - name: "role delta carrying usage commits", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}],"usage":{"prompt_tokens":10,"completion_tokens":0,"total_tokens":10}}`, - want: false, - }, - { - name: "null usage field is still boilerplate", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}],"usage":null}`, - want: true, - }, - { - name: "done terminator commits", - chunk: "data: [DONE]", - want: false, - }, - { - name: "responses created event is boilerplate", - chunk: `data: {"type":"response.created","response":{"id":"resp_1","object":"response","status":"in_progress"}}`, - want: true, - }, - { - name: "responses in_progress event is boilerplate", - chunk: `data: {"type":"response.in_progress","response":{"id":"resp_1","object":"response","status":"in_progress"}}`, - want: true, - }, - { - name: "responses output_text delta commits", - chunk: `data: {"type":"response.output_text.delta","delta":"Hello"}`, - want: false, - }, - { - // Regression: a chat content delta that QUOTES "response.created" in - // its content text must NOT be misread as a Responses boilerplate - // event — it carries real output and must commit. The old substring - // check dropped/retried it. - name: "chat content delta quoting response.created commits", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"The \"response.created\" event signals the start"},"finish_reason":null}]}`, - want: false, - }, - { - // Same false positive for the role-only-shaped delta carrying the - // literal in content: content is non-empty, so it commits. - name: "content delta quoting response.in_progress commits", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"see response.in_progress in the docs"},"finish_reason":null}]}`, - want: false, - }, - { - // A genuine Responses lifecycle event (parsed top-level type) is - // still boilerplate even when extra fields mention the string. - name: "real response.created event with nested mentions is boilerplate", - chunk: `data: {"type":"response.created","response":{"id":"resp_1","object":"response","status":"in_progress","instructions":"explain response.in_progress"}}`, - want: true, - }, - { - name: "complete chat.completion object commits", - chunk: `data: {"id":"chatcmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`, - want: false, - }, - { - name: "garbage commits", - chunk: "data: not json at all", - want: false, - }, - { - name: "garbage mentioning role commits", - chunk: `data: "role" but not json`, - want: false, - }, - { - name: "empty string commits", - chunk: "", - want: false, - }, - { - name: "empty choices commits", - chunk: `data: {"object":"chat.completion.chunk","model":"role-model","choices":[]}`, - want: false, - }, - { - name: "delta without role commits", - chunk: `data: {"object":"chat.completion.chunk","model":"role-model","choices":[{"index":0,"delta":{},"finish_reason":null}]}`, - want: false, - }, - { - name: "unknown delta field commits", - chunk: `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","audio":{"id":"a1"}},"finish_reason":null}]}`, - want: false, - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - if got := isBoilerplateChunk(tc.chunk); got != tc.want { - t.Errorf("isBoilerplateChunk(%q) = %v, want %v", tc.chunk, got, tc.want) - } - }) - } -} - -func TestRequestHasTools(t *testing.T) { - cases := []struct { - name string - body string - want bool - }{ - {name: "absent", body: `{"model":"m","messages":[]}`, want: false}, - {name: "empty array", body: `{"model":"m","tools":[]}`, want: false}, - {name: "non-empty array", body: `{"model":"m","tools":[{"type":"function","function":{"name":"f"}}]}`, want: true}, - {name: "two tools", body: `{"model":"m","tools":[{"type":"function"},{"type":"function"}]}`, want: true}, - {name: "wrong type string", body: `{"model":"m","tools":"function"}`, want: false}, - {name: "wrong type object", body: `{"model":"m","tools":{"type":"function"}}`, want: false}, - {name: "wrong type number", body: `{"model":"m","tools":3}`, want: false}, - {name: "null", body: `{"model":"m","tools":null}`, want: false}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - var parsed map[string]any - if err := json.Unmarshal([]byte(tc.body), &parsed); err != nil { - t.Fatalf("unmarshal test body: %v", err) - } - if got := requestHasTools(parsed); got != tc.want { - t.Errorf("requestHasTools(%s) = %v, want %v", tc.body, got, tc.want) - } - }) - } -} - // TestStreamingFirstChunksEmittedInOrder verifies the held-preamble plumbing: // every element of firstChunks is written in order ahead of the relay loop, // with the single-chunk special-casing ([DONE] swallowing, normalization) diff --git a/coordinator/api/desired_models.go b/coordinator/api/desired_models.go new file mode 100644 index 0000000000..caf042693b --- /dev/null +++ b/coordinator/api/desired_models.go @@ -0,0 +1,51 @@ +package api + +import ( + "github.com/eigeninference/d-inference/coordinator/registry" +) + +// fanOutDesiredModels pushes the current desired_models to every connected +// provider that should learn it. It is gated per provider: only Swift-runtime +// providers at/above minProviderVersionForDesiredModels receive the message, +// because a pre-feature provider's strict decoder throws on unknown types. +// IDs+entries are collected under the registry's read lock and the sends happen +// afterward (SendDesiredModels takes the lock again). +func (s *Server) fanOutDesiredModels() { + // Collect eligible provider IDs under the registry read lock, then compute + // entries and send AFTER releasing it. DesiredModelsForProvider and + // SendDesiredModels each take r.mu themselves, so calling them inside the + // ForEachProvider callback (which already holds r.mu.RLock) would nest the + // read lock — a deadlock once a writer queues between the outer and inner + // RLock (Go's RWMutex blocks new readers while a writer waits). + var eligibleIDs []string + s.registry.ForEachProvider(func(p *registry.Provider) { + p.Mu().Lock() + id, backend, version := p.ID, p.Backend, p.Version + p.Mu().Unlock() + if s.providerSupportsDesiredModels(backend, version) { + eligibleIDs = append(eligibleIDs, id) + } + }) + for _, id := range eligibleIDs { + // Empty entry sets are sent too: "nothing is desired" is meaningful + // state — it marks a provider's in-flight prefetch for a now-deleted/ + // repointed alias as stale (see SendDesiredModels). + if err := s.registry.SendDesiredModels(id, s.registry.DesiredModelsForProvider(id)); err != nil { + s.logger.Warn("failed to push desired_models", "provider_id", id, "error", err) + } + } +} + +// providerSupportsDesiredModels reports whether a provider can receive the +// desired_models message: it must run the Swift backend and report a version at +// or above minProviderVersionForDesiredModels. A provider that reports no version +// is treated as too old (fail-closed). +func (s *Server) providerSupportsDesiredModels(backend, version string) bool { + if !registry.BackendUsesSwiftRuntime(backend) { + return false + } + if version == "" { + return false + } + return !semverLess(version, minProviderVersionForDesiredModels) +} diff --git a/coordinator/api/device_auth.go b/coordinator/api/device_auth.go deleted file mode 100644 index 76e10ea123..0000000000 --- a/coordinator/api/device_auth.go +++ /dev/null @@ -1,244 +0,0 @@ -package api - -// Device authorization endpoints (RFC 8628-style flow). -// -// This implements a device login flow for provider machines: -// 1. Provider CLI calls POST /v1/device/code → gets device_code + user_code -// 2. User opens verification_uri in browser, logs in via Privy, enters user_code -// 3. Provider CLI polls POST /v1/device/token with device_code → gets auth token -// 4. Provider uses auth token in WebSocket registration to link to account - -import ( - "crypto/rand" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "fmt" - "math/big" - "net/http" - "strings" - "time" - - "github.com/eigeninference/d-inference/coordinator/auth" - "github.com/eigeninference/d-inference/coordinator/store" -) - -const ( - // DeviceCodeExpiry is how long a device code is valid. - DeviceCodeExpiry = 15 * time.Minute - - // DeviceCodePollInterval is the minimum interval between polls (seconds). - DeviceCodePollInterval = 5 -) - -// handleDeviceCode creates a new device authorization request. -// POST /v1/device/code -// No auth required — the provider CLI is not yet authenticated. -func (s *Server) handleDeviceCode(w http.ResponseWriter, r *http.Request) { - // Generate device code (opaque, high-entropy secret). - deviceCodeBytes := make([]byte, 32) - if _, err := rand.Read(deviceCodeBytes); err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("server_error", "failed to generate device code")) - return - } - deviceCode := hex.EncodeToString(deviceCodeBytes) - - // Generate user code (short, human-readable, uppercase alphanumeric). - userCode, err := generateUserCode() - if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("server_error", "failed to generate user code")) - return - } - - dc := &store.DeviceCode{ - DeviceCode: deviceCode, - UserCode: userCode, - Status: "pending", - ExpiresAt: time.Now().Add(DeviceCodeExpiry), - } - - if err := s.store.CreateDeviceCode(dc); err != nil { - // User code collision — retry once. - userCode, _ = generateUserCode() - dc.UserCode = userCode - if err := s.store.CreateDeviceCode(dc); err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("server_error", "failed to create device code")) - return - } - } - - // Build verification URI. If a console URL is configured (separate frontend), - // use that. Otherwise fall back to the coordinator's own host. - var verificationURI string - if s.consoleURL != "" { - verificationURI = strings.TrimRight(s.consoleURL, "/") + "/link" - } else { - scheme := "https" - if r.TLS == nil && !strings.Contains(r.Host, "darkbloom.dev") { - scheme = "http" - } - verificationURI = fmt.Sprintf("%s://%s/link", scheme, r.Host) - } - - writeJSON(w, http.StatusOK, map[string]any{ - "device_code": deviceCode, - "user_code": userCode, - "verification_uri": verificationURI, - "expires_in": int(DeviceCodeExpiry.Seconds()), - "interval": DeviceCodePollInterval, - }) - - s.logger.Info("device code created", - "user_code", userCode, - "expires_in", DeviceCodeExpiry.String(), - ) -} - -// handleDeviceToken polls for a device authorization result. -// POST /v1/device/token -// No auth required — security comes from the device_code being secret. -func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) { - var req struct { - DeviceCode string `json:"device_code"` - } - if !decodeCappedJSON(w, r, maxControlPlaneBodyBytes, &req) { - return - } - if req.DeviceCode == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request", "device_code is required")) - return - } - - dc, err := s.store.GetDeviceCode(req.DeviceCode) - if err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("invalid_grant", "device code not found")) - return - } - - // Check expiry. - if time.Now().After(dc.ExpiresAt) { - writeJSON(w, http.StatusGone, errorResponse("expired_token", "device code has expired")) - return - } - - switch dc.Status { - case "pending": - // RFC 8628: "authorization_pending" — not yet approved. - writeJSON(w, http.StatusOK, map[string]any{ - "status": "authorization_pending", - }) - - case "approved": - // Generate a long-lived provider token. - tokenBytes := make([]byte, 32) - if _, err := rand.Read(tokenBytes); err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("server_error", "failed to generate token")) - return - } - rawToken := "eigeninference-pt-" + hex.EncodeToString(tokenBytes) - tokenHash := sha256Hash(rawToken) - - pt := &store.ProviderToken{ - TokenHash: tokenHash, - AccountID: dc.AccountID, - Label: "device-" + dc.UserCode, - Active: true, - } - if err := s.store.CreateProviderToken(pt); err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("server_error", "failed to create token")) - return - } - - s.logger.Info("provider token issued", - "account_id", dc.AccountID, - "user_code", dc.UserCode, - ) - - writeJSON(w, http.StatusOK, map[string]any{ - "status": "authorized", - "token": rawToken, - "account_id": dc.AccountID, - }) - - default: - writeJSON(w, http.StatusGone, errorResponse("expired_token", "device code is no longer valid")) - } -} - -// handleDeviceApprove approves a device code, linking it to the authenticated user's account. -// POST /v1/device/approve -// Requires Privy auth — the user must be logged in. -func (s *Server) handleDeviceApprove(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusUnauthorized, errorResponse("auth_error", "Privy authentication required")) - return - } - - var req struct { - UserCode string `json:"user_code"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.UserCode == "" { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request", "user_code is required")) - return - } - - // Normalize: uppercase, trim spaces. - userCode := strings.ToUpper(strings.TrimSpace(req.UserCode)) - - dc, err := s.store.GetDeviceCodeByUserCode(userCode) - if err != nil { - writeJSON(w, http.StatusNotFound, errorResponse("invalid_code", "device code not found — check the code and try again")) - return - } - - if time.Now().After(dc.ExpiresAt) { - writeJSON(w, http.StatusGone, errorResponse("expired_code", "this code has expired — run 'darkbloom login' again")) - return - } - - if dc.Status != "pending" { - writeJSON(w, http.StatusConflict, errorResponse("already_used", "this code has already been used")) - return - } - - if err := s.store.ApproveDeviceCode(dc.DeviceCode, user.AccountID); err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse("server_error", "failed to approve device")) - return - } - - s.logger.Info("device approved", - "user_code", userCode, - "account_id", user.AccountID, - "email", user.Email, - ) - - writeJSON(w, http.StatusOK, map[string]any{ - "status": "approved", - "message": "Device linked successfully. Your provider will connect to your account shortly.", - }) -} - -// generateUserCode creates a short, human-readable code like "ABCD-1234". -func generateUserCode() (string, error) { - // Use alphanumeric chars (no ambiguous chars: 0/O, 1/I/L). - const charset = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" - - code := make([]byte, 8) - for i := range code { - n, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset)))) - if err != nil { - return "", err - } - code[i] = charset[n.Int64()] - } - - // Format as XXXX-XXXX for readability. - return string(code[:4]) + "-" + string(code[4:]), nil -} - -// sha256Hash returns the hex-encoded SHA-256 digest. -func sha256Hash(s string) string { - h := sha256.Sum256([]byte(s)) - return hex.EncodeToString(h[:]) -} diff --git a/coordinator/api/device_auth_test.go b/coordinator/api/device_auth_test.go deleted file mode 100644 index 87c44799c7..0000000000 --- a/coordinator/api/device_auth_test.go +++ /dev/null @@ -1,315 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "fmt" - "log/slog" - "net/http" - "net/http/httptest" - "os" - "strings" - "testing" - "time" - - "github.com/eigeninference/d-inference/coordinator/auth" - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/store" -) - -func deviceTestServer() (*Server, store.Store) { - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - st := store.NewMemory(store.Config{AdminKey: "test-key"}) - reg := registry.New(logger) - srv := NewServer(reg, st, ServerConfig{}, logger) - return srv, st -} - -func withUser(ctx context.Context, accountID, email string) context.Context { - return context.WithValue(ctx, auth.CtxKeyUser, &store.User{ - AccountID: accountID, - Email: email, - }) -} - -func TestDeviceCodeGeneration(t *testing.T) { - srv, _ := deviceTestServer() - req := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) - w := httptest.NewRecorder() - - srv.handleDeviceCode(w, req) - - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200, body: %s", w.Code, w.Body.String()) - } - - var resp map[string]any - json.Unmarshal(w.Body.Bytes(), &resp) - - dc := resp["device_code"].(string) - if len(dc) != 64 { - t.Errorf("device_code length = %d, want 64", len(dc)) - } - - uc := resp["user_code"].(string) - if len(uc) != 9 || uc[4] != '-' { - t.Errorf("user_code = %q, want XXXX-XXXX format", uc) - } - - if _, ok := resp["verification_uri"]; !ok { - t.Error("missing verification_uri") - } - if resp["expires_in"].(float64) != DeviceCodeExpiry.Seconds() { - t.Errorf("expires_in = %v, want %v", resp["expires_in"], DeviceCodeExpiry.Seconds()) - } - if resp["interval"].(float64) != DeviceCodePollInterval { - t.Errorf("interval = %v, want %v", resp["interval"], DeviceCodePollInterval) - } -} - -func TestDeviceCodeUniquePerCall(t *testing.T) { - srv, _ := deviceTestServer() - seen := make(map[string]bool) - - for range 10 { - req := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) - w := httptest.NewRecorder() - srv.handleDeviceCode(w, req) - - var resp map[string]any - json.Unmarshal(w.Body.Bytes(), &resp) - dc := resp["device_code"].(string) - if seen[dc] { - t.Error("duplicate device code generated") - } - seen[dc] = true - } -} - -func TestDeviceTokenPending(t *testing.T) { - srv, _ := deviceTestServer() - - codeReq := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) - codeW := httptest.NewRecorder() - srv.handleDeviceCode(codeW, codeReq) - - var codeResp map[string]any - json.Unmarshal(codeW.Body.Bytes(), &codeResp) - - body := fmt.Sprintf(`{"device_code":"%s"}`, codeResp["device_code"].(string)) - tokenReq := httptest.NewRequest(http.MethodPost, "/v1/device/token", strings.NewReader(body)) - tokenW := httptest.NewRecorder() - srv.handleDeviceToken(tokenW, tokenReq) - - if tokenW.Code != http.StatusOK { - t.Fatalf("status = %d, want 200", tokenW.Code) - } - var tokenResp map[string]any - json.Unmarshal(tokenW.Body.Bytes(), &tokenResp) - if tokenResp["status"] != "authorization_pending" { - t.Errorf("status = %q, want authorization_pending", tokenResp["status"]) - } -} - -func TestDeviceTokenNotFound(t *testing.T) { - srv, _ := deviceTestServer() - req := httptest.NewRequest(http.MethodPost, "/v1/device/token", strings.NewReader(`{"device_code":"nonexistent"}`)) - w := httptest.NewRecorder() - srv.handleDeviceToken(w, req) - if w.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", w.Code) - } -} - -func TestDeviceTokenMissingField(t *testing.T) { - srv, _ := deviceTestServer() - req := httptest.NewRequest(http.MethodPost, "/v1/device/token", strings.NewReader(`{}`)) - w := httptest.NewRecorder() - srv.handleDeviceToken(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) - } -} - -func TestDeviceApproveAndTokenAuthorized(t *testing.T) { - srv, _ := deviceTestServer() - - // Create device code. - codeReq := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) - codeW := httptest.NewRecorder() - srv.handleDeviceCode(codeW, codeReq) - var codeResp map[string]any - json.Unmarshal(codeW.Body.Bytes(), &codeResp) - deviceCode := codeResp["device_code"].(string) - userCode := codeResp["user_code"].(string) - - // Approve with user context. - approveBody := fmt.Sprintf(`{"user_code":"%s"}`, userCode) - approveReq := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(approveBody)) - approveReq = approveReq.WithContext(withUser(approveReq.Context(), "acct-1", "user@test.com")) - approveW := httptest.NewRecorder() - srv.handleDeviceApprove(approveW, approveReq) - - if approveW.Code != http.StatusOK { - t.Fatalf("approve status = %d, body: %s", approveW.Code, approveW.Body.String()) - } - - // Poll token — should be authorized. - tokenBody := fmt.Sprintf(`{"device_code":"%s"}`, deviceCode) - tokenReq := httptest.NewRequest(http.MethodPost, "/v1/device/token", strings.NewReader(tokenBody)) - tokenW := httptest.NewRecorder() - srv.handleDeviceToken(tokenW, tokenReq) - - var tokenResp map[string]any - json.Unmarshal(tokenW.Body.Bytes(), &tokenResp) - if tokenResp["status"] != "authorized" { - t.Errorf("status = %q, want authorized", tokenResp["status"]) - } - token := tokenResp["token"].(string) - if !strings.HasPrefix(token, "eigeninference-pt-") { - t.Errorf("token = %q, want eigeninference-pt- prefix", token) - } - if tokenResp["account_id"] != "acct-1" { - t.Errorf("account_id = %q, want acct-1", tokenResp["account_id"]) - } -} - -func TestDeviceApproveRequiresAuth(t *testing.T) { - srv, _ := deviceTestServer() - req := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(`{"user_code":"ABCD-1234"}`)) - w := httptest.NewRecorder() - srv.handleDeviceApprove(w, req) - if w.Code != http.StatusUnauthorized { - t.Errorf("status = %d, want 401", w.Code) - } -} - -func TestDeviceApproveNotFound(t *testing.T) { - srv, _ := deviceTestServer() - req := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(`{"user_code":"ZZZZ-9999"}`)) - req = req.WithContext(withUser(req.Context(), "a1", "")) - w := httptest.NewRecorder() - srv.handleDeviceApprove(w, req) - if w.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", w.Code) - } -} - -func TestDeviceApproveAlreadyUsed(t *testing.T) { - srv, _ := deviceTestServer() - - codeReq := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) - codeW := httptest.NewRecorder() - srv.handleDeviceCode(codeW, codeReq) - var codeResp map[string]any - json.Unmarshal(codeW.Body.Bytes(), &codeResp) - userCode := codeResp["user_code"].(string) - - body := fmt.Sprintf(`{"user_code":"%s"}`, userCode) - - // First approval. - req1 := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(body)) - req1 = req1.WithContext(withUser(req1.Context(), "a1", "")) - w1 := httptest.NewRecorder() - srv.handleDeviceApprove(w1, req1) - if w1.Code != http.StatusOK { - t.Fatalf("first approve: %d", w1.Code) - } - - // Second approval — conflict. - req2 := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(body)) - req2 = req2.WithContext(withUser(req2.Context(), "a1", "")) - w2 := httptest.NewRecorder() - srv.handleDeviceApprove(w2, req2) - if w2.Code != http.StatusConflict { - t.Errorf("second approve status = %d, want 409", w2.Code) - } -} - -func TestDeviceTokenExpired(t *testing.T) { - srv, st := deviceTestServer() - st.CreateDeviceCode(&store.DeviceCode{ - DeviceCode: "expired-code-123", - UserCode: "EXPR-TEST", - Status: "pending", - ExpiresAt: time.Now().Add(-1 * time.Minute), - }) - - req := httptest.NewRequest(http.MethodPost, "/v1/device/token", strings.NewReader(`{"device_code":"expired-code-123"}`)) - w := httptest.NewRecorder() - srv.handleDeviceToken(w, req) - if w.Code != http.StatusGone { - t.Errorf("status = %d, want 410", w.Code) - } -} - -func TestDeviceApproveExpiredCode(t *testing.T) { - srv, st := deviceTestServer() - st.CreateDeviceCode(&store.DeviceCode{ - DeviceCode: "expired-approve", - UserCode: "EXPX-TEST", - Status: "pending", - ExpiresAt: time.Now().Add(-1 * time.Minute), - }) - - req := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(`{"user_code":"EXPX-TEST"}`)) - req = req.WithContext(withUser(req.Context(), "a1", "")) - w := httptest.NewRecorder() - srv.handleDeviceApprove(w, req) - if w.Code != http.StatusGone { - t.Errorf("status = %d, want 410", w.Code) - } -} - -func TestDeviceApproveCaseInsensitive(t *testing.T) { - srv, _ := deviceTestServer() - - codeReq := httptest.NewRequest(http.MethodPost, "/v1/device/code", nil) - codeW := httptest.NewRecorder() - srv.handleDeviceCode(codeW, codeReq) - var codeResp map[string]any - json.Unmarshal(codeW.Body.Bytes(), &codeResp) - userCode := codeResp["user_code"].(string) - - // Approve with lowercase. - body := fmt.Sprintf(`{"user_code":"%s"}`, strings.ToLower(userCode)) - req := httptest.NewRequest(http.MethodPost, "/v1/device/approve", strings.NewReader(body)) - req = req.WithContext(withUser(req.Context(), "a1", "")) - w := httptest.NewRecorder() - srv.handleDeviceApprove(w, req) - if w.Code != http.StatusOK { - t.Errorf("lowercase approve status = %d, want 200", w.Code) - } -} - -func TestGenerateUserCodeFormat(t *testing.T) { - for range 20 { - code, err := generateUserCode() - if err != nil { - t.Fatalf("generateUserCode: %v", err) - } - if len(code) != 9 || code[4] != '-' { - t.Errorf("code = %q, want XXXX-XXXX format", code) - } - for _, c := range strings.ReplaceAll(code, "-", "") { - if c == '0' || c == 'O' || c == '1' || c == 'I' || c == 'L' { - t.Errorf("code %q contains ambiguous char %q", code, c) - } - } - } -} - -func TestSha256HashDeterministic(t *testing.T) { - h1 := sha256Hash("test-input") - h2 := sha256Hash("test-input") - if h1 != h2 { - t.Error("sha256Hash should be deterministic") - } - if len(h1) != 64 { - t.Errorf("hash length = %d, want 64", len(h1)) - } - h3 := sha256Hash("different") - if h1 == h3 { - t.Error("different inputs should produce different hashes") - } -} diff --git a/coordinator/api/dispatch.go b/coordinator/api/dispatch.go deleted file mode 100644 index a38606b5eb..0000000000 --- a/coordinator/api/dispatch.go +++ /dev/null @@ -1,3898 +0,0 @@ -package api - -// Per-request dispatch state machine for the consumer inference path. -// -// This file holds the speculative TTFT-aware dispatch loop that handleChatCompletions -// drives: it picks a provider (or queues), waits for the first CONTENT chunk with a -// speculative backup race, fails over invisibly on provider error/timeout up to -// maxDispatchAttempts, and commits exactly once. It is a PURELY STRUCTURAL extraction -// of what previously lived inline in consumer.go — every select arm, timer Stop/Reset, -// channel-close+ErrorCh grace window, heldChunks cap, liveness extension, speculative -// race (backup dispatch / cancel-loser / skipBackup), refund-exactly-once, breaker -// call, DD metric, and status code is preserved exactly. -// -// Control-flow mapping (former labeled blocks → methods): -// -// for attempt := range maxDispatchAttempts → dispatchState.run (the orchestrator) -// dispatch-primary block (incl. queue path) → dispatchState.dispatchPrimary -// firstChunkWait + speculative race → dispatchState.waitFirstChunk -// noBackupWait → dispatchState.waitNoBackup -// race + sub-waits → dispatchState.runRace -// backupFailedPrimaryWait → dispatchState.raceBackupFailedWaitPrimary -// primaryFailedBackupWait → dispatchState.racePrimaryFailedWaitBackup -// backupFailedWaitPrimary → dispatchState.raceBackupErrWaitPrimary -// acceptedWait → dispatchState.waitAccepted -// -// The former labeled jumps become method returns: `continue dispatch` → outcomeRetry, -// `break`/commit → outcomeCommitted, `break