feat: per-session token burn in logs, monitor rings, and usage snapshots

Every anonymous-lane session draws from one shared upstream IP bucket,
but nothing showed which conversation was draining it. Carry the
canonical ses_ ID into RequestMeta and the request_routed line, the
recent-request ring, and per-model/per-tier style usageSessions maps in
both lifetime and hourly snapshots.

The lifetime sessions map is capped at 500 entries (smallest-first
eviction): session IDs are high-cardinality and an unbounded map grows
forever. Buckets and snapshots are short-lived and stay uncapped.
This commit is contained in:
sk-dev-ai committed 2026-10-14 17:31:40 +05:30
1 parent 61769a9b9f
commit 773b64bf9e
3 files changed
+55 -12

No files matched your search

+2
View File
@@ -178,6 +178,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)
@@ -339,6 +340,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()
+15 -10
View File
@@ -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)
}
+38 -2
View File
@@ -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"`
@@ -307,10 +314,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)
addCappedSessionTokens(m.lifetimeUsage.Sessions, 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 +458,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 +505,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 +538,37 @@ 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; evict the smallest entry when full. Buckets and snapshots are
// short-lived and stay uncapped.
const maxLifetimeSessions = 500
func addCappedSessionTokens(target map[string]TokenCounts, key string, value TokenCounts) {
if key == "" {
return
}
if _, ok := target[key]; !ok && len(target) >= maxLifetimeSessions {
victim, victimTotal := "", uint64(0)
first := true
for k, v := range target {
if first || v.Total < victimTotal {
victim, victimTotal, first = k, v.Total, false
}
}
if victim != "" {
delete(target, victim)
}
}
addTokenMap(target, key, value)
}
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
}