Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

usage: a period's summary counts only the log's blocks since the last

yetone28c89afcef44
diff --git a/internal/usage/log_index.go b/internal/usage/log_index.go
index 3b5b2f2c6..3d67a2c2d 100644
--- a/internal/usage/log_index.go
+++ b/internal/usage/log_index.go
@@ -265,10 +265,17 @@ func (o routeRows) handedOn(c *rowChunk, r *Record) {
// rows of its own, the Sessions, Usage and Routing pages' reads of the
// log allocated ~800 MB of rows a minute while calls came in (#2278). A
// record's strings are the block's own, not the buffer's.
-func (s *logSnapshot) visit(since time.Time, fn func(Record)) {
+func (s *logSnapshot) visit(since time.Time, fn func(Record)) { visitBlocks(s.blocks, since, fn) }
+
+// blockReader reads blocks as visit reads the log's.
+func blockReader(blocks []*rowChunk, since time.Time) func(func(Record)) {
+ return func(fn func(Record)) { visitBlocks(blocks, since, fn) }
+}
+
+func visitBlocks(blocks []*rowChunk, since time.Time, fn func(Record)) {
rows := chunkRows{}
defer rows.release()
- for _, packed := range s.blocks {
+ for _, packed := range blocks {
if !since.IsZero() && packed.Latest.Before(since) {
continue
}
diff --git a/internal/usage/summary_cache.go b/internal/usage/summary_cache.go
index 86116d58d..cea386c32 100644
--- a/internal/usage/summary_cache.go
+++ b/internal/usage/summary_cache.go
@@ -88,7 +88,10 @@ func topSummary(p Period, now time.Time, n int) Summary {
if ok && old.version == snapshot.version && old.meta == meta && (n >= 0 && n <= len(old.value.Sessions) || old.value.SessionCount == len(old.value.Sessions)) {
return topOf(cloneSummary(old.value), n)
}
- value := work()
+ summaries.Lock()
+ summaries.worked++
+ summaries.Unlock()
+ value := foldSummary(k, p, now, snapshot, meta)
// the cache keeps a copy with the top sessions only; the answer has as
// many as asked
kept := value
diff --git a/internal/usage/summary_fold.go b/internal/usage/summary_fold.go
new file mode 100644
index 000000000..0842243b6
--- /dev/null
+++ b/internal/usage/summary_fold.go
@@ -0,0 +1,394 @@
+package usage
+
+import (
+ "maps"
+ "slices"
+ "sort"
+ "time"
+
+ "github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// A summary is two passes over the log: the first finds what tells a
+// provider's calls apart (the hosts they went to, the accounts that
+// answered), the second counts each call into its groups by that. Each new
+// call to the log made the Usage page's periods count every call of the
+// month again, ~10% of magpie's CPU while a window was open and calls came
+// in (#2278). The log's full blocks never change, so a period keeps its
+// counts up to the last block but one (summaryPrefix) and counts only the
+// blocks after it, as long as the calls are told apart as they were.
+
+// summaryRun is what one summary reads its calls by.
+type summaryRun struct {
+ now time.Time
+ renamed provider.Renames
+ alias func(string) string
+ cleared *clearSet
+ from, until time.Time
+ since time.Time
+ bucket string
+ series []Point // the empty timeline
+ period Period
+ historicalKeys map[string]bool
+ priceOf func(Record) *catalog.Price
+}
+
+func newSummaryRun(p Period, now, first time.Time, historicalKeys map[string]bool) *summaryRun {
+ u := &summaryRun{now: now, renamed: provider.UsageRenames()}
+ // the names models' usage is counted under (SlouchyQuill507): a model's
+ // row sums its ids, each call priced by its own id first
+ u.alias = provider.UsageAlias()
+ u.historicalKeys = map[string]bool{}
+ for id := range historicalKeys {
+ for _, next := range u.renamed.Each(id) {
+ u.historicalKeys[next] = true
+ }
+ }
+ // the user's clears (cleared.go): a call cleared is in no figure, and a
+ // clear of everything starts the timeline again
+ u.cleared = readCleared()
+ first = u.cleared.clearedSince(first)
+ // a picked range's own days alone: its chart can start on the Monday
+ // before its first, and it ends before now (#1492)
+ u.from, u.until = p.Since(now), p.Until(now)
+ u.since, u.bucket, u.series = timeline(p, now, first)
+ u.period = p.shown()
+ u.priceOf = Pricer()
+ return u
+}
+
+// read hands fn the calls of read that the summary counts, as it counts
+// them.
+func (u *summaryRun) read(read func(func(Record)), fn func(Record)) {
+ read(func(r Record) {
+ if r.Time.Before(u.from) || after(u.until, r.Time) {
+ return
+ }
+ r.renameBy(u.renamed)
+ if u.cleared.hides(&r) {
+ return
+ }
+ fn(r)
+ })
+}
+
+// summaryHosts is the first pass: the places each provider id went in the
+// period, and the providers an account answered for in it.
+type summaryHosts struct {
+ hosts map[string]map[string]bool
+ accounts map[string]bool
+}
+
+func newSummaryHosts() summaryHosts {
+ return summaryHosts{hosts: map[string]map[string]bool{}, accounts: map[string]bool{}}
+}
+
+func (h summaryHosts) note(r Record, since time.Time) {
+ if r.IsRejected() || r.Time.Before(since) {
+ return
+ }
+ if r.Account() != "" {
+ h.accounts[r.Provider] = true
+ }
+ if r.Host != "" {
+ if h.hosts[r.Provider] == nil {
+ h.hosts[r.Provider] = map[string]bool{}
+ }
+ h.hosts[r.Provider][who(r.Host)] = true
+ }
+}
+
+func (h summaryHosts) clone() summaryHosts {
+ c := summaryHosts{hosts: make(map[string]map[string]bool, len(h.hosts)), accounts: maps.Clone(h.accounts)}
+ for p, ws := range h.hosts {
+ c.hosts[p] = maps.Clone(ws)
+ }
+ return c
+}
+
+// summaryKeying is how the second pass tells calls apart: by host where a
+// provider went to more than one or goes elsewhere now, by key, by account.
+type summaryKeying struct {
+ goesNow map[string]string
+ manyHosts map[string]bool
+ // the providers whose calls are told apart by key, and by account:
+ // those an account answered for in the period, and those signed in now
+ keyProviders map[string]bool
+ accountProviders map[string]bool
+}
+
+func (u *summaryRun) keying(h summaryHosts) summaryKeying {
+ k := summaryKeying{goesNow: map[string]string{}, manyHosts: map[string]bool{}, keyProviders: map[string]bool{}, accountProviders: maps.Clone(h.accounts)}
+ for p, ws := range h.hosts {
+ if len(ws) > 1 {
+ k.manyHosts[p] = true
+ }
+ }
+ for _, p := range provider.All() {
+ k.goesNow[p.ID] = who(p.Where())
+ if p.Account == nil && p.Key != "" {
+ k.keyProviders[p.ID] = true
+ }
+ if p.Account != nil {
+ k.accountProviders[p.ID] = true
+ }
+ }
+ for id := range u.historicalKeys {
+ k.keyProviders[id] = true
+ }
+ return k
+}
+
+func (k summaryKeying) equal(o summaryKeying) bool {
+ return maps.Equal(k.goesNow, o.goesNow) && maps.Equal(k.manyHosts, o.manyHosts) && maps.Equal(k.keyProviders, o.keyProviders) && maps.Equal(k.accountProviders, o.accountProviders)
+}
+
+// groupSet is a summary's groups by key: those of base, which other
+// summaries share and nothing writes, under those counted since (own).
+type groupSet struct {
+ base map[string]*Group
+ own map[string]*Group
+}
+
+// at is the group of k to count into, made by mk when there is none.
+func (g *groupSet) at(k string, mk func() Group) *Group {
+ if x := g.own[k]; x != nil {
+ return x
+ }
+ var x Group
+ if b := g.base[k]; b != nil {
+ x = *b
+ } else {
+ x = mk()
+ }
+ if g.own == nil {
+ g.own = map[string]*Group{}
+ }
+ g.own[k] = &x
+ return &x
+}
+
+func (g *groupSet) list() []Group {
+ out := make([]Group, 0, len(g.base)+len(g.own))
+ for k, x := range g.base {
+ if g.own[k] == nil {
+ out = append(out, *x)
+ }
+ }
+ for _, x := range g.own {
+ out = append(out, *x)
+ }
+ return out
+}
+
+// freeze makes g's groups one base, which g counts on over from here.
+func (g *groupSet) freeze() {
+ if len(g.own) == 0 {
+ return
+ }
+ m := make(map[string]*Group, len(g.base)+len(g.own))
+ maps.Copy(m, g.base)
+ maps.Copy(m, g.own)
+ g.base, g.own = m, nil
+}
+
+// summaryCounts is the second pass's sums.
+type summaryCounts struct {
+ totals Totals
+ series []Point
+ agents, models, keys, accounts, callerKeys, sessions groupSet
+}
+
+func (u *summaryRun) newCounts() summaryCounts {
+ return summaryCounts{series: slices.Clone(u.series)}
+}
+
+func (c *summaryCounts) sets() []*groupSet {
+ return []*groupSet{&c.agents, &c.models, &c.keys, &c.accounts, &c.callerKeys, &c.sessions}
+}
+
+// carried is a copy of c to count on in, which leaves c as it is: c's
+// groups must have been frozen.
+func (c summaryCounts) carried() summaryCounts {
+ c.series = slices.Clone(c.series)
+ return c
+}
+
+// freeze makes c's groups their base, and gives a copy of c as it is now.
+func (c *summaryCounts) freeze() summaryCounts {
+ for _, g := range c.sets() {
+ g.freeze()
+ }
+ return c.carried()
+}
+
+func (c *summaryCounts) add(u *summaryRun, k *summaryKeying, r Record) {
+ if r.IsRejected() {
+ return
+ }
+ t := r.Time.In(u.now.Location())
+ if t.Before(u.since) {
+ return
+ }
+ pr := u.priceOf(r)
+ c.totals.add(r, pr)
+ i := bucketIndex(u.bucket, u.since, t)
+ if i >= 0 && i < len(c.series) {
+ c.series[i].add(r, pr)
+ }
+ id := ReportedAs(r.Agent) // one kept before magpie knew the agent by name
+ c.agents.at(id, func() Group { return Group{ID: id} }).add(r, pr)
+ model := r.Model
+ if u.alias != nil {
+ model = u.alias(model)
+ }
+ key, host := r.Provider+"/"+model, ""
+ if w := who(r.Host); w != "" && (k.manyHosts[r.Provider] || w != k.goesNow[r.Provider]) {
+ key, host = key+" @ "+w, w
+ }
+ m := c.models.at(key, func() Group { return Group{ID: key, Provider: r.Provider, Model: model, Host: host} })
+ m.add(r, pr)
+ m.addOwn(r, pr)
+ if r.CallerKeyID != "" {
+ g := c.callerKeys.at(r.CallerKeyID, func() Group { return Group{ID: r.CallerKeyID, CallerKeyID: r.CallerKeyID} })
+ g.CallerKeyName = r.CallerKeyName
+ g.add(r, pr)
+ }
+ if k.keyProviders[r.Provider] {
+ g := c.keys.at(r.Provider+"#"+r.ProviderKeyID, func() Group {
+ return Group{ID: r.Provider + "#" + r.ProviderKeyID, Provider: r.Provider, ProviderKeyID: r.ProviderKeyID}
+ })
+ g.ProviderKeyName = r.ProviderKeyName
+ g.add(r, pr)
+ g.addOwn(r, pr)
+ }
+ if k.accountProviders[r.Provider] {
+ who := r.Account()
+ g := c.accounts.at(r.Provider+"@"+who, func() Group { return Group{ID: r.Provider + "@" + who, Provider: r.Provider, Account: who} })
+ g.add(r, pr)
+ g.addOwn(r, pr)
+ }
+ if r.Session != "" {
+ c.sessions.at(id+"|"+r.Session, func() Group { return Group{ID: r.Session, Agent: id} }).add(r, pr)
+ }
+}
+
+func (c *summaryCounts) summary(u *summaryRun) Summary {
+ s := Summary{Period: u.period, Since: u.since, Totals: c.totals, Bucket: u.bucket, Series: c.series}
+ byTokens := func(gs []Group) []Group {
+ sort.SliceStable(gs, func(i, j int) bool {
+ if a, b := gs[i].Tokens(), gs[j].Tokens(); a != b {
+ return a > b
+ }
+ if gs[i].Calls != gs[j].Calls {
+ return gs[i].Calls > gs[j].Calls
+ }
+ return gs[i].ID < gs[j].ID
+ })
+ return gs
+ }
+ s.Agents = byTokens(c.agents.list())
+ s.Models = byTokens(c.models.list())
+ s.ProviderKeys = byTokens(c.keys.list())
+ s.Accounts = byTokens(c.accounts.list())
+ s.CallerKeys = byTokens(c.callerKeys.list())
+ s.Sessions = byTokens(c.sessions.list())
+ s.SessionCount = len(s.Sessions)
+ return s
+}
+
+// summaryPrefix is a period's counts of the log's blocks up to the last
+// but one, for the next summary of a log grown since to count on from.
+type summaryPrefix struct {
+ version uint64
+ // the blocks counted: how many, and the last of them. Only a parse
+ // that continues a snapshot carries its blocks on, all of them in their
+ // places, so the last one being there says the rest are too; holding
+ // it alone keeps a rewritten log's old blocks from staying in memory.
+ n int
+ last *rowChunk
+ // what the counts were made by
+ meta, cleared string
+ from, until time.Time
+ since time.Time
+ bucket string
+ series []time.Time
+ hosts summaryHosts // the first pass over the blocks counted
+ keyed summaryKeying
+ counts summaryCounts
+}
+
+// fits is whether p's counts are of blocks' first ones, counted as u
+// counts.
+func (p *summaryPrefix) fits(u *summaryRun, meta string, blocks []*rowChunk) bool {
+ if p == nil || p.n > len(blocks) || p.n > 0 && blocks[p.n-1] != p.last || p.meta != meta || p.cleared != u.cleared.key {
+ return false
+ }
+ if !p.from.Equal(u.from) || !p.until.Equal(u.until) || !p.since.Equal(u.since) || p.bucket != u.bucket || len(p.series) != len(u.series) {
+ return false
+ }
+ for i, t := range p.series {
+ if !t.Equal(u.series[i].Time) || u.series[i].Label != p.counts.series[i].Label {
+ return false
+ }
+ }
+ return true
+}
+
+// summaryPrefixes are held under summaries' lock.
+var summaryPrefixes struct {
+ m map[summaryKey]*summaryPrefix
+ carried int // how many summaries counted on from a prefix, for the tests
+}
+
+// foldSummary is summarizeFrom over snapshot, counting on from the
+// period's prefix where it fits.
+func foldSummary(k summaryKey, p Period, now time.Time, snapshot *logSnapshot, meta string) Summary {
+ u := newSummaryRun(p, now, snapshot.first, snapshot.keyProviders)
+ blocks := snapshot.blocks
+ cut := max(len(blocks)-1, 0)
+ summaries.Lock()
+ pre := summaryPrefixes.m[k]
+ summaries.Unlock()
+ if !pre.fits(u, meta, blocks) || pre.n > cut {
+ pre = nil
+ }
+ from, hosts := 0, newSummaryHosts()
+ if pre != nil {
+ from, hosts = pre.n, pre.hosts.clone()
+ }
+ note := func(r Record) { hosts.note(r, u.since) }
+ u.read(blockReader(blocks[from:cut], u.from), note)
+ cutHosts := hosts.clone()
+ u.read(blockReader(blocks[cut:], u.from), note)
+ keyed := u.keying(hosts)
+ var counts summaryCounts
+ if pre != nil && keyed.equal(pre.keyed) {
+ counts = pre.counts.carried()
+ summaries.Lock()
+ summaryPrefixes.carried++
+ summaries.Unlock()
+ } else {
+ from, counts = 0, u.newCounts()
+ }
+ count := func(r Record) { counts.add(u, &keyed, r) }
+ u.read(blockReader(blocks[from:cut], u.from), count)
+ next := &summaryPrefix{version: snapshot.version, n: cut, meta: meta, cleared: u.cleared.key, from: u.from, until: u.until, since: u.since, bucket: u.bucket, hosts: cutHosts, keyed: keyed, counts: counts.freeze()}
+ if cut > 0 {
+ next.last = blocks[cut-1]
+ }
+ for _, pt := range u.series {
+ next.series = append(next.series, pt.Time)
+ }
+ summaries.Lock()
+ if summaryPrefixes.m == nil {
+ summaryPrefixes.m = map[summaryKey]*summaryPrefix{}
+ }
+ if old := summaryPrefixes.m[k]; old == nil || old.version <= snapshot.version {
+ summaryPrefixes.m[k] = next
+ }
+ summaries.Unlock()
+ u.read(blockReader(blocks[cut:], u.from), count)
+ return counts.summary(u)
+}
diff --git a/internal/usage/summary_fold_test.go b/internal/usage/summary_fold_test.go
new file mode 100644
index 000000000..540e076e3
--- /dev/null
+++ b/internal/usage/summary_fold_test.go
@@ -0,0 +1,120 @@
+package usage
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+ "time"
+)
+
+// foldRecord is the i-th call of a month of calls: three providers, two
+// hosts and two accounts, keys, callers and sessions, at prices that sum
+// to floats which an order of adding changes.
+func foldRecord(now time.Time, i int) Record {
+ r := Record{
+ Time: now.Add(-time.Duration(i%(31*24)) * time.Hour).Add(-time.Duration(i%60) * time.Minute),
+ Agent: []string{"codex", "claude", "opencode"}[i%3],
+ Provider: []string{"openai", "relay", "glm"}[i%3],
+ Model: []string{"m", "m2"}[i%2],
+ Session: fmt.Sprintf("s%d-%d", i%3, i%97),
+ Input: 10 + i%13, Output: 1 + i%7, CacheRead: i % 5,
+ Status: 200, TTFT: int64(i % 300),
+ }
+ if i%3 == 1 {
+ r.Host = "relay.example"
+ r.ProviderKeyID, r.ProviderKeyName = fmt.Sprint("k", i%2), "key"
+ }
+ if i%3 == 2 {
+ r.ProviderAccount = []string{"[email protected]", "[email protected]"}[i%2]
+ }
+ if i%11 == 0 {
+ r.CallerKeyID, r.CallerKeyName = "ck", fmt.Sprint("caller ", i)
+ }
+ if i%17 == 0 {
+ r.Status = 500
+ }
+ return r
+}
+
+func writeFoldLog(t *testing.T, now time.Time, n int) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(Path()), 0700); err != nil {
+ t.Fatal(err)
+ }
+ f, err := os.Create(Path())
+ if err != nil {
+ t.Fatal(err)
+ }
+ enc := json.NewEncoder(f)
+ for i := n - 1; i >= 0; i-- { // the oldest first, as the log has them
+ if err := enc.Encode(foldRecord(now, i)); err != nil {
+ f.Close()
+ t.Fatal(err)
+ }
+ }
+ if err := f.Close(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// A period's summary counted on from the blocks it counted before is the
+// summary counted afresh, to the last bit of every float: as calls come in
+// over a block's edge, when a provider's calls go to another host, when an
+// account first answers for a provider and its calls are told apart by
+// account from then on, in every block counted before too, and when the log
+// is written over.
+func TestSummaryCountedOnIsCountedAfresh(t *testing.T) {
+ pageHome(t)
+ now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
+ writeFoldLog(t, now, 3*logBlockRows+100)
+ periods := []Period{Today, Week, Month, All}
+ carried := func() int {
+ summaries.Lock()
+ defer summaries.Unlock()
+ return summaryPrefixes.carried
+ }
+ check := func(step string) {
+ t.Helper()
+ snapshot := readLogSnapshot()
+ for _, p := range periods {
+ got := SummarizeTop(p, -1)
+ want := summarizeFrom(p.shown(), now, snapshot.first, snapshot.keyProviders, func(fn func(Record)) { snapshot.visit(p.Since(now), fn) })
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("%s, %s: counted on\n%+v\nafresh\n%+v", step, p, got.Totals, want.Totals)
+ }
+ if got.Calls == 0 {
+ t.Fatalf("%s, %s: no calls", step, p)
+ }
+ }
+ }
+ check("first")
+ before := carried()
+ // over the edge of the last block, and a block more
+ for i := 0; i < logBlockRows+50; i++ {
+ r := foldRecord(now, i)
+ r.Time = now.Add(-time.Duration(i) * time.Second)
+ Append(r)
+ if i == 0 || i == 600 {
+ check(fmt.Sprint("appended ", i+1))
+ }
+ }
+ check("appended a block")
+ if n := carried() - before; n < len(periods) {
+ t.Fatalf("only %d summaries counted on from what they had counted", n)
+ }
+ // a call to a host glm's calls never went to
+ Append(Record{Time: now, Agent: "opencode", Provider: "glm", Model: "m", Host: "glm.other", Input: 5, Status: 200})
+ check("a second host")
+ // a provider an account first answers for is counted by account
+ Append(Record{Time: now, Agent: "codex", Provider: "openai", Model: "m", ProviderAccount: "[email protected]", Input: 5, Status: 200})
+ check("an account")
+ for i := 0; i < logBlockRows; i++ {
+ Append(foldRecord(now, i))
+ }
+ check("another block")
+ writeFoldLog(t, now, 2*logBlockRows+7)
+ check("written over")
+}
diff --git a/internal/usage/usage.go b/internal/usage/usage.go
index bef53bb45..d3ef41ac4 100644
--- a/internal/usage/usage.go
+++ b/internal/usage/usage.go
@@ -940,191 +940,13 @@ func summarize(p Period, now time.Time, recs []Record) Summary {
}
func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[string]bool, read func(func(Record))) Summary {
- renamed := provider.UsageRenames()
- // the names models' usage is counted under (SlouchyQuill507): a model's
- // row sums its ids, each call priced by its own id first
- alias := provider.UsageAlias()
- normalizedKeys := map[string]bool{}
- for id := range historicalKeys {
- for _, next := range renamed.Each(id) {
- normalizedKeys[next] = true
- }
- }
- historicalKeys = normalizedKeys
- // the user's clears (cleared.go): a call cleared is in no figure, and a
- // clear of everything starts the timeline again
- cleared := readCleared()
- first = cleared.clearedSince(first)
- // a picked range's own days alone: its chart can start on the Monday
- // before its first, and it ends before now (#1492)
- from, until := p.Since(now), p.Until(now)
- visit := func(fn func(Record)) {
- read(func(r Record) {
- if r.Time.Before(from) || after(until, r.Time) {
- return
- }
- r.renameBy(renamed)
- if cleared.hides(&r) {
- return
- }
- fn(r)
- })
- }
- s := Summary{Period: p, Bucket: "day", Agents: []Group{}, Models: []Group{}, ProviderKeys: []Group{}, Accounts: []Group{}, CallerKeys: []Group{}, Sessions: []Group{}, Series: []Point{}}
- s.Since, s.Bucket, s.Series = timeline(p, now, first)
- s.Period = p.shown()
-
- priceOf := Pricer()
- // the places each provider id went in the period, and goes now
- hosts := map[string]map[string]bool{}
- // the providers whose calls are told apart by account: those an
- // account answered for in the period, and those signed in now
- accountProviders := map[string]bool{}
- visit(func(r Record) {
- if r.IsRejected() {
- return
- }
- if r.Account() != "" && !r.Time.Before(s.Since) {
- accountProviders[r.Provider] = true
- }
- if r.Host != "" && !r.Time.Before(s.Since) {
- if hosts[r.Provider] == nil {
- hosts[r.Provider] = map[string]bool{}
- }
- hosts[r.Provider][who(r.Host)] = true
- }
- })
- goesNow := map[string]string{}
- keyProviders := map[string]bool{}
- for _, p := range provider.All() {
- goesNow[p.ID] = who(p.Where())
- keyProviders[p.ID] = p.Account == nil && p.Key != ""
- if p.Account != nil {
- accountProviders[p.ID] = true
- }
- }
- for id := range historicalKeys {
- keyProviders[id] = true
- }
- agents := map[string]*Group{}
- models := map[string]*Group{}
- keys := map[string]*Group{}
- accounts := map[string]*Group{}
- callerKeys := map[string]*Group{}
- sessions := map[string]*Group{}
- visit(func(r Record) {
- if r.IsRejected() {
- return
- }
- t := r.Time.In(now.Location())
- if t.Before(s.Since) {
- return
- }
- pr := priceOf(r)
- s.Totals.add(r, pr)
- i := bucketIndex(s.Bucket, s.Since, t)
- if i >= 0 && i < len(s.Series) {
- s.Series[i].add(r, pr)
- }
- id := ReportedAs(r.Agent) // one kept before magpie knew the agent by name
- a := agents[id]
- if a == nil {
- a = &Group{ID: id}
- agents[id] = a
- }
- a.add(r, pr)
- model := r.Model
- if alias != nil {
- model = alias(model)
- }
- k, host := r.Provider+"/"+model, ""
- if w := who(r.Host); w != "" && (len(hosts[r.Provider]) > 1 || w != goesNow[r.Provider]) {
- k, host = k+" @ "+w, w
- }
- m := models[k]
- if m == nil {
- m = &Group{ID: k, Provider: r.Provider, Model: model, Host: host}
- models[k] = m
- }
- m.add(r, pr)
- m.addOwn(r, pr)
- if r.CallerKeyID != "" {
- g := callerKeys[r.CallerKeyID]
- if g == nil {
- g = &Group{ID: r.CallerKeyID, CallerKeyID: r.CallerKeyID}
- callerKeys[r.CallerKeyID] = g
- }
- g.CallerKeyName = r.CallerKeyName
- g.add(r, pr)
- }
- if keyProviders[r.Provider] {
- id := r.Provider + "#" + r.ProviderKeyID
- g := keys[id]
- if g == nil {
- g = &Group{ID: id, Provider: r.Provider, ProviderKeyID: r.ProviderKeyID}
- keys[id] = g
- }
- g.ProviderKeyName = r.ProviderKeyName
- g.add(r, pr)
- g.addOwn(r, pr)
- }
- if accountProviders[r.Provider] {
- who := r.Account()
- id := r.Provider + "@" + who
- g := accounts[id]
- if g == nil {
- g = &Group{ID: id, Provider: r.Provider, Account: who}
- accounts[id] = g
- }
- g.add(r, pr)
- g.addOwn(r, pr)
- }
- if r.Session != "" {
- g := sessions[id+"|"+r.Session]
- if g == nil {
- g = &Group{ID: r.Session, Agent: id}
- sessions[id+"|"+r.Session] = g
- }
- g.add(r, pr)
- }
- })
- for _, g := range agents {
- s.Agents = append(s.Agents, *g)
- }
- for _, g := range models {
- s.Models = append(s.Models, *g)
- }
- byTokens := func(gs []Group) {
- sort.SliceStable(gs, func(i, j int) bool {
- if a, b := gs[i].Tokens(), gs[j].Tokens(); a != b {
- return a > b
- }
- if gs[i].Calls != gs[j].Calls {
- return gs[i].Calls > gs[j].Calls
- }
- return gs[i].ID < gs[j].ID
- })
- }
- byTokens(s.Agents)
- byTokens(s.Models)
- for _, g := range keys {
- s.ProviderKeys = append(s.ProviderKeys, *g)
- }
- byTokens(s.ProviderKeys)
- for _, g := range accounts {
- s.Accounts = append(s.Accounts, *g)
- }
- byTokens(s.Accounts)
- for _, g := range callerKeys {
- s.CallerKeys = append(s.CallerKeys, *g)
- }
- byTokens(s.CallerKeys)
- for _, g := range sessions {
- s.Sessions = append(s.Sessions, *g)
- }
- byTokens(s.Sessions)
- s.SessionCount = len(s.Sessions)
- return s
+ u := newSummaryRun(p, now, first, historicalKeys)
+ hosts := newSummaryHosts()
+ u.read(read, func(r Record) { hosts.note(r, u.since) })
+ keyed := u.keying(hosts)
+ counts := u.newCounts()
+ u.read(read, func(r Record) { counts.add(u, &keyed, r) })
+ return counts.summary(u)
}
// ---- last seen --------------------------------------------------------------