Files
kandev/apps/backend/internal/agent/usage/cache.go
T
João Salavisa 55c8b461be feat: surface agent subscription usage in settings and chat tooltip (#1697)
* feat: surface agent subscription usage in settings and chat tooltip

Adds live subscription rate-limit visibility for Claude Code and Codex:

- GET /api/v1/agents/usage lists per-agent utilization windows (plan, percent,
  reset time) for host agents with subscription credentials; ?fresh=true
  bypasses the 5-minute cache with a 15s per-provider clamp.
- Fixes both existing usage clients: Claude parsed float utilization as int
  (decode failure) and now reads the richer limits[] array incl. per-model
  weekly windows; Codex read a nonexistent auth.json field and response
  headers - now reads tokens.access_token, parses the body windows, and
  refreshes OAuth tokens on 401. Token refresh persists without dropping
  unknown credential fields.
- Settings > Agents gains a Subscription Usage section; the chat context
  doughnut tooltip shows the session agent's windows, fetched fresh on hover.
- Shared UsageWindowRows component (bars, Good/High/Critical status,
  reset countdowns) keeps settings, tooltip, and office surfaces consistent.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: recompute agent billing type on every read

Subscription billing detection for Claude and Codex was cached with
sync.OnceValue for the process lifetime, so logging in with OAuth after
the backend started never flipped billing badges or office usage checks
until restart. Detection now re-reads the credential files on each call
and reuses the usage clients' HasSubscriptionCredentials checks. Also
adds a regression assertion that fractional-second resets_at timestamps
parse under the RFC3339 layout.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: address subscription usage review feedback

- serialize empty utilization windows as arrays, not null
- sanitize per-agent usage errors in the API (raw provider errors are
  logged server-side; they can carry credential paths/response bodies)
- persist refreshed CLI credentials via atomic temp-file rename
- keep previous settings usage on transient refresh failure; drop stale
  tooltip usage (and its memo) when a fresh fetch fails
- add controller tests for SubscriptionUsage mapping and fresh propagation

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: coalesce concurrent usage fetches and guard codex token refresh

- serialize usage-cache fetches per key with a double-checked lock so
  concurrent fresh requests make one provider call instead of a burst
- reject codex refresh responses with an empty access_token instead of
  persisting them and wiping working credentials
- pin the usage-rows reset fixture 30s under the day boundary so the
  formatted value is deterministic on fast runners

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: coalesce failed usage fetches with short negative caching

Concurrent lookups after a fetch error each retried the provider once
the per-key lock rotated. Failures are now cached for 15 seconds (never
longer than the caller's staleness bound), so bursts share one error
result and the provider gets a breather before the next retry.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: keep stale usage through failed refreshes and skip caching cancellations

Track the last success and last failure independently in the usage
cache: a failed fresh refresh no longer evicts a still-valid success
(non-fresh callers keep the stale value while fresh callers share the
recent error), and a caller-cancelled context no longer records a
negative entry that would penalize other callers.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: synchronize concurrent usage-cache tests with a channel barrier

Replaces the sleep-widened race window in the coalescing tests with a
started/release barrier per the backend testing guidelines, and dedupes
the two concurrent-caller tests into one helper.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-15 08:50:21 +01:00

155 lines
4.6 KiB
Go

package usage
import (
"context"
"crypto/sha256"
"fmt"
"sync"
"time"
)
const cacheTTL = 5 * time.Minute
// failureCacheTTL bounds negative caching: after a fetch error, lookups for
// the same key return the cached error instead of re-querying the provider,
// so bursts of concurrent callers coalesce failures as well as successes.
const failureCacheTTL = 15 * time.Second
// cachedEntry tracks the last success and the last failure independently, so
// a failed refresh never evicts a still-valid success: non-fresh callers keep
// being served the stale value while fresh callers share the recent error.
type cachedEntry struct {
usage *ProviderUsage
successAt time.Time
err error
errAt time.Time
}
// UsageCache is a thread-safe in-memory cache for provider usage responses.
type UsageCache struct {
mu sync.RWMutex
entries map[string]*cachedEntry
// fetchLocks serializes fetches per cache key so concurrent misses
// coalesce into a single provider request instead of a burst.
fetchMu sync.Mutex
fetchLocks map[string]*sync.Mutex
}
// NewUsageCache creates an empty UsageCache.
func NewUsageCache() *UsageCache {
return &UsageCache{
entries: make(map[string]*cachedEntry),
fetchLocks: make(map[string]*sync.Mutex),
}
}
// CacheKey builds a deterministic cache key from provider name and credential path.
func CacheKey(provider, credentialPath string) string {
h := sha256.Sum256([]byte(provider + ":" + credentialPath))
return fmt.Sprintf("%x", h[:8])
}
// GetOrFetch returns a cached entry if fresh; otherwise calls fetchFn, stores the
// result, and returns it. A nil result from fetchFn is stored as a negative cache
// entry so callers avoid hammering a provider that returned nothing.
func (c *UsageCache) GetOrFetch(
ctx context.Context,
key string,
fetchFn func(ctx context.Context) (*ProviderUsage, error),
) (*ProviderUsage, error) {
return c.GetOrFetchWithin(ctx, key, cacheTTL, fetchFn)
}
// GetOrFetchWithin is GetOrFetch with a caller-chosen staleness bound: the
// cached entry is served only while younger than maxAge. Fetch failures are
// shared with concurrent and near-term callers via a short-lived negative
// entry, except cancellations, which only affect the cancelled caller.
func (c *UsageCache) GetOrFetchWithin(
ctx context.Context,
key string,
maxAge time.Duration,
fetchFn func(ctx context.Context) (*ProviderUsage, error),
) (*ProviderUsage, error) {
if usage, ok, err := c.lookup(key, maxAge); ok {
return usage, err
}
lock := c.keyLock(key)
lock.Lock()
defer lock.Unlock()
// Re-check after acquiring the per-key lock: a concurrent caller may have
// completed the fetch while this one was waiting.
if usage, ok, err := c.lookup(key, maxAge); ok {
return usage, err
}
usage, err := fetchFn(ctx)
if err != nil {
// Do not poison the cache when this caller's context was cancelled —
// the provider was not necessarily at fault.
if ctx.Err() == nil {
c.storeFailure(key, err)
}
return nil, err
}
c.storeSuccess(key, usage)
return usage, nil
}
func (c *UsageCache) keyLock(key string) *sync.Mutex {
c.fetchMu.Lock()
defer c.fetchMu.Unlock()
lock, ok := c.fetchLocks[key]
if !ok {
lock = &sync.Mutex{}
c.fetchLocks[key] = lock
}
return lock
}
// lookup returns the cached value when still valid: successes live for
// maxAge, failures for at most failureCacheTTL (never longer than maxAge).
// A preserved stale success does not mask a newer failure for callers whose
// maxAge excludes it.
func (c *UsageCache) lookup(key string, maxAge time.Duration) (*ProviderUsage, bool, error) {
c.mu.RLock()
defer c.mu.RUnlock()
e, found := c.entries[key]
if !found {
return nil, false, nil
}
if !e.successAt.IsZero() && time.Since(e.successAt) < maxAge {
return e.usage, true, nil
}
if e.err != nil && time.Since(e.errAt) < min(failureCacheTTL, maxAge) {
return nil, true, e.err
}
return nil, false, nil
}
func (c *UsageCache) storeSuccess(key string, usage *ProviderUsage) {
c.mu.Lock()
defer c.mu.Unlock()
c.entries[key] = &cachedEntry{usage: usage, successAt: time.Now()}
}
// storeFailure records the error alongside — not instead of — any previous
// success, so callers with a wider staleness bound keep the stale value.
func (c *UsageCache) storeFailure(key string, err error) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.entries[key]
if !ok {
e = &cachedEntry{}
c.entries[key] = e
}
e.err = err
e.errAt = time.Now()
}
// Invalidate removes the cache entry for the given key.
func (c *UsageCache) Invalidate(key string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.entries, key)
}