mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 16:04:01 +00:00
feat: per-session token burn in logs, monitor rings, and usage snapshots (#77)
Carry the canonical ses_ ID into RequestMeta, the request_routed line, the recent-request ring, and per-session usage maps in the lifetime and hourly snapshots, including rotation requests. The lifetime map keeps the 500 most recently seen sessions. Co-authored-by: sk-dev-ai <githubkrishsk@gmail.com>
This commit is contained in:
1 parent
16f68b84e8
commit
bbfe07133c
4 files changed
+59
-12
No files matched your search
@@ -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()
|
||||
|
||||
@@ -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{}
|
||||
|
||||
+15
-10
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user