buildGatewaySessions grew each session's Daily and Models an item at a
time from empty. The projection is kept for as long as the log is
unchanged, and so was the spare room append had left each list (five
days took eight). slices.Clip in gatewayProjection hides that room from
callers but doesn't free it. On the 720k-call sandbox, that append was
the largest single allocation of the build (319 MB of 1.14 GB), and the
lists are most of what the start keeps for the Sessions page.
Each list is now made at the size its map already counts.
TestGatewayProjectionKeepsNoSpareRoom builds 3000 sessions x 5 days
with one to five models each, and measures the heap the projection
keeps. The bound is its days and models x1.3, plus the sessions' list
and index. Fixed: 9,233,056 bytes, against a bound of 10,478,400. With
the two makes taken out by hand: red, 12,754,488 bytes.
720k-call sandbox, cold start, the four first asks together, the live
heap 20 s after them, back to back: 541 MB before, 479 MB after. The
machine's load was ~250-290 and the answers took ~140 s in both runs,
so their peak RSS (1395 and 1891 MB) measured the load, not this.
Run: go test -p 4 -count=1 ./internal/usage/: ok.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
410 lines
12 KiB
Go
410 lines
12 KiB
Go
package usage
|
|
|
|
import (
|
|
"slices"
|
|
"sort"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/catalog"
|
|
"github.com/yetone/magpie/internal/sessions"
|
|
)
|
|
|
|
// GatewaySessionWindow returns gateway sessions and their daily usage for a
|
|
// local-date range. It is kept separate from the GUI conversion so callers
|
|
// can use the same single usage-log snapshot for list and stats.
|
|
func GatewaySessionWindow(since time.Time) ([]GatewaySession, []GatewayDayUsage) {
|
|
return gatewaySessionSnapshot(since, nil)
|
|
}
|
|
|
|
func GatewaySessionWindowExcept(since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage) {
|
|
return gatewaySessionSnapshot(since, nativeKeys)
|
|
}
|
|
|
|
type GatewayDayUsage struct {
|
|
Date, Agent, Model string
|
|
sessions.Tokens
|
|
Cost float64
|
|
Priced 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
|
|
// gateway. Its identity is the agent name and the session id supplied by the
|
|
// client. Unidentified requests and generated recording identities are left out.
|
|
type GatewaySession struct {
|
|
Agent string `json:"agent"`
|
|
ID string `json:"id"`
|
|
Start time.Time `json:"start"`
|
|
Last time.Time `json:"last"`
|
|
Models []GatewayModel `json:"models"`
|
|
Daily []GatewayDayUsage `json:"-"`
|
|
sessions.Tokens
|
|
Cost float64 `json:"cost"`
|
|
Unpriced int `json:"unpriced"`
|
|
}
|
|
|
|
type GatewayModel struct {
|
|
Model string `json:"model"`
|
|
sessions.Tokens
|
|
Cost float64 `json:"cost"`
|
|
Priced bool `json:"priced"`
|
|
}
|
|
|
|
// GatewaySessions aggregates one usage snapshot without reading routing
|
|
// history or agent files. NativeKeys contains identities already represented
|
|
// by local session files and is used to suppress the duplicate projection.
|
|
//
|
|
// A session's Models and Daily are the kept projection's own, shared by
|
|
// every caller, which reads them and never changes them: each ask cloned
|
|
// every session's days, and the start's first asks together held ~450 MB
|
|
// of copies over ~720k calls (#2776). They are clipped, so an append
|
|
// makes a slice of the caller's own.
|
|
func GatewaySessions(since time.Time, nativeKeys map[string]bool) []GatewaySession {
|
|
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, 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 s, true
|
|
}
|
|
w := GatewaySession{Agent: s.Agent, ID: s.ID, Models: []GatewayModel{}, Daily: 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
|
|
}
|
|
agent = ReportedAs(agent)
|
|
if nativeKeys[agent+"|"+id] {
|
|
return GatewaySession{}, false
|
|
}
|
|
entry := gatewayProjection()
|
|
i, ok := entry.byID[agent+"|"+id]
|
|
if !ok {
|
|
return GatewaySession{}, false
|
|
}
|
|
return cloneGatewaySession(entry.sessions[i]), true
|
|
}
|
|
|
|
type gatewayProjectionEntry struct {
|
|
version uint64
|
|
meta string
|
|
zone *time.Location // the zone its days are dates in
|
|
sessions []GatewaySession
|
|
byID 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
|
|
entry *gatewayProjectionEntry
|
|
}
|
|
|
|
func gatewayProjection() gatewayProjectionEntry {
|
|
snapshot := readLogSnapshot()
|
|
meta := usagePriceCacheKey(time.Now())
|
|
gatewayCache.Lock()
|
|
defer gatewayCache.Unlock()
|
|
if e := gatewayCache.entry; e != nil && e.version == snapshot.version && e.meta == meta && e.zone == time.Local {
|
|
return *e
|
|
}
|
|
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
|
|
// handed out as they are: an append is the caller's own
|
|
ss[i].Models, ss[i].Daily = slices.Clip(s.Models), slices.Clip(s.Daily)
|
|
}
|
|
// A failed or partial read must be retried, not published as current.
|
|
if snapshot.info != nil && snapshot.off == snapshot.info.Size() {
|
|
gatewayCache.entry = &e
|
|
}
|
|
return e
|
|
}
|
|
|
|
func cloneGatewaySession(s GatewaySession) GatewaySession {
|
|
s.Models, s.Daily = slices.Clone(s.Models), slices.Clone(s.Daily)
|
|
return s
|
|
}
|
|
|
|
func gatewaySessionSnapshot(since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage) {
|
|
out := GatewaySessions(since, nativeKeys)
|
|
return out, gatewayDays(out)
|
|
}
|
|
|
|
func gatewayDays(ss []GatewaySession) []GatewayDayUsage {
|
|
type key struct{ date, agent, model string }
|
|
groups := map[key]GatewayDayUsage{}
|
|
for _, s := range ss {
|
|
for _, d := range s.Daily {
|
|
k := key{d.Date, d.Agent, d.Model}
|
|
v, ok := groups[k]
|
|
if !ok {
|
|
v.Date, v.Agent, v.Model, v.Priced = d.Date, d.Agent, d.Model, true
|
|
}
|
|
v.Input += d.Input
|
|
v.Output += d.Output
|
|
v.CacheRead += d.CacheRead
|
|
v.CacheWrite += d.CacheWrite
|
|
v.CacheWrite1h += d.CacheWrite1h
|
|
v.Cost += d.Cost
|
|
v.Priced = v.Priced && d.Priced
|
|
groups[k] = v
|
|
}
|
|
}
|
|
out := make([]GatewayDayUsage, 0, len(groups))
|
|
for _, d := range groups {
|
|
out = append(out, d)
|
|
}
|
|
sort.Slice(out, func(i, j int) bool {
|
|
a, b := out[i], out[j]
|
|
if a.Date != b.Date {
|
|
return a.Date < b.Date
|
|
}
|
|
if a.Agent != b.Agent {
|
|
return a.Agent < b.Agent
|
|
}
|
|
return a.Model < b.Model
|
|
})
|
|
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{}
|
|
models := map[key]map[string]*GatewayModel{}
|
|
type dayKey struct{ date, agent, model string }
|
|
daily := map[dayKey]*GatewayDayUsage{}
|
|
perSession := map[key]map[dayKey]*GatewayDayUsage{}
|
|
keep := keptStrings{}
|
|
snapshot.visit(since, func(r Record) {
|
|
if r.IsRejected() || r.IsReported() || r.Session == "" {
|
|
return
|
|
}
|
|
a := keep.of(ReportedAs(r.Agent))
|
|
r.Session, r.Model = keep.of(r.Session), keep.of(r.Model)
|
|
k := key{a, r.Session}
|
|
if nativeKeys != nil && nativeKeys[a+"|"+r.Session] {
|
|
return
|
|
}
|
|
s := groups[k]
|
|
if s == nil {
|
|
s = &GatewaySession{Agent: a, ID: r.Session, Models: []GatewayModel{}}
|
|
groups[k] = s
|
|
models[k] = map[string]*GatewayModel{}
|
|
perSession[k] = map[dayKey]*GatewayDayUsage{}
|
|
}
|
|
if s.Start.IsZero() || r.Time.Before(s.Start) {
|
|
s.Start = r.Time
|
|
}
|
|
end := r.Time.Add(time.Duration(max(0, r.Millis)) * time.Millisecond)
|
|
if end.After(s.Last) {
|
|
s.Last = end
|
|
}
|
|
p := priceOf(r)
|
|
cost, priced := 0.0, true
|
|
if r.Input+r.Output > 0 {
|
|
if p == nil {
|
|
priced = false
|
|
} else {
|
|
cost = r.CostAt(*p)
|
|
}
|
|
}
|
|
tokens := sessions.Tokens{Input: r.Input, Output: r.Output, CacheRead: r.CacheRead, CacheWrite: r.CacheWrite, CacheWrite1h: r.CacheWrite1h}
|
|
dk := dayKey{r.Time.In(time.Local).Format(time.DateOnly), a, r.Model}
|
|
for _, kept := range []map[dayKey]*GatewayDayUsage{daily, perSession[k]} {
|
|
d := kept[dk]
|
|
if d == nil {
|
|
d = &GatewayDayUsage{Date: dk.date, Agent: a, Model: r.Model, Priced: true}
|
|
kept[dk] = d
|
|
}
|
|
d.Input += tokens.Input
|
|
d.Output += tokens.Output
|
|
d.CacheRead += tokens.CacheRead
|
|
d.CacheWrite += tokens.CacheWrite
|
|
d.CacheWrite1h += tokens.CacheWrite1h
|
|
d.Cost += cost
|
|
d.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.Input
|
|
s.Output += r.Output
|
|
s.CacheRead += r.CacheRead
|
|
s.CacheWrite += r.CacheWrite
|
|
s.CacheWrite1h += r.CacheWrite1h
|
|
m := models[k][r.Model]
|
|
if m == nil {
|
|
m = &GatewayModel{Model: r.Model, Priced: true}
|
|
models[k][r.Model] = m
|
|
}
|
|
m.addRecord(r, p)
|
|
})
|
|
for k, s := range groups {
|
|
// of their own size: the projection keeps them, and grown an item
|
|
// at a time they kept append's spare room, ~40% of them (#2776)
|
|
s.Daily = make([]GatewayDayUsage, 0, len(perSession[k]))
|
|
s.Models = make([]GatewayModel, 0, len(models[k]))
|
|
for _, d := range perSession[k] {
|
|
s.Daily = append(s.Daily, *d)
|
|
}
|
|
sort.Slice(s.Daily, func(i, j int) bool {
|
|
if s.Daily[i].Date != s.Daily[j].Date {
|
|
return s.Daily[i].Date < s.Daily[j].Date
|
|
}
|
|
return s.Daily[i].Model < s.Daily[j].Model
|
|
})
|
|
for _, m := range models[k] {
|
|
s.Models = append(s.Models, *m)
|
|
}
|
|
finishGatewayModels(s)
|
|
}
|
|
out := make([]GatewaySession, 0, len(groups))
|
|
for _, s := range groups {
|
|
out = append(out, *s)
|
|
}
|
|
sort.Slice(out, func(i, j int) bool {
|
|
if !out[i].Last.Equal(out[j].Last) {
|
|
return out[i].Last.After(out[j].Last)
|
|
}
|
|
return out[i].Agent+"|"+out[i].ID < out[j].Agent+"|"+out[j].ID
|
|
})
|
|
days := make([]GatewayDayUsage, 0, len(daily))
|
|
for _, d := range daily {
|
|
days = append(days, *d)
|
|
}
|
|
sort.Slice(days, func(i, j int) bool {
|
|
if days[i].Date != days[j].Date {
|
|
return days[i].Date < days[j].Date
|
|
}
|
|
if days[i].Agent != days[j].Agent {
|
|
return days[i].Agent < days[j].Agent
|
|
}
|
|
return days[i].Model < days[j].Model
|
|
})
|
|
return out, days
|
|
}
|
|
|
|
func (m *GatewayModel) addRecord(r Record, p *catalog.Price) {
|
|
m.Input += r.Input
|
|
m.Output += r.Output
|
|
m.CacheRead += r.CacheRead
|
|
m.CacheWrite += r.CacheWrite
|
|
m.CacheWrite1h += r.CacheWrite1h
|
|
if r.Input+r.Output == 0 {
|
|
return
|
|
}
|
|
if p == nil {
|
|
m.Priced = false
|
|
return
|
|
}
|
|
m.Cost += r.CostAt(*p)
|
|
}
|