usage, sessions: one model option for a found routing group's two ids (#5892, Norethcy on X)

A found routing group is called by its public id (auto/<model>) and is
kept as group/auto-<slug>; calls recorded under either were counted as two
models, so Usage › Sessions' model filter listed the same group twice and
the ledger, summaries and session lists split its calls.

Ported from NorethSea's 30d6261cd on their fork: UsageAlias names a found
group by its public id before the user's alias (both spellings, old
session files too), sessions' lists, the ledger keyer, the summary cache's
key and Codex's model/effort read through it, and a cache keyed on the
group names (UsageNamesKey) is read again when a group is renamed. A user's
own provider named "auto" keeps auto/<model> (autoRefsOn).

Changed in review: the patch's ledger filter compared every record with
provider.SameRef, which reads the providers (customIDs, a stat of
providers.json) for each record a filter passes over. FilterOf, the one
place a Filter is made from a query, now canonicalizes the model once, and
keepsRecord asks the providers only for an auto/ record under a group/
filter (sameGroupModel).

Run (mote's sshd reset every connection all afternoon, so on the Linux box
through wsl-run; the package run at base 720200092, and the -run tests,
quota-holds and i18n-keys again at this head on 208b89422; rebased since onto 44732325e,
a gateway test only):
- go test -count=1 -tags nogui ./internal/gui ./internal/provider
  ./internal/sessions ./internal/usage ./internal/usageapi: ok
- go vet -tags nogui (linux), GOOS=darwin CGO_ENABLED=0 go vet (provider,
  usage, usageapi, sessions), and go vet on Windows (win-run, those and
  internal/gui): clean. gofmt -l: clean.
- GUI: usage-ledger-model-pick, usage-ledger, quota-fit-batched,
  i18n-keys in chromium and webkit. usage-ledger's "newest live route
  needs no return-to-live button" (and zh "request routing links") is red
  the same on origin/main 987eac0aa on that box: #3104, #4078.

Broken by hand:
- keepsRecord back to r.Model != f.Model: TestUsageFoundGroupNames and
  TestLedgerFoundGroupNames red.
- usageGroupNames returning nothing: TestUsageFoundGroupNames (provider,
  usage), TestSessionsFoundGroupNames, TestCodexEffortFoundGroupNames,
  TestLedgerFoundGroupNames red.

Not tried: a macOS run (mote unreachable), the darwin gui package's vet,
and the reporter's own usage log.

Co-authored-by: NorethSea <963979204@qq.com>
This commit is contained in:
yetone
2026-11-10 18:01:13 +08:00
co-authored by NorethSea
parent 44732325e7
commit 4921bf5a97
17 changed files with 663 additions and 55 deletions
+23 -2
View File
@@ -173,9 +173,30 @@ record by its own model and keys its day and model rows by the alias, and
[`alias.go`](../../internal/sessions/alias.go)) merge a native session's rows
the same way, into new slices so the memo is never changed. The alias is read
before any lock, and an unreadable settings.json keeps the last aliases read.
Requests, the Requests ledger and model lists keep each call's own id.
Found routing groups are also merged under their public `auto/<model>` id
by this mapper: a native file or old usage row naming `group/auto-<slug>`
and one naming `auto/<model>` form one model option. Vendor spellings of
`auto/<model>` follow `PublicRef`; effort and `[1m]` suffixes are preserved.
The mapping is a snapshot taken before usage locks and before grouping,
so lists (`ListAgent` and `Manage` too), details, daily stats, summaries,
filtered overviews and Codex's model/effort rows agree. Original parses,
ledger rows and prices stay intact.
An unavailable group or a user's pre-existing provider named `auto` keeps
its original names. User usage aliases are applied after public spelling.
`UsageNamesKey` invalidates named caches when the group catalog changes.
Requests keep their original priced model ids internally; their model shares,
chart legends and model filters treat both routing-group ids as one (the
filter's model is made the kept `group/auto-…` once, in `usageapi.FilterOf`,
so only an `auto/…` record reads the providers), and
`usageapi.LedgerPage` displays the public spelling for both `model` and `req`.
This does not apply user usage aliases to Requests. A clear made under either
group id covers both spellings. Model lists continue to use the catalog ids.
Verification: `TestUsageAliasCountsTwoIdsAsOne`,
`TestSessionsCountAliasedModelsAsOne`, `TestAliasStatsLeavesItsInputAlone`.
`TestSessionsCountAliasedModelsAsOne`, `TestAliasStatsLeavesItsInputAlone`,
`TestSessionsFoundGroupNames`, `TestSessionsAPIFoundGroupNames`,
`TestUsageFoundGroupNames`, `TestCodexEffortFoundGroupNames`,
`TestLedgerFoundGroupNames`.
The Usage page can clear its figures (CrazyMouse_TT on X): a model's row's
"…" has "Clear usage…", and "Clear all usage…" sits under the lists. Each
+12 -8
View File
@@ -144,8 +144,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
// told so without the rows being made, encoded and hashed again,
// ~60% of an unchanged poll's ~22 MB over ~17k real sessions
logV, logKnown := usage.LogVersion()
aliases := provider.UsageAliases()
now := listTag{log: logV, drawn: drawn.String(), aliases: aliases}
now := listTag{log: logV, drawn: drawn.String(), names: provider.UsageNamesKey()}
made := -1
listTags.Lock()
if t, ok := listTags.m[n]; ok && logKnown && t.same(now) && r.Header.Get("X-Magpie-Had") == t.tag {
@@ -592,15 +591,15 @@ var listTags struct {
var listsRowed atomic.Int64
type listTag struct {
made int // sessions.ListUnless's listing
log uint64 // usage.LogVersion
drawn string // the agents' names and icons, and the folders
aliases map[string]string
tag string
made int // sessions.ListUnless's listing
log uint64 // usage.LogVersion
drawn string // the agents' names and icons, and the folders
names string // usage aliases and found groups' public ids
tag string
}
func (t listTag) same(u listTag) bool {
return t.log == u.log && t.drawn == u.drawn && maps.Equal(t.aliases, u.aliases)
return t.log == u.log && t.drawn == u.drawn && t.names == u.names
}
// sameStats is whether a and b would be sent the same: a read again
@@ -643,6 +642,11 @@ var overviewsMade atomic.Int64
const overviewsKept = 8
func writeOverview(rw http.ResponseWriter, days int, agentID, model, cwd string) {
if model != "" {
if alias := provider.UsageAlias(); alias != nil {
model = alias(model)
}
}
st, gen := statsForGen(days)
key := overviewKey{days, gen, agentID, model, cwd}
overviews.Lock()
+108
View File
@@ -0,0 +1,108 @@
package gui
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
"github.com/yetone/magpie/internal/usage"
)
// The model menu takes stats' model names, while the list and overview
// filter their own models. All three must agree for old and new group ids.
func TestSessionsAPIFoundGroupNames(t *testing.T) {
home := sandboxHome(t)
proj := filepath.Join(home, ".claude", "projects", "-work-auto")
t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude"))
if err := os.MkdirAll(proj, 0o755); err != nil {
t.Fatal(err)
}
for _, id := range []string{"ds-a", "ds-b"} {
if err := provider.Save(provider.Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"deepseek-flash"}}); err != nil {
t.Fatal(err)
}
}
at := time.Now().Add(-time.Minute)
for i, model := range []string{"group/auto-deepseek-flash", "auto/deepseek-flash"} {
id := fmt.Sprintf("abcdef0%d-abcd-abcd-abcd-abcdefabcdef", i+1)
body := fmt.Sprintf(`{"type":"assistant","isSidechain":false,"message":{"model":%q,"id":%q,"role":"assistant","content":[],"usage":{"input_tokens":10,"output_tokens":2}},"timestamp":%q,"cwd":"/work/auto","sessionId":%q}`+"\n", model, id, at.Format(time.RFC3339Nano), id)
if err := os.WriteFile(filepath.Join(proj, id+".jsonl"), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
usage.Append(usage.Record{Time: at, Agent: "pi", Session: "gateway-auto", Provider: "relay", Model: "group/auto-deepseek-flash", Input: 10, Output: 2, Status: 200})
sessions.Reset()
forgetStats()
t.Cleanup(func() { sessions.Reset(); forgetStats() })
mux := http.NewServeMux()
sessionRoutes(mux, folderOnly{})
get := func(path, tag string) *httptest.ResponseRecorder {
t.Helper()
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", path, nil)
r.Header.Set("X-Magpie-Had", tag)
mux.ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
}
return w
}
first := get("/api/sessions", "")
var list sessionsJSON
if err := json.Unmarshal(first.Body.Bytes(), &list); err != nil {
t.Fatal(err)
}
if len(list.Sessions) != 3 {
t.Fatalf("list has %d sessions", len(list.Sessions))
}
for _, s := range list.Sessions {
if len(s.Models) != 1 || s.Models[0].Model != "auto/deepseek-flash" {
t.Fatalf("list's group names: %+v", s.Models)
}
}
var stats struct {
Days []sessions.Day `json:"days"`
}
if err := json.Unmarshal(get("/api/sessions/stats?days=0", "").Body.Bytes(), &stats); err != nil {
t.Fatal(err)
}
total := 0
for _, d := range stats.Days {
for _, u := range d.Usage {
if u.Model != "auto/deepseek-flash" {
t.Fatalf("duplicate model option: %q", u.Model)
}
total += u.Input
}
}
if total != 30 {
t.Fatalf("stats input %d, want 30", total)
}
for _, model := range []string{"auto/deepseek-flash", "group/auto-deepseek-flash"} {
var o sessions.Overview
if err := json.Unmarshal(get("/api/sessions/overview?days=0&model="+url.QueryEscape(model), "").Body.Bytes(), &o); err != nil {
t.Fatal(err)
}
if o.Count != 3 {
t.Fatalf("%s filter lost sessions: %+v", model, o)
}
}
tag := first.Header().Get("X-Magpie-Tag")
if w := get("/api/sessions", tag); w.Header().Get("X-Magpie-Same") != "1" {
t.Fatal("unchanged names did not keep the list tag")
}
if err := provider.SetAutoGroups(false); err != nil {
t.Fatal(err)
}
if w := get("/api/sessions", tag); w.Header().Get("X-Magpie-Same") == "1" {
t.Fatal("group catalog changed but list kept old names")
}
}
+43 -6
View File
@@ -68,10 +68,18 @@ func IsGroupRef(ref string) bool {
// back to it before key limits, routing and the usage log see it, so the
// two ids of one group are one.
func CanonicalRef(ref string) string {
if !strings.HasPrefix(strings.TrimSpace(ref), AutoPrefix) {
return ref
}
return canonicalRef(ref, autoRefsOn())
}
// canonicalRef uses the ownership read by its caller, without reading settings.
func canonicalRef(ref string, enabled bool) string {
s := strings.TrimSpace(ref)
s, marked := strings.CutSuffix(s, "[1m]")
m, ok := strings.CutPrefix(s, AutoPrefix)
if !ok || strings.TrimSpace(m) == "" || !autoRefsOn() {
if !ok || strings.TrimSpace(m) == "" || !enabled {
return ref
}
level := ""
@@ -135,24 +143,53 @@ func (g Group) Ref() string {
// (Group.Ref), its effort and [1m] mark kept; any other ref as it is, a
// found group magpie has none of now too.
func PublicRef(ref string) string {
s := strings.TrimSpace(ref)
if !strings.HasPrefix(s, AutoPrefix) && !strings.HasPrefix(s, GroupPrefix+"auto-") {
return ref
}
if !autoRefsOn() {
return ref
}
return publicRef(ref, func(gid string) string {
g, _ := groupOf(sharedGroups(), gid)
return g.Spelled
})
}
// PublicRefs snapshots the found groups' public spellings for a whole usage
// read. The returned mapper reads no files or shared catalog; nil means the
// public namespace is inactive or no found group has a public spelling.
func PublicRefs() func(string) string {
groups := usageGroupNames()
if len(groups) == 0 {
return nil
}
return func(ref string) string {
return publicRef(ref, func(gid string) string { return groups[gid] })
}
}
// publicRef uses a group's spelling read by the caller. Usage takes a snapshot
// before its locks, so naming each row never reads providers or settings.
func publicRef(ref string, spelling func(string) string) string {
s := strings.TrimSpace(ref)
if strings.HasPrefix(s, AutoPrefix) {
s = CanonicalRef(s)
s = canonicalRef(s, true)
}
s, marked := strings.CutSuffix(s, "[1m]")
gid, ok := strings.CutPrefix(s, GroupPrefix)
if !ok || !strings.HasPrefix(gid, "auto-") || !autoRefsOn() {
if !ok || !strings.HasPrefix(gid, "auto-") {
return ref
}
level := ""
if i := strings.LastIndex(gid, ":"); i > 0 {
gid, level = gid[:i], gid[i:]
}
g, ok := groupOf(sharedGroups(), gid)
if !ok || g.Spelled == "" {
model := spelling(gid)
if model == "" {
return ref
}
out := g.Ref() + level
out := AutoPrefix + model + level
if marked {
out += "[1m]"
}
+61
View File
@@ -0,0 +1,61 @@
package provider
import (
"encoding/json"
"os"
"testing"
)
// Found groups keep one usage name, even when an agent wrote the old id or
// another vendor spelling into a session. Ordinary models remain distinct.
func TestUsageFoundGroupNames(t *testing.T) {
autoRefHome(t)
alias := UsageAlias()
if alias == nil {
t.Fatal("found group has no usage name mapper")
}
for _, ref := range []string{"group/auto-claude-opus-5-5", "auto/claude-opus-5-5", "auto/claude-opus-5.5"} {
if got := alias(ref); got != "auto/claude-opus-5.5" {
t.Errorf("%s counted as %q", ref, got)
}
if got := alias(ref + ":high[1m]"); got != "auto/claude-opus-5.5:high[1m]" {
t.Errorf("effort/window lost: %q", got)
}
}
for _, ref := range []string{"claude-opus-5-5", "a/claude-opus-5-5", "group/mine", "group/auto-gone", "auto/gone"} {
if got := alias(ref); got != ref {
t.Errorf("unrelated model %q counted as %q", ref, got)
}
}
key := UsageNamesKey()
if _, err := SetUsageAlias("claude-opus-5.5", "opus"); err != nil {
t.Fatal(err)
}
alias = UsageAlias()
if alias("group/auto-claude-opus-5-5") != "opus" || alias("auto/claude-opus-5.5") != "opus" {
t.Fatal("the two ids did not follow the same user alias")
}
if UsageNamesKey() == key {
t.Fatal("a user's alias did not invalidate usage names")
}
}
func TestUsageFoundGroupNamesKeepAutoProvider(t *testing.T) {
autoRefHome(t)
// A provider saved before auto was reserved still owns this namespace.
f := load()
f.Providers = append(f.Providers, Provider{ID: "auto", Name: "Legacy auto", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"claude-opus-5.5"}})
b, err := json.Marshal(f)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(Path(), b, 0o600); err != nil {
t.Fatal(err)
}
alias := UsageAlias()
for _, ref := range []string{"auto/claude-opus-5.5", "group/auto-claude-opus-5-5"} {
if alias != nil && alias(ref) != ref {
t.Fatalf("legacy provider's %s was renamed", ref)
}
}
}
+50 -8
View File
@@ -1,6 +1,7 @@
package provider
import (
"encoding/json"
"errors"
"fmt"
"maps"
@@ -164,15 +165,56 @@ func usageAliasesNow() map[string]string {
return m
}
// UsageAlias is the name a model's usage is counted under: the alias the
// user set for it, followed through any alias of that, else the model's
// own id. It is nil when there are no aliases, so a caller does nothing
// for each row. Read once for a whole summary, not for each row; it reads
// settings.json, so it is taken before any lock a reader of the usage
// waits on.
func UsageAlias() func(string) string { return usageAliasOf(usageAliasesNow()) }
// UsageAlias names a model's usage after pricing: a found group's public id,
// then the user's alias. Both group spellings count together, including in
// old session files. Read once before any usage lock; the returned function
// reads no settings or providers. It is nil when no names need mapping.
func UsageAlias() func(string) string {
alias, groups := usageAliasOf(usageAliasesNow()), usageGroupNames()
if len(groups) == 0 {
return alias
}
var memo sync.Map
return func(model string) string {
if v, ok := memo.Load(model); ok {
return v.(string)
}
out := publicRef(model, func(gid string) string { return groups[gid] })
if alias != nil {
out = alias(out)
}
memo.Store(model, out)
return out
}
}
// UsageAliasIn is UsageAlias for the aliases m.
// usageGroupNames is the spelling of every found group that has a public id.
// A user's pre-existing provider named auto keeps ownership of auto/<model>.
func usageGroupNames() map[string]string {
var names map[string]string
if autoRefsOn() {
for _, g := range sharedGroups() {
if g.Spelled != "" {
if names == nil {
names = map[string]string{}
}
names[g.ID] = g.Spelled
}
}
}
return names
}
// UsageNamesKey changes when an alias or a found group's public spelling does,
// so a cached view never holds the names from before a catalog change.
func UsageNamesKey() string {
b, _ := json.Marshal(struct {
Aliases, Groups map[string]string
}{usageAliasesNow(), usageGroupNames()})
return string(b)
}
// UsageAliasIn maps only the user aliases m, without the current group catalog.
func UsageAliasIn(m map[string]string) func(string) string { return usageAliasOf(m) }
func usageAliasOf(m map[string]string) func(string) string {
+35 -5
View File
@@ -1,17 +1,22 @@
package sessions
import "sort"
import (
"slices"
"sort"
)
// A session's models are counted under the names the user gave them
// (provider.UsageAlias, `magpie model alias`): two ids of one model are one
// row. Each was priced by its own id before; the merged row adds those
// costs and is priced only when every id in it was. Everything here makes
// new slices, so what List and Stats keep for the next read is never
// changed.
// costs and is priced only when every id in it was. Changed rows use new
// slices, so what List and Stats keep for the next read is never changed.
// aliasModels is ms with the models alias names alike made one, the most
// used first as assembleListed sorts them.
func aliasModels(ms []Model, alias func(string) string) []Model {
if !slices.ContainsFunc(ms, func(m Model) bool { return alias(m.Model) != m.Model }) {
return ms
}
out := make([]Model, 0, len(ms))
at := make(map[string]int, len(ms))
for _, m := range ms {
@@ -57,9 +62,28 @@ func aliasSession(s *Session, alias func(string) string) {
s.ModelEffort = aliasEffort(s.ModelEffort, alias)
}
// aliasManaged names the management page's sessions after their own pricing.
// Its mapper is read before the session lock, like List's and Stats'.
func aliasManaged(ms []Managed, alias func(string) string) {
if alias != nil {
for i := range ms {
aliasSession(&ms[i].Session, alias)
}
}
}
// aliasStats is st with each day's usage and each session's models counted
// under their aliases.
func aliasStats(st Stats, alias func(string) string) Stats {
changed := slices.ContainsFunc(st.Days, func(d Day) bool {
return slices.ContainsFunc(d.Usage, func(u Usage) bool { return alias(u.Model) != u.Model })
}) || slices.ContainsFunc(st.Sessions, func(s Summary) bool {
return slices.ContainsFunc(s.Models, func(m string) bool { return alias(m) != m }) ||
slices.ContainsFunc(s.ModelEffort, func(e ModelEffort) bool { return alias(e.Model) != e.Model })
})
if !changed {
return st
}
days := make([]Day, len(st.Days))
for i, d := range st.Days {
d.Usage = aliasUsage(d.Usage, alias)
@@ -79,6 +103,9 @@ func aliasStats(st Stats, alias func(string) string) Stats {
// aliasUsage is a day's usage with the rows of one agent, folder and
// aliased model made one, in the order they first came.
func aliasUsage(us []Usage, alias func(string) string) []Usage {
if !slices.ContainsFunc(us, func(u Usage) bool { return alias(u.Model) != u.Model }) {
return us
}
type key struct{ agent, cwd, model string }
out := make([]Usage, 0, len(us))
at := make(map[key]int, len(us))
@@ -102,6 +129,9 @@ func aliasUsage(us []Usage, alias func(string) string) []Usage {
// aliasNames is names under their aliases, each once, in the order they
// first came (the most used first stays first).
func aliasNames(names []string, alias func(string) string) []string {
if !slices.ContainsFunc(names, func(n string) bool { return alias(n) != n }) {
return names
}
out := make([]string, 0, len(names))
seen := make(map[string]bool, len(names))
for _, n := range names {
@@ -117,7 +147,7 @@ func aliasNames(names []string, alias func(string) string) []string {
// aliasEffort is a session's model and effort rows with those of one
// aliased model and effort made one, in the order they first came.
func aliasEffort(es []ModelEffort, alias func(string) string) []ModelEffort {
if len(es) == 0 {
if !slices.ContainsFunc(es, func(e ModelEffort) bool { return alias(e.Model) != e.Model }) {
return es
}
type key struct{ model, effort string }
+7 -1
View File
@@ -12,6 +12,7 @@ import (
"strings"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
@@ -155,13 +156,16 @@ func agentCounts(all []file) []AgentCount {
// ListAgent is every session of one agent, the most recently active first,
// with no limit; one nothing was said in is listed too, to be cleared away.
func ListAgent(agent string) []Managed {
alias := provider.UsageAlias()
storeMu.RLock()
defer storeMu.RUnlock()
mu.Lock()
defer mu.Unlock()
loadCache()
defer useDBs()()
return listAgent(agent, allFiles())
out := listAgent(agent, allFiles())
aliasManaged(out, alias)
return out
}
// NativeIDs are the ids of every session the agents named keep themselves,
@@ -196,6 +200,7 @@ type ManageView struct {
// Only native's agents and the one picked are read: a change to another
// agent's sessions waits for a page that shows it (#2776).
func Manage(native map[string]bool, pick func([]AgentCount, map[string]map[string]bool) string) ManageView {
alias := provider.UsageAlias()
storeMu.RLock()
defer storeMu.RUnlock()
mu.Lock()
@@ -207,6 +212,7 @@ func Manage(native map[string]bool, pick func([]AgentCount, map[string]map[strin
v.Agent = pick(v.Agents, v.Native)
if v.Agent != "" {
v.Sessions = listAgentWith(v.Agent, all, true)
aliasManaged(v.Sessions, alias)
}
return v
}
+98
View File
@@ -0,0 +1,98 @@
package sessions
import (
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
func TestSessionsFoundGroupNames(t *testing.T) {
inZone(t, 0)
claude, _ := setup(t)
PriceOf = priceOf
for _, id := range []string{"ds-a", "ds-b"} {
if err := provider.Save(provider.Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"deepseek-flash"}}); err != nil {
t.Fatal(err)
}
}
cfg := settings.Load()
cfg.ModelPrices = map[string]settings.ModelPrice{
"*/auto-deepseek-flash": {Input: new(2.0), Output: new(0.0), CacheRead: new(0.0), CacheWrite: new(0.0)},
"*/deepseek-flash": {Input: new(5.0), Output: new(0.0), CacheRead: new(0.0), CacheWrite: new(0.0)},
}
if err := settings.Save(cfg); err != nil {
t.Fatal(err)
}
dir := filepath.Join(claude, "projects", "-work-alias")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
id := "44444444-2222-3333-4444-555555555555"
body := aliasMsg("m1", "group/auto-deepseek-flash", "2026-09-25T10:00:00Z", 1000000) + aliasMsg("m2", "auto/deepseek-flash", "2026-09-25T10:01:00Z", 1000000)
if err := os.WriteFile(filepath.Join(dir, id+".jsonl"), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
check := func(s Session) {
t.Helper()
if len(s.Models) != 1 || s.Models[0].Model != "auto/deepseek-flash" || s.Input != 2000000 || s.Models[0].Input != 2000000 || !near(s.Cost, 7) || !near(s.Models[0].Cost, 7) {
t.Fatalf("split group or changed price: %+v", s)
}
}
for range 2 { // the kept parse still has its original ids and prices
var found bool
for _, s := range List(All) {
if s.ID == id {
found = true
check(s)
}
}
if !found {
t.Fatal("missing native session")
}
}
if s, ok := Get("claude:" + id); !ok {
t.Fatal("Get missing session")
} else {
check(s)
}
if s, ok := Find("claude", id); !ok {
t.Fatal("Find missing session")
} else {
check(s)
}
for _, list := range [][]Managed{ListAgent("claude"), Manage(nil, func([]AgentCount, map[string]map[string]bool) string { return "claude" }).Sessions} {
found := false
for _, s := range list {
if s.ID == id {
found = true
check(s.Session)
}
}
if !found {
t.Fatal("management list lost session")
}
}
st := statsAt(0, statsNow)
var rows []Usage
for _, d := range st.Days {
for _, u := range d.Usage {
if u.Cwd == "/work/alias" {
rows = append(rows, u)
}
}
}
if len(rows) != 1 || rows[0].Model != "auto/deepseek-flash" || rows[0].Input != 2000000 || !near(rows[0].Cost, 7) {
t.Fatalf("model filter would split: %+v", rows)
}
for _, s := range st.Sessions {
if s.ID == id && (len(s.Models) != 1 || s.Models[0] != "auto/deepseek-flash") {
t.Fatalf("summary split: %+v", s)
}
}
if got := st.Overview("claude", "auto/deepseek-flash", "/work/alias", 8); got.Count != 1 {
t.Fatalf("overview lost group: %+v", got)
}
}
+7 -7
View File
@@ -37,21 +37,21 @@ var clearedAs atomic.Pointer[clearSet]
// reader of the usage waits on.
func readCleared() *clearSet {
marks := settings.UsageClearedNow()
var aliases map[string]string
names := ""
if len(marks) > 0 {
aliases = provider.UsageAliases()
names = provider.UsageNamesKey()
}
b, _ := json.Marshal(struct {
M []settings.UsageClear
A map[string]string
}{marks, aliases})
N string
}{marks, names})
key := string(b)
if cur := clearedAs.Load(); cur != nil && cur.key == key {
return cur
}
c := &clearSet{marks: marks, key: key}
if len(aliases) > 0 {
c.alias = provider.UsageAliasIn(aliases)
if len(marks) > 0 {
c.alias = provider.UsageAlias()
}
for _, m := range marks {
if m.Provider == "" && m.Model == "" && m.Time().After(c.all) {
@@ -92,7 +92,7 @@ func (c *clearSet) hides(r *Record) bool {
if model == "" {
model = c.alias(r.Model)
}
if model == m.Model {
if model == c.alias(m.Model) {
return true
}
}
+33
View File
@@ -2,12 +2,14 @@ package usage
import (
"hash/maphash"
"maps"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
)
@@ -593,6 +595,37 @@ var effortBuilt func()
// never write it. A copy of every thread's for each ask was ~230 MB every
// 80 s of a Sessions page open over a large history (#2278).
func CodexModelEffort(p Period) map[string][]sessions.ModelEffort {
return namedModelEffort(keptCodexModelEffort(p), provider.UsageAlias())
}
// namedModelEffort maps only the returned view. The ledger and its kept sums
// retain their original model ids and prices, as session parses do.
func namedModelEffort(in map[string][]sessions.ModelEffort, alias func(string) string) map[string][]sessions.ModelEffort {
if alias == nil {
return in
}
var out map[string][]sessions.ModelEffort
for actor, rows := range in {
if !slices.ContainsFunc(rows, func(r sessions.ModelEffort) bool { return alias(r.Model) != r.Model }) {
continue
}
if out == nil {
out = maps.Clone(in)
}
sums := effortSums{}
for _, row := range rows {
row.Model = alias(row.Model)
sums.addValue(actor, row)
}
out[actor] = sums.values()[actor]
}
if out != nil {
return out
}
return in
}
func keptCodexModelEffort(p Period) map[string][]sessions.ModelEffort {
if LogCalls != nil { // synthetic logs carry no state to key on
return codexModelEffort(codexEffortRows(p, Clock(), LogCalls))
}
+37 -8
View File
@@ -183,6 +183,15 @@ func (f Filter) keeps(r Record) bool {
return f.keepsRecord(&r, false, "", "")
}
// sameGroupModel is whether a record's model is the found routing group
// a filter names by its kept id (group/auto-…, FilterOf), written by an
// agent's own session file as auto/<model>. Only such pairs read the
// providers, not every record a filter passes over.
func sameGroupModel(recorded, filtered string) bool {
return strings.HasPrefix(filtered, provider.GroupPrefix) && strings.HasPrefix(recorded, provider.AutoPrefix) &&
provider.CanonicalRef(recorded) == filtered
}
func (f Filter) keepsRecord(r *Record, codexIdentity bool, subagent, parentAgent string) bool {
if f.Day != "" {
var day [len(time.DateOnly)]byte
@@ -196,7 +205,7 @@ func (f Filter) keepsRecord(r *Record, codexIdentity bool, subagent, parentAgent
if f.RouteID != 0 && r.RouteID != f.RouteID {
return false
}
if f.Model != "" && r.Model != f.Model {
if f.Model != "" && r.Model != f.Model && !sameGroupModel(r.Model, f.Model) {
return false
}
if f.Agent != "" && ReportedAs(r.Agent) != f.Agent {
@@ -1077,16 +1086,36 @@ func (r *Row) key(by string) string {
// keyer is Row.key for many rows, made once for each provider and model:
// a "modelAt" is a string built of two, which a page of thousands of rows
// would otherwise build again for each.
type keyer map[[2]string]string
type keyer struct {
public func(string) string
models map[string]string
at map[[2]string]string
}
func newKeyer() keyer {
return keyer{public: provider.PublicRefs(), models: map[string]string{}, at: map[[2]string]string{}}
}
func (m keyer) key(r *Row, by string) string {
if by != "modelAt" {
if by != "modelAt" && by != "model" {
return r.key(by)
}
k, ok := m[[2]string{r.Provider, r.Model}]
model := r.Model
if m.public != nil {
var ok bool
model, ok = m.models[r.Model]
if !ok {
model = m.public(r.Model)
m.models[r.Model] = model
}
}
if by == "model" {
return model
}
k, ok := m.at[[2]string{r.Provider, r.Model}]
if !ok {
k = r.key(by)
m[[2]string{r.Provider, r.Model}] = k
k = ModelAtKey(r.Provider, model)
m.at[[2]string{r.Provider, r.Model}] = k
}
return k
}
@@ -1105,7 +1134,7 @@ type Share struct {
func Breakdown(rows []Row, by string) []Share {
at := map[string]*Share{}
var out []*Share
keys := keyer{}
keys := newKeyer()
for _, r := range rows {
if r.IsRejected() {
continue
@@ -1226,7 +1255,7 @@ func ledgerSeriesAt(p Period, rows []Row, now time.Time) (bucket string, pts []S
}
}
kept := map[string]map[string]bool{}
keys := keyer{}
keys := newKeyer()
for _, d := range Dimensions {
kept[d] = map[string]bool{}
for i, s := range Breakdown(rows, d) {
+4 -1
View File
@@ -875,6 +875,9 @@ func readRequestState(now time.Time) requestState {
}
}
meta += fmt.Sprintf("|%x|%s", h.Sum(nil), liveListKey("antigravity"))
// Group spellings also name chart shares and the model filter. A change
// must invalidate cells whose filter was judged under the old namespace.
meta += "|" + provider.UsageNamesKey()
h.Reset()
snapshot := readLogSnapshot()
fmt.Fprint(h, meta, snapshot.version, now.In(time.Local).Format("2006-01-02 MST"))
@@ -2489,7 +2492,7 @@ func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time,
groups := map[string]map[string]*Share{}
chartGroups := map[string]map[string]*Share{}
seriesGroups := map[string]map[string]*Share{}
keys := keyer{}
keys := newKeyer()
for _, d := range Dimensions {
groups[d] = map[string]*Share{}
chartGroups[d] = map[string]*Share{}
+1 -2
View File
@@ -139,8 +139,7 @@ func usagePriceCacheKey(now time.Time) string {
prices, _ := json.Marshal(st.ModelPrices)
aliases := provider.UsageRenames().Key()
// and the names models' usage is counted under, which the groups key on
usageAliases, _ := json.Marshal(st.UsageAliases)
fmt.Fprint(h, string(prices), string(aliases), string(usageAliases))
fmt.Fprint(h, string(prices), string(aliases), provider.UsageNamesKey())
for _, current := range provider.All() {
fmt.Fprintf(h, "%q:%q:%v:%t:%t:%t;", current.ID, current.Where(), current.Catalogs(), current.IsPlugin(), current.Account == nil, current.Key != "")
if current.Account != nil {
+96
View File
@@ -0,0 +1,96 @@
package usage
import (
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
"github.com/yetone/magpie/internal/settings"
)
func TestUsageFoundGroupNames(t *testing.T) {
resetUsageTest(t)
for _, id := range []string{"ds-a", "ds-b"} {
if err := provider.Save(provider.Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"deepseek-flash"}}); err != nil {
t.Fatal(err)
}
}
at := Clock().Add(-time.Minute)
for i, model := range []string{"group/auto-deepseek-flash", "auto/deepseek-flash"} {
Append(Record{Time: at, Agent: "pi", Session: "auto-ref", Provider: "relay", Model: model, Input: (i + 1) * 10, Status: 200})
}
check := func() {
t.Helper()
got := GatewaySessions(time.Time{}, nil)
if len(got) != 1 || len(got[0].Models) != 1 || got[0].Models[0].Model != "auto/deepseek-flash" || got[0].Input != 30 {
t.Fatalf("gateway session split: %+v", got)
}
_, days := GatewaySessionWindow(time.Time{})
if len(days) != 1 || days[0].Model != "auto/deepseek-flash" || days[0].Input != 30 {
t.Fatalf("gateway days split: %+v", days)
}
if s := Summarize(All); len(s.Models) != 1 || s.Models[0].Model != "auto/deepseek-flash" || s.Input != 30 {
t.Fatalf("usage overview split: %+v", s.Models)
}
}
check()
check() // cached reads
for _, model := range []string{"auto/deepseek-flash", "group/auto-deepseek-flash"} {
// the API takes either id to the kept one (usageapi.FilterOf)
page := QueryPage(All, Filter{Model: provider.CanonicalRef(model)}, 0, 20)
if page.Total != 2 || page.Sum.Input != 30 {
t.Fatalf("request filter %s split group: %d rows, %d input", model, page.Total, page.Sum.Input)
}
for _, dim := range []string{"model", "modelAt"} {
want := "auto/deepseek-flash"
if dim == "modelAt" {
want = "relay/" + want
}
if got := page.By[dim]; len(got) != 1 || got[0].ID != want || got[0].Input != 30 {
t.Fatalf("%s ranking split group: %+v", dim, got)
}
}
}
// Clearing the displayed group also clears calls recorded under its old id.
cfg := settings.Load()
cfg.UsageCleared = []settings.UsageClear{{Provider: "relay", Model: "auto/deepseek-flash", At: Clock().UnixMilli()}}
if err := settings.Save(cfg); err != nil {
t.Fatal(err)
}
if s := Summarize(All); s.Calls != 0 {
t.Fatalf("old group id survived clear: %+v", s.Models)
}
}
// Codex's model/effort rows are attached after the native session is listed.
// They use the same names and keep the cost of both original ids.
func TestCodexEffortFoundGroupNames(t *testing.T) {
resetUsageTest(t)
for _, id := range []string{"ds-a", "ds-b"} {
if err := provider.Save(provider.Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"deepseek-flash"}}); err != nil {
t.Fatal(err)
}
}
in := map[string][]sessions.ModelEffort{"thread": {
{Model: "group/auto-deepseek-flash", Effort: "high", Tokens: sessions.Tokens{Input: 10}, Reasoning: 3, Cost: 2, Priced: true},
{Model: "auto/deepseek-flash", Effort: "high", Tokens: sessions.Tokens{Input: 20}, Reasoning: 5, Cost: 7, Priced: false},
{Model: "auto/deepseek-flash", Effort: "low", Tokens: sessions.Tokens{Input: 4}, Cost: 1, Priced: true},
}}
got := namedModelEffort(in, provider.UsageAlias())["thread"]
if len(got) != 2 {
t.Fatalf("effort rows split: %+v", got)
}
for _, row := range got {
if row.Model != "auto/deepseek-flash" {
t.Fatalf("effort's group: %+v", row)
}
if row.Effort == "high" && (row.Input != 30 || row.Reasoning != 8 || row.Cost != 9 || row.Priced) {
t.Fatalf("effort totals changed: %+v", row)
}
}
if len(in["thread"]) != 3 || in["thread"][0].Model != "group/auto-deepseek-flash" {
t.Fatal("kept effort was changed")
}
}
+41
View File
@@ -0,0 +1,41 @@
package usageapi
import (
"net/url"
"path/filepath"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
func TestLedgerFoundGroupNames(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"))
for _, id := range []string{"ds-a", "ds-b"} {
if err := provider.Save(provider.Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"deepseek-flash"}}); err != nil {
t.Fatal(err)
}
}
for i, ref := range []string{"auto/deepseek-flash", "group/auto-deepseek-flash"} {
usage.Append(usage.Record{Time: time.Now().Add(-time.Duration(i+1) * time.Minute), Agent: "pi", Provider: "relay", Model: ref, Requested: ref, Input: 10, Status: 200})
}
for _, model := range []string{"auto/deepseek-flash", "group/auto-deepseek-flash"} {
if page := LedgerPage(usage.All, FilterOf(url.Values{"model": {model}}), 0, 20); len(page.Rows) != 2 {
t.Fatalf("model filter %s dropped the other id: %d rows", model, len(page.Rows))
}
}
page := LedgerPage(usage.All, FilterOf(url.Values{"model": {"auto/deepseek-flash"}}), 0, 20)
for _, row := range page.Rows {
if row.Model != "auto/deepseek-flash" || row.Requested != "auto/deepseek-flash" {
t.Fatalf("ledger leaked internal name: model %q, requested %q", row.Model, row.Requested)
}
}
if got := page.By["model"]; len(got) != 1 || got[0].ID != "auto/deepseek-flash" {
t.Fatalf("model menu split: %+v", got)
}
}
+7 -7
View File
@@ -224,9 +224,12 @@ func PeriodOf(s string) usage.Period {
return usage.Month
}
// FilterOf is the filter a request's query names. A found routing group's
// model is taken as magpie keeps it (group/auto-…), as the menu offers it
// by its public auto/<model>, so either id picks the group's calls.
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", Retried: q.Get("retried") == "1", Query: q.Get("q"), Computer: q.Get("computer"), Through: viaOf(q.Get("via"))}
return usage.Filter{Day: q.Get("day"), RouteID: id, Model: provider.CanonicalRef(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", Retried: q.Get("retried") == "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.
@@ -361,15 +364,12 @@ func LedgerPage(p usage.Period, f usage.Filter, offset, limit int) Ledger {
}
// a group magpie found is named as agents pick it, auto/<model>; the
// ledger keeps group/auto-<slug> (provider.CanonicalRef)
pub := map[string]string{}
pub := provider.PublicRefs()
for _, r := range page {
a := who(r.Agent)
lr := Row{Row: r, AgentName: a.Name, Icon: a.Icon, ProviderName: which(r.Provider).Name, Canceled: r.Canceled()}
if req := r.Requested; strings.HasPrefix(req, provider.GroupPrefix) {
if _, ok := pub[req]; !ok {
pub[req] = provider.PublicRef(req)
}
lr.Requested = pub[req]
if pub != nil {
lr.Model, lr.Requested = pub(r.Model), pub(r.Requested)
}
if r.Source != "log" && r.Source != usage.SourceReported {
lr.Access = access[r.Provider]