usage: a day card's switch builds one page, not one per agent
WaiooT on X: "每日用量卡,切换日期的时候,账单计算很卡". The day-card
page's usage:day read is usageapi.SpanOf. For each date it built the
day's page, then one more page of the same day for every agent (up to
12) only to read that agent's By["modelAt"], and every one of those
builds listed and stat'd every agent session file again
(readRequestState). A switch to an older day misses the request-page
cache (16 pages), so it paid all of them each time.
- RequestPage.AgentModels: each agent's By["modelAt"], counted in the
same cell pass as By (cellGroup bit of modelAt, keyed by ReportedAs as
a filter's Agent is), and from the ledger's rows on the LogCalls path.
SpanOf reads it in place of a page per agent. The calls that named no
agent are still listed by model only when they are all there are.
- SpanOf holds sessions.OneListing() for its reads, as the sessions
overview and stats handlers do, so the session folders are listed once
a read.
Measured on mote (a throwaway test, not committed: 401,502 gateway
records over 365 days in 6 agents x 6 providers, plus 20 Claude Code
session files a day of 60 calls each, half mirrored by gateway records),
origin/main 6ac19f4bc against this:
- switch to a past day: 243-300ms -> 32-48ms
- today again after it: 57-94ms -> 20-28ms
- 7-day span 400ms -> 44ms, 30-day 1.17s -> 91ms, all time 12.3s -> 2.2s
- 30 switches back a day each (180-day ledger): 4.0-4.9s -> 0.87s
The CPU profile before: readRequestState 46%, then the per-agent builds.
TestAgentModelsAreEachAgentsPage holds AgentModels to the page of
each agent, for a whole week and for a day in it, on the cells path and
the ledger path. Broken by hand: counting from the chart's bits (the
whole period) goes red on cells; the whole ledger in place of the
filter's rows goes red on ledger. Keying by the raw agent instead of
ReportedAs stays green: rows carry the reported name already, and only a
renamed client could tell the two apart.
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
|
||||
// A page's AgentModels are, for each agent, what the same page with that
|
||||
// agent picked has as its By["modelAt"]: a day's card reads them off the
|
||||
// day's own page instead of building a page of each agent (WaiooT on X),
|
||||
// on the cells' path and on the ledger's (LogCalls) alike.
|
||||
func TestAgentModelsAreEachAgentsPage(t *testing.T) {
|
||||
for _, viaLog := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "cells", true: "ledger"}[viaLog], func(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
os.MkdirAll(filepath.Join(home, ".config"), 0o755)
|
||||
now := holdClock(t, time.Date(2026, 11, 15, 12, 0, 0, 0, time.Local))
|
||||
for i, r := range []Record{
|
||||
{Agent: "claude-cli/2.1", Provider: "anthropic", Model: "claude-x", Input: 50, Output: 5},
|
||||
{Agent: "claude-cli/2.1", Provider: "relay", Model: "claude-x", Input: 40, Output: 4},
|
||||
{Agent: "claude-cli/2.1", Provider: "anthropic", Model: "claude-y", Input: 30, Output: 3},
|
||||
{Agent: "codex_cli_rs/0.9", Provider: "openai", Model: "gpt-z", Input: 20, Output: 2},
|
||||
{Agent: "", Provider: "openai", Model: "gpt-z", Input: 10, Output: 1},
|
||||
// yesterday's, which a page of today leaves out
|
||||
{Agent: "claude-cli/2.1", Provider: "anthropic", Model: "claude-old", Input: 8, Output: 8, Time: now.AddDate(0, 0, -1)},
|
||||
{Agent: "codex_cli_rs/0.9", Provider: "openai", Model: "gpt-old", Input: 9, Output: 9, Time: now.AddDate(0, 0, -1)},
|
||||
} {
|
||||
if r.Time.IsZero() {
|
||||
r.Time = now.Add(-time.Duration(i+1) * time.Minute)
|
||||
}
|
||||
r.Status = 200
|
||||
Append(r)
|
||||
}
|
||||
if viaLog {
|
||||
old := LogCalls
|
||||
LogCalls = func(time.Time) []sessions.Call {
|
||||
return []sessions.Call{{Time: now.Add(-time.Hour), Agent: "codex", Session: "c1", Model: "gpt-w", Tokens: sessions.Tokens{Input: 7, Output: 7}}}
|
||||
}
|
||||
t.Cleanup(func() { LogCalls = old })
|
||||
}
|
||||
today := Filter{Day: now.Format(time.DateOnly), Zone: time.Local}
|
||||
yesterday := Filter{Day: now.AddDate(0, 0, -1).Format(time.DateOnly), Zone: time.Local}
|
||||
for _, f := range []Filter{{}, today, yesterday} {
|
||||
page := QueryPage(Week, f, 0, 1)
|
||||
if len(page.By["agent"]) < 1 {
|
||||
t.Fatalf("agents %+v", page.By["agent"])
|
||||
}
|
||||
for _, a := range page.By["agent"] {
|
||||
if a.ID == "" {
|
||||
continue
|
||||
}
|
||||
af := f
|
||||
af.Agent = a.ID
|
||||
want := QueryPage(Week, af, 0, 1).By["modelAt"]
|
||||
if got := page.AgentModels[a.ID]; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("%+v: %s's models %+v, its own page's %+v", f, a.ID, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1126,6 +1126,15 @@ func (r Row) Floor() (tokens int, ms int64) {
|
||||
// so the clients a shared gateway serves can be compared (#2521).
|
||||
var Dimensions = []string{"provider", "agent", "model", "modelAt", "callerKey"}
|
||||
|
||||
// modelAtDim is "modelAt"'s place in Dimensions.
|
||||
const modelAtDim = 3
|
||||
|
||||
func init() {
|
||||
if Dimensions[modelAtDim] != "modelAt" {
|
||||
panic("usage: modelAtDim is not modelAt's place in Dimensions")
|
||||
}
|
||||
}
|
||||
|
||||
// NoCallerKey is the "callerKey" of a call that carried no gateway key: one
|
||||
// that wasn't counted against any, as this computer's own agents' are, or
|
||||
// that came before keys were recorded. As a filter it keeps only those.
|
||||
|
||||
@@ -55,6 +55,12 @@ type RequestPage struct {
|
||||
Series []SeriesPoint
|
||||
By map[string][]Share
|
||||
ChartBy map[string][]Share // the whole period's legend while a day is selected
|
||||
// AgentModels is each agent's By["modelAt"], by the agent a filter
|
||||
// names it by (ReportedAs): what the same page with that agent picked
|
||||
// would have as its By["modelAt"], counted in the same pass. A day's
|
||||
// card asked for a page of each agent beside the day's own, a whole
|
||||
// build each, every time the day was switched (WaiooT on X).
|
||||
AgentModels map[string][]Share
|
||||
// Computers are the rows told apart by the computer they were made on,
|
||||
// ThisComputer's and each other's by id, of the rows without the
|
||||
// filter's computer, and Names what the others are called: none when no
|
||||
@@ -2542,6 +2548,8 @@ func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time,
|
||||
chartGroups[d] = map[string]*Share{}
|
||||
seriesGroups[d] = map[string]*Share{}
|
||||
}
|
||||
agentModels := map[string]map[string]*Share{}
|
||||
reported := map[string]string{} // ReportedAs, once for each agent
|
||||
// Bound the requested prefix before adding limit: external offsets can
|
||||
// reach MaxInt, and a page beyond all sources needs no heap at all.
|
||||
maxRows := 0
|
||||
@@ -2667,7 +2675,21 @@ func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time,
|
||||
add(chartGroups[dim], keys.key(&r, dim), d)
|
||||
}
|
||||
if cell.bits&(cellGroup<<j) != 0 {
|
||||
add(groups[dim], keys.key(&r, dim), d)
|
||||
k := keys.key(&r, dim)
|
||||
add(groups[dim], k, d)
|
||||
if j == modelAtDim {
|
||||
a, ok := reported[agent]
|
||||
if !ok {
|
||||
a = ReportedAs(agent)
|
||||
reported[agent] = a
|
||||
}
|
||||
m := agentModels[a]
|
||||
if m == nil {
|
||||
m = map[string]*Share{}
|
||||
agentModels[a] = m
|
||||
}
|
||||
add(m, k, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2711,6 +2733,10 @@ func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time,
|
||||
for _, d := range Dimensions {
|
||||
out.By[d] = sharesOf(groups[d])
|
||||
}
|
||||
out.AgentModels = make(map[string][]Share, len(agentModels))
|
||||
for a, m := range agentModels {
|
||||
out.AgentModels[a] = sharesOf(m)
|
||||
}
|
||||
if f.Day != "" {
|
||||
out.ChartBy = map[string][]Share{}
|
||||
for _, d := range Dimensions {
|
||||
@@ -2846,6 +2872,17 @@ func pageFromLedgerAt(p Period, f Filter, offset, limit int, all Ledgered, now t
|
||||
}
|
||||
})
|
||||
}
|
||||
out.AgentModels = map[string][]Share{}
|
||||
byAgent := map[string][]Row{}
|
||||
for _, r := range all.Filtered(f.Without("modelAt")).Rows {
|
||||
a := ReportedAs(r.Agent)
|
||||
byAgent[a] = append(byAgent[a], r)
|
||||
}
|
||||
for a, rows := range byAgent {
|
||||
if m := Breakdown(rows, "modelAt"); len(m) > 0 {
|
||||
out.AgentModels[a] = m
|
||||
}
|
||||
}
|
||||
for _, d := range Dimensions {
|
||||
g := f.Without(d)
|
||||
out.By[d] = Breakdown(all.Filtered(g).Rows, d)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
@@ -120,6 +121,10 @@ func SpanOf(from, date string, zone *time.Location) (Day, error) {
|
||||
if date > today {
|
||||
return Day{}, fmt.Errorf("%s is after today, %s", date, today)
|
||||
}
|
||||
// the session folders listed once for the reads below, not once
|
||||
// each: a long history's thousands of files were listed and stat'd
|
||||
// for every one of them (WaiooT on X)
|
||||
defer sessions.OneListing()()
|
||||
f := usage.Filter{Zone: zone}
|
||||
var p usage.Period
|
||||
switch from {
|
||||
@@ -165,16 +170,17 @@ func SpanOf(from, date string, zone *time.Location) (Day, error) {
|
||||
if c := agents[s.ID]; c != nil {
|
||||
a.Name, a.Icon = c.Name, c.Icon
|
||||
}
|
||||
af := f
|
||||
af.Agent = s.ID
|
||||
if s.ID == "" {
|
||||
// a filter of "" keeps every agent: the calls that named none
|
||||
// are this group's own, and are listed by model without it
|
||||
af.Agent = ""
|
||||
}
|
||||
// each agent's models are of the same build as the day's own
|
||||
// (AgentModels): a page of each agent beside it was a build each,
|
||||
// all of them again on every switch of the day (WaiooT on X)
|
||||
var models []usage.Share
|
||||
if s.ID != "" || len(all.By["agent"]) == 1 {
|
||||
models = usage.QueryPage(p, af, 0, 1).By["modelAt"]
|
||||
switch {
|
||||
case s.ID != "":
|
||||
models = all.AgentModels[s.ID]
|
||||
case len(all.By["agent"]) == 1:
|
||||
// the calls that named no agent are all there are: a filter of
|
||||
// "" would keep every agent's, so they are listed only alone
|
||||
models = all.By["modelAt"]
|
||||
}
|
||||
for j, m := range models {
|
||||
if j == DayModels {
|
||||
|
||||
Reference in New Issue
Block a user