diff --git a/internal/catalog/live.go b/internal/catalog/live.go index 0ddc1be9e..a8836ec44 100644 --- a/internal/catalog/live.go +++ b/internal/catalog/live.go @@ -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. diff --git a/internal/catalog/live_key_test.go b/internal/catalog/live_key_test.go new file mode 100644 index 000000000..dfac0e213 --- /dev/null +++ b/internal/catalog/live_key_test.go @@ -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") + } +} diff --git a/internal/usage/live_list_key_test.go b/internal/usage/live_list_key_test.go new file mode 100644 index 000000000..996550f18 --- /dev/null +++ b/internal/usage/live_list_key_test.go @@ -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") + } +} diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 4ed602390..b92468ce9 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -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")) diff --git a/internal/usage/summary_cache.go b/internal/usage/summary_cache.go index fdb0b8060..f102f84a0 100644 --- a/internal/usage/summary_cache.go +++ b/internal/usage/summary_cache.go @@ -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)