diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 88bda9e..de8c6a0 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -196,6 +196,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { ids := identity.DeriveRequestIDs(r, payload) if meta != nil { meta.Request = ids.Request + meta.Session = ids.Session } stream := jsonutil.BoolAt(payload, "stream") requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second) @@ -367,6 +368,7 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body ids := identity.DeriveRequestIDs(r, payload) if meta != nil { meta.Request = ids.Request + meta.Session = ids.Session } requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second) defer cancel() diff --git a/internal/gateway/rotation.go b/internal/gateway/rotation.go index c858ffa..c3845cb 100644 --- a/internal/gateway/rotation.go +++ b/internal/gateway/rotation.go @@ -70,6 +70,7 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa meta := telemetry.MetaFromRequest(r) if meta != nil { meta.Request = ids.Request + meta.Session = ids.Session meta.ModelAlias = alias } visited := map[string]bool{} diff --git a/internal/telemetry/http.go b/internal/telemetry/http.go index 36f5f92..8f9cedd 100644 --- a/internal/telemetry/http.go +++ b/internal/telemetry/http.go @@ -17,15 +17,20 @@ type RequestMeta struct { Tier string Protocol protocol.Protocol Request string - KeyID string - Channel string - Anonymous bool - Proxy string - Attempts int - Legs []string - Stop string - Tail string - Stream bool + // Session is the canonical upstream session (ses_...). All turns of one + // conversation share it, so per-session token burn is visible in logs + // and monitoring: every session draws from the same upstream IP bucket + // on the anonymous lane. + Session string + KeyID string + Channel string + Anonymous bool + Proxy string + Attempts int + Legs []string + Stop string + Tail string + Stream bool // Shaped marks a key-tier free-model request whose wire body was // normalized to agent shape (stream + core tools) like the anonymous // lane. Non-streaming responses for shaped requests arrive as SSE @@ -112,7 +117,7 @@ func Middleware(monitor *Monitor, logger *slog.Logger, next http.Handler) http.H if meta.Channel != "" { logger.Info("request routed", "component", "http", "event", "request_routed", "method", r.Method, "path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "request_id", meta.Request, - "model", meta.Model, "model_alias", meta.ModelAlias, "tier", meta.Tier, "key_id", meta.KeyID, "channel", meta.Channel, + "model", meta.Model, "model_alias", meta.ModelAlias, "session", meta.Session, "tier", meta.Tier, "key_id", meta.KeyID, "channel", meta.Channel, "anonymous", meta.Anonymous, "attempts", meta.Attempts, "legs", strings.Join(meta.Legs, " "), "stream", meta.Stream, "outcome", outcome, "stop", meta.Stop, "in", meta.Usage.Input, "out", meta.Usage.Output, "reasoning_tokens", meta.Usage.Reasoning, "cached", meta.Usage.Cached, "tail", meta.Tail) } diff --git a/internal/telemetry/metrics.go b/internal/telemetry/metrics.go index f280a9f..e76683b 100644 --- a/internal/telemetry/metrics.go +++ b/internal/telemetry/metrics.go @@ -25,6 +25,7 @@ type metricBucket struct { tokens TokenCounts usageModels map[string]TokenCounts usageTiers map[string]TokenCounts + usageSessions map[string]TokenCounts } func (b *metricBucket) reset(minute int64) { @@ -32,6 +33,7 @@ func (b *metricBucket) reset(minute int64) { minute: minute, endpoints: make(map[string]uint64), models: make(map[string]uint64), tiers: make(map[string]uint64), statuses: make(map[string]uint64), usageModels: make(map[string]TokenCounts), usageTiers: make(map[string]TokenCounts), + usageSessions: make(map[string]TokenCounts), } } @@ -50,6 +52,10 @@ type UsagePeriod struct { Tokens TokenCounts `json:"tokens"` Models map[string]TokenCounts `json:"models"` Tiers map[string]TokenCounts `json:"tiers"` + // Sessions maps canonical session ID to token burn. Sessions share one + // upstream IP bucket on the anonymous lane, so this shows which + // conversation is draining the daily budget. + Sessions map[string]TokenCounts `json:"sessions"` } type UsageSnapshot struct { @@ -93,6 +99,7 @@ type UpstreamAttempt struct { type UpstreamRequest struct { Time time.Time `json:"time"` RequestID string `json:"request_id"` + Session string `json:"session,omitempty"` Model string `json:"model"` Tier string `json:"tier,omitempty"` KeyID string `json:"key_id,omitempty"` @@ -232,6 +239,7 @@ type Monitor struct { mu sync.Mutex buckets [60]metricBucket lifetimeUsage UsagePeriod + sessionSeen map[string]int64 attemptLifetime AttemptAggregate attemptBuckets [60]attemptBucket recentRequests upstreamRequestRing @@ -242,6 +250,7 @@ func NewMonitor() *Monitor { return &Monitor{ started: time.Now().UTC(), lifetimeUsage: newUsagePeriod(), + sessionSeen: make(map[string]int64), attemptLifetime: newAttemptAggregate(), recentRequests: newUpstreamRequestRing(), recentAttempts: newUpstreamAttemptRing(), @@ -307,10 +316,12 @@ func (m *Monitor) Record(endpoint string, status int, duration time.Duration, me addTokenMap(bucket.usageTiers, meta.Tier, tokens) addTokenMap(m.lifetimeUsage.Models, meta.Model, tokens) addTokenMap(m.lifetimeUsage.Tiers, meta.Tier, tokens) + addTokenMap(bucket.usageSessions, meta.Session, tokens) + m.addLifetimeSessionLocked(meta.Session, tokens) } if meta.Request != "" && meta.Model != "" { request := UpstreamRequest{ - Time: time.Now().UTC(), RequestID: meta.Request, Model: meta.Model, Tier: meta.Tier, + Time: time.Now().UTC(), RequestID: meta.Request, Session: meta.Session, Model: meta.Model, Tier: meta.Tier, KeyID: meta.KeyID, Channel: meta.Channel, Anonymous: meta.Anonymous, Proxy: meta.Proxy, Attempts: meta.Attempts, Status: status, DurationMS: max(duration.Milliseconds(), 0), Success: success, @@ -449,6 +460,7 @@ func (m *Monitor) Snapshot() MonitorSnapshot { addTokenCounts(&usageWindow.Tokens, bucket.tokens) mergeTokenMaps(usageWindow.Models, bucket.usageModels) mergeTokenMaps(usageWindow.Tiers, bucket.usageTiers) + mergeTokenMaps(usageWindow.Sessions, bucket.usageSessions) } attemptBucket := &m.attemptBuckets[minute%60] if attemptBucket.minute == minute { @@ -495,7 +507,7 @@ func mergeCounts(target, source map[string]uint64) { } func newUsagePeriod() UsagePeriod { - return UsagePeriod{Models: make(map[string]TokenCounts), Tiers: make(map[string]TokenCounts)} + return UsagePeriod{Models: make(map[string]TokenCounts), Tiers: make(map[string]TokenCounts), Sessions: make(map[string]TokenCounts)} } func tokenCounts(usage protocol.Usage) TokenCounts { @@ -528,11 +540,38 @@ func mergeTokenMaps(target, source map[string]TokenCounts) { } } +// maxLifetimeSessions bounds the lifetime per-session burn map. Session IDs +// are high-cardinality (one per conversation), so an unbounded map grows +// forever. When full, the least recently seen session is evicted: evicting the +// smallest total would drop the newest conversation first, so every new +// session would push out the previous one. Buckets and snapshots are +// short-lived and stay uncapped. +const maxLifetimeSessions = 500 + +func (m *Monitor) addLifetimeSessionLocked(session string, tokens TokenCounts) { + if session == "" { + return + } + if _, ok := m.lifetimeUsage.Sessions[session]; !ok && len(m.lifetimeUsage.Sessions) >= maxLifetimeSessions { + victim, oldest := "", int64(0) + for key, seen := range m.sessionSeen { + if victim == "" || seen < oldest { + victim, oldest = key, seen + } + } + delete(m.lifetimeUsage.Sessions, victim) + delete(m.sessionSeen, victim) + } + m.sessionSeen[session] = time.Now().UnixNano() + addTokenMap(m.lifetimeUsage.Sessions, session, tokens) +} + func cloneUsagePeriod(source UsagePeriod) UsagePeriod { result := newUsagePeriod() result.Requests, result.Reported, result.Tokens = source.Requests, source.Reported, source.Tokens mergeTokenMaps(result.Models, source.Models) mergeTokenMaps(result.Tiers, source.Tiers) + mergeTokenMaps(result.Sessions, source.Sessions) return result }