diff --git a/internal/catalog/cache_key.go b/internal/catalog/cache_key.go new file mode 100644 index 000000000..428d283bc --- /dev/null +++ b/internal/catalog/cache_key.go @@ -0,0 +1,72 @@ +package catalog + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "fmt" + "os" + "sync" + "time" +) + +// CacheKey names the catalog kept on disk, models.dev's provider catalog +// and the lab catalog beside it, by what the files hold, not by when they +// were written. A Claude account's model list fetches the catalog again +// every 45 minutes (Asked), and usage keyed its whole index on the file's +// mtime: each fetch, the same bytes, had the next usage query read every +// session file again, ~15 s of CPU over a long history. +func CacheKey() string { return fileKey(CachePath()) + "|" + fileKey(LabsPath()) } + +// fileKeys holds each file's last key by the stat it was hashed at, so a +// key costs a stat until the file changes. +var fileKeys = struct { + sync.Mutex + m map[string]keyedFile +}{m: map[string]keyedFile{}} + +type keyedFile struct { + size int64 + mod time.Time + key string +} + +// fileKey is a hash of path's bytes, "missing" when there is no file, and +// its stat when it can't be read: an unknown read is a change each time +// the file is written, as it was before. +func fileKey(path string) string { + st, err := os.Stat(path) + if err != nil { + return "missing" + } + fileKeys.Lock() + k, ok := fileKeys.m[path] + fileKeys.Unlock() + if ok && k.size == st.Size() && k.mod.Equal(st.ModTime()) { + return k.key + } + b, err := os.ReadFile(path) + if err != nil { + return fmt.Sprintf("stat:%d:%d", st.Size(), st.ModTime().UnixNano()) + } + sum := sha256.Sum256(b) + key := hex.EncodeToString(sum[:]) + fileKeys.Lock() + fileKeys.m[path] = keyedFile{size: st.Size(), mod: st.ModTime(), key: key} + fileKeys.Unlock() + return key +} + +// keepFetched writes b to p, unless p holds b already: then only p's time +// is now, which Stale, Missing and Asked read as the fetch. It reports +// whether p's bytes changed. +func keepFetched(p string, b []byte) (bool, error) { + if old, err := os.ReadFile(p); err == nil && bytes.Equal(old, b) { + now := time.Now() + if err := os.Chtimes(p, now, now); err != nil { + return false, err + } + return false, nil + } + return true, writeWhole(p, b, time.Time{}) +} diff --git a/internal/catalog/cache_key_test.go b/internal/catalog/cache_key_test.go new file mode 100644 index 000000000..64b3f9b70 --- /dev/null +++ b/internal/catalog/cache_key_test.go @@ -0,0 +1,97 @@ +package catalog + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "sync" + "testing" + "time" +) + +// A Claude account's list fetches the catalog again every 45 minutes +// (Asked), most often to the same bytes. Each fetch forgot the parsed +// catalog, told every agent to rewrite its list (Changed) and, as usage +// keyed its index on the file's mtime, had the next usage query read the +// whole session history again. The same bytes are only dated now; bytes +// that changed, in either file, are kept and told as before. +func TestSameCatalogFetchedAgainChangesNothing(t *testing.T) { + freshCache(t) + var mu sync.Mutex + api := `{"openai":{"id":"openai","models":{"gpt-6.1-sol":{"id":"gpt-6.1-sol","cost":{"input":2,"output":10}}}}}` + labs := `{"openai/gpt-6.1-sol":{"id":"gpt-6.1-sol","limit":{"context":400000}}}` + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + switch r.URL.Path { + case "/api.json": + w.Write([]byte(api)) + case "/models.json": + w.Write([]byte(labs)) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + pointAt(t, srv.URL+"/api.json") + told := 0 + was := Changed + Changed = func() { told++ } + t.Cleanup(func() { Changed = was; labsTried.Store(false) }) + + again := func() { + t.Helper() + if err := Sync(context.Background()); err != nil { + t.Fatal(err) + } + } + again() + if told != 1 { + t.Fatalf("a first fetch told the agents %d times", told) + } + key := CacheKey() + old := time.Now().Add(-48 * time.Hour) + if err := os.Chtimes(CachePath(), old, old); err != nil { + t.Fatal(err) + } + if !Stale() { + t.Fatal("a catalog two days old isn't stale") + } + again() + if told != 1 { + t.Error("the same catalog fetched again told the agents") + } + if got := CacheKey(); got != key { + t.Error("the same catalog fetched again changed its key") + } + if Stale() { + t.Error("the same catalog fetched again stayed stale: its time wasn't now") + } + + mu.Lock() + labs = `{"openai/gpt-6.1-sol":{"id":"gpt-6.1-sol","limit":{"context":800000}}}` + mu.Unlock() + again() + if told != 2 { + t.Error("a lab catalog that changed wasn't told") + } + if got := CacheKey(); got == key { + t.Error("a lab catalog that changed kept the key") + } + key = CacheKey() + + mu.Lock() + api = `{"openai":{"id":"openai","models":{"gpt-6.1-sol":{"id":"gpt-6.1-sol","cost":{"input":3,"output":10}}}}}` + mu.Unlock() + again() + if told != 3 { + t.Error("a catalog that changed wasn't told") + } + if got := CacheKey(); got == key { + t.Error("a catalog that changed kept the key") + } + if pr, ok := PriceOf("openai", "gpt-6.1-sol"); !ok || pr.Input != 3 { + t.Errorf("a catalog that changed wasn't read again: %+v %v", pr, ok) + } +} diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 3ce64ffb8..7133a48b9 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -880,15 +880,21 @@ func syncLock(ctx context.Context, onlyIfMissing bool) error { return fmt.Errorf("models.dev: unexpected payload") } // written whole through a rename: a reader never sees it half - // written, and a failed write keeps the last good copy - if err := writeWhole(CachePath(), b, time.Time{}); err != nil { + // written, and a failed write keeps the last good copy. The same + // bytes again are only dated now: a Claude account's list asks for a + // fetch every 45 minutes (Asked), and each one forgot the parsed + // catalog and rewrote every agent's list for nothing changed. + changed, err := keepFetched(CachePath(), b) + if err != nil { return err } // the lab catalog beside it is best effort: without it the provider // catalog answers alone, and one kept before is kept - _ = syncLabs(ctx) - Reset() - Touched() // names, reasoning levels and context windows may be others + labsChanged, _ := syncLabs(ctx) + if changed || labsChanged { + Reset() + Touched() // names, reasoning levels and context windows may be others + } return nil } diff --git a/internal/catalog/labs.go b/internal/catalog/labs.go index b2a4d86df..800ee63aa 100644 --- a/internal/catalog/labs.go +++ b/internal/catalog/labs.go @@ -21,7 +21,6 @@ import ( "slices" "strings" "sync/atomic" - "time" ) // LabsPath is where Sync keeps models.dev's lab catalog (models.json), @@ -59,34 +58,34 @@ func readLabs() map[string]mdModel { // syncLabs fetches the lab catalog into LabsPath, written whole through a // rename. A failed fetch keeps the one kept before. -func syncLabs(ctx context.Context) error { +func syncLabs(ctx context.Context) (bool, error) { u := labsURL() if u == "" { - return nil + return false, nil } labsTried.Store(true) req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { - return err + return false, err } req.Header.Set("User-Agent", "magpie") resp, err := http.DefaultClient.Do(req) if err != nil { - return err + return false, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return fmt.Errorf("models.dev labs: %s", resp.Status) + return false, fmt.Errorf("models.dev labs: %s", resp.Status) } b, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20)) if err != nil { - return err + return false, err } var probe map[string]mdModel if err := json.Unmarshal(b, &probe); err != nil || len(probe) == 0 { - return fmt.Errorf("models.dev labs: unexpected payload") + return false, fmt.Errorf("models.dev labs: unexpected payload") } - return writeWhole(LabsPath(), b, time.Time{}) + return keepFetched(LabsPath(), b) } // labsMissing says the provider catalog is magpie's own but no lab catalog diff --git a/internal/usage/catalog_key_test.go b/internal/usage/catalog_key_test.go new file mode 100644 index 000000000..c0604f7d0 --- /dev/null +++ b/internal/usage/catalog_key_test.go @@ -0,0 +1,51 @@ +package usage + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" +) + +// A Claude account's model list fetches models.dev again every 45 minutes +// (catalog.Asked), most often to the same bytes. Keyed on models.json's +// mtime, each fetch dropped the request index and the file of it on disk, +// and the next usage query read every session file again: ~15 s of CPU +// over a long history. Only a catalog that changed may drop them. +func TestRequestStateKeptAcrossACatalogFetchedAgain(t *testing.T) { + pageHome(t) + now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) + p := catalog.CachePath() + write := func(b string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(b), 0o644); err != nil { + t.Fatal(err) + } + } + const one = `{"openai":{"id":"openai","models":{"gpt-6.1-sol":{"id":"gpt-6.1-sol","cost":{"input":2,"output":10}}}}}` + write(one) + old := time.Now().Add(-time.Hour) + if err := os.Chtimes(p, old, old); err != nil { + t.Fatal(err) + } + before, price := readRequestState(now).meta, usagePriceCacheKey(now) + write(one) + if st, err := os.Stat(p); err != nil || !st.ModTime().After(old.Add(30*time.Minute)) { + t.Fatalf("not written again: %v %v", st, err) + } + if got := readRequestState(now).meta; got != before { + t.Error("the same catalog fetched again changed the request index's meta") + } + if got := usagePriceCacheKey(now); got != price { + t.Error("the same catalog fetched again changed the price key") + } + write(`{"openai":{"id":"openai","models":{"gpt-6.1-sol":{"id":"gpt-6.1-sol","cost":{"input":3,"output":10}}}}}`) + if readRequestState(now).meta == before || usagePriceCacheKey(now) == price { + t.Error("a catalog 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 271d3c3e3..8012b4a7b 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -875,7 +875,7 @@ func readRequestState(now time.Time) requestState { cfg := settings.Load() prices, _ := json.Marshal(cfg.ModelPrices) wires, _ := json.Marshal(cfg.Wires()) - meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), statKey(catalog.CachePath()), clientAgentsKey(), clearedKey()) + meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), catalog.CacheKey(), clientAgentsKey(), clearedKey()) 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 != "") diff --git a/internal/usage/summary_cache.go b/internal/usage/summary_cache.go index 31efe097c..a4ab7c437 100644 --- a/internal/usage/summary_cache.go +++ b/internal/usage/summary_cache.go @@ -133,7 +133,7 @@ func usagePriceCacheKey(now time.Time) string { // one catalog for the providers and the group names read below (#5978) defer provider.Hold()() _, offset := now.Zone() - 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) + meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%d", statKey(settings.Path()), statKey(provider.Path()), catalog.CacheKey(), 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()