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
102 changes: 4 additions & 98 deletions coordinator/api/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,110 +2,16 @@ package api

import (
"net/http"
"sync"
"time"

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

// ttlCache stores pre-serialized JSON bytes — or, for shared intermediate
// results such as the public model entry list, a typed value — keyed by
// request signature. Skipping both the DB query and json.Marshal on hit makes
// hot endpoints (stats, leaderboard, model catalog) sub-millisecond.
//
// Single-node in-memory only — sized for tens of keys, not millions. Hits
// are just a map lookup under RLock; misses recompute and Set without
// locking the read path.
type ttlCache struct {
mu sync.RWMutex
data map[string]ttlEntry
// generation orders guarded fills against invalidation.
generation uint64
}

type ttlEntry struct {
value []byte
obj any
expiresAt time.Time
}

func newTTLCache() *ttlCache {
return &ttlCache{data: make(map[string]ttlEntry)}
}

func (c *ttlCache) lookup(key string) (ttlEntry, bool) {
c.mu.RLock()
e, ok := c.data[key]
c.mu.RUnlock()
if !ok || time.Now().After(e.expiresAt) {
return ttlEntry{}, false
}
return e, true
}

// Get returns the cached bytes if present and not expired.
func (c *ttlCache) Get(key string) ([]byte, bool) {
e, ok := c.lookup(key)
if !ok || e.value == nil {
return nil, false
}
return e.value, true
}

// GetValue returns the cached typed value if present and not expired. The
// value is shared between all callers and must be treated as immutable.
func (c *ttlCache) GetValue(key string) (any, bool) {
e, ok := c.lookup(key)
if !ok || e.obj == nil {
return nil, false
}
return e.obj, true
}

// Set stores bytes with an absolute expiry time.
func (c *ttlCache) Set(key string, value []byte, ttl time.Duration) {
c.mu.Lock()
c.data[key] = ttlEntry{value: value, expiresAt: time.Now().Add(ttl)}
c.mu.Unlock()
}

// SetValue stores a typed value with an absolute expiry time.
func (c *ttlCache) SetValue(key string, v any, ttl time.Duration) {
c.mu.Lock()
c.data[key] = ttlEntry{obj: v, expiresAt: time.Now().Add(ttl)}
c.mu.Unlock()
}
// Response cache storage and synchronization live in readcache.
type ttlCache = readcache.Cache

// Invalidate removes a single key. Useful when an action changes the
// underlying data (e.g. registering a new release invalidates cached
// /api/version and /v1/runtime/manifest).
func (c *ttlCache) Invalidate(key string) {
c.mu.Lock()
delete(c.data, key)
c.generation++
c.mu.Unlock()
}

// Purge expired entries. Called by a background goroutine — bounded
// growth even when keys are added but never re-read.
func (c *ttlCache) PurgeExpired() {
now := time.Now()
c.mu.Lock()
for k, e := range c.data {
if now.After(e.expiresAt) {
delete(c.data, k)
}
}
c.mu.Unlock()
}

// Len returns the number of entries currently held (including not-yet-purged
// expired ones). Used by the janitor's tests to observe reclamation.
func (c *ttlCache) Len() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.data)
}
func newTTLCache() *ttlCache { return readcache.New() }

