Skip to content

ci: require approval before running e2e benchmarks - #227

Merged
Gajesh2007 merged 1 commit into
masterfrom
ci/benchmark-require-approval
May 27, 2026
Merged

Gajesh2007 merged 1 commit into
masterfrom
ci/benchmark-require-approval

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented May 27, 2026 •

Copy link
Copy Markdown
Member

Adds environment: benchmarks to the benchmark job so it waits for manual approval instead of running on every PR.

The benchmarks environment has already been created with required reviewers.


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

@vercel

vercel Bot commented May 27, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview May 27, 2026 4:01am
d-inference-console-ui-dev Ready Ready Preview May 27, 2026 4:01am
d-inference-landing Ready Ready Preview May 27, 2026 4:01am

Request Review

@Gajesh2007
Gajesh2007 merged commit 65aa424 into master May 27, 2026
16 of 17 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

No threat-model-relevant changes detected: this PR modifies only the GitHub Actions integration workflow, which is explicitly out of scope for the current threat model.

The threat model's out_of_scope section explicitly excludes "GitHub Actions / R2 release supply chain," so no TB-xxx boundaries are touched and no T-xxx threats apply.

That said, one question worth a quick human glance before merge: if this workflow provisions or rotates any of the secrets that are in scope — specifically coordinator_release_api_key (A-005), the Solana wallet mnemonic (A-006), or any Privy/admin credentials — then the workflow itself becomes a trust boundary that the threat model currently has no coverage for. Please confirm:

  1. No new secrets are introduced into the workflow that map to in-scope assets.
  2. No new outbound calls are added that reach the production coordinator (e.g. POST /v1/releases), which would make CI a new actor in TB-006.
  3. pull_request_target is not used (or if it is, that secrets are not exposed to fork PRs — a common misconfiguration in integration workflows).

If any of the above apply, consider opening a threat model amendment to add a TB-010 covering the CI → coordinator release-registration path and mapping it to T-024.

No SEC-* findings are resolved by this PR.


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

hankbobtheresearchoor pushed a commit to hankbobtheresearchoor/d-inference that referenced this pull request May 28, 2026
ethenotethan added a commit that referenced this pull request May 28, 2026
* 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>

This branch had an error being deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant