Files
magpie/internal/usageapi/usageapi.go
T
yetone 99fcddeeba usage: the Requests tab, its filters and refresh, the charts, the TUI and magpie usage answer at once over a long history (Vantiboo1ean)
Vantiboo1ean (Discord, macOS M2, v0.1.1157) has ~750,000 requests in
usage.jsonl. On Usage > Requests every filter, model pick and refresh
spun forever and the page never updated.

Reproduced in a sandbox HOME with 750k generated records in the real
format (400 MB usage.jsonl, ~84k sessions), on magpie web and in process.
The cause: the #563 budget dropped the index's blocks once they passed
24 MB (60 MB here), so every read, of any period, parsed the whole file
again (6 s CPU) and priced every call again; All took 12 s of CPU, the
heatmap 13 s, and the page read both at once.

What changed:
- log_index: the gateway's blocks are always kept (about 80 bytes a call,
  S2-compressed instead of flate); the file is parsed once, then only
  what was appended.
- block_price: the gateway's blocks are priced per query, once per set of
  provider/model/served/effort names rather than per call, into pooled
  buffers; range loops go by pointer (a packed row is 264 bytes).
- request_page: pages are always cached (16 at most), session-file chunks
  stay in the budget, and a page asked again while it is worked out (the
  refresh button, the timer) waits for that one instead of starting a
  second scan.
- Siblings that read the same history:
  - The heatmap names each day once.
  - A day filter no longer allocates per call.
  - The ledger behind the TUI, magpie usage, the CSV export and sync
    (LedgerOf, OwnDays) reads the gateway's calls from the index instead
    of Load parsing the whole file.
  - Direct/Summaries matches the session files' calls against the index's
    blocks without pricing all 750k gateway calls.
  - A summary of more than 1024 sessions is now cached with its top 1024
    (it was not cached at all). The Usage page's /api/usage gets the top
    100 (it was sent all 84k, 19 MB, which it never draws) plus a new
    sessionCount. /v1/magpie/usage still lists every session, and magpie
    usage says "top 10 of <sessionCount>".

Timings, CPU (the box was at load 130-190 on 14 cores, so wall is
inflated; min of repeated runs), before -> after:
  Requests today            6.0 s  -> 20 ms
  Requests 7d               5.8 s  -> 93 ms
  Requests 30d              ~6 s   -> 362 ms
  Requests all              12.4 s -> 2.4 s first, ~8 ms again
  all, model filter         12.3 s -> 1.5 s
  all, agent filter         11.3 s -> 1.8 s
  30d, search "opus"        6.7 s  -> 353 ms
  day filter                6.0 s  -> ~0.1 s
  heatmap                   13.7 s -> ~2.3 s first
  summary today / all       6.0 / 9.2 s -> 25 ms / 1.6 s first, <1 ms again
  /api/usage?period=all     1.6 s + 19 MB JSON each time -> <1 ms, 53 KB
  TUI Summaries(all)        ~8.5 s (Load + ledger) -> 1.1 s first, <1 ms again
  TUI Summaries(today)      ~6 s   -> 29 ms
  Visit 7d (budget, codex)  5.9 s  -> 10 ms
The first read of the file after start costs ~5 s of CPU, once.

Tests (each seen red with its guarantee broken by hand):
- TestUsageOverBudgetHistoryIsReadOnce
- TestUsageSessionChunksStayInBudget
- TestUsageOverBudgetPageIsCached
- TestUsagePageAskedTwiceIsWorkedOutOnce
- TestUsageLedgerReadsTheIndexNotTheFile
- TestUsageLargeSummaryIsCompleteAndKeptTrimmed (was ...ButNotCached)
- TestDirectCountsOnlySessionFileCalls, now with a request-id match,
  checks that Direct/Summaries equal the ledger's.

Run: go test -tags nogui ./... (temp HOME), gofmt -l, GOOS=linux and
GOOS=windows go vet on the touched packages.
2026-10-11 04:44:13 +08:00

383 lines
12 KiB
Go

// Package usageapi builds what magpie tells of its usage log: the Usage
// page's summary and its requests, a page at a time. The GUI's /api/usage
// and the gateway's /v1/magpie/usage answer the same JSON from here, so an
// app reading one reads the other.
package usageapi
import (
"net/url"
"os"
"slices"
"strconv"
"strings"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// Client is an agent as the usage JSON names it.
type Client struct{ ID, Name, Icon string }
// Clients are the agents magpie knows, for their names and logos: set by
// the GUI (internal/agent imports the gateway, which imports this). Unset,
// an agent is named by its id.
var Clients func() []Client
func clients() map[string]*Named {
out := map[string]*Named{}
if Clients == nil {
return out
}
for _, c := range Clients() {
out[c.ID] = &Named{ID: c.ID, Name: c.Name, Icon: c.Icon}
}
return out
}
// Tilde is p with the home folder written ~.
func Tilde(p string) string {
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(p, home) {
return "~" + p[len(home):]
}
return p
}
// Group is a usage.Group with what the UI needs to draw it.
type Group struct {
usage.Group
Name string `json:"name"`
Sub string `json:"sub,omitempty"` // models: the provider's name
Icon string `json:"icon,omitempty"` // a real logo, or "generic" for an unknown client
}
type Usage struct {
usage.Summary
Agents []Group `json:"agents"`
Models []Group `json:"models"`
Accounts []Group `json:"accounts"`
CallerKeys []Group `json:"callerKeys"`
Path string `json:"path"`
}
// State is the Usage page's summary of a period: what /api/usage and the
// gateway's GET /v1/magpie/usage answer.
func State(p usage.Period) Usage { return stateOf(usage.Summarize(p)) }
// PageSessions is how many sessions Page lists: the Usage page draws none of
// them, and SessionCount says how many there are.
const PageSessions = 100
// Page is State with the top PageSessions sessions only, which is what the
// Usage page asks for: over a long history (Vantiboo1ean, ~750k requests)
// State sent the page every one of ~84k sessions (22 MB) and worked the
// summary out again for each refresh.
func Page(p usage.Period) Usage { return stateOf(usage.SummarizeTop(p, PageSessions)) }
func stateOf(s usage.Summary) Usage {
out := Usage{Summary: s, Agents: []Group{}, Models: []Group{}, Accounts: []Group{}, Path: Tilde(usage.Path())}
agents := clients()
for _, g := range s.Agents {
ug := Group{Group: g, Name: g.ID, Icon: "generic"}
if a := agents[g.ID]; a != nil {
ug.Name, ug.Icon = a.Name, a.Icon
}
out.Agents = append(out.Agents, ug)
}
providers := map[string]provider.Provider{}
for _, p := range provider.All() {
providers[p.ID] = p
}
for _, g := range s.Models {
ug := Group{Group: g, Name: g.Model, Sub: g.Provider, Icon: "generic"}
if p, ok := providers[g.Provider]; ok {
ug.Sub = p.Name
if p.Icon != "" {
ug.Icon = p.Icon
}
}
if g.Host != "" {
ug.Sub += " · " + g.Host
}
out.Models = append(out.Models, ug)
}
// each subscription account's share, by the account that answered
// (#557); Name "" is the calls whose record names none, the page
// saying "account not recorded"
for _, g := range s.Accounts {
ug := Group{Group: g, Name: g.Account, Sub: g.Provider, Icon: "generic"}
if p, ok := providers[g.Provider]; ok {
ug.Sub = p.Name
if p.Icon != "" {
ug.Icon = p.Icon
}
}
out.Accounts = append(out.Accounts, ug)
}
out.CallerKeys = callerGroups(s)
return out
}
func callerGroups(s usage.Summary) []Group {
keys := []Group{}
current, _ := access.List()
names := map[string]string{}
for _, k := range current {
names[k.ID] = k.Name
}
for _, g := range s.CallerKeys {
n := names[g.CallerKeyID]
if n == "" {
n = g.CallerKeyName
}
if n == "" {
n = g.CallerKeyID
}
keys = append(keys, Group{Group: g, Name: n, Icon: "generic"})
}
return keys
}
// PeriodOf is the period a ?period= names: a preset, or days picked as
// "2026-10-01..2026-10-07" (#1492); 30 days for anything else.
func PeriodOf(s string) usage.Period {
if p := usage.Period(s); p.Known() {
return p
}
return usage.Month
}
func FilterOf(q url.Values) usage.Filter {
id, _ := strconv.ParseInt(q.Get("route"), 10, 64)
return usage.Filter{Day: q.Get("day"), RouteID: id, Model: q.Get("model"), Agent: q.Get("agent"), Provider: q.Get("provider"), Purpose: q.Get("purpose"), Account: q.Get("account"), CallerKey: q.Get("callerKey"), Failed: q.Get("failed") == "1", Query: q.Get("q"), Computer: q.Get("computer"), Through: viaOf(q.Get("via"))}
}
// viaOf is the source a request's ?via= names, "" for both.
func viaOf(s string) string {
switch s {
case usage.SourceGateway, usage.SourceSession:
return s
}
return ""
}
// Row is a usage.Row with the names the page shows it by.
type Row struct {
usage.Row
CallerKeyLabel string `json:"callerKeyLabel,omitempty"`
AgentName string `json:"agentName"`
Icon string `json:"icon"` // the agent's
ProviderName string `json:"providerName"`
Access string `json:"access,omitempty"` // known account/route type, independent of model maker
PricingModel string `json:"pricing_model,omitempty"`
// ComputerName is the other computer a call was made on, shared through sync (#542)
ComputerName string `json:"computerName,omitempty"`
}
type Ledger struct {
CallerKeys []Group `json:"callerKeys"`
Period usage.Period `json:"period"`
Rows []Row `json:"rows"`
Offset int `json:"offset"`
Total int `json:"total"` // the rows the filter keeps, on every page
// Series: the period by hour, day or week (Bucket), before the day filter
Bucket string `json:"bucket"`
Series []usage.SeriesPoint `json:"series"`
// By: the rows told apart by provider, agent, model and model at each
// provider ("modelAt", named "model · provider"), the most tokens
// first. The one by a dimension the filter has picked is of the rows
// without that pick, so the others are still there to switch to.
By map[string][]Share `json:"by"`
ChartBy map[string][]Share `json:"chartBy,omitempty"`
Day string `json:"day,omitempty"`
usage.Totals
// Through and Direct: the rows the gateway served, and the rows read
// from the agents' own session files, which it never saw. Totals is
// the two together, so the page can show all three (#the usage report).
Through usage.Totals `json:"through"`
Direct usage.Totals `json:"direct"`
// Agents, Providers and Purposes: those with calls in the period, for the filters
Agents []Named `json:"agents"`
Providers []Named `json:"providers"`
Purposes []string `json:"purposes"`
// Accounts: the subscription accounts that answered calls in the
// period, for the Account filter (#557)
Accounts []Account `json:"accounts"`
// Computers: this one ("this", no name) and the others whose usage
// sync brought (#542), for the filter; none while there are none
Computers []Share `json:"computers,omitempty"`
}
// Share is a usage.Share with the name and logo the page shows it by.
type Share struct {
usage.Share
Name string `json:"name"`
Icon string `json:"icon,omitempty"`
}
// Account is a subscription account the Account filter offers: its
// name, and the providers it answered for, by name.
type Account struct {
ID string `json:"id"`
Providers []string `json:"providers"`
}
type Named struct {
ID string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
}
// LedgerPage is one page of the ledger: limit rows (100 when none is
// given, 500 at most) from offset.
func LedgerPage(p usage.Period, f usage.Filter, offset, limit int) Ledger {
l := usage.QueryPage(p, f, offset, limit)
offset = max(0, min(offset, l.Total))
page := l.Rows
agents := clients()
// A session file without route evidence is a local source, not a supplier.
names := map[string]string{usage.UnknownProvider: "Local session"}
icons := map[string]string{}
access := map[string]string{}
for _, pr := range provider.All() {
names[pr.ID], icons[pr.ID] = pr.Name, pr.Icon
if pr.Account != nil {
access[pr.ID] = "subscription"
} else if pr.Key != "" {
access[pr.ID] = "api"
}
}
who := func(id string) Named {
if a := agents[id]; a != nil {
return Named{ID: id, Name: a.Name, Icon: a.Icon}
}
return Named{ID: id, Name: id, Icon: "generic"}
}
which := func(id string) Named {
a := Named{ID: id, Name: names[id], Icon: icons[id]}
if a.Name == "" {
a.Name = id
}
if a.Icon == "" {
a.Icon = "generic"
}
return a
}
out := Ledger{Period: p, Rows: make([]Row, 0, len(page)), Offset: offset, Total: l.Total, Totals: l.Sum, Agents: []Named{}, Providers: []Named{}, Accounts: []Account{}}
out.Through, out.Direct = l.Through, l.Direct
out.Bucket, out.Series = l.Bucket, l.Series
out.Purposes = l.Purposes
out.Day = f.Day
out.CallerKeys = callerGroups(usage.Summary{CallerKeys: l.CallerKeys})
callerLabels := map[string]string{}
for _, g := range out.CallerKeys {
callerLabels[g.CallerKeyID] = g.Name
}
for _, r := range page {
a := who(r.Agent)
lr := Row{Row: r, AgentName: a.Name, Icon: a.Icon, ProviderName: names[r.Provider]}
if r.Source != "log" {
lr.Access = access[r.Provider]
}
if r.Priced {
if model := provider.PricedNameFor(r.Provider, r.Model); model != r.Model {
lr.PricingModel = model
}
}
if lr.ProviderName == "" {
lr.ProviderName = r.Provider
}
lr.CallerKeyLabel = callerLabels[r.CallerKeyID]
if r.Computer != "" {
lr.ComputerName = l.Names[r.Computer]
if lr.ComputerName == "" {
lr.ComputerName = r.Computer
}
}
out.Rows = append(out.Rows, lr)
}
for _, id := range l.Agents {
out.Agents = append(out.Agents, who(id))
}
for _, id := range l.Providers {
out.Providers = append(out.Providers, which(id))
}
// one choice per account, most used first, with the providers it
// answered for: the same email may be a Codex and a Claude account
at := map[string]int{}
for _, g := range l.Accounts {
name := which(g.Provider).Name
if i, ok := at[g.Account]; ok {
if a := &out.Accounts[i]; !slices.Contains(a.Providers, name) {
a.Providers = append(a.Providers, name)
}
continue
}
at[g.Account] = len(out.Accounts)
out.Accounts = append(out.Accounts, Account{ID: g.Account, Providers: []string{name}})
}
// what each is of: the rows of the filter, or, for the dimension the
// filter has picked, of the rows without that pick
sharesJSON := func(by map[string][]usage.Share) map[string][]Share {
out := map[string][]Share{}
for _, d := range usage.Dimensions {
shares := []Share{}
for _, s := range by[d] {
ls := Share{Share: s, Name: s.ID}
switch d {
case "provider":
a := which(s.ID)
ls.Name, ls.Icon = a.Name, a.Icon
case "agent":
a := who(s.ID)
ls.Name, ls.Icon = a.Name, a.Icon
case "modelAt":
// the model, and the provider it went to
prov, model, _ := strings.Cut(s.ID, "/")
a := which(prov)
ls.Name, ls.Icon = model+" · "+a.Name, a.Icon
}
shares = append(shares, ls)
}
out[d] = shares
}
return out
}
out.By = sharesJSON(l.By)
if l.ChartBy != nil {
out.ChartBy = sharesJSON(l.ChartBy)
}
for _, s := range l.Computers {
ls := Share{Share: s, Name: l.Names[s.ID]}
if s.ID != usage.ThisComputer && ls.Name == "" {
ls.Name = s.ID
}
out.Computers = append(out.Computers, ls)
}
return out
}
// OwnPage is l, a page filtered to the gateway key key's own calls, with
// its filter lists cut to what those calls had: they are drawn from every
// call in the period, and so would name the other keys, and the agents,
// providers and accounts only someone else's calls reached.
func OwnPage(l Ledger, key string) Ledger {
l.CallerKeys = slices.DeleteFunc(l.CallerKeys, func(g Group) bool { return g.CallerKeyID != key })
had := func(d string) map[string]bool {
m := map[string]bool{}
for _, s := range l.By[d] {
m[s.ID] = true
}
return m
}
agents, providers := had("agent"), had("provider")
l.Agents = slices.DeleteFunc(l.Agents, func(a Named) bool { return !agents[a.ID] })
l.Providers = slices.DeleteFunc(l.Providers, func(a Named) bool { return !providers[a.ID] })
accounts := map[string]bool{}
for _, r := range l.Rows {
accounts[r.Account()] = true
}
l.Accounts = slices.DeleteFunc(l.Accounts, func(a Account) bool { return !accounts[a.ID] })
return l
}