Repository navigation
fix(coordinator): resolve DB connection starvation, deprecate Python providers - #228
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Before / After ArchitectureBefore: DB Connection Starvation Cascadeflowchart TD
subgraph "20 Connection Pool"
C1[Conn 1]
C2[Conn 2]
C3[Conn ...]
C20[Conn 20]
end
HB["Heartbeats<br/>~80 upserts/min<br/>(every heartbeat persists)"] -->|"INSERT ON CONFLICT<br/>26 columns, 5s timeout"| C1
HB --> C2
STATS["/v1/stats cache miss<br/>5 concurrent queries"] -->|"SELECT COUNT, SUM<br/>FROM usage (NO INDEX)<br/>10s hold"| C3
STATS -->|"full table scan"| C20
EARN["/v1/provider/account-earnings<br/>498 calls / 22 min"] -->|"SELECT SUM(*)<br/>FROM provider_earnings<br/>scans ALL rows"| C2
BILLING["Billing Settlement<br/>per inference completion"] -->|"5-7 sequential ops<br/>5s timeout each<br/>= 30s total hold"| C1
AUTH["Auth Middleware<br/>every request"] -->|"3 sequential queries<br/>ValidateKey → GetKeyAccount → GetUser"| C3
TELEM["Telemetry Batch INSERT<br/>100 events × 14 cols"] -->|"NO TIMEOUT<br/>unbounded hold"| C20
C1 --> EXHAUST["ALL 20 CONNECTIONS<br/>EXHAUSTED"]
C2 --> EXHAUST
C3 --> EXHAUST
C20 --> EXHAUST
EXHAUST -->|"5s timeout"| TIMEOUT["context deadline exceeded<br/>2,425 errors in 22 min"]
TIMEOUT --> SYNC["SyncRuntimeManifest()<br/>triggered"]
SYNC -->|"ListReleases() timeout → nil"| NUKE["manifest = nil"]
NUKE --> REVAL["revalidateConnectedProviders()"]
REVAL -->|"manifest == nil →<br/>RuntimeVerified = false<br/>for ALL providers"| DEAD["🔴 ENTIRE FLEET DEROUTED<br/>0 providers routable"]
DEAD -->|"challenge responses<br/>skip check when<br/>manifest == nil"| STUCK["RuntimeVerified stays false<br/>permanently"]
style EXHAUST fill:#ff4444,color:#fff
style DEAD fill:#cc0000,color:#fff
style STUCK fill:#cc0000,color:#fff
style TIMEOUT fill:#ff6666,color:#fff
style NUKE fill:#ff8800,color:#fff
After: Resilient Connection Managementflowchart TD
subgraph "80 Connection Pool"
C1[Conn 1-20]
C2[Conn 21-40]
C3[Conn 41-60]
C4[Conn 61-80]
end
HB["Heartbeats<br/>~3 upserts/min<br/>(30s throttle per provider)"] -->|"throttled writes"| C1
STATS["/v1/stats<br/>indexed queries"] -->|"idx_usage_created<br/>idx_usage_consumer<br/>idx_usage_provider"| C2
EARN["/v1/provider/account-earnings"] -->|"PK lookup on<br/>earnings_summary<br/>(materialized counters)"| C1
BILLING["Billing Settlement"] -->|"1 CTE round-trip<br/>+ 1 concurrent credit<br/>+ 1 async usage INSERT"| C3
AUTH["Auth Middleware"] -->|"LRU cache hit → 0 DB<br/>cache miss → 1 query<br/>(ValidateKeyFull)"| C2
TELEM["Telemetry Batch INSERT<br/>5s timeout guard"] -->|"bounded hold"| C4
subgraph "Manifest Safety"
SYNC2["SyncRuntimeManifest()"]
GUARD{"ListReleases()<br/>== nil?"}
KEEP["Keep existing manifest<br/>log warning"]
REBUILD["Rebuild manifest<br/>from releases"]
SYNC2 --> GUARD
GUARD -->|"nil (DB timeout)"| KEEP
GUARD -->|"valid data"| REBUILD
end
REBUILD --> REVAL2["revalidateProviders()"]
REVAL2 --> CHECK{"manifest nil?"}
CHECK -->|"nil (intentional<br/>withdrawal only)"| DEROUTE["Deroute providers"]
CHECK -->|"non-nil"| VERIFY["Verify hashes<br/>per provider"]
KEEP -->|"no revalidation<br/>providers stay routable"| SAFE["✅ Fleet stays online"]
subgraph "Python Deprecated"
SWIFT["mlx-swift provider"] -->|"metallib hash check"| ROUTE["✅ Routable"]
PYTHON["inprocess-mlx provider"] -->|"immediately rejected"| BLOCK["❌ Not routable"]
end
style SAFE fill:#00aa00,color:#fff
style ROUTE fill:#00aa00,color:#fff
style BLOCK fill:#888,color:#fff
style KEEP fill:#00aa00,color:#fff
style C1 fill:#4488ff,color:#fff
style C2 fill:#4488ff,color:#fff
style C3 fill:#4488ff,color:#fff
style C4 fill:#4488ff,color:#fff
DB Operations Per Inference Requestflowchart LR
subgraph "BEFORE: 9-12 sequential DB ops"
B1["GetModelPrice"] --> B2["GetModelPrice<br/>(provider)"]
B2 --> B3["ValidateKey"]
B3 --> B4["GetKeyAccount"]
B4 --> B5["GetUser"]
B5 --> B6["Credit/Debit<br/>(refund)"]
B6 --> B7["RecordUsage<br/>(sync)"]
B7 --> B8["BEGIN"]
B8 --> B9["UPDATE balances"]
B9 --> B10["SELECT balance"]
B10 --> B11["INSERT ledger"]
B11 --> B12["INSERT earnings"]
B12 --> B13["COMMIT"]
B13 --> B14["Credit platform"]
end
subgraph "AFTER: 2-3 concurrent ops"
A1["Auth: LRU cache hit<br/>(0 DB ops)"]
A1 --> A2["Credit/Debit<br/>(refund)"]
A2 --> A3["CTE: credit + ledger<br/>+ earning + 2× summary<br/>(1 round-trip)"]
A2 --> A4["Credit platform<br/>(concurrent)"]
A2 -.->|"async fire-and-forget"| A5["RecordUsage"]
end
style B1 fill:#ff6666,color:#fff
style B14 fill:#ff6666,color:#fff
style A1 fill:#00aa00,color:#fff
style A3 fill:#00aa00,color:#fff
style A5 fill:#88ccff,color:#000
|
|
This PR makes two unrelated removals in Trust Boundaries Touched
Threat AnalysisT-038 — Missing T-032 — Solana wallet mnemonic exfiltration (TB-008) T-007 / T-012 / T-027 — Provider serves manipulated model outputs / weight substitution (TB-002, TB-003, TB-007)
Recommendation: Add a startup warning log if New Attack Surface Not Covered by Existing ThreatsR2 site-packages CDN URL removal (
Open Findings ResolvedNone. SEC-007, SEC-027, and SEC-017 remain open and are not addressed by this PR. 🔐 Threat model: |
…providers Production outage root cause: Postgres connection pool (20 max) exhausted by concurrent stats scans, heartbeat upserts, and billing settlement. When SyncRuntimeManifest happened to overlap with pool exhaustion, ListReleases timed out, the manifest was nuked, and revalidateConnectedProvidersAgainstRuntimePolicy set RuntimeVerified=false for ALL providers — instantly derouting the fleet. Critical fixes: - Increase pool MaxConns from 20 to 80, MinConns from 5 to 10 - SyncRuntimeManifest: return early on ListReleases nil (DB timeout) instead of nuking a working manifest - revalidateConnectedProvidersAgainstRuntimePolicy: only deroute on intentional manifest withdrawal, not transient DB failures - Add 5s timeout to telemetry batch INSERT (was unbounded) Python/legacy provider deprecation: - privateTextBackendSupported only accepts mlx-swift - verifyRuntimeHashesForBackend immediately rejects non-Swift backends - providerSupportsPrivateTextLocked: remove dead Python caps branch - Remove dead code: r2SitePackagesCDNURL, verifyRuntimeHashes(), EIGENINFERENCE_KNOWN_PYTHON_HASHES, EIGENINFERENCE_KNOWN_RUNTIME_HASHES - All test fixtures updated from inprocess-mlx to mlx-swift DB performance optimizations: - CreditProviderAccount: 6 sequential round-trips → single CTE - Usage recording made async (saferun.Go) - Provider credit + platform fee run concurrently (WaitGroup) - Auth middleware: 3 DB queries → 1 (ValidateKeyFull) + LRU cache (60s TTL) - PersistProviderThrottled: heartbeat writes rate-limited to 1x/30s per provider - Add indexes: idx_usage_created, idx_usage_consumer, idx_usage_provider - Add earnings_summary materialized table: eliminates full-table SUM scans on /v1/provider/account-earnings (PK lookup instead) - Backfill migration populates earnings_summary from existing data - Add detailed mismatch logging (component+hash, not just count) All migrations are idempotent (CREATE IF NOT EXISTS / ON CONFLICT DO NOTHING). No manual SQL required — indexes and tables auto-create on restart. All tests pass. go vet clean.
c043386 to
c85f3d0
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c043386ccf
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if err == nil { | ||
| s.storeAPIKeyCache(token, apiKeyCacheEntry{ | ||
| active: keyActive, | ||
| ownerAccountID: ownerAccountID, | ||
| cachedAt: time.Now(), | ||
| }) |
There was a problem hiding this comment.
Avoid accepting revoked API keys from sibling instances
In deployments with more than one coordinator process, caching active=true here lets a revoked API key continue to authenticate on any other process that saw it within the last 60 seconds, because handleRevokeKey only invalidates the local in-memory map while those sibling processes skip ValidateKeyFull and never observe active = FALSE in Postgres. This weakens key revocation semantics; either avoid caching positive auth results or add a shared invalidation/version check before authorizing cached keys.
Useful? React with 👍 / 👎.
| if err != nil { | ||
| // No rows = no earnings yet, return zeros (not an error). | ||
| return ProviderEarningsSummary{}, nil |
There was a problem hiding this comment.
Return DB errors from earnings summary lookups
When this query fails for reasons other than pgx.ErrNoRows (for example a timeout under DB pressure), the provider/account earnings endpoints now return a successful response with zero lifetime totals instead of surfacing the error, even if the recent earnings query just returned rows. This can make dashboards report that an account has no earnings during transient database failures; only the no-rows case should be converted to an empty summary.
Useful? React with 👍 / 👎.
| saferun.Go(s.logger, "recordUsage", func() { | ||
| s.store.RecordUsageWithCostAndLocation(providerID, pr.ConsumerKey, pr.Model, msg.RequestID, msg.Usage.PromptTokens, msg.Usage.CompletionTokens, totalCost, pr.ConsumerLocation) |
There was a problem hiding this comment.
Keep usage persistence on the settlement path
Because billing is settled before this fire-and-forget goroutine runs, any coordinator crash/restart or shutdown immediately after a completion can leave the consumer charged and provider credited without the matching usage row. That row is the durable history used after restarts and by stats/location aggregations, so moving it off the synchronous completion path can corrupt persisted accounting for completed requests.
Useful? React with 👍 / 👎.
…providers (Layr-Labs#228) Production outage root cause: Postgres connection pool (20 max) exhausted by concurrent stats scans, heartbeat upserts, and billing settlement. When SyncRuntimeManifest happened to overlap with pool exhaustion, ListReleases timed out, the manifest was nuked, and revalidateConnectedProvidersAgainstRuntimePolicy set RuntimeVerified=false for ALL providers — instantly derouting the fleet. Critical fixes: - Increase pool MaxConns from 20 to 80, MinConns from 5 to 10 - SyncRuntimeManifest: return early on ListReleases nil (DB timeout) instead of nuking a working manifest - revalidateConnectedProvidersAgainstRuntimePolicy: only deroute on intentional manifest withdrawal, not transient DB failures - Add 5s timeout to telemetry batch INSERT (was unbounded) Python/legacy provider deprecation: - privateTextBackendSupported only accepts mlx-swift - verifyRuntimeHashesForBackend immediately rejects non-Swift backends - providerSupportsPrivateTextLocked: remove dead Python caps branch - Remove dead code: r2SitePackagesCDNURL, verifyRuntimeHashes(), EIGENINFERENCE_KNOWN_PYTHON_HASHES, EIGENINFERENCE_KNOWN_RUNTIME_HASHES - All test fixtures updated from inprocess-mlx to mlx-swift DB performance optimizations: - CreditProviderAccount: 6 sequential round-trips → single CTE - Usage recording made async (saferun.Go) - Provider credit + platform fee run concurrently (WaitGroup) - Auth middleware: 3 DB queries → 1 (ValidateKeyFull) + LRU cache (60s TTL) - PersistProviderThrottled: heartbeat writes rate-limited to 1x/30s per provider - Add indexes: idx_usage_created, idx_usage_consumer, idx_usage_provider - Add earnings_summary materialized table: eliminates full-table SUM scans on /v1/provider/account-earnings (PK lookup instead) - Backfill migration populates earnings_summary from existing data - Add detailed mismatch logging (component+hash, not just count) All migrations are idempotent (CREATE IF NOT EXISTS / ON CONFLICT DO NOTHING). No manual SQL required — indexes and tables auto-create on restart. All tests pass. go vet clean.
* refactor: extract per-package config structs from main.go Each package now owns its Config struct and ReadConfig() function with env var constants scoped to the package that consumes them: - coordinator/config: AppConfig composition + shared helpers - coordinator/store: database URL / memory store selection - coordinator/billing: Stripe, mnemonic, referral, mock mode - coordinator/auth: Privy app ID, verification key, app secret - coordinator/ratelimit: consumer + financial rate limits - coordinator/registry: min trust level - coordinator/mdm: MDM URL + API key - coordinator/api: ServerConfig (port, URLs, CORS, min version) main.go goes from ~40 inline os.Getenv() calls to a single config.ReadAppConfig() call, with all env reads scoped to the package that owns each config domain. Pattern adapted from: https://github.com/Layr-Labs/eigenda-proxy * fix: move Config structs into config.go, add Check methods - billing.Config moved from billing.go to config.go - auth.Config moved from privy.go to config.go - Added Check() to billing, auth, registry, mdm, datadog Configs - Fixed config/app_config.go to use correct function names - Removed duplicate Config from ratelimit/ratelimit.go * refactor: inject config structs through constructors - store.NewPostgres(ctx, cfg store.Config) — replaces connString param - store.NewMemory(cfg store.Config) — replaces adminKey param - mdm.NewClient(cfg mdm.Config, logger) — replaces baseURL/apiKey params - api.NewServer(reg, st, cfg api.ServerConfig, logger) — injects cfg fields Added AdminKey to store.Config and ServerConfig (AdminKey/AdminEmails/ReleaseKey). Updated all 117 NewMemory call sites, 2 NewPostgres callers, 1 mdm.NewClient, 1 api.NewServer in main.go, and ~20 api.NewServer test callers via testServer helper. All tests pass (go test -race ./...). * fix: update e2e testbed for new constructor signatures - store/config.go: pass AdminKey in ReadConfig - e2e/testbed/coordinator.go: use store.Config for NewMemory/NewPostgres - e2e/testbed/suite.go: pass api.ServerConfig to NewServer * fix: use shared env.EnvPrefix in ratelimit config Create coordinator/env/ package with shared EnvPrefix constant so that ratelimit/config.go can reference it without creating an import cycle (config->ratelimit would conflict with ratelimit->config). config/app_config.go now defines EnvPrefix = env.EnvPrefix as a package-level alias. ratelimit/config.go imports env and uses env.EnvPrefix+"_RATE_LIMIT_RPS" etc. * fix: wire env prefix + deduplicate NewServer wiring Addresses review feedback on PR #187: 1. All per-package configs now use env.EnvPrefix instead of hardcoded "EIGENINFERENCE" strings. Previously only ratelimit/ used it; now store/, billing/, auth/, mdm/, registry/, and api/server_config do too. No import cycles — all packages import coordinator/env. 2. NewServer now applies same trimming as the Set* methods: - strings.TrimRight for baseURL, r2CDNURL, r2SitePackagesCDNURL - strings.TrimSpace for minProviderVersion - strings.ToLower(strings.TrimSpace) for admin emails This fixes an inconsistency where NewServer left URLs untrimmed but the Set* calls in main.go would trim them later. 3. Removed redundant Set* calls from main.go. NewServer already sets all ServerConfig fields, so the conditional SetConsoleURL / SetCORSOrigin / SetBaseURL / SetMinProviderVersion / SetR2CDNURL / SetR2SitePackagesCDNURL / SetReleaseKey / SetAdminKey blocks were duplicate work. * chore: add TODO for admin email storage antipattern (PR feedback) * ratelimit: reuse env helpers instead of local duplicates Move EnvFloat/EnvInt/EnvOr/FirstNonEmpty from coordinator/config to coordinator/env so they're accessible without import cycles. coordinator/config now forwards to env for backward compatibility. ratelimit/config.go now calls env.EnvFloat/env.EnvInt directly instead of defining its own duplicate helpers. Fixes: config→app_config→api→ratelimit import cycle that prevented ratelimit from importing coordinator/config directly. * fix: reuse env.EnvOr/env.FirstNonEmpty instead of local helpers * registry: validate MinTrustLevel is a recognized value in Check() * fix(billing): add MockMode+StripeSecretKey mutual exclusion to Check() * fix: guard threat-model-review for fork PRs where ANTHROPIC_API_KEY unavailable Two-part fix: 1. Workflow: add `if: github.event.pull_request.head.repo.full_name == github.repository` to skip the entire job for fork PRs (secrets not shared with forks). 2. Script: handle missing ANTHROPIC_API_KEY env var gracefully by returning a skip message instead of crashing. * Revert guard block from threat-model-review.py per review feedback * revert: remove out-of-scope workflow guard from config refactor PR * feat(coordinator): use registry max_output_length for default max_tokens bound The coordinator was hardcoding defaultMaxOutputTokens=8192 for all models when the consumer didn't specify max_tokens. Now it looks up the model's max_output_length from the registry (set at registration) and uses that as the bound. Falls back to 8192 for models not in the registry. GPT-OSS 20B and Gemma 4 both support 32K output, so consumers that omit max_tokens now get up to 32K instead of being capped at 8K. The registry lookup piggybacks on the existing GetModelRegistryRecord call used for reasoning_parser injection -- no additional DB query. * fix(provider-swift): exclude sliding attention layers from per-token KV cost Sliding-attention layers have a fixed KV cache bounded by the window size (e.g. 128 tokens for GPT-OSS 20B). Their memory does not grow with sequence length, so counting them in kvBytesPerToken overestimates the per-token cost and underestimates the token budget by up to 2x. GPT-OSS 20B: 12 full + 12 sliding layers. Before: 48 KB/token, budget ~2.1M tokens on 128GB. After: 24 KB/token, budget ~4.2M tokens. Gemma 4 has a similar hybrid layout and benefits equally. * fix: update test files for store.Config and ServerConfig signatures * rebrand: research preview -> public alpha (#220) Rename all instances of 'Research Preview' and 'research project' to 'Public Alpha' across UI, landing page, legal terms, and README. - console-ui: sidebar label, footer disclaimer, login page, provider setup, LLM system prompt - landing: banner tag (now 'Low-cost private inference on idle Macs'), marketing copy (3 sections), terms.html (6 clauses) - docs: terms-of-service.md (6 matching clauses) - README: top-level callout No legal meaning changed -- the existing ToS already listed 'alpha' as a valid label. CSS class names (.research-tag) left unchanged. * feat: add Vercel Web Analytics to console-ui and landing page (#221) * feat: add Vercel Web Analytics to console-ui and landing page Install @vercel/analytics alongside existing Google Analytics on both surfaces. Vercel Analytics is cookieless and collects only anonymized page-view data, so no consent banner is required. console-ui (Next.js): - Added @vercel/analytics dependency - Added <Analytics /> component to root layout (imported from @vercel/analytics/next for automatic route tracking) landing (plain HTML): - Added va queue shim + deferred script tag pointing at /_vercel/insights/script.js Google Analytics remains untouched -- both systems run in parallel. Vercel Analytics tracks by default; GA continues to be consent-gated. Note: Web Analytics must also be enabled in the Vercel project dashboard for data to start flowing. * feat: mirror custom events to Vercel Analytics Add Vercel track() call inside the existing trackEvent() function so all 45 custom event call sites automatically send to both GA and Vercel Analytics with zero call-site changes. Vercel track() fires unconditionally (cookieless, always-on). GA continues to be consent-gated. Vercel track() limits: string values only and max 5 key-value pairs per event, so we convert and cap. * feat: add landing page funnel tracking with Vercel Analytics Add scroll-based section visibility and CTA click tracking to landing/index.html using Vercel Analytics va() events. Section funnel (IntersectionObserver, fires once per section at 30% visibility threshold): hero -> what-you-get -> why-it-costs-less -> privacy-problem -> privacy-architecture -> developer-experience -> pricing -> earn -> footer CTA click tracking: - Hero buttons (Start building, Estimate earnings, Read the Paper) - Card buttons (Open Console, Start Earning) - Paper download links (eigen-block CTAs) - Nav anchor clicks (Why, Privacy, API, Pricing, Earn) - Footer link clicks - Install tab toggle (CLI vs Mac App) All events use the va() queue shim already present in <head>. The existing scroll-reveal animation is preserved and runs alongside. * improve stats model catalog display (#222) * Improve stats model catalog display * Enable analytics by default co-authored with codex * feat: streamline provider onboarding to one post-install command (#223) * Improve stats model catalog display * feat: streamline provider onboarding to one post-install command Reduce the provider onboarding flow from 5+ manual steps to a single command after the curl installer. install.sh: - Remove [5/5] model catalog step (redundant with start's picker) - Make MDM enrollment non-blocking (no more read -p wait) - Replace 5-line 'next steps' with: source ~/.zshrc && darkbloom start - Renumber steps from [1/5]...[5/5] to [1/4]...[4/4] LoginCommand.swift: - Fix stale 'darkbloom serve' -> 'darkbloom start' in success message StartCommand.swift: - Add preflight doctor checks (SIP, debugger, min RAM) before model picker so problems surface before downloading GBs of weights - Add inline login prompt ('Link account? [Y/n]') before model picker so users don't need a separate darkbloom login step - Both are skipped in non-interactive/foreground/--model modes * fix: default 'darkbloom models' to catalog instead of local list A new user running 'darkbloom models' with nothing downloaded saw 'No local MLX models found.' -- unhelpful. Now it shows the full coordinator catalog with download status markers (✓ for downloaded), so they can immediately see what's available. 'darkbloom models list' still works for the local-only view. * feat: show supported vs local-only models in 'darkbloom models' Split the catalog view into two sections: Supported models ✓ Qwen 3.5 [qwen3.5-4b] ~2.5 GB Llama 4 [llama-4-8b] ~4.8 GB Local only (not in current catalog) old-model-v1 3.2 GB These models are no longer served by the network. Remove with: darkbloom models remove <id> Users immediately see what's active vs what's just taking up disk space from old downloads. Nudges cleanup without being aggressive. * feat(console-ui): public models catalog proxy and earn page resilience (#224) Models API route: - Unauthenticated requests now proxy to /v1/models/catalog + /v1/models/capacity instead of the auth-gated /v1/models, so the earn page and other public surfaces can display the full model catalog without an API key. - toModelEntry() normalizes catalog fields (size_gb, min_ram_gb, architecture, capacity stats) into the standard model shape the UI expects. Client (api.ts): - fetchModels() handles three response shapes: data.data (OpenAI list), data.models (catalog), or a raw array. Earn page: - Models without explicit pricing fall back to a default output price instead of being filtered out entirely. Tests: - Add catalog response unwrapping test for fetchModels. - Update earn page tests to mock fetchModels/fetchPricing from @/lib/api. * feat: multi-model swap — download multiple models, serve one at a time (#225) * feat: multi-model swap — download multiple models, serve one at a time Providers can now select and download multiple models even when their combined size exceeds available RAM. Only one model is warm (loaded in GPU memory) at a time; the coordinator manages demand-driven model swaps via the existing load_model protocol. Provider (Swift): - TUI picker: removed simultaneous memory budget constraint; each model only needs to individually fit. Shows 'one model active at a time (swap on demand)' when total exceeds RAM. - Fixed pre-existing download resume bug: range-resumption (HTTP 206) now appends to the partial file instead of replacing it. Coordinator (Go): - Cold-start routing: freeMemoryAdmits now admits idle providers that have the model on disk but not loaded, accounting for LRU eviction. - Raised cold-start penalty from 2.5s to 30s (realistic for model swap times of 15–60s) so warm providers are strongly preferred. - Proactive model swap: TriggerModelSwaps sends load_model to idle cold providers when queued requests have no warm provider. Includes deduplication (2-min cooldown per provider+model pair), one-provider- per-pass selection, and full routing safety gates (trust, runtime, privacy, challenge freshness, catalog). - SendLoadModel, ClearPendingModelLoad, QueuedModels helpers. * chore: gofmt billing_handlers.go and pricing_test.go * fix: address review — routing gates on warm check, stale WarmModels, idle-only swaps, Content-Range validation - hasWarmProviderLocked now applies full routing gates (trust, runtime, privacy, challenge freshness) so stale-attested providers don't suppress model swaps - Heartbeat always overwrites WarmModels (including empty) to clear stale entries after model unload - bestModelLoadProviderLocked only selects idle providers (pendingCount == 0) to avoid failed load_model on busy single-slot providers - Download resume validates Content-Range start offset before appending; falls back to full re-download on mismatch * fix: address second review round — idle slot penalty, Content-Range strictness, load oscillation, catalog gate - slotStatePenalty: handle 'idle' state as running (0ms) — provider reports 'idle' for warm-but-no-active-requests models - Content-Range: discard partial on missing/unparseable header instead of appending optimistically; test mock now sends Content-Range - bestModelLoadProviderLocked: skip providers with ANY pending load_model (providerHasPendingLoad) to prevent swap oscillation - providerHasWarmModelLocked: add catalog gate so retired/hash-changed models don't suppress swap planning * fix: per-provider reservation race + drain queue on load success - reservePendingModelLoads: check providerHasPendingLoad (not just per-key) to prevent concurrent heartbeat goroutines from reserving the same idle provider for different models - load_model_status handler: drain queued requests immediately on success instead of waiting for next heartbeat (up to 5s) * fix: adversarial review — BackendCapacity authority, load failure backoff, disconnect cleanup, TUI preselect - providerHasWarmModelLocked: BackendCapacity is authoritative when present; only 'running'/'idle' slots count as warm. Prevents crashed slots from suppressing needed model swaps via stale WarmModels. - load_model_status: only clear pendingModelLoads on success. Failures retain the 2-min cooldown to prevent retry storms against providers that consistently fail (deleted files, OOM). - Disconnect: clear pendingModelLoads entries for the disconnected provider to prevent stale entries from blocking future swaps. - TUI preselect: check canFitIndividually before preselecting a downloaded model. * feat: reject queued requests immediately when model is unservable When load_model fails and no other provider can serve the model, queued requests are now rejected immediately with a fast error instead of waiting 120 seconds for the queue timeout. - FailQueuedRequestsForModel: sends nil to all ResponseChs, causing waiters to receive ErrQueueTimeout - RejectUnservableQueuedRequests: checks QuickCapacityCheck after a load failure; if no eligible provider exists, flushes the queue - Wired into load_model_status handler alongside the existing success/drain path * fix: clear stale CurrentModel on nil heartbeat, mark provider warm before queue drain - Heartbeat: clear CurrentModel when active_model is nil/omitted, preventing attestation challenges from comparing against unloaded models - load_model_status:succeeded: call MarkModelWarm before draining so the scheduler sees the provider as warm immediately, not after the next heartbeat (up to 5s delay) * fix: RejectUnservableQueuedRequests must check capacityRejections Only reject queued requests when NO provider serves the model at all. If providers exist but are temporarily at capacity, requests should wait — those providers may finish current work and become available. * fix: MarkModelWarm injects synthetic BackendCapacity slot The scheduler uses BackendCapacity.Slots (not WarmModels) for Swift providers. When load_model_status:succeeded arrives before the next heartbeat, the model had no slot so the scheduler still saw it as cold/unknown. Now injects an 'idle' slot so DrainQueuedRequestsForModel immediately routes to the just-warmed provider. * fix: MarkModelWarm clears stale evicted slots from BackendCapacity When a swap evicts model A and loads model B, stale 'running'/'idle' slots for A remained in BackendCapacity until the next heartbeat, causing the scheduler to treat A as still warm. Now drops all warm slots except the newly loaded model. * fix: MarkModelWarm preserves existing warm slots Provider may have multiple model slots loaded simultaneously (maxModelSlots=3). Only add/update the new model's slot; leave existing slots untouched. Next heartbeat provides authoritative state. * docs: add coordinator state model and mutation checklist to AGENTS.md Documents the overlapping state views (BackendCapacity vs WarmModels vs CurrentModel vs pendingModelLoads), their precedence rules, and a 5-point checklist for mutating provider state. Learned from 10 fix iterations on the multi-model swap feature. * docs: fix WarmModels reader list — include legacy ScoreProvider and /v1/me/providers * ci: require approval before running e2e benchmarks (#227) * chore: remove dead coordinator code (#211) Remove unused functions, methods, constants, and a duplicate directory: - coordinator/internal/e2e/e2e/: accidental byte-identical copy of parent directory, never imported by any code - api/provider.go: SendInferenceRequest() -- consumer path writes directly to provider.Conn, this was a leftover from a refactor - registry/queue.go: WaitForProvider() -- superseded by WaitForProviderContext(), the only method actually called - registry/queue.go: TryAssign() -- stale queue method from older design, never called from production code - registry/queue.go: CleanStale() -- stale queue method, never called (inline cleanStaleLocked is still used by Enqueue) - registry/registry.go: BackendInprocessMLX const -- dead enum value, the in-process MLX path was removed. String literal kept where needed for backward compat with old providers. - registry/registry.go: ForceTrustProvider() -- bypasses attestation with no legitimate production use. Tests updated to use testMakeTextRoutable(). - registry/registry.go: ProviderCountByChip() -- analytics method never wired to any endpoint - registry/registry.go: ModelProviderCounts() -- analytics method never wired to any endpoint Tests updated: removed 3 tests for deleted methods, migrated 2 tests from ForceTrustProvider to testMakeTextRoutable, replaced WaitForProvider calls with WaitForProviderContext. All tests pass. go vet clean. * [codex] Add stats leaderboard tab (#226) * Add stats leaderboard tab * Add earn now CTA to stats leaderboard * fix(coordinator): resolve DB connection starvation, deprecate Python providers (#228) Production outage root cause: Postgres connection pool (20 max) exhausted by concurrent stats scans, heartbeat upserts, and billing settlement. When SyncRuntimeManifest happened to overlap with pool exhaustion, ListReleases timed out, the manifest was nuked, and revalidateConnectedProvidersAgainstRuntimePolicy set RuntimeVerified=false for ALL providers — instantly derouting the fleet. Critical fixes: - Increase pool MaxConns from 20 to 80, MinConns from 5 to 10 - SyncRuntimeManifest: return early on ListReleases nil (DB timeout) instead of nuking a working manifest - revalidateConnectedProvidersAgainstRuntimePolicy: only deroute on intentional manifest withdrawal, not transient DB failures - Add 5s timeout to telemetry batch INSERT (was unbounded) Python/legacy provider deprecation: - privateTextBackendSupported only accepts mlx-swift - verifyRuntimeHashesForBackend immediately rejects non-Swift backends - providerSupportsPrivateTextLocked: remove dead Python caps branch - Remove dead code: r2SitePackagesCDNURL, verifyRuntimeHashes(), EIGENINFERENCE_KNOWN_PYTHON_HASHES, EIGENINFERENCE_KNOWN_RUNTIME_HASHES - All test fixtures updated from inprocess-mlx to mlx-swift DB performance optimizations: - CreditProviderAccount: 6 sequential round-trips → single CTE - Usage recording made async (saferun.Go) - Provider credit + platform fee run concurrently (WaitGroup) - Auth middleware: 3 DB queries → 1 (ValidateKeyFull) + LRU cache (60s TTL) - PersistProviderThrottled: heartbeat writes rate-limited to 1x/30s per provider - Add indexes: idx_usage_created, idx_usage_consumer, idx_usage_provider - Add earnings_summary materialized table: eliminates full-table SUM scans on /v1/provider/account-earnings (PK lookup instead) - Backfill migration populates earnings_summary from existing data - Add detailed mismatch logging (component+hash, not just count) All migrations are idempotent (CREATE IF NOT EXISTS / ON CONFLICT DO NOTHING). No manual SQL required — indexes and tables auto-create on restart. All tests pass. go vet clean. * fix(coordinator): unblock WebSocket read loop from billing settlement Root cause of challenge timeouts: handleComplete runs billing DB calls (GetModelPrice, Credit, Charge) synchronously on the WebSocket read loop. Under DB pressure (cross-cloud RDS latency), these block for 5+ seconds, preventing the read loop from receiving attestation challenge responses. The 30s challenge timeout expires, RecordChallengeFailure clears LastChallengeVerified, and the provider becomes unroutable. Fixes: - Move handleComplete to a saferun.Go goroutine so billing settlement never blocks the read loop - RecordChallengeFailure: only clear LastChallengeVerified on security failures (SIP disabled, signature mismatch, etc.), NOT on transient timeouts. Transient timeouts only deroute at MaxFailedChallenges (3). - Move MaxFailedChallenges constant to registry package (was hardcoded) All tests pass. go vet clean. * refactor(coordinator): replace MaxMind with ip-api.com for provider geolocation Remove the geoip2-golang dependency and MaxMind .mmdb file requirement. Provider geolocation now uses ip-api.com (free, no API key, 45 req/min). Called once per provider WebSocket connection so rate limit is never hit. The resolver always initializes now — no env vars needed for basic geo. EIGENINFERENCE_TRUST_GEO_HEADERS=1 still works as a fast-path when behind Cloudflare/Vercel. EIGENINFERENCE_GEOIP_DB is removed. * style: gofmt provider.go, postgres.go * perf(coordinator): stop writing telemetry to Postgres — Datadog is sole sink Removes the synchronous InsertTelemetryEvents call from the telemetry handler. With 60 providers sending batches every 10s, this was 6 INSERTs per second, each writing up to 50 rows into a table with 5 indexes. That alone consumed ~30-40% of the DB connection pool. Datadog already receives all telemetry asynchronously via the Logs API. The Postgres copy was documented as best-effort secondary storage and adds no value that Datadog doesn't already provide. The telemetry_events table and its schema are left intact (no migration needed). New events simply stop being written. * fix(provider-swift): migrate SE key to AfterFirstUnlock for background signing The SE key was created with kSecAttrAccessibleWhenUnlockedThisDeviceOnly, which blocks signing when the screen is locked. This caused all attestation challenges to fail with OSStatus -25308 (errSecInteractionNotAllowed) on provider machines with locked screens, making them unroutable. Changes: - New keys use kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly — accessible after first unlock even when screen subsequently locks - loadOrCreate performs a test sign on existing keys; if it gets -25308, deletes the old key and recreates with the new policy - Migration is automatic on provider restart — no manual intervention Providers need to update to this version and restart. The old key is deleted and a new one is created, which means the provider will re-attest with a new public key on next coordinator connection. * chore: bump provider version to 0.5.11 * fix: add missing r2SitePackagesCDNURL field and setter from PR branch * fix: DB perf optimizations, error classification, and provider diagnostics (#232) * fix: DB perf optimizations, error classification, and provider diagnostics Coordinator DB performance: - Add usage_totals counter table (O(1) vs full-table scan) - Add partial index on usage.request_location IS NOT NULL - Replace UsageRecordsSince + ListProviderRecords with SQL JOIN - Add 60s cache to /v1/models/catalog endpoint - Fix N+1 query in ListActiveModelRegistryWithError (batch file load) - Add 20s cache to /v1/provider/account-earnings - Merge GetBalance + GetWithdrawableBalance into single query Billing error classification: - Add ErrInsufficientBalance sentinel to store package - Debit() distinguishes pgx.ErrNoRows from DB timeouts - Consumer handler returns 503 (not 402) for DB errors - Provider handler logs warn vs error for balance vs DB failures Provider diagnostics: - darkbloom logs now streams macOS unified logging by default - darkbloom logs --last 1h shows historical unified logs - darkbloom logs --file falls back to provider.log - New darkbloom report command uploads 24h unified logs - New POST /v1/provider/log-report endpoint (API key auth) - New GET /v1/admin/log-reports admin endpoints - New provider_log_reports DB table Closes #230 * fix: address Codex review findings - Accept provider tokens (eigeninference-pt-...) in requireAuth so darkbloom report works with device-login tokens - Include limit param in earnings cache key to prevent stale responses - Invalidate catalog cache in SyncModelCatalog after admin changes - Fix log show to use --info flag instead of --level info (macOS log(1)) * fix: restore in-memory telemetry buffer, no-op Postgres telemetry writes The telemetry Postgres removal (e0a63cc) removed both the Postgres INSERT and the in-memory buffer write. The in-memory buffer is free (no DB, bounded at 10K entries) and is needed by the admin metrics endpoint and test assertions. - Restore InsertTelemetryEvents call in the handler (writes to in-memory MemoryStore buffer only) - Make PostgresStore.InsertTelemetryEvents a no-op (was still doing the expensive batch INSERT that the removal intended to eliminate) - All 9 telemetry tests now pass (were failing on master) * fix: remove telemetry Postgres writes, fix tests to assert on Datadog path Telemetry is forwarded to Datadog only — no store writes. The previous fix incorrectly re-added InsertTelemetryEvents to the HTTP handler. - Remove InsertTelemetryEvents call from ingestion handler - Make PostgresStore.InsertTelemetryEvents a no-op (was still doing the expensive batch INSERT the removal intended to eliminate) - Update 3 tests to assert on HTTP response counts and metrics counters instead of TelemetryEventsSnapshot (which is empty since the handler no longer writes to the store) - Recover middleware test unchanged (uses Emitter path, not HTTP handler) All 12 packages pass with zero failures. * style: gofmt server.go, stats.go, memory.go * feat: trust_status message, auto-report, and MDM re-verification (#233) Coordinator → Provider trust status notification: - Add TypeTrustStatus protocol message (Go + Swift) - Send trust_status after SE attestation (self_signed), MDM upgrade (hardware), ACME upgrade (hardware), and MarkUntrusted - Provider receives trust level and status over WebSocket Provider auto-report on degraded trust: - When provider learns it is self_signed or untrusted, schedules a one-time auto-report of 24h unified logs after 10 minutes - Report is uploaded to POST /v1/provider/log-report - Cancelled if trust is upgraded before the 10-min window - Once-per-session flag prevents spamming MDM re-verification for self_signed providers: - Challenge loop now re-attempts MDM verification after a successful challenge if the provider is still at self_signed trust - Providers that install MDM enrollment after registration will get upgraded to hardware trust on the next challenge cycle (5 minutes) instead of being stuck at self_signed forever * chore: bump provider version to 0.5.12 * fix: MDM channel saturation, timeout-marks-untrusted, and model load memory gate MDM channel architecture (coordinator/mdm/mdm.go): - Replace shared buffered channels (size 16) with per-UDID waiter maps - Eliminates channel saturation: late/unsolicited webhooks no longer fill the buffer and block all future MDM verifications - Eliminates CPU busy-spin: no more read-put-back loops when waiting for a specific UDID while other UDIDs are in the buffer - Same fix applied to attestation (MDA) response path MDM timeout handling (coordinator/api/provider.go): - SecurityInfo timeout no longer marks provider untrusted - Timeout is APN latency, not evidence of compromise - Provider stays at self_signed trust, MDM re-check retries on next challenge cycle (every 5 minutes) Model load memory gate (coordinator/registry/registry.go): - TriggerModelSwaps now checks provider memory before sending load_model - Uses catalog SizeGB * 2.5 as the coordinator-side memory threshold - Prevents sending load_model to machines that will always reject (e.g., 32GB Mac for gpt-oss-20b needing 40.5GB) - Stops the infinite retry loop of failed load_model commands * fix: APN reliability for MDM — network assertions, 90s timeout, late-arrival path Provider (Swift): - Add NetworkPowerAssertion: IOKit assertions for NetworkClientActive and BackgroundTask, acquired for the entire provider session - Keeps the macOS network stack alive during sleep so APN pushes (courier.push.apple.com:5223) can be delivered for MDM commands - No root required — uses IOPMAssertionCreateWithName API Coordinator: - Increase SecurityInfo timeout from 30s to 90s to cover Power Nap cycles (every ~15 minutes on AC power) - Add OnLateSecurityInfoCallback: when a SecurityInfo webhook arrives after the 90s timeout, retroactively upgrade the self_signed provider to hardware trust instead of silently dropping the response - Wire up the callback in main.go alongside the existing SetOnMDA callback, using the same ForEachProvider + serial match pattern * chore: bump provider version to 0.5.13 * chore: remove telemetry_events Postgres table and writes (#234) * chore: remove telemetry_events Postgres table and writes The telemetry_events table + 5 indexes was the single largest source of DB write pressure (60 providers × batch/10s × 50 rows × 5 indexes consumed ~30-40% of the connection pool). The /v1/telemetry/events ingestion handler already skips Postgres entirely — Datadog is the sole durable sink. No read endpoints consumed this table. - Remove CREATE TABLE telemetry_events + 5 CREATE INDEX from migration - Delete telemetry_postgres.go, telemetry_memory.go, telemetry_test.go - Remove InsertTelemetryEvents from Store interface - Remove store field/param from telemetry.Emitter - Remove telemetryEvents ring buffer from MemoryStore - Update all callers (main.go, server.go, tests) * ci: trigger re-run --------- Co-authored-by: ethenotethan <42627790+ethenotethan@users.noreply.github.com> Co-authored-by: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Production Outage Fix
Root Cause
Two-layer failure causing all providers to be excluded from routing:
Postgres connection pool exhaustion (20 max connections): stats endpoint full-table scans (10s each), heartbeat upserts (80/min), billing settlement (5-7 sequential DB ops per inference), and unbounded telemetry INSERTs competed for 20 pool slots. Under load, all connections were locked and every operation timed out with
context deadline exceeded.Manifest nuke on DB timeout: When
SyncRuntimeManifest()was triggered during pool exhaustion,ListReleases()timed out and returned nil. The code treated nil as "no releases" → set manifest to nil →revalidateConnectedProvidersAgainstRuntimePolicy()setRuntimeVerified=falsefor ALL providers → entire fleet derouted instantly.Critical Fixes
SyncRuntimeManifestnil guardPython/Legacy Provider Deprecation
privateTextBackendSupportedonly acceptsmlx-swiftverifyRuntimeHashesForBackendimmediately rejects non-Swift backendsproviderSupportsPrivateTextLockedsimplified (dead Python branch removed)r2SitePackagesCDNURL,verifyRuntimeHashes(),EIGENINFERENCE_KNOWN_PYTHON_HASHES,EIGENINFERENCE_KNOWN_RUNTIME_HASHESinprocess-mlx→mlx-swiftDB Performance Optimizations
CreditProviderAccountsaferun.Go)WaitGroup)SUM(*)full scan per requestMigrations
All idempotent — auto-run on coordinator restart:
CREATE TABLE IF NOT EXISTS earnings_summary+ backfill viaINSERT ... ON CONFLICT DO NOTHINGCREATE INDEX IF NOT EXISTSfor usage table (3 indexes)Testing
go vetcleanNeed help on this PR? Tag
@codesmithwith what you need. Autofix is disabled.