usage: a model list fetched again unchanged keeps the usage index

Each account's model list is fetched again on every start and every 45
minutes, and saveLive writes it again with only its "fetched" time moved.
Usage keyed the request index (and its file on disk, requests-v1.bin) and
the priced summaries on that file's mtime (statKey(catalog.LivePath)), so
each such save dropped every chunk: every start, and every refresh while
running, read the whole session history again, decoded every call shard
and rebuilt every row.

catalog.LiveKey names a saved list by a hash of its bytes without the
fetch time, made once per parse of the file (readLive's memo). A list
saved before Since was kept is dated by its fetch (LiveSince), so its
fetch time stays in its key. usage's liveListKey uses it for every
provider and Antigravity in readRequestState's meta and in
usagePriceCacheKey (the same mtime key, the sibling), and falls back to
the stat when the list can't be read.

Found by dumping both disk headers on mote: same binary, same sources,
and only the providers' hash differed, run to run.

Measured on mote, a copy of the owner's real accounts, GUI open, network
blocked, the Claude list rewritten as a start's fetch does. Restart of
the same build, t10 (main) against t11 (this):
  CPU in the first ~3 minutes   11.6s -> 2.5s
  allocated                     2.74GB -> 0.81GB
  sessions.loadCalls            771MB -> gone from the top
  footprint                     174MB -> 175MB
The first start after an upgrade that changes usage's code still builds
everything once (requestDiskBinary), as before.

Tests: TestRequestStateKeptAcrossAListFetchedAgain saves the same list
again an hour later and needs readRequestState's meta and
usagePriceCacheKey unchanged, and both changed for another list; on the
old usage code it is red on both. TestLiveKeyOnlyMovesWithTheList and
TestLiveKeyOfAnOldListKeepsItsFetch cover the key itself.

Run on mote at this tree: go test ./internal/catalog ./internal/usage
./internal/provider -count=1 ok; go vet ./... ok; GOOS darwin/linux/
windows go vet ./internal/catalog ./internal/usage ok (./... cross-OS
stops at wails' cgo files, as on main); gofmt clean.
Not run: the full ./... suite before the push (running after), GUI.
This commit is contained in:
yetone
2026-11-10 00:36:16 +08:00
parent 80161247a0
commit 7e5cebb86c
5 changed files with 172 additions and 4 deletions
+39
View File
@@ -3,6 +3,8 @@ package catalog
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -58,6 +60,8 @@ type liveFile struct {
// the list each time cost 2,500 models' /v1/models seconds (K.Liu on
// Discord)
byID map[string][]Model
// key names what the file holds but for when it was fetched (LiveKey)
key string
}
func readLive(provider string) (liveFile, error) {
@@ -66,6 +70,7 @@ func readLive(provider string) (liveFile, error) {
if err := json.Unmarshal(b, &f); err != nil {
return f, err
}
f.key = liveKey(b, f.Since != nil)
mendKinds(f.Models)
for _, side := range f.Sides {
mendKinds(side)
@@ -96,6 +101,40 @@ func mendKinds(ms []Model) {
}
}
// LiveKey names the list saved for provider by what it holds, not by
// when it was fetched: each account's list is fetched again every 45
// minutes and on every start, and saved again with only its fetch time
// moved (saveLive). Usage keyed its whole index on the file's mtime, so
// each of those saves dropped it, and every start and every refresh read
// the whole session history again (~1.5 GB allocated, seconds of CPU).
// "missing" when there is no list; ok is false when it can't be read.
func LiveKey(provider string) (key string, ok bool) {
f, err := readLive(provider)
if errors.Is(err, os.ErrNotExist) {
return "missing", true
}
if err != nil {
return "", false
}
return f.key, true
}
// liveKey hashes a saved list's bytes without its fetch time, the first
// key saveLive writes. A list saved before Since was kept is dated by its
// fetch (LiveSince), so its fetch time is part of what it holds.
func liveKey(b []byte, dropFetched bool) string {
h := sha256.New()
if i := bytes.Index(b, []byte(`"fetched":`)); dropFetched && i >= 0 {
if j := bytes.IndexByte(b[i:], '\n'); j >= 0 {
h.Write(b[:i])
h.Write(b[i+j:])
return hex.EncodeToString(h.Sum(nil))
}
}
h.Write(b)
return hex.EncodeToString(h.Sum(nil))
}
// LiveByID are the models of Live with this id, in the list's order
// (a list may name one twice): what a look through Live finds, without
// the list copied for each model asked about.
+70
View File
@@ -0,0 +1,70 @@
package catalog
import (
"os"
"path/filepath"
"testing"
"time"
)
// A list fetched again as it was keeps its key: what usage builds on it
// is kept. A list that differs in anything but when it was fetched, or is
// gone, gets another.
func TestLiveKeyOnlyMovesWithTheList(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
key := func() string {
t.Helper()
k, ok := LiveKey("acct")
if !ok {
t.Fatal("LiveKey not ok")
}
return k
}
if k := key(); k != "missing" {
t.Fatalf("no list: %q", k)
}
a := []Model{{ID: "gpt-a", Context: 200000}, {ID: "gpt-b"}}
if err := SaveLive("acct", "https://a/v1", a); err != nil {
t.Fatal(err)
}
first := key()
old := time.Now().Add(-time.Hour)
if err := os.Chtimes(LivePath("acct"), old, old); err != nil {
t.Fatal(err)
}
if err := SaveLive("acct", "https://a/v1", []Model{{ID: "gpt-a", Context: 200000}, {ID: "gpt-b"}}); err != nil {
t.Fatal(err)
}
if f, _ := readLive("acct"); f.Fetched.Before(old.Add(30 * time.Minute)) {
t.Fatalf("not saved again: fetched %v", f.Fetched)
}
if k := key(); k != first {
t.Errorf("the same list fetched again: key %q, was %q", k, first)
}
if err := SaveLive("acct", "https://a/v1", []Model{{ID: "gpt-a", Context: 100000}, {ID: "gpt-b"}}); err != nil {
t.Fatal(err)
}
if k := key(); k == first {
t.Error("a list with a model changed kept its key")
}
os.Remove(LivePath("acct"))
if k := key(); k != "missing" {
t.Errorf("list removed: %q", k)
}
}
// A list saved before Since was kept is dated by its fetch, so its fetch
// time is part of its key.
func TestLiveKeyOfAnOldListKeepsItsFetch(t *testing.T) {
a := []byte("{\n \"fetched\": \"2026-01-01T00:00:00Z\",\n \"models\": [{\"id\":\"m\"}]\n}")
b := []byte("{\n \"fetched\": \"2026-02-01T00:00:00Z\",\n \"models\": [{\"id\":\"m\"}]\n}")
if liveKey(a, false) == liveKey(b, false) {
t.Error("an old list's fetch time left out of its key")
}
if liveKey(a, true) != liveKey(b, true) {
t.Error("a list's fetch time in its key")
}
}
+45
View File
@@ -0,0 +1,45 @@
package usage
import (
"os"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
)
// A provider's list is saved again on every start and each 45 minutes,
// changed only in when it was fetched. Keyed on the file's mtime, each save
// dropped the request index's chunks (and the file of them on disk) and
// the priced summaries, so every start read the whole session history
// again. Only a list that changed may drop them.
func TestRequestStateKeptAcrossAListFetchedAgain(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
save := func(ctx int) {
t.Helper()
if err := catalog.SaveLive("antigravity", "https://a/v1", []catalog.Model{{ID: "m", Context: ctx}}); err != nil {
t.Fatal(err)
}
}
save(1000)
before, price := readRequestState(now).meta, usagePriceCacheKey(now)
old := time.Now().Add(-time.Hour)
if err := os.Chtimes(catalog.LivePath("antigravity"), old, old); err != nil {
t.Fatal(err)
}
save(1000)
if st, err := os.Stat(catalog.LivePath("antigravity")); err != nil || !st.ModTime().After(old.Add(30*time.Minute)) {
t.Fatalf("not saved again: %v %v", st, err)
}
if got := readRequestState(now).meta; got != before {
t.Error("the same list fetched again changed the request index's meta")
}
if got := usagePriceCacheKey(now); got != price {
t.Error("the same list fetched again changed the price key")
}
save(2000)
if readRequestState(now).meta == before || usagePriceCacheKey(now) == price {
t.Error("a list that changed kept the request meta or the price key")
}
}
+16 -2
View File
@@ -796,6 +796,20 @@ func statKey(path string) string {
}
return fmt.Sprintf("%s:%d:%d", path, s.Size(), s.ModTime().UnixNano())
}
// liveListKey names a provider's fetched model list by what it holds
// (catalog.LiveKey), not its mtime: the list is saved again, unchanged
// but for its fetch time, on every start and every 45 minutes, and each
// save dropped every chunk and summary built on it. A list that can't be
// read is named by its stat, as before.
func liveListKey(id string) string {
p := catalog.LivePath(id)
if k, ok := catalog.LiveKey(id); ok {
return p + ":" + k
}
return statKey(p)
}
func recordHash(path string, n int64) string {
f, e := os.Open(path)
if e != nil {
@@ -844,7 +858,7 @@ func readRequestState(now time.Time) requestState {
h := sha256.New()
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 != "")
fmt.Fprint(h, statKey(catalog.LivePath(current.ID)))
fmt.Fprint(h, liveListKey(current.ID))
}
for _, root := range sessions.DesktopDataDirs() {
for _, kind := range []string{"local-agent-mode-sessions", "claude-code-sessions"} {
@@ -854,7 +868,7 @@ func readRequestState(now time.Time) requestState {
}
}
}
meta += fmt.Sprintf("|%x|%s", h.Sum(nil), statKey(catalog.LivePath("antigravity")))
meta += fmt.Sprintf("|%x|%s", h.Sum(nil), liveListKey("antigravity"))
h.Reset()
snapshot := readLogSnapshot()
fmt.Fprint(h, meta, snapshot.version, now.In(time.Local).Format("2006-01-02 MST"))
+2 -2
View File
@@ -131,7 +131,7 @@ func cloneSummary(s Summary) Summary {
// usagePriceCacheKey invalidates priced views when local prices or provider feeds change.
func usagePriceCacheKey(now time.Time) string {
_, offset := now.Zone()
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%d", statKey(settings.Path()), statKey(provider.Path()), statKey(catalog.CachePath()), statKey(catalog.LivePath("antigravity")), now.Format("2006-01-02"), now.Location(), offset)
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%d", statKey(settings.Path()), statKey(provider.Path()), statKey(catalog.CachePath()), liveListKey("antigravity"), now.Format("2006-01-02"), now.Location(), offset)
// Sign-ins and plugin lists can change independently of providers.json.
// Their identity and price feeds affect both grouping and historical costs.
h := sha256.New()
@@ -148,7 +148,7 @@ func usagePriceCacheKey(now time.Time) string {
// paid ChatGPT plan only (provider.ChatGPTReviewFree)
fmt.Fprintf(h, "%q;", current.Account.Plan)
}
fmt.Fprint(h, statKey(catalog.LivePath(current.ID)))
fmt.Fprint(h, liveListKey(current.ID))
}
meta += fmt.Sprintf("|%x", h.Sum(nil))
// and the clients the user counts as agents (#1958)