Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
usage: one gateway session projection is kept, and a range of days is read out of it (#2776)
yetonee7114d3882e6
diff --git a/internal/usage/gateway_sessions.go b/internal/usage/gateway_sessions.goindex 888afc7ab..8eb143629 100644--- a/internal/usage/gateway_sessions.go+++ b/internal/usage/gateway_sessions.go@@ -4,6 +4,7 @@ import ("slices""sort""sync"+ "sync/atomic""time""github.com/yetone/magpie/internal/catalog"@@ -26,6 +27,10 @@ type GatewayDayUsage struct {sessions.TokensCost float64Priced bool+ // first and last bound the day's requests (last includes the request's+ // own duration), so a session seen from a later midnight is derived+ // from the one kept projection instead of a second copy (#2776).+ first, last time.Time}// GatewaySession is a read-only projection of requests served by this@@ -54,16 +59,105 @@ type GatewayModel struct {// history or agent files. NativeKeys contains identities already represented// by local session files and is used to suppress the duplicate projection.func GatewaySessions(since time.Time, nativeKeys map[string]bool) []GatewaySession {- e := gatewayProjection(since)- out := make([]GatewaySession, 0, len(e.sessions))- for _, s := range e.sessions {- if !nativeKeys[s.Agent+"|"+s.ID] {- out = append(out, cloneGatewaySession(s))+ if since.IsZero() {+ e := gatewayProjection()+ out := make([]GatewaySession, 0, len(e.sessions))+ for _, s := range e.sessions {+ if !nativeKeys[s.Agent+"|"+s.ID] {+ out = append(out, cloneGatewaySession(s))+ }+ }+ return out+ }+ if date, ok := localMidnight(since); ok {+ // a range of whole days is the all-time projection's days from+ // its first on: no copy of it is kept per range (#2776)+ e := gatewayProjection()+ out := make([]GatewaySession, 0, len(e.sessions))+ for _, s := range e.sessions {+ if nativeKeys[s.Agent+"|"+s.ID] || !s.Last.After(since) {+ continue+ }+ if w, ok := gatewaySessionFrom(s, date); ok {+ out = append(out, w)+ }}+ return out}+ // any other start is read from the log, and not kept+ snapshot := readLogSnapshot()+ out, _ := buildGatewaySessions(snapshot, since, nativeKeys)return out}+// localMidnight is since's local date when since is that date's start.+func localMidnight(since time.Time) (string, bool) {+ date := since.In(time.Local).Format(time.DateOnly)+ start, err := time.ParseInLocation(time.DateOnly, date, time.Local)+ return date, err == nil && start.Equal(since)+}++// gatewaySessionFrom is s as it was read from the start of date on: its+// days from then, and its models, tokens, cost and times summed from them.+func gatewaySessionFrom(s GatewaySession, date string) (GatewaySession, bool) {+ i := sort.Search(len(s.Daily), func(i int) bool { return s.Daily[i].Date >= date })+ if i == len(s.Daily) {+ return GatewaySession{}, false+ }+ if i == 0 {+ return cloneGatewaySession(s), true+ }+ w := GatewaySession{Agent: s.Agent, ID: s.ID, Models: []GatewayModel{}, Daily: slices.Clone(s.Daily[i:])}+ models := map[string]int{} // index in w.Models, which grows+ for _, d := range w.Daily {+ if w.Start.IsZero() || d.first.Before(w.Start) {+ w.Start = d.first+ }+ if d.last.After(w.Last) {+ w.Last = d.last+ }+ w.Input += d.Input+ w.Output += d.Output+ w.CacheRead += d.CacheRead+ w.CacheWrite += d.CacheWrite+ w.CacheWrite1h += d.CacheWrite1h+ at, ok := models[d.Model]+ if !ok {+ at = len(w.Models)+ w.Models = append(w.Models, GatewayModel{Model: d.Model, Priced: true})+ models[d.Model] = at+ }+ m := &w.Models[at]+ m.Input += d.Input+ m.Output += d.Output+ m.CacheRead += d.CacheRead+ m.CacheWrite += d.CacheWrite+ m.CacheWrite1h += d.CacheWrite1h+ m.Cost += d.Cost+ m.Priced = m.Priced && d.Priced+ }+ finishGatewayModels(&w)+ return w, true+}++// finishGatewayModels sums s's models' cost into it, counts those not priced+// and puts the models in order, the most tokens first.+func finishGatewayModels(s *GatewaySession) {+ for _, m := range s.Models {+ s.Cost += m.Cost+ if !m.Priced && m.Input+m.Output > 0 {+ s.Unpriced+++ }+ }+ sort.Slice(s.Models, func(i, j int) bool {+ a, b := s.Models[i], s.Models[j]+ if a.Input+a.Output != b.Input+b.Output {+ return a.Input+a.Output > b.Input+b.Output+ }+ return a.Model < b.Model+ })+}+func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySession, bool) {if id == "" {return GatewaySession{}, false@@ -72,7 +166,7 @@ func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySeif nativeKeys[agent+"|"+id] {return GatewaySession{}, false}- entry := gatewayProjection(time.Time{})+ entry := gatewayProjection()i, ok := entry.byID[agent+"|"+id]if !ok {return GatewaySession{}, false@@ -83,42 +177,37 @@ func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySetype gatewayProjectionEntry struct {version uint64meta string- since time.Time+ zone *time.Location // the zone its days are dates insessions []GatewaySessionbyID map[string]int}+// gatewayCache keeps one projection, of all time, not one copy for every+// native exclusion set or range: a range of days is read out of it. With+// ~600k calls each range kept was another ~37 MB, four of them at once+// (#2776). The log snapshot version also detects rewrites and changes of+// config directory.var gatewayCache struct {sync.Mutex- entries []gatewayProjectionEntry+ entry *gatewayProjectionEntry}-// Retain a few window projections, not one copy for every native exclusion set.-// The log snapshot version also detects rewrites and changes of config directory.-func gatewayProjection(since time.Time) gatewayProjectionEntry {+func gatewayProjection() gatewayProjectionEntry {snapshot := readLogSnapshot()meta := usagePriceCacheKey(time.Now())gatewayCache.Lock()defer gatewayCache.Unlock()- for _, e := range gatewayCache.entries {- if e.version == snapshot.version && e.meta == meta && e.since.Equal(since) {- return e- }+ if e := gatewayCache.entry; e != nil && e.version == snapshot.version && e.meta == meta && e.zone == time.Local {+ return *e}- ss, _ := buildGatewaySessions(snapshot, since, nil)- e := gatewayProjectionEntry{version: snapshot.version, meta: meta, since: since, sessions: ss, byID: make(map[string]int, len(ss))}+ ss, _ := buildGatewaySessions(snapshot, time.Time{}, nil)+ e := gatewayProjectionEntry{version: snapshot.version, meta: meta, zone: time.Local, sessions: ss, byID: make(map[string]int, len(ss))}for i, s := range ss {e.byID[s.Agent+"|"+s.ID] = i}// A failed or partial read must be retried, not published as current.if snapshot.info != nil && snapshot.off == snapshot.info.Size() {- gatewayCache.entries = slices.DeleteFunc(gatewayCache.entries, func(old gatewayProjectionEntry) bool {- return old.version != e.version || old.meta != e.meta || old.since.Equal(since)- })- if len(gatewayCache.entries) >= 4 {- gatewayCache.entries = gatewayCache.entries[1:]- }- gatewayCache.entries = append(gatewayCache.entries, e)+ gatewayCache.entry = &e}return e}@@ -170,7 +259,11 @@ func gatewayDays(ss []GatewaySession) []GatewayDayUsage {return out}+// gatewayBuilds counts the projections built from the log, for tests.+var gatewayBuilds atomic.Int64+func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage) {+ gatewayBuilds.Add(1)priceOf := Pricer()type key struct{ agent, id string }groups := map[key]*GatewaySession{}@@ -199,7 +292,8 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys mapif s.Start.IsZero() || r.Time.Before(s.Start) {s.Start = r.Time}- if end := r.Time.Add(time.Duration(max(0, r.Millis)) * time.Millisecond); end.After(s.Last) {+ end := r.Time.Add(time.Duration(max(0, r.Millis)) * time.Millisecond)+ if end.After(s.Last) {s.Last = end}p := priceOf(r)@@ -226,6 +320,12 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys mapd.CacheWrite1h += tokens.CacheWrite1hd.Cost += costd.Priced = d.Priced && priced+ if d.first.IsZero() || r.Time.Before(d.first) {+ d.first = r.Time+ }+ if end.After(d.last) {+ d.last = end+ }}s.Input += r.Inputs.Output += r.Output@@ -251,18 +351,8 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map})for _, m := range models[k] {s.Models = append(s.Models, *m)- s.Cost += m.Cost- if !m.Priced && m.Input+m.Output > 0 {- s.Unpriced++- }}- sort.Slice(s.Models, func(i, j int) bool {- a, b := s.Models[i], s.Models[j]- if a.Input+a.Output != b.Input+b.Output {- return a.Input+a.Output > b.Input+b.Output- }- return a.Model < b.Model- })+ finishGatewayModels(s)}out := make([]GatewaySession, 0, len(groups))for _, s := range groups {diff --git a/internal/usage/gateway_sessions_test.go b/internal/usage/gateway_sessions_test.goindex 5158c5a76..f28dca083 100644--- a/internal/usage/gateway_sessions_test.go+++ b/internal/usage/gateway_sessions_test.go@@ -2,6 +2,7 @@ package usageimport ("github.com/yetone/magpie/internal/settings"+ "math""os""path/filepath""testing"@@ -116,3 +117,70 @@ func TestGatewaySessionsCachePricesWindowsAndRewrite(t *testing.T) {t.Fatalf("rewrite retained routing: %+v", got)}}++// A range of whole days is read out of the one all-time projection: no+// second copy is built or kept for it, and what it reads equals a direct+// build from that midnight (#2776).+func TestGatewayWindowsShareOneProjection(t *testing.T) {+ resetUsageTest(t)+ price := 3.0+ cfg := settings.Load()+ cfg.ModelPrices = map[string]settings.ModelPrice{"*/priced": {Input: &price, Output: &price, CacheRead: new(0.0), CacheWrite: new(0.0)}}+ if err := settings.Save(cfg); err != nil {+ t.Fatal(err)+ }+ today := time.Now()+ day := func(back int) time.Time {+ y, m, d := today.AddDate(0, 0, -back).Date()+ return time.Date(y, m, d, 0, 0, 0, 0, time.Local)+ }+ for back := 5; back >= 0; back-- {+ at := day(back).Add(10 * time.Hour)+ Append(Record{Time: at, Agent: "pi", Session: "long", Provider: "p", Model: "priced", Input: 1000 * (back + 1), Output: 7, Millis: 1500, Status: 200})+ Append(Record{Time: at.Add(time.Minute), Agent: "pi", Session: "long", Provider: "p", Model: "free", Input: 11, Output: 3, CacheRead: 5, Status: 200})+ if back%2 == 0 {+ Append(Record{Time: at.Add(2 * time.Minute), Agent: "codex", Session: "even", Provider: "p", Model: "priced", Input: 300, Output: 9, Millis: 250, Status: 200})+ }+ }+ Append(Record{Time: day(5).Add(time.Hour), Agent: "pi", Session: "old", Provider: "p", Model: "priced", Input: 9, Status: 200})++ key := func(ss []GatewaySession) map[string]GatewaySession {+ m := map[string]GatewaySession{}+ for _, s := range ss {+ m[s.Agent+"|"+s.ID] = s+ }+ return m+ }+ backs := []int{0, 1, 2, 3, 7}+ base := gatewayBuilds.Load()+ GatewaySessions(time.Time{}, nil)+ got := map[int][]GatewaySession{}+ for _, back := range backs {+ got[back] = GatewaySessions(day(back), nil)+ }+ if built := gatewayBuilds.Load() - base; built != 1 {+ t.Fatalf("built %d projections for one log and %d ranges, want 1 kept and shared by them all", built, len(backs))+ }+ for _, back := range backs {+ want, _ := buildGatewaySessions(readLogSnapshot(), day(back), nil)+ g, w := key(got[back]), key(want)+ if len(g) != len(w) {+ t.Fatalf("from %d days back: %d sessions, want %d: %+v", back, len(g), len(w), got[back])+ }+ for k, ws := range w {+ gs, ok := g[k]+ if !ok {+ t.Fatalf("from %d days back: %s missing", back, k)+ }+ if !gs.Start.Equal(ws.Start) || !gs.Last.Equal(ws.Last) || gs.Tokens != ws.Tokens || gs.Unpriced != ws.Unpriced || math.Abs(gs.Cost-ws.Cost) > 1e-9 || len(gs.Models) != len(ws.Models) || len(gs.Daily) != len(ws.Daily) {+ t.Fatalf("from %d days back, %s:\n got %+v\nwant %+v", back, k, gs, ws)+ }+ for i := range ws.Models {+ a, b := gs.Models[i], ws.Models[i]+ if a.Model != b.Model || a.Tokens != b.Tokens || a.Priced != b.Priced || math.Abs(a.Cost-b.Cost) > 1e-9 {+ t.Fatalf("from %d days back, %s model %d: got %+v want %+v", back, k, i, a, b)+ }+ }+ }+ }+}diff --git a/internal/usage/kept_strings_test.go b/internal/usage/kept_strings_test.goindex 0e03230de..4d50fe3e4 100644--- a/internal/usage/kept_strings_test.go+++ b/internal/usage/kept_strings_test.go@@ -63,7 +63,7 @@ func TestSessionCachesHoldNoDecodedBlocks(t *testing.T) {logIndex.Unlock()withCaches := held()gatewayCache.Lock()- gatewayCache.entries = nil+ gatewayCache.entry = nilgatewayCache.Unlock()viasCache.Lock()viasCache.value = nil