diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 7133a48b9..cb72ea6b7 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -18,6 +18,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "unicode" @@ -829,6 +830,7 @@ func Reset() { loaded = false built = nil gen++ + resets.Add(1) mdev, images, windows, outputs, efforts, thinks, names, listed, canonical, labs, normal = nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil loadMu.Unlock() if Forget != nil { @@ -836,6 +838,16 @@ func Reset() { } } +// resets counts Reset's calls: a catalog read again because it may have +// changed, not one let go of while idle. +var resets atomic.Int64 + +// Resets is how many times the catalog was forgotten for one that may +// differ (Reset). What was asked of the catalog before may be answered +// otherwise after, though the file's key (CacheKey) is the same: Sync +// writes the file first and resets after. +func Resets() int64 { return resets.Load() } + // Sync downloads the models.dev catalog into CachePath. It serializes with // itself so a background refresh and a manual one cannot interleave writes. func Sync(ctx context.Context) error { diff --git a/internal/usage/catalog_asks.go b/internal/usage/catalog_asks.go new file mode 100644 index 000000000..e501cb6f7 --- /dev/null +++ b/internal/usage/catalog_asks.go @@ -0,0 +1,257 @@ +package usage + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "sync" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/sessions" + "github.com/yetone/magpie/internal/settings" +) + +// The request index's rows hold what the catalog said of each call: its +// price, and whether the reply's model is the one the provider lists under +// the name asked (ListedAs). Its meta named the catalog by the bytes of +// models.json, so every change models.dev made, most of them to aggregators' +// lists no call of the user's names, read every session file again: ~15 s +// of CPU on a long history, several times a day. +// +// So the index is named by catalogBase instead: the catalog it was built +// under, kept while every question its rows asked of the catalog is +// answered the same by the one on disk now. Each question and its answer +// is noted as it is first asked (noteAsk); a new catalog asks them all +// again, and one answered otherwise names the index anew, which builds it +// again, as any change did before. + +// catalogAsks is the questions asked under base, and their answers. +type catalogAsks struct { + // Base names the catalog the index is built under; Checked, the one + // the asks were last answered the same by. + Base, Checked string + Asks map[string]string +} + +var asks struct { + sync.Mutex + path string + state catalogAsks + // dirty: asks noted since the file was written; suspect: a question + // answered otherwise than first, or one past asksMax not kept + dirty, suspect bool + // resets is catalog.Resets when the asks were last checked: the file + // is written before the catalog is read again (Sync), so a check + // between the two asked the old one + resets int64 +} + +// checking holds one check of the asks at a time. +var checking sync.Mutex + +// asksMax bounds the questions kept: past it the index is named anew +// with the next catalog, as before, rather than every one asked again. +const asksMax = 50000 + +func catalogAsksPath() string { + return filepath.Join(filepath.Dir(sessions.CachePath()), "catalog-asks-v1.json") +} + +// loadAsks reads the asks of this home's file, once per home; asks is +// held. A file that can't be read or parsed is no asks: the index is named +// anew (the current catalog), so its rows are all asked again. +func loadAsks() { + p := catalogAsksPath() + if asks.path == p { + return + } + asks.path, asks.state, asks.dirty, asks.suspect = p, catalogAsks{}, false, false + asks.resets = catalog.Resets() // this process reads the file as it is now + if b, err := os.ReadFile(p); err == nil { + var st catalogAsks + if json.Unmarshal(b, &st) == nil && st.Base != "" && st.Checked != "" { + asks.state = st + } + } + if asks.state.Asks == nil { + asks.state.Asks = map[string]string{} + } +} + +// noteAsk keeps a question asked of the catalog with its answer, the +// first time it is asked. The rows made of the answer hold it, so it is +// the answer a later catalog is held to, whichever catalog gave it. A +// question answered otherwise later means rows of both answers may be +// held: the next check names the index anew. +func noteAsk(q, answer string) { + asks.Lock() + defer asks.Unlock() + loadAsks() + if was, ok := asks.state.Asks[q]; ok { + if was != answer { + asks.suspect = true + } + return + } + if len(asks.state.Asks) >= asksMax { + asks.suspect = true + return + } + asks.state.Asks[q] = answer + asks.dirty = true +} + +// catalogBase names the catalog the request index's rows were made under. +// It is the catalog on disk while the asks are unchanged by it. +func catalogBase() string { + checking.Lock() + defer checking.Unlock() + rs := catalog.Resets() + cur := catalog.CacheKey() + asks.Lock() + loadAsks() + st := asks.state + if st.Base == "" { + // no asks on record: the rows made now are named by this catalog + asks.state = catalogAsks{Base: cur, Checked: cur, Asks: map[string]string{}} + asks.dirty, asks.suspect, asks.resets = true, false, rs + asks.Unlock() + saveAsks() + return cur + } + if cur == st.Checked && rs == asks.resets && !asks.suspect { + asks.Unlock() + return st.Base + } + suspect := asks.suspect + qs := make(map[string]string, len(st.Asks)) + for q, a := range st.Asks { + qs[q] = a + } + asks.suspect = false + asks.Unlock() + + same := !suspect && answersSame(qs) + asks.Lock() + if same { + asks.state.Checked = cur + } else { + // asking again noted the new answers as differing too: a new + // base holds none of the old rows + asks.state = catalogAsks{Base: cur, Checked: cur, Asks: map[string]string{}} + asks.suspect = false + } + asks.dirty, asks.resets = true, rs + base := asks.state.Base + asks.Unlock() + saveAsks() + return base +} + +// answersSame asks qs again of the catalog now, and reports whether each +// is answered as it was. +func answersSame(qs map[string]string) bool { + forgetListed() // a provider's list as the catalog has it now + s := settings.Load() + wires := s.Wires() + for q, was := range qs { + now, ok := answerAsk(s, wires, q) + if !ok || now != was { + return false + } + } + return true +} + +// saveAsks writes the asks when some were noted since they were last +// written. A cache written of rows names the asks they were made of, so +// it is called before one is (toDisk and the rest): a file of rows whose +// asks were lost would keep their answers through a catalog that changes +// them. +func saveAsks() { + asks.Lock() + if !asks.dirty || asks.path == "" { + asks.Unlock() + return + } + b, err := json.Marshal(asks.state) + p := asks.path + asks.dirty = false + asks.Unlock() + if err != nil { + return + } + if err := writeAsks(p, b); err != nil { + asks.Lock() + asks.dirty = true + asks.Unlock() + } +} + +func writeAsks(p string, b []byte) error { + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { + return err + } + out, err := os.CreateTemp(filepath.Dir(p), ".catalog-asks-*") + if err != nil { + return err + } + defer os.Remove(out.Name()) + _, err = out.Write(b) + if cerr := out.Close(); err == nil { + err = cerr + } + if err != nil { + return err + } + return os.Rename(out.Name(), p) +} + +// The questions: a price (p) and a listed name (l), each its fields +// joined by a byte no name holds. +const askSep = "\x00" + +func (a priceAsk) ask() string { + u := "0" + if a.Unknown { + u = "1" + } + return strings.Join([]string{"p", a.ID, a.Model, a.Served, a.SessionProvider, a.Effort, a.Key, u}, askSep) +} + +func listedAsk(prov, model, served string) string { + return strings.Join([]string{"l", prov, model, served}, askSep) +} + +// priceAnswer is a base price and its windows as an answer. +func priceAnswer(pr *catalog.Price, ws []provider.RateWindow) string { + b, _ := json.Marshal(struct { + P *catalog.Price `json:"p"` + W []provider.RateWindow `json:"w,omitempty"` + }{pr, ws}) + return string(b) +} + +func boolAnswer(b bool) string { + if b { + return "1" + } + return "0" +} + +// answerAsk answers q of the catalog now; false for a question it doesn't +// know, which counts as answered otherwise. +func answerAsk(s settings.Settings, wires map[string]string, q string) (string, bool) { + f := strings.Split(q, askSep) + switch { + case f[0] == "p" && len(f) == 8: + a := priceAsk{ID: f[1], Model: f[2], Served: f[3], SessionProvider: f[4], Effort: f[5], Key: f[6], Unknown: f[7] == "1"} + pr, ws := basePriceIn(s, wires, a) + return priceAnswer(pr, ws), true + case f[0] == "l" && len(f) == 4: + return boolAnswer(listedAsNow(f[1], f[2], f[3])), true + } + return "", false +} diff --git a/internal/usage/catalog_key_test.go b/internal/usage/catalog_key_test.go index c0604f7d0..52f292020 100644 --- a/internal/usage/catalog_key_test.go +++ b/internal/usage/catalog_key_test.go @@ -1,6 +1,7 @@ package usage import ( + "fmt" "os" "path/filepath" "testing" @@ -45,7 +46,90 @@ func TestRequestStateKeptAcrossACatalogFetchedAgain(t *testing.T) { 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") + if usagePriceCacheKey(now) == price { + t.Error("a catalog that changed kept the price key") + } +} + +// models.dev changes several times a day, mostly in aggregators' lists no +// call of the user's names. The request index is built again only when a +// price or a listed name its rows hold is answered otherwise, across a +// restart too. +func TestRequestStateKeptAcrossACatalogChangeNoRowAsks(t *testing.T) { + pageHome(t) + now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) + p := catalog.CachePath() + at := time.Now().Add(-2 * time.Hour) + reset := true + write := func(sol, kilo int) { + t.Helper() + b := fmt.Sprintf(`{"openai":{"id":"openai","models":{"gpt-6.1-sol":{"id":"gpt-6.1-sol","cost":{"input":%d,"output":10}}}},`+ + `"kilo":{"id":"kilo","models":{"x/y":{"id":"x/y","cost":{"input":%d,"output":1}}}}}`, sol, kilo) + 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) + } + at = at.Add(time.Minute) // each write a time of its own + if err := os.Chtimes(p, at, at); err != nil { + t.Fatal(err) + } + if reset { + catalog.Reset() // as Sync does once the file changed + } + } + // a session file's call priced at the catalog's word (#4278) + row := Record{Provider: UnknownProvider, SessionProvider: "openai", Model: "gpt-6.1-sol", Input: 1} + priced := func(want float64) { + t.Helper() + pr := Pricer()(row) + if pr == nil || pr.Input != want { + t.Fatalf("priced %+v, want input %v", pr, want) + } + } + // rows reach a file only after their asks did (saveAsks) + restart := func() { + saveAsks() + asks.Lock() + asks.path = "" + asks.Unlock() + } + write(2, 1) + meta := readRequestState(now).meta + priced(2) + write(2, 5) + if readRequestState(now).meta != meta { + t.Fatal("a change to a model no row names built the index again") + } + write(3, 5) + again := readRequestState(now).meta + if again == meta { + t.Fatal("a new price of a model a row names kept the index") + } + priced(3) + restart() + write(3, 7) + if readRequestState(now).meta != again { + t.Fatal("after a restart, a change no row asks of built the index again") + } + restart() + write(4, 7) + fourth := readRequestState(now).meta + if fourth == again { + t.Fatal("after a restart, a new price a row holds kept the index") + } + // Sync writes the file before it resets the catalog: a check between + // the two asks the catalog the file no longer holds, and the reset + // asks again + priced(4) + reset = false + write(5, 7) + if readRequestState(now).meta != fourth { + t.Fatal("the catalog still loaded answered otherwise") + } + catalog.Reset() + if readRequestState(now).meta == fourth { + t.Fatal("a check before the catalog was read again kept the index past it") } } diff --git a/internal/usage/effort_split.go b/internal/usage/effort_split.go index b1016f9ab..885f76bc7 100644 --- a/internal/usage/effort_split.go +++ b/internal/usage/effort_split.go @@ -107,6 +107,7 @@ func internEffortNames(sums map[string][]sessions.ModelEffort) { // effortDiskWrite keeps sums under key, in place of the entry of the same // since, through a file renamed over the last. func effortDiskWrite(key string, cut, since time.Time, sums map[string][]sessions.ModelEffort) error { + saveAsks() // the asks its rows were made of first (catalogBase) all := []effortDiskEntry{{Key: key, Cut: cut, Since: since, Sums: sums}} for _, o := range effortDiskEntries() { if o.Key != key && !o.Since.Equal(since) && len(all) < effortDiskPeriods { diff --git a/internal/usage/heat_digest_disk.go b/internal/usage/heat_digest_disk.go index cdc902f36..24672fa4f 100644 --- a/internal/usage/heat_digest_disk.go +++ b/internal/usage/heat_digest_disk.go @@ -196,6 +196,7 @@ func sourceDigestsSave() { // writeFileRenamed writes b to p through a temp file renamed over it. func writeFileRenamed(p string, b []byte) { + saveAsks() // the asks its rows were made of first (catalogBase) dir := filepath.Dir(p) if os.MkdirAll(dir, 0o700) != nil { return diff --git a/internal/usage/heat_disk.go b/internal/usage/heat_disk.go index 4cb92aa9e..5b0fee773 100644 --- a/internal/usage/heat_disk.go +++ b/internal/usage/heat_disk.go @@ -73,6 +73,7 @@ func heatDiskRead(key string) ([]Day, bool) { // heatDiskWrite keeps days before cut from since under key, through a // file renamed over the last. func heatDiskWrite(key string, cut, since time.Time, days []Day) error { + saveAsks() // the asks its rows were made of first (catalogBase) b, err := json.Marshal(heatDiskEntry{Key: key, Cut: cut, Since: since, Days: days}) if err != nil { return err diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index 61313f51b..f336b4ee4 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -609,48 +609,11 @@ func Pricer() func(Record) *catalog.Price { if pr, ok := prices[k]; ok { return atWindow(pr, windows[id], r.Time) } - var pr *catalog.Price - var v catalog.Price - var ws []provider.RateWindow - var ok bool - // the swap the ledger marks: the reply named another model than - // asked, no rename of it (#5340) - if servedInstead(wires, id, r.Model, r.Effort, served) { - // a price the user set for the model asked for still says what - // that model costs them, a zero included - if v, ok, ws = provider.UserBasePriceIn(s, id, r.Model); !ok { - // the model that ran is priced as itself, what the vendor - // billed; with none, the asked-for one's price stands - if v, ok, ws = provider.BaseKeyPriceIn(s, id, key, served); !ok { - v, ok, ws = provider.BaseKeyPriceIn(s, id, key, r.Model) - } - } - } else { - v, ok, ws = provider.BaseKeyPriceIn(s, id, key, r.Model) - } - if !ok && served != "" { - v, ok, ws = provider.BaseKeyPriceIn(s, id, key, served) - } - if ok { - pr = &v + a := priceAsk{ID: id, Model: r.Model, Served: served, SessionProvider: r.SessionProvider, Effort: r.Effort, Key: key, Unknown: r.Provider == UnknownProvider} + pr, ws := basePriceIn(s, wires, a) + noteAsk(a.ask(), priceAnswer(pr, ws)) + if pr != nil { windows[id] = ws - } else if r.Provider == UnknownProvider && r.SessionProvider != "" { - // A session file's usage entry names the provider the call went - // through (omp's model_usage: provider openrouter, model - // typesafe/jev-1.14, #4278), which its billing provider, the - // unknown one, never says. The name is the file's word for the - // route, not an account of ours, so it prices only what the - // catalog itself lists under it: this very model id, at that - // provider, at a price. A provider models.dev doesn't know, a - // model it lists that provider without, and a listing with no - // price are none: the row stays unpriced, its CSV cost empty, - // rather than priced at another entry's guess. - if v, ok := catalog.PriceOf(r.SessionProvider, r.Model); ok { - pr = &v - // the failed lookup's windows are the billing provider's, - // not the session provider's: none holds for this price - ws = nil - } } if pr == nil { catalog.Missing() // models.dev may list it by now @@ -660,6 +623,62 @@ func Pricer() func(Record) *catalog.Price { } } +// priceAsk is what Pricer prices a record by, less its time: the base +// price and rate windows answer it, and every record that asks the same +// is priced the same. +type priceAsk struct { + ID, Model, Served, SessionProvider, Effort, Key string + Unknown bool +} + +// basePriceIn is a's price before its time's rate window, and the +// provider's windows, as Pricer finds it: nil when none is known. +func basePriceIn(s settings.Settings, wires map[string]string, a priceAsk) (*catalog.Price, []provider.RateWindow) { + var pr *catalog.Price + var v catalog.Price + var ws []provider.RateWindow + var ok bool + // the swap the ledger marks: the reply named another model than + // asked, no rename of it (#5340) + if servedInstead(wires, a.ID, a.Model, a.Effort, a.Served) { + // a price the user set for the model asked for still says what + // that model costs them, a zero included + if v, ok, ws = provider.UserBasePriceIn(s, a.ID, a.Model); !ok { + // the model that ran is priced as itself, what the vendor + // billed; with none, the asked-for one's price stands + if v, ok, ws = provider.BaseKeyPriceIn(s, a.ID, a.Key, a.Served); !ok { + v, ok, ws = provider.BaseKeyPriceIn(s, a.ID, a.Key, a.Model) + } + } + } else { + v, ok, ws = provider.BaseKeyPriceIn(s, a.ID, a.Key, a.Model) + } + if !ok && a.Served != "" { + v, ok, ws = provider.BaseKeyPriceIn(s, a.ID, a.Key, a.Served) + } + if ok { + pr = &v + } else if a.Unknown && a.SessionProvider != "" { + // A session file's usage entry names the provider the call went + // through (omp's model_usage: provider openrouter, model + // typesafe/jev-1.14, #4278), which its billing provider, the + // unknown one, never says. The name is the file's word for the + // route, not an account of ours, so it prices only what the + // catalog itself lists under it: this very model id, at that + // provider, at a price. A provider models.dev doesn't know, a + // model it lists that provider without, and a listing with no + // price are none: the row stays unpriced, its CSV cost empty, + // rather than priced at another entry's guess. + if v, ok := catalog.PriceOf(a.SessionProvider, a.Model); ok { + pr = &v + // the failed lookup's windows are the billing provider's, + // not the session provider's: none holds for this price + ws = nil + } + } + return pr, ws +} + // servedInstead reports whether the vendor answered a call on model with // another model, served, and not the same one under a name of its own: the // swap the ledger marks (#5340). It is judged on the model the record is diff --git a/internal/usage/page_split.go b/internal/usage/page_split.go index 38f1eb57d..2ae2c57a0 100644 --- a/internal/usage/page_split.go +++ b/internal/usage/page_split.go @@ -391,6 +391,7 @@ func pageDiskPart(e pageDiskEntry) *chunkPart { // pageDiskWrite keeps part, a page's cells before cut from since, under // key with the pages written last, through a file renamed over the last. func pageDiskWrite(key string, cut, since time.Time, part *chunkPart) error { + saveAsks() // the asks its rows were made of first (catalogBase) e := pageDiskEntry{Key: key, Cut: cut, Since: since, At: time.Now(), Kept: part.kept, First: part.first, Cells: make([]pageDiskCell, len(part.cells)), Speeds: part.speeds, Big: part.big} for i := range part.cells { c := &part.cells[i] diff --git a/internal/usage/request_disk.go b/internal/usage/request_disk.go index b23eb9f9f..42845ed93 100644 --- a/internal/usage/request_disk.go +++ b/internal/usage/request_disk.go @@ -92,13 +92,13 @@ func sourceKey(src embed.FS, salt string) string { // and read back through: TestRequestDiskNamesTheCodeOfItsRows finds them // from its roots, and fails when one is missing or another isn't one. // -//go:embed block_price.go client_agents.go codex_actors.go codex_identity.go gateway_alias.go ledger.go request_disk.go request_disk_map_other.go request_disk_map_unix.go request_page.go request_snapshot.go request_spill.go served.go session_provider.go usage.go +//go:embed block_price.go catalog_asks.go client_agents.go codex_actors.go codex_identity.go gateway_alias.go ledger.go request_disk.go request_disk_map_other.go request_disk_map_unix.go request_page.go request_snapshot.go request_spill.go served.go session_provider.go usage.go var rowSource embed.FS // logSource is the files a log is read into blocks, kept and read back // through, found as rowSource's are. // -//go:embed block_price.go client_agents.go codex_actors.go codex_identity.go ledger.go log_change_darwin.go log_change_linux.go log_change_other.go log_change_windows.go log_disk.go log_file.go log_file_other.go log_index.go probes.go refset.go request_cells.go request_disk.go request_disk_map_other.go request_disk_map_unix.go request_page.go request_snapshot.go served.go usage.go +//go:embed block_price.go catalog_asks.go client_agents.go codex_actors.go codex_identity.go ledger.go log_change_darwin.go log_change_linux.go log_change_other.go log_change_windows.go log_disk.go log_file.go log_file_other.go log_index.go probes.go refset.go request_cells.go request_disk.go request_disk_map_other.go request_disk_map_unix.go request_page.go request_snapshot.go served.go usage.go var logSource embed.FS // requestDiskLeast is how many session files must want reading before the @@ -400,6 +400,7 @@ func (idx *requestIndex) fromDisk(want map[string]sessions.CallSource) { // toDisk writes chunks, and the entries of the file before it for the // paths in on that chunks doesn't hold, as the file for root and meta. func toDisk(root, meta string, chunks map[string]*rowChunk, on map[string]bool) error { + saveAsks() // the asks its rows were made of first (catalogBase) path, binary := requestDiskPath(), requestDiskBinary() if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return err diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 8012b4a7b..6ae9d7397 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()), catalog.CacheKey(), clientAgentsKey(), clearedKey()) + meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), "asked:"+catalogBase(), 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/served.go b/internal/usage/served.go index c878fd45a..ffe0d1f78 100644 --- a/internal/usage/served.go +++ b/internal/usage/served.go @@ -129,6 +129,14 @@ func ListedAs(prov, model, served string) bool { if prov == "" || model == "" || served == "" { return false } + ok := listedAsNow(prov, model, served) + // a provider's list can come of the catalog: the request index's + // rows hold the answer (catalogBase) + noteAsk(listedAsk(prov, model, served), boolAnswer(ok)) + return ok +} + +func listedAsNow(prov, model, served string) bool { n := listedNames(prov)[model] return n != "" && n != model && SameSpelled(n, served) }