From 6d55972b603640d2182b1ff152cab96d4ccbde5d Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Thu, 26 Nov 2026 02:34:38 +0000 Subject: [PATCH] fix(metrics): render fleet-wide families from the shared store The /metrics route runs in its own instance. That instance handles no chat traffic, so its in-memory families stayed empty. With a limiter store, /metrics now reads the router, decision, latency, prompt-cache, provenance and rejection families from shared counters. Their HELP text uses the store-backed aggregation note. Without a store, or without the stats flag a family needs, the in-memory rendering is unchanged. The latency counters gain day-window sums in milliseconds and streaming-only bucket counters. The histograms can then emit a real _sum and keep the stream label. Provenance writes use countAsync. The rejection month counter rides the existing rejection batch. A store read failure skips the affected families. --- README.md | 32 ++-- fleet_metrics.go | 341 ++++++++++++++++++++++++++++++++++++++++ fleet_metrics_test.go | 276 ++++++++++++++++++++++++++++++++ limits.go | 16 +- metrics.go | 35 ++++- prompt_cache_stats.go | 11 +- smart_router_metrics.go | 44 +++++- stats_write_test.go | 8 +- 8 files changed, 731 insertions(+), 32 deletions(-) create mode 100644 fleet_metrics.go create mode 100644 fleet_metrics_test.go diff --git a/README.md b/README.md index 9706509..d118dbf 100644 --- a/README.md +++ b/README.md @@ -2941,6 +2941,7 @@ counting calls is exactly counting round trips): | `admin.enabled: false` | 3 (2 sync — `checkAndCount`, `accountWith` — + 1 async — `recordProviderAttempt`) — `l.statsAdmin` (`adminEnabled(cfg)`, `newConfiguredLimiter`) is false, so no "always-on-with-admin" family, last-seen included, ever writes (`TestRoundTrips_SingleGroupChat_Defaults_TwoSyncOneAsync`, `stats_write_test.go`) | | `admin.enabled: true` (`admin.stats.userModel`/`latency` on or off — **both default off, and neither changes this row**: `l.statsAdmin` is `adminEnabled(cfg)` alone, so last-seen and the rest of the always-on family are gated on `admin.enabled` by itself), cache miss or no cache, this scope's last-seen already written within `lastSeenGateThrottle` by this replica | 3 — every new counter family except last-seen rides one of the two existing sync batches above, never a new round trip; `userModel`/`latency`, when on, add entries to those SAME batches, never a new call | | Same as above, but this scope's last-seen is DUE (its first admitted request ever, or `lastSeenGateThrottle` — 60s — has elapsed since this replica's last write for it) | 4 — adds `recordLastSeen`'s own async write (P9 fix, moved off `checkAndCount`'s own batch — see [Limits and accounting](#limits-and-accounting)). This is the common case for a request from a SCOPE'S FIRST admitted request under a fresh limiter, `admin.enabled: true` regardless of the opt-in stats (`TestRoundTrips_SingleGroupChat_AdminEnabledStatsOff_FourRoundTripsWhenLastSeenDue`, `TestRoundTrips_SingleGroupChat_AllStatsOn_NoNewSyncRoundTrips`, `stats_write_test.go`) | +| Any row above that completes an upstream call with `metrics.enabled: true` and a store | +1 async — the usage-provenance mirror (`countProvenanceShared`, `fleet_metrics.go`) that `llmgateway_usage_provenance_*` reads fleet-wide (`TestRoundTrips_SingleGroupChat_AllStatsOn_NoNewSyncRoundTrips`) | | Cache hit (`cache.enabled: true`, `admin.enabled: true`), last-seen already throttled | 2 (`checkAndCount` + `recordCacheHit`'s async write) — `accountWith`/`recordProviderAttempt` never run at all, since the hit branch returns before either is reached | | Cache hit, last-seen due | 3 — adds `recordLastSeen`'s own async write, same condition as the row above | @@ -3208,14 +3209,22 @@ plugin's config. carries the identical measurements broken out per `(provider, stream, model)` too. These are distinct metric names, not the unlabelled pair re-emitted under a wider label set, so a query against the unlabelled - families is unaffected either way. + families is unaffected either way. With `redis` and + `admin.stats.latency`, all four read the shared latency counters (UTC + day window; counters restart at the day rollover, which `rate()` treats + as a reset) and `_sum` starts at the deploy, so it can lag `_count` on + the first day; otherwise they are per process. - `llmgateway_router_requests_total{router,tier,reason}` / `llmgateway_router_escalations_total{router,from_tier,to_tier}` — - per-process counters for [smart routers](#smart-routers). They - appear after the first routed request. + counters for [smart routers](#smart-routers). They appear after the + first routed request. With `redis` and `admin.enabled`, they and the + decision families read the shared router counters (month window), so + every replica reports the fleet-wide value; otherwise they are per + process. - `llmgateway_prompt_cache_tokens_total{provider,model,kind}` — prompt - tokens by `kind`: `read`, `write` or `uncached`. Per instance. See - [Prompt caching](#prompt-caching). + tokens by `kind`: `read`, `write` or `uncached`. With `redis` it reads + the model-scope counters (UTC month window), so it is fleet-wide; + otherwise it is per instance. See [Prompt caching](#prompt-caching). - `llmgateway_provider_healthy{provider}` — `1`/`0` gauge from the discovery circuit breaker (`healthState` in the admin API); see [Provider health](#provider-health-discovery-circuit-breaker). @@ -3237,7 +3246,10 @@ plugin's config. - `llmgateway_rate_limit_rejections_total{scope_kind,scope_id}` — how many requests a rate or budget limit actually refused, by scope. This one has no equivalent in the admin JSON API: nothing else tracks it. - It does **not** reset only on process restart: a scope's own count + With `redis` it is a UTC-month counter shared by all replicas + (`user` and `group` scopes only; `store_down` rejections stay local and + are not exported). Without `redis`, it does **not** reset only on + process restart: a scope's own count also resets to `0` when that user is removed via a hot-reloaded users file, and **every** tracked scope resets together, in one bulk cliff, the instant more than 2000 distinct scopes have ever been seen in @@ -3263,9 +3275,11 @@ plugin's config. becomes the correct aggregation instead. This flips on that one config bit; know which one you are running before wiring an alert. Four families do **not** follow this rule: - - `llmgateway_rate_limit_rejections_total` lives only in each replica's - own process memory, **never** in Redis, regardless of the `redis` - config — `sum()` is always correct for it. + - Without `redis`, `llmgateway_rate_limit_rejections_total` and the + `llmgateway_usage_provenance_*` families live only in each replica's + own process memory — `sum()` is correct for them. With `redis` they + read shared month-window counters instead and follow the `max()` + rule, like the router, latency and prompt-cache families. - `llmgateway_provider_healthy` reflects each replica's own, independently-running discovery circuit breaker — never shared via Redis either — so two replicas can legitimately disagree about one diff --git a/fleet_metrics.go b/fleet_metrics.go new file mode 100644 index 0000000..e3c47e3 --- /dev/null +++ b/fleet_metrics.go @@ -0,0 +1,341 @@ +package traefikllmgateway + +import ( + "fmt" + "sort" + "strings" + "time" +) + +// Fleet metrics: with a limiter store, /metrics renders these families from +// the shared counters instead of this pod's memory, because the route that +// serves /metrics handles no chat traffic itself. + +const ( + kindProvenance = "provenance" + metricProvenanceReq = "vreq" + metricProvenanceTok = "vtok" + + // Latency sums are in milliseconds. The "s" variants count streaming + // observations only; the non-streaming series is the difference, so the + // existing ld/lt counters keep their meaning. + metricLatDurSum = "ldsum" + metricLatTTFBSum = "ltsum" + metricLatStreamDurSum = "lsdsum" + metricLatStreamTTFBSum = "lstsum" + latencyStreamDurFmt = "lsd%02d" + latencyStreamTTFBFmt = "lst%02d" +) + +var provenanceOutcomes = []string{provenanceReported, provenanceEstimated, provenanceUnbilled} + +// latencyHistKeys is how many store keys one (kind, id) latency block reads: +// per histogram, every bucket plus overflow and one sum, for all and streaming. +var latencyHistKeys = 2 * (len(latencyBucketBounds) + 2) + +func durationMillis(d time.Duration) int64 { + return int64((d + time.Millisecond/2) / time.Millisecond) +} + +// fleetLatencyEntries returns the day-window sum and streaming counters that +// ride beside the ld/lt bucket counters. +func fleetLatencyEntries(kind, id string, lat latencySample, wb windowBuckets, et enforceTTLSet) []counterIncr { + out := make([]counterIncr, 0, 8) + add := func(metric string, delta int64) { + if delta <= 0 { + return + } + out = append(out, counterIncr{key: windowKeyForBucket(kind, id, metric, windowDay, wb.day), delta: delta, ttl: dayWindowTTL, enforceTTL: et.day}) + } + durIdx, _ := latencyBucketIndex(lat.duration) + durMs := durationMillis(lat.duration) + add(metricLatDurSum, durMs) + if lat.streaming { + add(fmt.Sprintf(latencyStreamDurFmt, durIdx), 1) + add(metricLatStreamDurSum, durMs) + } + if lat.hasTTFB { + ttfbIdx, _ := latencyBucketIndex(lat.ttfb) + ttfbMs := durationMillis(lat.ttfb) + add(metricLatTTFBSum, ttfbMs) + if lat.streaming { + add(fmt.Sprintf(latencyStreamTTFBFmt, ttfbIdx), 1) + add(metricLatStreamTTFBSum, ttfbMs) + } + } + return out +} + +// fleetStore reports whether this Gateway has a shared limiter store. +func (g *Gateway) fleetStore() bool { + return g.limiter != nil && g.limiter.store != nil +} + +func (g *Gateway) fleetLatencyEnabled() bool { + return g.fleetStore() && g.limiter.statsLatency +} + +// latencyBlockKeys lists one (kind, id) block in a fixed order: duration then +// TTFB; within each, all-bucket counters, all-sum, streaming buckets, +// streaming-sum. +func latencyBlockKeys(kind, id, bucket string) []string { + n := len(latencyBucketBounds) + 1 + keys := make([]string, 0, 2*latencyHistKeys) + key := func(metric string) string { + return windowKeyForBucket(kind, id, metric, windowDay, bucket) + } + for i := 0; i < n; i++ { + keys = append(keys, key(latencyDurationMetric(i))) + } + keys = append(keys, key(metricLatDurSum)) + for i := 0; i < n; i++ { + keys = append(keys, key(fmt.Sprintf(latencyStreamDurFmt, i))) + } + keys = append(keys, key(metricLatStreamDurSum)) + for i := 0; i < n; i++ { + keys = append(keys, key(latencyTTFBMetric(i))) + } + keys = append(keys, key(metricLatTTFBSum)) + for i := 0; i < n; i++ { + keys = append(keys, key(fmt.Sprintf(latencyStreamTTFBFmt, i))) + } + keys = append(keys, key(metricLatStreamTTFBSum)) + return keys +} + +func clampNonNegative(v int64) int64 { + if v < 0 { + return 0 + } + return v +} + +// latencyHalf is the dense bucket counts (overflow last), their sum in +// milliseconds, and their total for one histogram of one stream class. +type latencyHalf struct { + buckets []int64 + sumMs int64 + count int64 +} + +// splitLatencyBlock turns one block of values into the non-streaming and +// streaming halves for duration and TTFB. A counter that lags its streaming +// twin is clamped at zero instead of going negative. +func splitLatencyBlock(vals []int64) (latencyHalf, latencyHalf, latencyHalf, latencyHalf) { + n := len(latencyBucketBounds) + 1 + half := func(off int) (latencyHalf, latencyHalf) { + all := vals[off : off+n] + allSum := vals[off+n] + str := vals[off+n+1 : off+2*n+1] + strSum := vals[off+2*n+1] + plain := latencyHalf{buckets: make([]int64, n), sumMs: clampNonNegative(allSum - strSum)} + stream := latencyHalf{buckets: make([]int64, n), sumMs: clampNonNegative(strSum)} + for i := 0; i < n; i++ { + stream.buckets[i] = clampNonNegative(str[i]) + plain.buckets[i] = clampNonNegative(all[i] - str[i]) + plain.count += plain.buckets[i] + stream.count += stream.buckets[i] + } + return plain, stream + } + step := 2*n + 2 + durPlain, durStream := half(0) + ttfbPlain, ttfbStream := half(step) + return durPlain, durStream, ttfbPlain, ttfbStream +} + +func latencySnapshotFrom(key latencyKey, dur, ttfb latencyHalf) latencySnapshot { + n := len(latencyBucketBounds) + return latencySnapshot{ + key: key, + ttfbBuckets: ttfb.buckets[:n], + durationBuckets: dur.buckets[:n], + ttfbSum: float64(ttfb.sumMs) / 1000, + durationSum: float64(dur.sumMs) / 1000, + ttfbCount: ttfb.count, + ttfbOverflow: ttfb.buckets[n], + durationCount: dur.count, + durationOverflow: dur.buckets[n], + } +} + +type latencyScope struct { + kind string + id string + key latencyKey +} + +// fleetLatencySnapshots reads every provider's (and, with model labels, every +// catalogued model's) latency counters. ok is false when the store read fails. +func (g *Gateway) fleetLatencySnapshots() ([]latencySnapshot, bool) { + snaps := g.registry.snapshot() + includeModel := g.cfg.Metrics != nil && g.cfg.Metrics.ModelLabel + scopes := make([]latencyScope, 0, len(snaps)) + for _, s := range snaps { + scopes = append(scopes, latencyScope{kind: kindProvider, id: s.name, key: latencyKey{provider: s.name}}) + } + if includeModel { + for _, s := range snaps { + for _, model := range s.models { + scopes = append(scopes, latencyScope{kind: kindModel, id: providerModelScopeID(s.name, model), key: latencyKey{provider: s.name, model: model}}) + } + } + } + bucket := bucketFor(g.limiter.now(), windowDay) + keys := make([]string, 0, len(scopes)*latencyHistKeys*2) + for _, sc := range scopes { + keys = append(keys, latencyBlockKeys(sc.kind, sc.id, bucket)...) + } + if len(keys) == 0 { + return nil, true + } + vals, ok := g.limiter.chunkedGetMulti(keys, usageModelsChunkKeys) + if !ok { + return nil, false + } + out := make([]latencySnapshot, 0, len(scopes)*2) + block := 2 * latencyHistKeys + for i, sc := range scopes { + durPlain, durStream, ttfbPlain, ttfbStream := splitLatencyBlock(vals[i*block : (i+1)*block]) + plainKey, streamKey := sc.key, sc.key + streamKey.streaming = true + out = append(out, latencySnapshotFrom(plainKey, durPlain, ttfbPlain), latencySnapshotFrom(streamKey, durStream, ttfbStream)) + } + return out, true +} + +// fleetPromptCache reads the model-scope prompt-cache counters for the whole +// catalog. uncached is the model's input tokens minus read and write. +func (g *Gateway) fleetPromptCache() (map[promptCacheKey]int64, bool) { + ids := g.catalogModelScopeIDs() + bucket := bucketFor(g.limiter.now(), windowMonth) + const perID = 3 + keys := make([]string, 0, len(ids)*perID) + for _, id := range ids { + for _, metric := range [...]string{metricTokIn, metricPcRead, metricPcWrite} { + keys = append(keys, windowKeyForBucket(kindModel, id, metric, windowMonth, bucket)) + } + } + out := make(map[promptCacheKey]int64) + if len(keys) == 0 { + return out, true + } + vals, ok := g.limiter.chunkedGetMulti(keys, usageModelsChunkKeys) + if !ok { + return nil, false + } + for i, id := range ids { + provider, model, _ := strings.Cut(id, "/") + tokIn, read, write := vals[i*perID], vals[i*perID+1], vals[i*perID+2] + if read > 0 { + out[promptCacheKey{provider, model, promptCacheKindRead}] = read + } + if write > 0 { + out[promptCacheKey{provider, model, promptCacheKindWrite}] = write + } + if rest := tokIn - read - write; rest > 0 { + out[promptCacheKey{provider, model, promptCacheKindUncached}] = rest + } + } + return out, true +} + +// countProvenanceShared mirrors one provenance observation into the shared +// month counters, async and droppable. +func (g *Gateway) countProvenanceShared(provider, provenance string, tokens int64) { + if !g.fleetStore() || g.cfg == nil || !metricsEnabled(g.cfg) { + return + } + bucket := bucketFor(g.limiter.now(), windowMonth) + entries := []counterIncr{{key: provenanceKeyFor(provider, metricProvenanceReq, provenance, bucket), delta: 1, ttl: monthWindowTTL, enforceTTL: enforceTTLMonthWindow}} + if tokens > 0 { + entries = append(entries, counterIncr{key: provenanceKeyFor(provider, metricProvenanceTok, provenance, bucket), delta: tokens, ttl: monthWindowTTL, enforceTTL: enforceTTLMonthWindow}) + } + g.limiter.countAsync(entries) +} + +func provenanceKeyFor(provider, metric, provenance, bucket string) string { + return windowKeyForBucket(kindProvenance, provider, metric+routerKeySep+provenance, windowMonth, bucket) +} + +// fleetProvenance reads the shared provenance counters for every provider. +func (g *Gateway) fleetProvenance() ([]provenanceSnapshot, bool) { + snaps := g.registry.snapshot() + bucket := bucketFor(g.limiter.now(), windowMonth) + keys := make([]string, 0, len(snaps)*len(provenanceOutcomes)*2) + for _, s := range snaps { + for _, p := range provenanceOutcomes { + keys = append(keys, provenanceKeyFor(s.name, metricProvenanceReq, p, bucket), provenanceKeyFor(s.name, metricProvenanceTok, p, bucket)) + } + } + if len(keys) == 0 { + return nil, true + } + vals, ok := g.limiter.chunkedGetMulti(keys, usageModelsChunkKeys) + if !ok { + return nil, false + } + var out []provenanceSnapshot + pos := 0 + for _, s := range snaps { + for _, p := range provenanceOutcomes { + reqs, toks := vals[pos], vals[pos+1] + pos += 2 + if reqs > 0 { + out = append(out, provenanceSnapshot{key: provenanceKey{provider: s.name, provenance: p}, requests: reqs, tokens: toks}) + } + } + } + return out, true +} + +// fleetRejections reads the shared month rejection counters for every user +// and group. +func (g *Gateway) fleetRejections() ([]rejectionSnapshot, bool) { + userSummaries, groupSummaries := g.auth.snapshot() + scopes := make([]limitScope, 0, len(userSummaries)+len(groupSummaries)) + for _, us := range userSummaries { + scopes = append(scopes, limitScope{kind: "user", id: us.name}) + } + for _, gs := range groupSummaries { + scopes = append(scopes, limitScope{kind: "group", id: gs.name}) + } + if len(scopes) == 0 { + return nil, true + } + now := g.limiter.now() + keys := make([]string, len(scopes)) + for i, sc := range scopes { + keys[i] = windowKey(sc.kind, sc.id, metricRej, windowMonth, now) + } + vals, ok := g.limiter.chunkedGetMulti(keys, usageModelsChunkKeys) + if !ok { + return nil, false + } + var out []rejectionSnapshot + for i, sc := range scopes { + if vals[i] > 0 { + out = append(out, rejectionSnapshot{kind: sc.kind, id: sc.id, count: vals[i]}) + } + } + return out, true +} + +func (g *Gateway) writeFleetRejectionMetrics(m *metricWriter) { + snaps, ok := g.fleetRejections() + if !ok { + return + } + sort.Slice(snaps, func(i, j int) bool { + if snaps[i].kind != snaps[j].kind { + return snaps[i].kind < snaps[j].kind + } + return snaps[i].id < snaps[j].id + }) + m.family("llmgateway_rate_limit_rejections_total", "counter", + "Total requests refused by a rate or budget limit this UTC month (resets at the UTC month start), by scope."+aggregationNoteStoreBacked) + for _, s := range snaps { + m.sampleInt("llmgateway_rate_limit_rejections_total", + []metricLabel{{"scope_kind", s.kind}, {"scope_id", s.id}}, s.count) + } +} diff --git a/fleet_metrics_test.go b/fleet_metrics_test.go new file mode 100644 index 0000000..9e6825f --- /dev/null +++ b/fleet_metrics_test.go @@ -0,0 +1,276 @@ +package traefikllmgateway + +import ( + "fmt" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const fleetCachedBody = `{"id":"c1","object":"chat.completion","model":"shared","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"prompt_tokens_details":{"cached_tokens":8}}}` + +// keyCountStore counts the keys each getMulti call carries. +type keyCountStore struct { + counterStore + total atomic.Int64 + maxOne atomic.Int64 +} + +func (s *keyCountStore) getMulti(keys []string) ([]int64, error) { + n := int64(len(keys)) + s.total.Add(n) + for { + cur := s.maxOne.Load() + if n <= cur || s.maxOne.CompareAndSwap(cur, n) { + break + } + } + return s.counterStore.getMulti(keys) +} + +func fleetConfig(statuses [3]int, body string, rpm int64) (*Config, func()) { + mk := func(status int) *routerBackend { + if status == 200 { + return newRouterBackend(status, body) + } + return newRouterBackend(status, routerFail) + } + a, b, c := mk(statuses[0]), mk(statuses[1]), mk(statuses[2]) + cfg := routerTestConfig(a, b, c, threeTiers()) + cfg.Admin = &AdminConfig{Enabled: true, Stats: &AdminStatsConfig{Latency: true}} + cfg.Metrics = &MetricsConfig{Enabled: true, ModelLabel: true} + cfg.Users.Inline[0].Limits = &LimitsConfig{RequestsPerMinute: rpm} + return cfg, func() { closeBackends(a, b, c) } +} + +func fleetGateway(t *testing.T, cfg *Config, store counterStore) *Gateway { + t.Helper() + _, gw := buildRouterGateway(t, cfg) + gw.limiter.spawn = func(f func()) { f() } + gw.limiter.store = store + return gw +} + +func fleetSamples(t *testing.T, gw *Gateway) (map[string]string, []promSample) { + t.Helper() + return parsePrometheusText(t, gw.renderMetrics()) +} + +func fleetHelp(t *testing.T, gw *Gateway, family string) string { + t.Helper() + for _, line := range strings.Split(string(gw.renderMetrics()), "\n") { + if strings.HasPrefix(line, "# HELP "+family+" ") { + return line + } + } + return "" +} + +func TestFleetMetricsStoreBacked(t *testing.T) { + store := newMemoryStore() + cfgA, closeA := fleetConfig([3]int{503, 200, 200}, fleetCachedBody, 1) + defer closeA() + cfgB, closeB := fleetConfig([3]int{200, 200, 200}, fleetCachedBody, 1) + defer closeB() + gwA := fleetGateway(t, cfgA, store) + gwB := fleetGateway(t, cfgB, store) + + require.Equal(t, 200, routerChat(t, gwA, routerName, "hi", nil).Code) + require.Equal(t, 429, routerChat(t, gwA, routerName, "hi", nil).Code, "second request exceeds rpm=1") + + require.Zero(t, gwB.routerStats.requests[routerRequestKey{router: routerName, tier: "t0", reason: "score"}], "B handled nothing") + _, samples := fleetSamples(t, gwB) + + tests := []struct { + name string + family string + labels map[string]string + want string + }{ + {"router request", "llmgateway_router_requests_total", map[string]string{"router": routerName, "tier": "t0", "reason": "score"}, "1"}, + {"router escalation", "llmgateway_router_escalations_total", map[string]string{"router": routerName, "from_tier": "t0", "to_tier": "t1"}, "1"}, + {"latency count", "llmgateway_upstream_duration_seconds_count", map[string]string{"provider": "beta", "stream": "false"}, "1"}, + {"latency inf bucket", "llmgateway_upstream_duration_seconds_bucket", map[string]string{"provider": "beta", "stream": "false", "le": "+Inf"}, "1"}, + {"ttfb count", "llmgateway_upstream_ttfb_seconds_count", map[string]string{"provider": "beta", "stream": "false"}, "1"}, + {"model latency count", "llmgateway_upstream_model_duration_seconds_count", map[string]string{"provider": "beta", "stream": "false", "model": "b1"}, "1"}, + {"cache read", "llmgateway_prompt_cache_tokens_total", map[string]string{"provider": "beta", "model": "b1", "kind": "read"}, "8"}, + {"cache uncached", "llmgateway_prompt_cache_tokens_total", map[string]string{"provider": "beta", "model": "b1", "kind": "uncached"}, "2"}, + {"provenance requests", "llmgateway_usage_provenance_requests_total", map[string]string{"provider": "beta", "provenance": provenanceReported}, "1"}, + {"provenance tokens", "llmgateway_usage_provenance_tokens_total", map[string]string{"provider": "beta", "provenance": provenanceReported}, "15"}, + {"rejection", "llmgateway_rate_limit_rejections_total", map[string]string{"scope_kind": "user", "scope_id": "alice"}, "1"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertSample(t, samples, tt.family, tt.labels, tt.want) + }) + } + + for _, fam := range []string{ + "llmgateway_router_requests_total", "llmgateway_router_escalations_total", + "llmgateway_upstream_duration_seconds", "llmgateway_upstream_ttfb_seconds", + "llmgateway_prompt_cache_tokens_total", "llmgateway_usage_provenance_requests_total", + "llmgateway_usage_provenance_tokens_total", "llmgateway_rate_limit_rejections_total", + } { + help := fleetHelp(t, gwB, fam) + assert.Contains(t, help, "aggregate with max()", fam) + assert.NotContains(t, help, "aggregate with sum(), which is always correct", fam) + } +} + +func TestFleetMetricsDecisionStoreBacked(t *testing.T) { + store := newMemoryStore() + a := newDecisionFixture(t, 3, "", okHandler).g + b := newDecisionFixture(t, 3, "", okHandler).g + for _, g := range []*Gateway{a, b} { + g.cfg.Metrics = &MetricsConfig{Enabled: true} + g.limiter.store = store + g.limiter.statsAdmin = true + g.limiter.spawn = func(f func()) { f() } + } + plan := decisionStatsPlan(decisionOverride, "ta", "tc") + plan.router = "auto" + a.recordRouterAttempt(plan, 0, cacheEndpointChat, nil) + + out := scrape(b) + assert.Contains(t, out, `llmgateway_router_decision_total{router="auto",outcome="override"} 1`) + assert.Contains(t, out, `llmgateway_router_decision_tiers_total{router="auto",heuristic="ta",model="tc"} 1`) + assert.Contains(t, out, "aggregate with max()") +} + +func TestFleetMetricsHistogramSumAndBuckets(t *testing.T) { + store := newMemoryStore() + cfg, closeAll := fleetConfig([3]int{200, 200, 200}, fleetCachedBody, 100) + defer closeAll() + gw := fleetGateway(t, cfg, store) + now := time.Date(2026, 8, 20, 10, 0, 0, 0, time.UTC) + gw.limiter.nowFn = func() time.Time { return now } + wb := bucketsFor(now) + et := enforceTTLsFor() + + samples := []latencySample{ + {duration: 300 * time.Millisecond, ttfb: 100 * time.Millisecond, hasTTFB: true}, + {duration: 1500 * time.Millisecond, ttfb: 200 * time.Millisecond, hasTTFB: true, streaming: true}, + {duration: 700 * time.Second, hasTTFB: false}, + } + for _, s := range samples { + _, ok := gw.limiter.storeIncrMulti(latencyCounterEntries(kindProvider, "alpha", s, wb, et)) + require.True(t, ok) + } + + _, got := fleetSamples(t, gw) + nonStream := map[string]string{"provider": "alpha", "stream": "false"} + stream := map[string]string{"provider": "alpha", "stream": "true"} + assertSample(t, got, "llmgateway_upstream_duration_seconds_count", nonStream, "2") + assertSample(t, got, "llmgateway_upstream_duration_seconds_count", stream, "1") + assertSample(t, got, "llmgateway_upstream_duration_seconds_sum", nonStream, "700.3") + assertSample(t, got, "llmgateway_upstream_duration_seconds_sum", stream, "1.5") + assertSample(t, got, "llmgateway_upstream_ttfb_seconds_count", nonStream, "1") + assertSample(t, got, "llmgateway_upstream_ttfb_seconds_sum", nonStream, "0.1") + + ne := map[string]string{"provider": "alpha", "stream": "false", "le": "0.25"} + assertSample(t, got, "llmgateway_upstream_duration_seconds_bucket", ne, "0") + ne["le"] = "0.5" + assertSample(t, got, "llmgateway_upstream_duration_seconds_bucket", ne, "1") + ne["le"] = "600" + assertSample(t, got, "llmgateway_upstream_duration_seconds_bucket", ne, "1") + ne["le"] = "+Inf" + assertSample(t, got, "llmgateway_upstream_duration_seconds_bucket", ne, "2") +} + +func TestFleetMetricsNoStoreUnchanged(t *testing.T) { + cfg, closeAll := fleetConfig([3]int{503, 200, 200}, fleetCachedBody, 1) + defer closeAll() + _, gw := buildRouterGateway(t, cfg) + require.Nil(t, gw.limiter.store) + require.Equal(t, 200, routerChat(t, gw, routerName, "hi", nil).Code) + require.Equal(t, 429, routerChat(t, gw, routerName, "hi", nil).Code) + + out := scrape(gw) + for _, want := range []string{ + `llmgateway_router_requests_total{router="auto",tier="t0",reason="score"} 1`, + `llmgateway_router_escalations_total{router="auto",from_tier="t0",to_tier="t1"} 1`, + `llmgateway_prompt_cache_tokens_total{provider="beta",model="b1",kind="read"} 8`, + `llmgateway_usage_provenance_requests_total{provider="beta",provenance="reported"} 1`, + `llmgateway_rate_limit_rejections_total{scope_kind="user",scope_id="alice"} 1`, + `llmgateway_upstream_duration_seconds_count{provider="beta",stream="false"} 1`, + } { + assert.Contains(t, out, want) + } + for _, fam := range []string{ + "llmgateway_router_requests_total", "llmgateway_upstream_duration_seconds", + "llmgateway_prompt_cache_tokens_total", "llmgateway_usage_provenance_requests_total", + "llmgateway_rate_limit_rejections_total", + } { + help := fleetHelp(t, gw, fam) + assert.NotContains(t, help, "aggregate with max()", fam) + assert.Contains(t, help, "aggregate with sum()", fam) + } +} + +func TestFleetMetricsStoreDownSkips(t *testing.T) { + store := newMemoryStore() + cfg, closeAll := fleetConfig([3]int{503, 200, 200}, fleetCachedBody, 1) + defer closeAll() + gw := fleetGateway(t, cfg, store) + require.Equal(t, 200, routerChat(t, gw, routerName, "hi", nil).Code) + require.Equal(t, 429, routerChat(t, gw, routerName, "hi", nil).Code) + + gw.limiter.store = alwaysErrStore{} + out := scrape(gw) + for _, fam := range []string{ + "llmgateway_router_requests_total{", "llmgateway_router_escalations_total{", + "llmgateway_upstream_duration_seconds_count{", "llmgateway_upstream_ttfb_seconds_count{", + "llmgateway_prompt_cache_tokens_total{", "llmgateway_usage_provenance_requests_total{", + "llmgateway_usage_provenance_tokens_total{", "llmgateway_rate_limit_rejections_total{", + } { + assert.NotContains(t, out, fam, "store down must not fabricate or fall back to local samples") + } + assert.Contains(t, out, "llmgateway_provider_healthy{", "non-store families still render") + assert.Contains(t, out, "llmgateway_limit_store_up 0") +} + +func TestFleetMetricsKeyBudget(t *testing.T) { + const providers, wantModels = 19, 333 + cfg, closeAll := fleetConfig([3]int{200, 200, 200}, fleetCachedBody, 100) + defer closeAll() + cfg.Providers = map[string]*ProviderConfig{} + for p := 0; p < providers; p++ { + count := wantModels / providers + if p < wantModels%providers { + count++ + } + models := make([]string, count) + for m := range models { + models[m] = fmt.Sprintf("m%02d", m) + } + cfg.Providers[fmt.Sprintf("p%02d", p)] = &ProviderConfig{Type: "openai", BaseURL: "http://x.invalid", APIKey: "k", Models: models} + } + cfg.SmartRouters = nil + store := &keyCountStore{counterStore: newMemoryStore()} + gw := fleetGateway(t, cfg, store) + require.Len(t, gw.catalogModelScopeIDs(), wantModels) + + out := scrape(gw) + require.Contains(t, out, "llmgateway_limit_store_up 1") + assert.LessOrEqual(t, store.total.Load(), int64(adminMaxKeysPerRequest), "one scrape") + assert.LessOrEqual(t, store.maxOne.Load(), int64(usageModelsChunkKeys), "every read is chunked") + t.Logf("scrape keys for %d models: %d (max per call %d)", len(gw.catalogModelScopeIDs()), store.total.Load(), store.maxOne.Load()) +} + +func TestFleetMetricsFallsBackWhenPrerequisiteOff(t *testing.T) { + cfg, closeAll := fleetConfig([3]int{200, 200, 200}, fleetCachedBody, 100) + defer closeAll() + cfg.Admin.Stats.Latency = false + gw := fleetGateway(t, cfg, newMemoryStore()) + require.Equal(t, 200, routerChat(t, gw, routerName, "hi", nil).Code) + + out := scrape(gw) + assert.Contains(t, out, `llmgateway_upstream_duration_seconds_count{provider="alpha",stream="false"} 1`, "latency stays in memory without statsLatency") + help := fleetHelp(t, gw, "llmgateway_upstream_duration_seconds") + assert.Contains(t, help, "aggregate with sum()") + assert.Contains(t, fleetHelp(t, gw, "llmgateway_router_requests_total"), "aggregate with max()", "router stays store-backed") +} diff --git a/limits.go b/limits.go index ef11446..bdd85e7 100644 --- a/limits.go +++ b/limits.go @@ -1908,6 +1908,9 @@ func (l *limiter) settleRejection(entries []counterIncr, violatedIdx int, scopes if totalPresent { comp = append(comp, rejectionCounterIncr(totalScopeKind, totalScopeID, windowDay, wb.day, et.day)) } + if l.store != nil { + comp = append(comp, rejectionCounterIncr(violated.kind, violated.id, windowMonth, wb.month, et.month)) + } // rej/hour (always-on-with-admin, DECISIONS): rides this SAME // compensation batch, never a second round trip, alongside the // existing always-on rej/day entries above. @@ -1924,13 +1927,16 @@ func (l *limiter) settleRejection(entries []counterIncr, violatedIdx int, scopes // rejectionCounterIncr builds the single rej counterIncr entry // settleRejection adds per scope it attributes a rejection to, for window -// (windowDay, always-on; windowHour, admin-gated) — delta 1, ttl the -// window's own matching constant (dayWindowTTL/hourWindowTTL), enforceTTL -// the caller's own et.day/et.hour. +// (windowDay, always-on; windowHour, admin-gated; windowMonth, store-only, +// read by /metrics) — delta 1, ttl the window's own matching constant, +// enforceTTL the caller's own et value. func rejectionCounterIncr(kind, id, window, bucket string, enforceTTL time.Duration) counterIncr { ttl := dayWindowTTL - if window == windowHour { + switch window { + case windowHour: ttl = hourWindowTTL + case windowMonth: + ttl = monthWindowTTL } return counterIncr{key: windowKeyForBucket(kind, id, metricRej, window, bucket), delta: 1, ttl: ttl, enforceTTL: enforceTTL} } @@ -2267,7 +2273,7 @@ func latencyCounterEntries(kind, id string, lat latencySample, wb windowBuckets, counterIncr{key: windowKeyForBucket(kind, id, ttfbMetric, windowDay, wb.day), delta: 1, ttl: dayWindowTTL, enforceTTL: et.day}, ) } - return out + return append(out, fleetLatencyEntries(kind, id, lat, wb, et)...) } // recordCacheHit accounts one response-cache HIT (Q7, DECISIONS: diff --git a/metrics.go b/metrics.go index 7a74252..1654c48 100644 --- a/metrics.go +++ b/metrics.go @@ -1054,6 +1054,15 @@ func (g *Gateway) recordLatency(provider, model string, sample latencySample) { // writeRejectionMetrics' own sort.Slice above. func (g *Gateway) writeLatencyMetrics(m *metricWriter) { snaps := g.latency.snapshot() + note := aggregationNoteLatency + if g.fleetLatencyEnabled() { + fleet, ok := g.fleetLatencySnapshots() + if !ok { + return + } + snaps = fleet + note = aggregationNoteStoreBacked + } if len(snaps) == 0 { return } @@ -1084,18 +1093,18 @@ func (g *Gateway) writeLatencyMetrics(m *metricWriter) { } writeUpstreamLatencyFamily(m, "llmgateway_upstream_ttfb_seconds", - "Time to first successful byte read from an upstream response body, in seconds, measured from just before the request was sent (watchdogBody, timeout.go). Meaningful as a distinct \"how fast did the provider start responding\" signal only for stream=\"true\": a non-streaming provider buffers its whole completion before sending anything, so its own TTFB is approximately equal to its own llmgateway_upstream_duration_seconds and carries the same output-length contamination duration does — always split by the stream label before comparing across requests of different lengths, never averaged across it."+aggregationNoteLatency, + "Time to first successful byte read from an upstream response body, in seconds, measured from just before the request was sent (watchdogBody, timeout.go). Meaningful as a distinct \"how fast did the provider start responding\" signal only for stream=\"true\": a non-streaming provider buffers its whole completion before sending anything, so its own TTFB is approximately equal to its own llmgateway_upstream_duration_seconds and carries the same output-length contamination duration does — always split by the stream label before comparing across requests of different lengths, never averaged across it."+note, "llmgateway_upstream_duration_seconds", - "Total upstream response body duration, in seconds, from just before the request was sent to the last successful read or Close (watchdogBody, timeout.go) — covers the whole body, not just headers. Roughly TTFB + output_tokens/tokens_per_sec: a long generation legitimately takes longer than a short one on an equally healthy provider, so a raw average across requests of very different output length is not by itself a \"provider degraded\" signal — llmgateway_tokens_total's completion direction (this file) gives the token side of that ratio for the non-streaming population, where duration approximates total generation time."+aggregationNoteLatency, + "Total upstream response body duration, in seconds, from just before the request was sent to the last successful read or Close (watchdogBody, timeout.go) — covers the whole body, not just headers. Roughly TTFB + output_tokens/tokens_per_sec: a long generation legitimately takes longer than a short one on an equally healthy provider, so a raw average across requests of very different output length is not by itself a \"provider degraded\" signal — llmgateway_tokens_total's completion direction (this file) gives the token side of that ratio for the non-streaming population, where duration approximates total generation time."+note, base, false) if len(withModel) == 0 { return } writeUpstreamLatencyFamily(m, "llmgateway_upstream_model_ttfb_seconds", - "Time to first successful byte read from an upstream response body, in seconds, by provider, stream, and model. Opt-in via metrics.modelLabel — see MetricsConfig's own doc comment for the cardinality trade-off. A separate metric name from llmgateway_upstream_ttfb_seconds (M4 fix), not the same series with an extra label, so summing one family never double-counts the other's requests."+aggregationNoteLatency, + "Time to first successful byte read from an upstream response body, in seconds, by provider, stream, and model. Opt-in via metrics.modelLabel — see MetricsConfig's own doc comment for the cardinality trade-off. A separate metric name from llmgateway_upstream_ttfb_seconds (M4 fix), not the same series with an extra label, so summing one family never double-counts the other's requests."+note, "llmgateway_upstream_model_duration_seconds", - "Total upstream response body duration, in seconds, by provider, stream, and model. Opt-in via metrics.modelLabel. A separate metric name from llmgateway_upstream_duration_seconds (M4 fix), not the same series with an extra label, so summing one family never double-counts the other's requests."+aggregationNoteLatency, + "Total upstream response body duration, in seconds, by provider, stream, and model. Opt-in via metrics.modelLabel. A separate metric name from llmgateway_upstream_duration_seconds (M4 fix), not the same series with an extra label, so summing one family never double-counts the other's requests."+note, withModel, true) } @@ -1254,6 +1263,7 @@ func (s *provenanceStore) snapshot() []provenanceSnapshot { // with metrics off calls this exactly zero times. func (g *Gateway) recordUsageProvenance(provider, provenance string, tokens int64) { g.provenance.record(provider, provenance, tokens) + g.countProvenanceShared(provider, provenance, tokens) } // writeProvenanceMetrics emits llmgateway_usage_provenance_requests_total @@ -1267,6 +1277,15 @@ func (g *Gateway) recordUsageProvenance(provider, provenance string, tokens int6 // writeLatencyMetrics' own reasoning. func (g *Gateway) writeProvenanceMetrics(m *metricWriter) { snaps := g.provenance.snapshot() + note := aggregationNotePerProcess + if g.fleetStore() { + fleet, ok := g.fleetProvenance() + if !ok { + return + } + snaps = fleet + note = aggregationNoteStoreBacked + } if len(snaps) == 0 { return } @@ -1284,14 +1303,14 @@ func (g *Gateway) writeProvenanceMetrics(m *metricWriter) { // exposition format requires one metric's lines to form a single // contiguous group. m.family("llmgateway_usage_provenance_requests_total", "counter", - "Total accounted candidate outcomes (a successful upstream response, callErr == nil, that reached usage accounting in runUnified, routes_unified.go), by provider and provenance. provenance is \"reported\" (the provider returned real usage), \"estimated\" (a non-streaming response carried none, so prompt was substituted with ceil(len(body)/4) and completion billed as zero — usage.estimated, limits.go), or \"unbilled\" (a streaming response carried none, so the request is counted but zero tokens are billed). This family only reports how an already-billed number was arrived at; it never changes what gets billed."+aggregationNotePerProcess) + "Total accounted candidate outcomes (a successful upstream response, callErr == nil, that reached usage accounting in runUnified, routes_unified.go), by provider and provenance. provenance is \"reported\" (the provider returned real usage), \"estimated\" (a non-streaming response carried none, so prompt was substituted with ceil(len(body)/4) and completion billed as zero — usage.estimated, limits.go), or \"unbilled\" (a streaming response carried none, so the request is counted but zero tokens are billed). This family only reports how an already-billed number was arrived at; it never changes what gets billed."+note) for _, s := range snaps { m.sampleInt("llmgateway_usage_provenance_requests_total", []metricLabel{{"provider", s.key.provider}, {"provenance", s.key.provenance}}, s.requests) } m.family("llmgateway_usage_provenance_tokens_total", "counter", - "Total tokens billed under each provenance (the SAME result.total() runUnified already passed to accounting, routes_unified.go — never a second, independent count), by provider and provenance. sum(...{provenance=\"reported\"}) / sum(...) across every provenance is the fraction of billed tokens that came from real provider-reported usage."+aggregationNotePerProcess) + "Total tokens billed under each provenance (the SAME result.total() runUnified already passed to accounting, routes_unified.go — never a second, independent count), by provider and provenance. sum(...{provenance=\"reported\"}) / sum(...) across every provenance is the fraction of billed tokens that came from real provider-reported usage."+note) for _, s := range snaps { m.sampleInt("llmgateway_usage_provenance_tokens_total", []metricLabel{{"provider", s.key.provider}, {"provenance", s.key.provenance}}, s.tokens) @@ -1308,6 +1327,10 @@ func (g *Gateway) writeProvenanceMetrics(m *metricWriter) { // -only, per-process-lifetime counter rather than a new windowed // counterStore key. func (g *Gateway) writeRejectionMetrics(m *metricWriter) { + if g.fleetStore() { + g.writeFleetRejectionMetrics(m) + return + } snaps := g.limiter.rejectionSnapshot() sort.Slice(snaps, func(i, j int) bool { if snaps[i].kind != snaps[j].kind { diff --git a/prompt_cache_stats.go b/prompt_cache_stats.go index e29ac99..16dae90 100644 --- a/prompt_cache_stats.go +++ b/prompt_cache_stats.go @@ -79,6 +79,15 @@ func unifiedPromptCacheSaved(canonical, bare string, u usage, overrides map[stri func (g *Gateway) writePromptCacheMetrics(m *metricWriter) { snap := g.promptCacheStats.snapshot() + note := aggregationNotePerProcess + if g.fleetStore() { + fleet, ok := g.fleetPromptCache() + if !ok { + return + } + snap = fleet + note = aggregationNoteStoreBacked + } if len(snap) == 0 { return } @@ -97,7 +106,7 @@ func (g *Gateway) writePromptCacheMetrics(m *metricWriter) { 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) + "Prompt tokens by provider, model and kind (read: served from the provider prompt cache, write: written to it, uncached: neither)."+note) for _, k := range keys { m.sampleInt("llmgateway_prompt_cache_tokens_total", []metricLabel{{"provider", k.provider}, {"model", k.model}, {"kind", k.kind}}, snap[k]) diff --git a/smart_router_metrics.go b/smart_router_metrics.go index b668308..551a47f 100644 --- a/smart_router_metrics.go +++ b/smart_router_metrics.go @@ -318,10 +318,38 @@ func decisionAnswered(outcome string) bool { return outcome == decisionAgree || outcome == decisionOverride || outcome == decisionLowConf || outcome == decisionCache } +// routerMetricSet is the counter source one scrape renders the router families from. +type routerMetricSet struct { + reqs map[routerRequestKey]int64 + escs map[routerEscalationKey]int64 + decs map[routerDecisionKey]int64 + decMx map[routerDecisionTierKey]int64 + note string +} + +// routerMetricSource reads the shared counters when the store backs them, else this pod's own. +// ok is false when the shared read fails, so the scrape skips the families. +func (g *Gateway) routerMetricSource() (routerMetricSet, bool) { + if g.routerSharedEnabled() { + c, ok := g.readRouterShared(g.limiter.now()) + if !ok { + return routerMetricSet{}, false + } + return routerMetricSet{reqs: c.reqs, escs: c.escs, decs: c.decs, decMx: c.decMx, note: aggregationNoteStoreBacked}, true + } + reqs, escs := g.routerStats.snapshot() + decs, decMx := g.routerStats.decisionSnapshot() + return routerMetricSet{reqs: reqs, escs: escs, decs: decs, decMx: decMx, note: aggregationNotePerProcess}, true +} + // writeRouterMetrics emits the router counter families; absent until the first observation. func (g *Gateway) writeRouterMetrics(m *metricWriter) { g.writeRouterCalibrationMetrics(m) - reqs, escs := g.routerStats.snapshot() + src, ok := g.routerMetricSource() + if !ok { + return + } + reqs, escs, note := src.reqs, src.escs, src.note if len(reqs) > 0 { keys := make([]routerRequestKey, 0, len(reqs)) for k := range reqs { @@ -338,13 +366,13 @@ func (g *Gateway) writeRouterMetrics(m *metricWriter) { return x.reason < y.reason }) m.family("llmgateway_router_requests_total", "counter", - "Smart router requests by router, first attempted tier and routing reason (score, keyword, floor, model, default, or skipped when lower tiers had no usable target)."+aggregationNotePerProcess) + "Smart router requests by router, first attempted tier and routing reason (score, keyword, floor, model, default, or skipped when lower tiers had no usable target)."+note) for _, k := range keys { m.sampleInt("llmgateway_router_requests_total", []metricLabel{{"router", k.router}, {"tier", k.tier}, {"reason", k.reason}}, reqs[k]) } } - g.writeRouterDecisionMetrics(m) + g.writeRouterDecisionMetrics(m, src) if len(escs) > 0 { keys := make([]routerEscalationKey, 0, len(escs)) for k := range escs { @@ -361,7 +389,7 @@ func (g *Gateway) writeRouterMetrics(m *metricWriter) { return x.to < y.to }) m.family("llmgateway_router_escalations_total", "counter", - "Smart router attempts that moved to a higher tier after a failure, by router, from_tier and to_tier. Same-tier failover is not counted."+aggregationNotePerProcess) + "Smart router attempts that moved to a higher tier after a failure, by router, from_tier and to_tier. Same-tier failover is not counted."+note) for _, k := range keys { m.sampleInt("llmgateway_router_escalations_total", []metricLabel{{"router", k.router}, {"from_tier", k.from}, {"to_tier", k.to}}, escs[k]) @@ -369,8 +397,8 @@ func (g *Gateway) writeRouterMetrics(m *metricWriter) { } } -func (g *Gateway) writeRouterDecisionMetrics(m *metricWriter) { - dec, mx := g.routerStats.decisionSnapshot() +func (g *Gateway) writeRouterDecisionMetrics(m *metricWriter, src routerMetricSet) { + dec, mx, note := src.decs, src.decMx, src.note if len(dec) > 0 { keys := make([]routerDecisionKey, 0, len(dec)) for k := range dec { @@ -383,7 +411,7 @@ func (g *Gateway) writeRouterDecisionMetrics(m *metricWriter) { return keys[a].outcome < keys[b].outcome }) m.family("llmgateway_router_decision_total", "counter", - "Smart router decision-model calls by router and outcome (agree, override, lowconf, timeout, error, breaker, cache)."+aggregationNotePerProcess) + "Smart router decision-model calls by router and outcome (agree, override, lowconf, timeout, error, breaker, cache)."+note) for _, k := range keys { m.sampleInt("llmgateway_router_decision_total", []metricLabel{{"router", k.router}, {"outcome", k.outcome}}, dec[k]) @@ -405,7 +433,7 @@ func (g *Gateway) writeRouterDecisionMetrics(m *metricWriter) { return x.model < y.model }) m.family("llmgateway_router_decision_tiers_total", "counter", - "Smart router answers from the decision model or its cache by router, heuristic tier and model-ranked tier."+aggregationNotePerProcess) + "Smart router answers from the decision model or its cache by router, heuristic tier and model-ranked tier."+note) for _, k := range keys { m.sampleInt("llmgateway_router_decision_tiers_total", []metricLabel{{"router", k.router}, {"heuristic", k.heuristic}, {"model", k.model}}, mx[k]) diff --git a/stats_write_test.go b/stats_write_test.go index 358b138..0a3b8a9 100644 --- a/stats_write_test.go +++ b/stats_write_test.go @@ -158,7 +158,9 @@ func TestRoundTrips_SingleGroupChat_Defaults_TwoSyncOneAsync(t *testing.T) { // this is a SEPARATE async call, not a batch this one rides. 2 sync + 2 // async = 4 total, once per admitted request from a scope l.lastSeen.due // has not already throttled within lastSeenGateThrottle (60s) — a fresh -// limiter's first request for a scope, as this test drives. +// limiter's first request for a scope, as this test drives. With metrics +// on and a store, the usage-provenance mirror (countProvenanceShared) adds a +// fifth, async round trip. func TestRoundTrips_SingleGroupChat_AllStatsOn_NoNewSyncRoundTrips(t *testing.T) { srv := roundTripTestUpstream(t) gw, counting := buildRoundTripTestGateway(t, srv, func(cfg *Config) { @@ -174,8 +176,8 @@ func TestRoundTrips_SingleGroupChat_AllStatsOn_NoNewSyncRoundTrips(t *testing.T) got := counting.total() t.Logf("AFTER (admin.stats.userModel=true, admin.stats.latency=true, metrics on, no cache): %d counterStore round trips for the SAME single-group chat request", got) - if got != 4 { - t.Errorf("round trips with all stats on = %d, want 4 (2 sync + 2 async: checkAndCount, accountWith, recordProviderAttempt, recordLastSeen) — every new counter family rides an EXISTING sync batch except last-seen, which is its own async write by design (P9 fix)", got) + if got != 5 { + t.Errorf("round trips with all stats on = %d, want 5 (2 sync + 3 async: checkAndCount, accountWith, recordProviderAttempt, recordLastSeen, provenance) — every new counter family rides an EXISTING sync batch except last-seen and, with metrics on, provenance, which are their own async writes by design", got) } }