From d661166eab69e5d8321a69645995c4d6270a67a7 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Thu, 26 Nov 2026 01:03:50 +0000 Subject: [PATCH] feat(metrics): count prompt-cache tokens and savings per model The gateway now counts cache-read, cache-write and uncached prompt tokens per provider and model as a Prometheus counter. It also writes the read, write and saved micro-USD totals to the Redis counters. The admin usage models detail view returns the three totals per model. Response-cache hits do not count, and free models save nothing. --- admin.go | 16 +++- limits.go | 13 ++++ llmgateway.go | 1 + metrics.go | 1 + prompt_cache_stats.go | 145 +++++++++++++++++++++++++++++++++++++ prompt_cache_stats_test.go | 139 +++++++++++++++++++++++++++++++++++ routes_passthrough.go | 7 ++ routes_unified.go | 4 +- 8 files changed, 324 insertions(+), 2 deletions(-) create mode 100644 prompt_cache_stats.go create mode 100644 prompt_cache_stats_test.go diff --git a/admin.go b/admin.go index 029f14d..43c5eb4 100644 --- a/admin.go +++ b/admin.go @@ -1480,6 +1480,10 @@ type adminUsageModelEntryView struct { // Free is populated only by serveAdminUsageModelsDetail too; false // (the non-detail zero value) is dropped by its own omitempty. Free bool `json:"free,omitempty"` + // Prompt-cache counters (detail mode only) are always emitted, zero included. + PromptCacheReadTokens int64 `json:"promptCacheReadTokens"` + PromptCacheWriteTokens int64 `json:"promptCacheWriteTokens"` + PromptCacheSavedMicroUSD int64 `json:"promptCacheSavedMicroUsd"` } // adminUsageModelsResponse is GET /admin/api/usage/models' body. Span @@ -1654,7 +1658,7 @@ func (g *Gateway) serveAdminUsageModels(sw *statusTrackingWriter, r *http.Reques // one through. keyMultiplier := 1 if detail { - keyMultiplier = len(usageModelsDetailMetrics()) + 1 // +1: r402, always read + keyMultiplier = len(usageModelsDetailMetrics()) + 1 + 3 // +1: r402, +3: pcr/pcw/pcsave, always read if g.buildAdminFeatures().CacheStats { keyMultiplier += 2 // chit, csave } @@ -1830,6 +1834,12 @@ func (g *Gateway) serveAdminUsageModelsDetail(sw *statusTrackingWriter, ids []st } r402ByID := r402Multi[0] + pcMulti, storeOK := g.chunkedModelSpanTotalsMulti(ids, []string{metricPcRead, metricPcWrite, metricPcSave}, window, now, span, offset) + if !storeOK { + writeOAIError(sw, http.StatusServiceUnavailable, "server_error", "usage history store unavailable") + return + } + // chit/csave (admin dashboard redesign, WP-B): only when // features.cacheStats (the response cache is configured) — nil // otherwise, as before. Unlike r402, a model's chit/csave are ONLY @@ -1881,6 +1891,10 @@ func (g *Gateway) serveAdminUsageModelsDetail(sw *statusTrackingWriter, ids []st Free: adminUsageModelFree(id, bare, g.cfg.Pricing, g.cfg.ModelMeta), PriceSource: source, R402: &r402, + + PromptCacheReadTokens: pcMulti[0][i], + PromptCacheWriteTokens: pcMulti[1][i], + PromptCacheSavedMicroUSD: pcMulti[2][i], } if chitByID != nil { chit := chitByID[i] diff --git a/limits.go b/limits.go index cefe639..5a6a673 100644 --- a/limits.go +++ b/limits.go @@ -1985,6 +1985,8 @@ type accountExtras struct { // increments prov/{failoverFrom}:fover when non-empty and admin stats // are on. failoverFrom string + // promptCacheSaved is the micro-USD the provider prompt cache saved this call. + promptCacheSaved int64 // lat/hasLat carry one completed upstream watchdogBody's latency // sample (metrics.go), when withLatencyRecorder was wired for this // call and it actually fired — hasLat false means no sample arrived @@ -1999,6 +2001,8 @@ type accountExtras struct { // calling it); recordCacheHit, below, is that path's own async // counterpart. cacheMiss bool + // responseCacheHit marks a gateway-cache replay: no provider prompt cache was involved. + responseCacheHit bool // noModelHistograms suppresses accountWith's own model-scope latency // AND user x model (umodel) writes even when scopes DOES carry a // kindModel scope (P13 fix, admin dashboard redesign verify round: @@ -2074,6 +2078,14 @@ func (l *limiter) accountWith(scopes []limitScope, u usage, costMicros int64, x } } + var pcRead, pcWrite, pcSave int64 + if !x.responseCacheHit { + pcRead, pcWrite, _ = promptCacheSplit(u) + pcSave = x.promptCacheSaved + if pcSave < 0 || pcSave > maxCostMicrosPerRequest { + pcSave = 0 + } + } entries := make([]counterIncr, 0, len(scopes)*12+16) userScopeCount := 0 var userScopeID string @@ -2132,6 +2144,7 @@ func (l *limiter) accountWith(scopes []limitScope, u usage, costMicros int64, x counterIncr{key: windowKeyForBucket(sc.kind, sc.id, metricTokIn, windowMonth, wb.month), delta: u.prompt, ttl: monthWindowTTL, enforceTTL: et.month}, ) } + entries = appendPromptCacheEntries(entries, sc, pcRead, pcWrite, pcSave, wb, et) if u.completion != 0 { entries = append(entries, counterIncr{key: windowKeyForBucket(sc.kind, sc.id, metricTokOut, windowHour, wb.hour), delta: u.completion, ttl: hourWindowTTL, enforceTTL: et.hour}, diff --git a/llmgateway.go b/llmgateway.go index 7846634..080b890 100644 --- a/llmgateway.go +++ b/llmgateway.go @@ -864,6 +864,7 @@ type Gateway struct { targetClient *http.Client provenance *provenanceStore routerStats *routerStats + promptCacheStats promptCacheStats routerSessions *routerSessions routerLearn *routerLearner tokenCalib *smartTokenCalibrator diff --git a/metrics.go b/metrics.go index 7e39a30..7a74252 100644 --- a/metrics.go +++ b/metrics.go @@ -485,6 +485,7 @@ func (g *Gateway) renderMetrics() []byte { g.writeLatencyMetrics(&m) g.writeProvenanceMetrics(&m) g.writeRouterMetrics(&m) + g.writePromptCacheMetrics(&m) g.writeRejectionMetrics(&m) g.writeStoreHealthMetrics(&m) return m.buf.Bytes() diff --git a/prompt_cache_stats.go b/prompt_cache_stats.go new file mode 100644 index 0000000..ab41f3a --- /dev/null +++ b/prompt_cache_stats.go @@ -0,0 +1,145 @@ +package traefikllmgateway + +import ( + "sort" + "sync" +) + +const ( + metricPcRead = "pcr" + metricPcWrite = "pcw" + metricPcSave = "pcsave" +) + +const ( + promptCacheKindRead = "read" + promptCacheKindWrite = "write" + promptCacheKindUncached = "uncached" +) + +type promptCacheKey struct { + provider string + model string + kind string +} + +// promptCacheStats holds per-instance counters; Traefik builds one plugin per route. +type promptCacheStats struct { + counts map[promptCacheKey]int64 + mu sync.Mutex +} + +func (s *promptCacheStats) add(k promptCacheKey, n int64) { + if n <= 0 { + return + } + s.mu.Lock() + if s.counts == nil { + s.counts = make(map[promptCacheKey]int64) + } + s.counts[k] += n + s.mu.Unlock() +} + +func (s *promptCacheStats) snapshot() map[promptCacheKey]int64 { + s.mu.Lock() + out := make(map[promptCacheKey]int64, len(s.counts)) + for k, v := range s.counts { + out[k] = v + } + s.mu.Unlock() + return out +} + +// promptCacheSplit clamps like computeCostMicros: cached in [0,prompt], write in [0,prompt-cached]. +func promptCacheSplit(u usage) (int64, int64, int64) { + cached := u.cached + if cached < 0 { + cached = 0 + } + if cached > u.prompt { + cached = u.prompt + } + write := u.cacheWrite + if write < 0 { + write = 0 + } + if write > u.prompt-cached { + write = u.prompt - cached + } + rest := u.prompt - cached - write + if rest < 0 { + rest = 0 + } + return cached, write, rest +} + +// recordPromptCache counts one real upstream response; never call it for a response-cache hit. +func (g *Gateway) recordPromptCache(provider, model string, u usage) { + if !metricsEnabled(g.cfg) { + return + } + cached, write, rest := promptCacheSplit(u) + g.promptCacheStats.add(promptCacheKey{provider, model, promptCacheKindRead}, cached) + g.promptCacheStats.add(promptCacheKey{provider, model, promptCacheKindWrite}, write) + g.promptCacheStats.add(promptCacheKey{provider, model, promptCacheKindUncached}, rest) +} + +// unifiedPromptCacheSaved resolves the price exactly as unifiedCostMicros does; a free model saves 0. +func unifiedPromptCacheSaved(canonical, bare string, u usage, overrides map[string]*ModelPricing, meta map[string]*ModelMetaConfig) int64 { + if u.cached <= 0 || modelMetaFree(canonical, bare, meta) { + return 0 + } + price, ok := lookupPricing(canonical, overrides) + if !ok { + price, ok = lookupPricing(bare, overrides) + } + if !ok { + return 0 + } + return promptCacheSavedMicros(price, u) +} + +func (g *Gateway) writePromptCacheMetrics(m *metricWriter) { + snap := g.promptCacheStats.snapshot() + if len(snap) == 0 { + return + } + keys := make([]promptCacheKey, 0, len(snap)) + for k := range snap { + keys = append(keys, k) + } + sort.Slice(keys, func(a, b int) bool { + x, y := keys[a], keys[b] + if x.provider != y.provider { + return x.provider < y.provider + } + if x.model != y.model { + return x.model < y.model + } + return x.kind < y.kind + }) + m.family("llmgateway_prompt_cache_tokens_total", "counter", + "Prompt tokens by provider, model and kind (read: served from the provider prompt cache, write: written to it, uncached: neither)."+aggregationNotePerProcess) + for _, k := range keys { + m.sampleInt("llmgateway_prompt_cache_tokens_total", + []metricLabel{{"provider", k.provider}, {"model", k.model}, {"kind", k.kind}}, snap[k]) + } +} + +func appendPromptCacheEntries(entries []counterIncr, sc limitScope, read, write, saved int64, wb windowBuckets, et enforceTTLSet) []counterIncr { + for _, p := range [...]struct { + metric string + delta int64 + }{{metricPcRead, read}, {metricPcWrite, write}, {metricPcSave, saved}} { + if p.delta <= 0 { + continue + } + entries = append(entries, + counterIncr{key: windowKeyForBucket(sc.kind, sc.id, p.metric, windowHour, wb.hour), delta: p.delta, ttl: hourWindowTTL, enforceTTL: et.hour}, + counterIncr{key: windowKeyForBucket(sc.kind, sc.id, p.metric, windowDay, wb.day), delta: p.delta, ttl: dayWindowTTL, enforceTTL: et.day}, + counterIncr{key: windowKeyForBucket(sc.kind, sc.id, p.metric, windowMonth, wb.month), delta: p.delta, ttl: monthWindowTTL, enforceTTL: et.month}, + ) + } + return entries +} diff --git a/prompt_cache_stats_test.go b/prompt_cache_stats_test.go new file mode 100644 index 0000000..798e21d --- /dev/null +++ b/prompt_cache_stats_test.go @@ -0,0 +1,139 @@ +package traefikllmgateway + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type pcEntryStore struct { + *memoryStore + batches [][]counterIncr +} + +func (s *pcEntryStore) incrMulti(entries []counterIncr) ([]int64, error) { + s.batches = append(s.batches, append([]counterIncr(nil), entries...)) + return s.memoryStore.incrMulti(entries) +} + +func (s *pcEntryStore) incrAndGetMulti(entries []counterIncr, reads []string) ([]int64, []int64, error) { + s.batches = append(s.batches, append([]counterIncr(nil), entries...)) + return s.memoryStore.incrAndGetMulti(entries, reads) +} + +func (s *pcEntryStore) entryCount() int { + n := 0 + for _, b := range s.batches { + n += len(b) + } + return n +} + +func TestAccountWithPromptCacheCounters(t *testing.T) { + t.Parallel() + l := newLimiter(newMemoryStore(), false) + now := time.Now() + scopes := []limitScope{{kind: kindModel, id: "p/m"}} + l.accountWith(scopes, usage{prompt: 1000, cached: 900, cacheWrite: 50}, 0, accountExtras{promptCacheSaved: 2430}) + + for _, window := range []string{windowHour, windowDay, windowMonth} { + for metric, want := range map[string]int64{metricPcRead: 900, metricPcWrite: 50, metricPcSave: 2430} { + got, _ := l.getCounter(kindModel, "p/m", metric, window, now) + assert.Equal(t, want, got, "%s %s", metric, window) + } + } + tokIn, _ := l.getCounter(kindModel, "p/m", metricTokIn, windowDay, now) + assert.EqualValues(t, 1000, tokIn, "day token limits keep counting full prompt tokens") +} + +func TestAccountWithNoCacheNoExtraWrites(t *testing.T) { + t.Parallel() + scopes := []limitScope{{kind: "user", id: "alice"}, {kind: kindModel, id: "p/m"}} + count := func(u usage) int { + st := &pcEntryStore{memoryStore: newMemoryStore()} + newLimiter(st, false).accountWith(scopes, u, 5, accountExtras{}) + return st.entryCount() + } + base := count(usage{prompt: 1000, completion: 10}) + assert.Equal(t, base, count(usage{prompt: 1000, completion: 10, cached: 0, cacheWrite: 0})) + assert.Greater(t, count(usage{prompt: 1000, completion: 10, cached: 900}), base) +} + +func TestAccountWithResponseCacheHitSkipsPromptCache(t *testing.T) { + t.Parallel() + l := newLimiter(newMemoryStore(), false) + l.accountWith([]limitScope{{kind: kindModel, id: "p/m"}}, usage{prompt: 100, cached: 90}, 0, accountExtras{responseCacheHit: true, promptCacheSaved: 5}) + got, _ := l.getCounter(kindModel, "p/m", metricPcRead, windowDay, time.Now()) + assert.Zero(t, got) +} + +func TestPromptCacheMetricsExposition(t *testing.T) { + t.Parallel() + cfg := newAdminTestConfig() + cfg.Metrics = &MetricsConfig{Enabled: true} + _, gw := newAdminGatewayHandle(t, cfg) + + assert.NotContains(t, string(gw.renderMetrics()), "llmgateway_prompt_cache_tokens_total") + gw.recordPromptCache("anthropic", "claude-x", usage{prompt: 1000, cached: 900, cacheWrite: 50}) + out := string(gw.renderMetrics()) + assert.Contains(t, out, `llmgateway_prompt_cache_tokens_total{provider="anthropic",model="claude-x",kind="read"} 900`) + assert.Contains(t, out, `llmgateway_prompt_cache_tokens_total{provider="anthropic",model="claude-x",kind="write"} 50`) + assert.Contains(t, out, `llmgateway_prompt_cache_tokens_total{provider="anthropic",model="claude-x",kind="uncached"} 50`) +} + +func TestUnifiedPromptCacheSavedFreeModelSavesZero(t *testing.T) { + t.Parallel() + in, cachedIn := 3.0, 0.3 + over := map[string]*ModelPricing{"p/m": {InputPerM: in, CachedInputPerM: &cachedIn}} + u := usage{prompt: 1000, cached: 1000} + assert.EqualValues(t, 2700, unifiedPromptCacheSaved("p/m", "m", u, over, nil)) + meta := map[string]*ModelMetaConfig{"p/m": {Free: true}} + assert.Zero(t, unifiedPromptCacheSaved("p/m", "m", u, over, meta)) +} + +func TestAdminUsageModelsPromptCache(t *testing.T) { + t.Parallel() + cfg := newAdminTestConfig() + h, gw := newAdminGatewayHandle(t, cfg) + now := time.Date(2026, 8, 20, 12, 30, 0, 0, time.UTC) + gw.limiter.nowFn = func() time.Time { return now } + seedModelCounter(gw, "alpha/a-model-1", metricReq, windowDay, now, 1) + seedModelCounter(gw, "alpha/a-model-1", metricPcRead, windowDay, now, 900) + seedModelCounter(gw, "alpha/a-model-1", metricPcWrite, windowDay, now, 50) + seedModelCounter(gw, "alpha/a-model-1", metricPcSave, windowDay, now, 2430) + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, adminRequest(http.MethodGet, adminUsageModelsPath+"?metric=req&window=day&detail=1", "sk-admin1")) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + assert.Contains(t, rec.Body.String(), `"promptCacheReadTokens":900`) + var got adminUsageModelsResponse + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + require.Len(t, got.Models, 1) + assert.EqualValues(t, 900, got.Models[0].PromptCacheReadTokens) + assert.EqualValues(t, 50, got.Models[0].PromptCacheWriteTokens) + assert.EqualValues(t, 2430, got.Models[0].PromptCacheSavedMicroUSD) +} + +func TestCacheHitDoesNotRecordPromptCache(t *testing.T) { + const respBody = `{"id":"c1","object":"chat.completion","model":"gpt-test","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"prompt_tokens_details":{"cached_tokens":8}}}` + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(respBody)) + })) + defer srv.Close() + gw := newCacheTestGateway(t, srv, nil, defaultCacheMaxBodyBytes) + gw.cfg.Cache.AccountHits = true + body := map[string]any{"model": "gpt-test", "messages": []any{map[string]any{"role": "user", "content": "hi"}}} + for _, want := range []string{"miss", "hit"} { + rec := httptest.NewRecorder() + gw.ServeHTTP(rec, newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body)) + require.Equal(t, want, rec.Header().Get("X-Llmgw-Cache")) + } + pcr, _ := gw.limiter.getCounter("user", "alice", metricPcRead, windowDay, time.Now()) + assert.EqualValues(t, 8, pcr, "only the upstream response counts, not the replay") +} diff --git a/routes_passthrough.go b/routes_passthrough.go index 5d1d092..353413a 100644 --- a/routes_passthrough.go +++ b/routes_passthrough.go @@ -1464,6 +1464,13 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u extras.lat = latSample extras.hasLat = true } + extras.promptCacheSaved = unifiedPromptCacheSaved(providerName+"/"+billModel, billModel, respUsage, g.cfg.Pricing, g.cfg.ModelMeta) + // The echoed id is upstream-controlled; an uncatalogued one must not mint label series. + statModel := respModel + if canonical == "" { + statModel = "unknown" + } + g.recordPromptCache(providerName, statModel, respUsage) g.limiter.accountWith(withModelScope(scopes, canonical), respUsage, cost, extras) } diff --git a/routes_unified.go b/routes_unified.go index 6b902fd..55c9b9e 100644 --- a/routes_unified.go +++ b/routes_unified.go @@ -523,7 +523,7 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop // actually saves the parse. if g.cfg.Cache.AccountHits { hitUsage := cachedUsage(cached.Body) - g.limiter.accountWith(scopes, hitUsage, unifiedCostMicros(cand.canonical, cand.upstreamModel, hitUsage, g.cfg.Pricing, g.cfg.ModelMeta, g.pricingWarn), accountExtras{provider: cand.providerName}) + g.limiter.accountWith(scopes, hitUsage, unifiedCostMicros(cand.canonical, cand.upstreamModel, hitUsage, g.cfg.Pricing, g.cfg.ModelMeta, g.pricingWarn), accountExtras{provider: cand.providerName, responseCacheHit: true}) } if g.limiter.statsAdmin { saved := unifiedCostMicros(cand.canonical, cand.upstreamModel, cachedUsage(cached.Body), g.cfg.Pricing, g.cfg.ModelMeta, func(string) {}) @@ -779,6 +779,8 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop extras.lat = latSample extras.hasLat = true } + extras.promptCacheSaved = unifiedPromptCacheSaved(cand.canonical, cand.upstreamModel, result, g.cfg.Pricing, g.cfg.ModelMeta) + g.recordPromptCache(providerName, cand.upstreamModel, result) g.limiter.accountWith(acctScopes, result, unifiedCostMicros(cand.canonical, cand.upstreamModel, result, g.cfg.Pricing, g.cfg.ModelMeta, g.pricingWarn), extras) if result.estimated { g.logf("%s: usage for model %q logged as estimated (%d prompt tokens derived from request body size, not the provider's reported usage)", logPrefix, cand.canonical, result.prompt)