Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ coordinator/ Go control plane (packages live at top level, not internal
│ ├── 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
│ ├── network/ public stats, geography, totals, series and leaderboard refresh state
│ ├── types/ canonical JSON shapes for consumer-facing endpoints
│ └── server.go route wiring, auth middleware, version gate
├── apns/ APNs-push code-identity attestation
Expand Down
90 changes: 0 additions & 90 deletions coordinator/api/cache_concurrency_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
package api

import (
"context"
"errors"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
Expand Down Expand Up @@ -84,89 +80,3 @@ func TestSummaryConcurrentExpiredMissesCoalescePerAccount(t *testing.T) {
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)
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package api
package network

import (
"context"
Expand Down
43 changes: 43 additions & 0 deletions coordinator/api/network/controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Package network owns public network statistics, geography, earnings totals,
// traffic series and pseudonymous leaderboards, including their refresh state.
package network

import (
"log/slog"
"sync"

"github.com/eigeninference/d-inference/coordinator/api/readcache"
)

// Dependencies binds read models to the router's current store, registry view,
// and shared response cache. The getters preserve bindings installed after
// route registration; Incr retains the existing metric delivery policy.
type Dependencies struct {
Store func() Store
Fleet func() Fleet
Cache func() *readcache.Cache
Logger *slog.Logger
Incr func(string, []string)
}

// Controller owns coalesced refreshes and serializes every earnings window
// through one query mutex. It does not own live providers or durable records.
type Controller struct {
store func() Store
registry func() Fleet
readCache func() *readcache.Cache
logger *slog.Logger
incr func(string, []string)
statsRefresh readcache.Refresher
statsGeographyRefresh readcache.Refresher
networkTotalsRefresh struct {
mu sync.Mutex
queryMu sync.Mutex
entries map[string]*readcache.Refresher
}
}

// New creates one owner to share between public handlers and refresh loops.
func New(d Dependencies) *Controller {
return &Controller{store: d.Store, registry: d.Fleet, readCache: d.Cache, logger: d.Logger, incr: d.Incr}
}
27 changes: 27 additions & 0 deletions coordinator/api/network/controller_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package network

import (
"log/slog"
"net/http"

"github.com/eigeninference/d-inference/coordinator/api/readcache"
"github.com/eigeninference/d-inference/coordinator/registry"
"github.com/eigeninference/d-inference/coordinator/store"
)

// Domain fixtures use the real fleet, store and shared cache implementation.
func newTestController(reg *registry.Registry, st store.Store, logger *slog.Logger) *Controller {
cache := readcache.New()
return New(Dependencies{Store: func() Store { return st }, Fleet: func() Fleet { return reg }, Cache: func() *readcache.Cache { return cache }, Logger: logger, Incr: func(string, []string) {}})
}

// Handler mounts the actual owner handlers for HTTP concurrency fixtures.
// Server route registration is exercised separately in package api.
func (s *Controller) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/stats", s.Stats)
mux.HandleFunc("GET /v1/network/totals", s.Totals)
mux.HandleFunc("GET /v1/network/series", s.Series)
mux.HandleFunc("GET /v1/leaderboard", s.Leaderboard)
return mux
}
16 changes: 16 additions & 0 deletions coordinator/api/network/fleet.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package network

import "github.com/eigeninference/d-inference/coordinator/registry"

// Fleet is the existing registry's read-only view. ForEachProvider retains the
// registry's synchronization and does not expose new locks or mutable state.
type Fleet interface {
PublicProviderModels() map[string]registry.PublicProviderModelSnapshot
ForEachProvider(func(*registry.Provider))
CodeAttestationCoverage() (int, int)
CodeAttestationEnforced() bool
CountProvidersWithCurrentApplicationEvidence() (int, int)
ApplicationEvidenceModelCoverage() map[string]registry.ModelEvidenceCoverage
ReleasePolicyEnforced() bool
NetworkUtilizationSnapshot() registry.NetworkUtilization
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package api
package network

import (
"encoding/json"
Expand Down Expand Up @@ -37,8 +37,8 @@ func unavailableStatsGeography() statsGeography {

// cachedStatsGeography is read-only and never starts or waits for SQL work.
// If the refresher has not completed yet, or its entry expired, report unknown.
func (s *Server) cachedStatsGeography() statsGeography {
if body, ok := s.readCache.Get(statsGeographyCacheKey); ok {
func (s *Controller) cachedStatsGeography() statsGeography {
if body, ok := s.readCache().Get(statsGeographyCacheKey); ok {
var geography statsGeography
if json.Unmarshal(body, &geography) == nil {
return geography
Expand All @@ -47,11 +47,11 @@ func (s *Server) cachedStatsGeography() statsGeography {
return unavailableStatsGeography()
}

func (s *Server) refreshStatsGeography() ([]byte, bool) {
func (s *Controller) refreshStatsGeography() ([]byte, bool) {
return s.refreshCachedEntry(&s.statsGeographyRefresh, statsGeographyCacheKey, s.computeStatsGeography)
}

func (s *Server) computeStatsGeography() ([]byte, error) {
func (s *Controller) computeStatsGeography() ([]byte, error) {
observedAt := time.Now()
since := observedAt.Add(-24 * time.Hour)
geography := unavailableStatsGeography()
Expand Down Expand Up @@ -81,9 +81,9 @@ func (s *Server) computeStatsGeography() ([]byte, error) {
return json.Marshal(geography)
}

func (s *Server) recordStatsGeographyFailure(section string, err error) {
func (s *Controller) recordStatsGeographyFailure(section string, err error) {
s.logger.Warn("stats geography unavailable", "section", section, "error", err)
s.ddIncr("cache.refresh_failed", []string{"key:" + statsGeographyCacheKey, "section:" + section})
s.incr("cache.refresh_failed", []string{"key:" + statsGeographyCacheKey, "section:" + section})
}

func (g statsGeography) addTo(response map[string]any) {
Expand Down
86 changes: 86 additions & 0 deletions coordinator/api/network/geography_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package network

import (
"strings"
)

// Privacy floor constants: aggregated location buckets with fewer entries
// than these thresholds are suppressed from public stats to prevent
// de-anonymization of individual providers or consumers.
const (
minProvidersPerCityBucket = 2
minRequestsPerCityBucket = 5
minRequestsPerFlowBucket = 5
)

// publicProviderLocationBucket is the privacy-safe shape returned to
// callers in the provider_locations array.
type publicProviderLocationBucket struct {
Key string `json:"key"`
Scope string `json:"scope"`
City string `json:"city,omitempty"`
Region string `json:"region,omitempty"`
RegionCode string `json:"region_code,omitempty"`
Country string `json:"country,omitempty"`
CountryCode string `json:"country_code,omitempty"`
Latitude float64 `json:"latitude,omitempty"`
Longitude float64 `json:"longitude,omitempty"`
Providers int `json:"providers"`
HardwareAttested int `json:"hardware_attested"`
GPUCores int `json:"gpu_cores"`
MemoryGB int `json:"memory_gb"`
Models []string `json:"models,omitempty"`
}

// publicRequestLocationBucket is the privacy-safe shape returned for
// request-origin location aggregation.
type publicRequestLocationBucket struct {
Key string `json:"key"`
Scope string `json:"scope"`
City string `json:"city,omitempty"`
Region string `json:"region,omitempty"`
RegionCode string `json:"region_code,omitempty"`
Country string `json:"country,omitempty"`
CountryCode string `json:"country_code,omitempty"`
Latitude float64 `json:"latitude,omitempty"`
Longitude float64 `json:"longitude,omitempty"`
Requests int64 `json:"requests"`
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
Providers int `json:"providers"`
}

// publicRequestFlowBucket represents a directional flow of requests
// between a consumer region and a provider region.
type publicRequestFlowBucket struct {
Key string `json:"key"`
From flowEndpoint `json:"from"`
To flowEndpoint `json:"to"`
Requests int64 `json:"requests"`
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
}

type flowEndpoint struct {
Key string `json:"key"`
Kind string `json:"kind"` // "consumer" or "provider"
City string `json:"city,omitempty"`
Region string `json:"region,omitempty"`
RegionCode string `json:"region_code,omitempty"`
Country string `json:"country,omitempty"`
CountryCode string `json:"country_code,omitempty"`
Latitude float64 `json:"latitude,omitempty"`
Longitude float64 `json:"longitude,omitempty"`
}

// locationKey builds a stable, lowercase key from country/region/city parts.
func locationKey(parts ...string) string {
clean := make([]string, 0, len(parts))
for _, part := range parts {
part = strings.ToLower(strings.TrimSpace(part))
if part != "" {
clean = append(clean, part)
}
}
return strings.Join(clean, "|")
}
Loading
Loading