// writeCachedJSON serves the exact pre-encoded response body.
func writeCachedJSON(w http.ResponseWriter, body []byte) {
Expand Down
30 changes: 9 additions & 21 deletions coordinator/api/cache_generation.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,21 @@ package api

import "time"

// readCacheGeneration snapshots the invalidation generation before a catalog
// computation reads its inputs. A concurrent admin sync may invalidate the
// result while it is being built; that request can finish with its snapshot,
// but must not repopulate the cache for requests after the sync completes.
func (s *Server) readCacheGeneration() uint64 {
if s.readCache == nil {
return 0
}
c := s.readCache
c.mu.RLock()
defer c.mu.RUnlock()
return c.generation
return s.readCache.Generation()
}

// readCacheSetEntryIfCurrent publishes a catalog fill only if no invalidation
// has raced it. The comparison and write use the same lock as Invalidate, so
// a successful check cannot race with the eviction it is meant to preserve.
func (s *Server) readCacheSetEntryIfCurrent(key string, entry ttlEntry, ttl time.Duration, generation uint64) {
if s.readCache == nil {
return
func (s *Server) readCacheSetIfCurrent(key string, body []byte, ttl time.Duration, generation uint64) {
if s.readCache != nil {
s.readCache.SetIfCurrent(key, body, ttl, generation)
}
c := s.readCache
c.mu.Lock()
defer c.mu.Unlock()
if c.generation != generation {
return
}

func (s *Server) readCacheSetValueIfCurrent(key string, value any, ttl time.Duration, generation uint64) {
if s.readCache != nil {
s.readCache.SetValueIfCurrent(key, value, ttl, generation)
}
entry.expiresAt = time.Now().Add(ttl)
c.data[key] = entry
}
46 changes: 12 additions & 34 deletions coordinator/api/cache_refresher.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package api

import (
"context"
"sync"
"time"

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

Expand All @@ -16,12 +16,8 @@ const (
refreshedCacheTTL = 5 * time.Minute
)

// cacheRefresher coalesces computations of one read-cache entry. Only complete
// successful results are cached; query errors never become partial JSON data.
type cacheRefresher struct {
mu sync.Mutex
inflight chan struct{}
}
// Each response entry owns its coalescing state in the read-cache package.
type cacheRefresher = readcache.Refresher

// getCachedEntry fills a cold cache. It rechecks the cache under the flight
// lock so a request delayed after its initial miss cannot start a second
Expand All @@ -36,36 +32,18 @@ func (s *Server) refreshCachedEntry(entry *cacheRefresher, key string, compute f
}

func (s *Server) computeCachedEntry(entry *cacheRefresher, key string, refresh bool, compute func() ([]byte, error)) ([]byte, bool) {
entry.mu.Lock()
if !refresh {
if body, ok := s.readCache.Get(key); ok {
entry.mu.Unlock()
return body, true
computeWithDiagnostics := func() ([]byte, error) {
body, err := compute()
if err != nil {
s.logger.Warn("cache refresh failed; keeping previous value", "key", key, "error", err)
s.ddIncr("cache.refresh_failed", []string{"key:" + key})
}
return body, err
}
if wait := entry.inflight; wait != nil {
entry.mu.Unlock()
<-wait
return s.readCache.Get(key)
}
done := make(chan struct{})
entry.inflight = done
entry.mu.Unlock()
defer func() {
entry.mu.Lock()
entry.inflight = nil
close(done)
entry.mu.Unlock()
}()

body, err := compute()
if err != nil {
s.logger.Warn("cache refresh failed; keeping previous value", "key", key, "error", err)
s.ddIncr("cache.refresh_failed", []string{"key:" + key})
return s.readCache.Get(key)
if refresh {
return entry.Refresh(s.readCache, key, refreshedCacheTTL, computeWithDiagnostics)
}
s.readCache.Set(key, body, refreshedCacheTTL)
return body, true
return entry.Get(s.readCache, key, refreshedCacheTTL, computeWithDiagnostics)
}

// runCacheRefreshLoop computes once at start and then every interval until
Expand Down
26 changes: 0 additions & 26 deletions coordinator/api/cache_refresher_test.go
Original file line number Diff line number Diff line change
@@ -1,37 +1,11 @@
package api

import (
"bytes"
"context"
"testing"
"time"
)

// A caller can observe a miss, then be descheduled until another caller has
// finished the fill. The flight lock alone does not coalesce that sequence.
func TestCachedEntryRechecksAfterDelayedMiss(t *testing.T) {
srv, _, _ := newStatsRefresherFixture(t)
const key = "test:delayed-miss"
var entry cacheRefresher
if _, ok := srv.readCache.Get(key); ok {
t.Fatal("expected cold cache")
}
calls := 0
compute := func() ([]byte, error) { calls++; return []byte(`{"value":1}`), nil }
first, ok := srv.getCachedEntry(&entry, key, compute)
if !ok {
t.Fatal("first fill failed")
}
delayed, ok := srv.getCachedEntry(&entry, key, compute)
if !ok || !bytes.Equal(delayed, first) || calls != 1 {
t.Fatalf("delayed miss: ok=%v calls=%d", ok, calls)
}
// The periodic owner still refreshes an unexpired entry.
if _, ok := srv.refreshCachedEntry(&entry, key, compute); !ok || calls != 2 {
t.Fatalf("periodic refresh: ok=%v calls=%d", ok, calls)
}
}

func TestCacheRefreshLoopCancelledBeforeStart(t *testing.T) {
srv, _, _ := newStatsRefresherFixture(t)
ctx, cancel := context.WithCancel(context.Background())
Expand Down
19 changes: 0 additions & 19 deletions coordinator/api/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,6 @@ import (
"time"
)

// PurgeExpired removes expired entries and keeps live ones.
func TestTTLCachePurgeExpired(t *testing.T) {
c := newTTLCache()
c.Set("stale", []byte("v"), -time.Second) // already expired
c.Set("fresh", []byte("v"), time.Minute) // live

c.PurgeExpired()

if c.Len() != 1 {
t.Fatalf("PurgeExpired: got %d entries, want 1", c.Len())
}
if _, ok := c.Get("stale"); ok {
t.Error("expired entry should be gone after PurgeExpired")
}
if _, ok := c.Get("fresh"); !ok {
t.Error("live entry should survive PurgeExpired")
}
}

// The janitor actually reclaims expired entries (PurgeExpired was previously
// never scheduled, so high-cardinality keys lingered forever) and stops on ctx
// cancel.
Expand Down
6 changes: 3 additions & 3 deletions coordinator/api/models_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (s *Server) cachedModelEntries(includeBuilds bool) ([]types.ModelEntry, err
if err != nil {
return nil, err
}
s.readCacheSetEntryIfCurrent(key, ttlEntry{obj: entries}, modelListCacheTTL, generation)
s.readCacheSetValueIfCurrent(key, entries, modelListCacheTTL, generation)
return entries, nil
}

Expand All @@ -66,7 +66,7 @@ func (s *Server) cachedModelListBody(includeBuilds bool) ([]byte, error) {
if err != nil {
return nil, err
}
s.readCacheSetEntryIfCurrent(modelEntriesCacheKey(includeBuilds), ttlEntry{obj: entries}, modelListCacheTTL, generation)
s.readCacheSetEntryIfCurrent(key, ttlEntry{value: body}, modelListCacheTTL, generation)
s.readCacheSetValueIfCurrent(modelEntriesCacheKey(includeBuilds), entries, modelListCacheTTL, generation)
s.readCacheSetIfCurrent(key, body, modelListCacheTTL, generation)
return body, nil
}
11 changes: 9 additions & 2 deletions coordinator/api/models_cache_invalidate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func TestCatalogSyncRejectsInflightCachePublication(t *testing.T) {
t.Fatal(err)
}
for _, key := range []string{modelEntriesCacheKey(false), modelListBodyCacheKey(false), openRouterFeedCacheKey} {
if _, ok := h.srv.readCache.lookup(key); ok {
if readCacheContains(h.srv.readCache, key) {
t.Fatalf("pre-sync request repopulated %q after invalidation", key)
}
}
Expand All @@ -127,9 +127,16 @@ func TestCatalogSyncRejectsInflightCachePublication(t *testing.T) {
} else if view == "openrouter" {
key = openRouterFeedCacheKey
}
if _, ok := h.srv.readCache.lookup(key); !ok {
if !readCacheContains(h.srv.readCache, key) {
t.Fatalf("post-sync request did not cache %q", key)
}
})
}
}

// Both representations share the same generation fence.
func readCacheContains(c *ttlCache, key string) bool {
_, bytesPresent := c.Get(key)
_, valuePresent := c.GetValue(key)
return bytesPresent || valuePresent
}
2 changes: 1 addition & 1 deletion coordinator/api/openrouter_endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (s *Server) handleListModelsOpenRouter(w http.ResponseWriter, r *http.Reque
writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to encode models"))
return
}
s.readCacheSetEntryIfCurrent(openRouterFeedCacheKey, ttlEntry{value: body}, openRouterFeedCacheTTL, generation)
s.readCacheSetIfCurrent(openRouterFeedCacheKey, body, openRouterFeedCacheTTL, generation)
writeCachedJSON(w, body)
}

Expand Down
Loading
Loading