Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

usage: a renamed provider is shown once, by the id it has now

yetone42976f9a082a
diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md
index 6b48b7bed..59e760526 100644
--- a/docs/subsystems/providers-accounts.md
+++ b/docs/subsystems/providers-accounts.md
@@ -24,6 +24,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Extra body | `ExtraBody` (`extraBody` in providers.json, the editor's *Extra body*, #1604) is a JSON object whose fields `WithExtraBody` adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's `forwardOnce` and in Test and Detect (`tested`). A field the body has already is kept; a name written `"!name"` replaces it. Values are put in as written, objects whole, not merged. `${sessionId}` in any string, at any depth, becomes the request's session: the agent's session header (`sessionOf`), else the id `conversationID` derives from the first user message (`magpie-` and its hash), so it stays the same through one conversation; Test and Detect send `magpie-test-` and 12 random letters, a new one each time. `model`, `stream` and the conversation (`messages`, `input`, `contents`, `system`, `systemInstruction`, `system_instruction`, `instructions`, `tools`, `ExtraBodyReserved`) are magpie's: Save refuses them with or without `!` (`ExtraBodyOK`), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (`cleanExtraBody`). Not sent with it: `count_tokens`, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests, except a ChatGPT (Codex) account's (magpie-releases#18): its requests are built as Codex CLI's (`codexBody`) and take the fields Codex CLI adds by choice, such as `access_programs` (OpenAI's Daybreak), while `store`, `tool_choice` and `include`, which the backend needs as `codexBody` sets them, can't be set (`codexOwned`). Its extraBody is written into providers.json by hand under the account's entry and kept onto the account by `withPicks`; the editor has no box for it. A client's own top-level `access_programs` on Responses or Chat is carried to a Responses build as it came (`Request.AccessPrograms`), so a request translated (a Codex account is streamed, so a whole Responses request is made again) keeps it as a relayed one does. One object goes to every API; fields for one API alone are not a thing yet. A `thinking` budget it puts in on an Anthropic endpoint is fitted to a Claude that thinks only adaptively after the merge, as an agent's is (`adaptiveThinking`, `TestExtraBodyBudgetFittedToAdaptiveModel`). | [`extrabody.go`](../../internal/provider/extrabody.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| Native compaction | `NativeCompaction` (`nativeCompaction` in providers.json, the editor's *Compaction* row, `magpie provider set <id> compaction=native\|magpie`; #1099) has Codex's compaction asked of the provider as Codex sent it and its sealed item returned unchanged. Off by default. Only a provider whose wire carries it can be set so (`CarriesCompaction`: a Responses API, a ChatGPT account, GitHub Copilot; not another agent's sign-in or a plugin's), and `CompactsOn(model)` also needs the model asked on Responses. `SetNativeCompaction`, the CLI and the GUI's save refuse it elsewhere. An account keeps it through `Save`'s picks (`withPicks`), and `AddCopy` carries it. The gateway's half is in [gateway-routing](gateway-routing.md). | [`native_compaction.go`](../../internal/provider/native_compaction.go) |
| providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) |
+| A provider renamed | `Rename` (the editor's id field, `magpie provider set <id> id=<new>`) keeps the old id in `Was`, so a model still picked by it reaches the provider. Usage is recorded under the id a call went out by and never rewritten; whatever reads it names the provider by its id now through `UsageRenames().Of(id, time)`: the summary, the Requests page (its blocks, the probe rows, other computers' days), the Sessions tab's vias, window holds, `NewPricer`/`NewCoster` and the gateway's `loggedAnswers` (cybercaius on Discord: a renamed provider was listed under both ids). `Visit` hands records out as recorded, so `Of` is taken once. An id another provider takes later (a rename onto it, or `Save` of a new provider under it) moves from the first one's `Was` to its `Gave` with the time (`giveID`): calls recorded under it before then stay the first one's, later ones are the new one's. An id held by a provider or a subscription now is never renamed (`Renamed`), and `freeID` doesn't hand out an id in any `Was`, so adding a vendor again gets `-2`. Ids reused before `Gave` existed have no time and go to whoever holds the id now. A providers.json that can't be read keeps the last renames read, not none. The summary and Requests caches key on `Renames.Key`, the vias cache too. | [`rename.go`](../../internal/provider/rename.go), [`block_price.go`](../../internal/usage/block_price.go) |
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). | [`provider.go`](../../internal/provider/provider.go) |
| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models <id> none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier `PickedFrom` had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (`Refetch`, `KeepListsFresh`, and a plugin's hourly `KeepPluginsListed`) leaves `Models` for `Delisted` (`dropGonePicks`), not served, and goes back among the picks when a later list has it (`relistPicks`): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps `Delisted` but for what it picks again (`delistedWith`); Select none clears it. A provider whose every pick is in `Delisted` serves none of its models (`waitsForPicks`), not the vendor's list. `KeepPluginsListed` asks again after `relistSoon` (5 minutes) when a list left a pick out. `TestPluginPicksComeBackWithTheirList`, `TestEveryPickDelistedServesNone` and `TestRelayPicksComeBackWithTheirList` cover it. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) |
| List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, or `re:` matching the whole id, both in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter); a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go
index bf0a19e7e..a2408de5a 100644
--- a/internal/gateway/codex_backend.go
+++ b/internal/gateway/codex_backend.go
@@ -415,7 +415,12 @@ func loggedAnswers(convs ...string) []loggedAnswer {
return nil
}
var all []loggedAnswer
+ // a provider renamed since answered by the id it has now, the one
+ // its candidates have (cybercaius: a renamed provider was told apart
+ // from itself)
+ renamed := provider.UsageRenames()
usage.Visit(time.Now().Add(-sealerKeep), func(r usage.Record) {
+ r.Provider = renamed.Of(r.Provider, r.Time)
if r.Provider == "" || r.Provider == "magpie" || r.IsRejected() || r.IsReported() || r.Status <= 0 || r.Status >= 400 || r.Computer != "" || isTitleKind(r.Kind) {
return
}
diff --git a/internal/gateway/codex_backend_test.go b/internal/gateway/codex_backend_test.go
index 781a0d17f..f7b246043 100644
--- a/internal/gateway/codex_backend_test.go
+++ b/internal/gateway/codex_backend_test.go
@@ -1139,3 +1139,23 @@ func TestCodexModelListOwnOnlyForFailover(t *testing.T) {
t.Errorf("%d X-Models-Etag %q", rec.Code, got)
}
}
+
+// A lead a provider answered before it was renamed was answered by the
+// id it has now, the one its candidates go by (cybercaius).
+func TestRenamedProviderAnsweredItsLead(t *testing.T) {
+ setHome(t, t.TempDir())
+ if err := provider.Save(provider.Provider{ID: "myrelay", Name: "My relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"gpt-5.5"}}); err != nil {
+ t.Fatal(err)
+ }
+ session := "lead-renamed-" + strconv.FormatInt(time.Now().UnixNano(), 10)
+ usage.Append(usage.Record{
+ Time: time.Now(), Agent: "codex", Provider: "myrelay", Host: "relay.example.com", ProviderKeyID: "fp",
+ Model: "gpt-5.5", Input: 9, Output: 2, Status: 200, Endpoint: CodexPath + "/responses", Session: session,
+ })
+ if err := provider.Rename("myrelay", "newrelay"); err != nil {
+ t.Fatal(err)
+ }
+ if a := loggedAnswers(session); len(a) != 1 || a[0].provider != "newrelay" || a[0].who != "newrelay#fp" {
+ t.Fatalf("answers %+v", a)
+ }
+}
diff --git a/internal/provider/importapps.go b/internal/provider/importapps.go
index 3d08bb649..7fbe2d319 100644
--- a/internal/provider/importapps.go
+++ b/internal/provider/importapps.go
@@ -242,8 +242,14 @@ func freeID(id string) string {
for _, p := range All() {
taken[p.ID] = true
}
+ // an id a provider had is taken too: its calls are recorded under it
+ // (Renames), and one added under it would be counted from then on
+ // only, its own history read apart from the renamed one's
for _, p := range load().Providers {
taken[p.ID] = true
+ for _, w := range p.Was {
+ taken[w] = true
+ }
}
for n, try := 2, id; ; n++ {
if !taken[try] {
diff --git a/internal/provider/provider.go b/internal/provider/provider.go
index a36e7df0f..5734a3cf3 100644
--- a/internal/provider/provider.go
+++ b/internal/provider/provider.go
@@ -23,6 +23,7 @@ import (
"strings"
"sync"
"sync/atomic"
+ "time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/catalog"
@@ -50,10 +51,14 @@ type Provider struct {
Name string `json:"name"`
// Was are ids the provider had before it was renamed (see Rename):
// a model still picked by one of them reaches it.
- Was []string `json:"was,omitempty"`
- Icon string `json:"icon,omitempty"`
- Preset string `json:"preset,omitempty"` // preset this was created from, if any
- Key string `json:"key"` // API key, as typed by the user
+ Was []string `json:"was,omitempty"`
+ // Gave are ids it had that another provider took after it (a rename
+ // onto one, a provider added under one), each with when: the calls
+ // recorded under such an id before then were this one's (Renames).
+ Gave []Gave `json:"gave,omitempty"`
+ Icon string `json:"icon,omitempty"`
+ Preset string `json:"preset,omitempty"` // preset this was created from, if any
+ Key string `json:"key"` // API key, as typed by the user
// AccessKeyID and SecretAccessKey are a Volcengine account's access
// key (TakesVolcAccessKey), what Ark tells its Coding or Agent Plan's
@@ -600,6 +605,7 @@ func All() []Provider {
// clone is p with its settings unshared: slices, maps and pointers copied.
func (p Provider) clone() Provider {
p.Was = slices.Clone(p.Was)
+ p.Gave = slices.Clone(p.Gave)
p.Keys = slices.Clone(p.Keys)
p.Fallback = slices.Clone(p.Fallback)
p.Models = slices.Clone(p.Models)
@@ -855,6 +861,9 @@ func Save(p Provider) error {
if p.Was == nil {
p.Was = was.Was
}
+ if p.Gave == nil {
+ p.Gave = was.Gave
+ }
if sameStored(*was, p) {
// Save pressed on an editor left as it was: providers.json
// would be written byte for byte as it is, and its write
@@ -864,6 +873,9 @@ func Save(p Provider) error {
}
f.Providers[i] = p
} else {
+ // a new provider under an id another had: what was recorded under
+ // it until now stays that one's
+ giveID(f.Providers, -1, p.ID, time.Now())
f.Providers = append(f.Providers, p)
}
if err := store(f); err != nil {
diff --git a/internal/provider/rename.go b/internal/provider/rename.go
index 66acc0275..6becafdbe 100644
--- a/internal/provider/rename.go
+++ b/internal/provider/rename.go
@@ -1,11 +1,14 @@
package provider
import (
+ "encoding/json"
"errors"
"fmt"
"os"
"slices"
"strings"
+ "sync/atomic"
+ "time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/settings"
@@ -58,11 +61,11 @@ func Rename(from, to string) error {
if slices.ContainsFunc(f.Providers, func(p Provider) bool { return p.ID == to }) {
return fmt.Errorf("there is a provider %q already", to)
}
- // an id another provider once had is this one's now
- for j := range f.Providers {
- f.Providers[j].Was = slices.DeleteFunc(f.Providers[j].Was, func(w string) bool { return w == to })
- }
+ // an id another provider once had is this one's now; the calls
+ // recorded under it until now stay that one's
+ giveID(f.Providers, i, to, time.Now())
p := &f.Providers[i]
+ p.Was = slices.DeleteFunc(p.Was, func(w string) bool { return w == to })
p.ID = to
// the subscription's id is the subscription's: an old ref to it isn't
// taken for this one
@@ -146,15 +149,133 @@ func RenamedRef(ref string) string {
return ref
}
-// Renamed maps the ids providers had to the ones they have now.
-func Renamed() map[string]string {
- out := map[string]string{}
- for _, p := range load().Providers {
+// Renamed maps the ids providers had to the ones they have now. An id
+// that a provider or a subscription has now is that one's, and is not
+// in it.
+func Renamed() map[string]string { return UsageRenames().now }
+
+// Gave is an id a provider had and gave up to another (Provider.Gave).
+type Gave struct {
+ ID string `json:"id"`
+ Until time.Time `json:"until"`
+}
+
+// Renames say which provider a call recorded under a provider id was
+// made to, as its id is now: a provider renamed takes the calls recorded
+// under the ids it had (Was), and an id another provider took since
+// (Gave) is that one's only from then on (cybercaius on Discord: a
+// renamed provider's usage was shown under its old id and its new one).
+type Renames struct {
+ now map[string]string
+ gave map[string][]gaveTo
+}
+
+type gaveTo struct {
+ Until time.Time `json:"until"`
+ To string `json:"to"`
+}
+
+// Of is the id the provider a call recorded under id at the time at has
+// now; id itself when it was not renamed. A zero at is before every
+// hand-over.
+func (r Renames) Of(id string, at time.Time) string {
+ for _, g := range r.gave[id] {
+ if at.Before(g.Until) {
+ return g.To
+ }
+ }
+ if to, ok := r.now[id]; ok {
+ return to
+ }
+ return id
+}
+
+// Timed is whether the id's calls go to more than one provider by when
+// they were made, so Of needs each call's time.
+func (r Renames) Timed(id string) bool { return len(r.gave[id]) > 0 }
+
+// Each is every id a call recorded under id can go to (Of), by when it
+// was made.
+func (r Renames) Each(id string) []string {
+ out := []string{r.Of(id, time.Time{})}
+ for _, g := range r.gave[id] {
+ out = append(out, g.To)
+ }
+ out = append(out, r.Of(id, time.Now().Add(100*365*24*time.Hour)))
+ slices.Sort(out)
+ return slices.Compact(out)
+}
+
+// RenamesOf are renames of ids to the ones they are now, none given away
+// (for a test).
+func RenamesOf(now map[string]string) Renames { return Renames{now: now} }
+
+// Empty is whether no id is renamed.
+func (r Renames) Empty() bool { return len(r.now) == 0 && len(r.gave) == 0 }
+
+// Key is r as text, for a cache of what was worked out with it.
+func (r Renames) Key() string {
+ b, _ := json.Marshal([]any{r.now, r.gave})
+ return string(b)
+}
+
+// lastRenames are the renames last read, kept for when providers.json
+// can't be read: a failed read is not "nothing renamed", and the usage of
+// every renamed provider would be shown split until it read again.
+var lastRenames atomic.Pointer[Renames]
+
+// UsageRenames are the renames of providers.json as it is now.
+func UsageRenames() Renames {
+ f, err := read()
+ if err != nil {
+ if r := lastRenames.Load(); r != nil {
+ return *r
+ }
+ return Renames{now: map[string]string{}}
+ }
+ r := renamesOf(f.Providers)
+ lastRenames.Store(&r)
+ return r
+}
+
+func renamesOf(ps []Provider) Renames {
+ r := Renames{now: map[string]string{}}
+ held := map[string]bool{}
+ for _, p := range ps {
+ held[p.ID] = true
+ }
+ for _, p := range ps {
for _, w := range p.Was {
- out[w] = p.ID
+ // the subscription's id is the subscription's (Rename)
+ if !held[w] && !subscriptionID(w) {
+ r.now[w] = p.ID
+ }
+ }
+ for _, g := range p.Gave {
+ if r.gave == nil {
+ r.gave = map[string][]gaveTo{}
+ }
+ r.gave[g.ID] = append(r.gave[g.ID], gaveTo{g.Until, p.ID})
}
}
- return out
+ for _, gs := range r.gave {
+ slices.SortStableFunc(gs, func(a, b gaveTo) int { return a.Until.Compare(b.Until) })
+ }
+ return r
+}
+
+// giveID moves id out of the Was of every provider of ps but ps[taker]
+// (-1 for one not among them) into its Gave at now: from now on id is
+// another's, and what was recorded under it before stays the one's that
+// had it.
+func giveID(ps []Provider, taker int, id string, now time.Time) {
+ for j := range ps {
+ if j == taker || !slices.Contains(ps[j].Was, id) {
+ continue
+ }
+ ps[j].Was = slices.DeleteFunc(ps[j].Was, func(w string) bool { return w == id })
+ ps[j].Gave = append(ps[j].Gave, Gave{ID: id, Until: now})
+ }
}
// OnAccountIDs are the user's own providers saved on a subscription's id,
diff --git a/internal/provider/rename_test.go b/internal/provider/rename_test.go
index 3643cc07e..82c561312 100644
--- a/internal/provider/rename_test.go
+++ b/internal/provider/rename_test.go
@@ -2,8 +2,10 @@ package provider
import (
"os"
+ "path/filepath"
"slices"
"testing"
+ "time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/settings"
@@ -87,3 +89,82 @@ func TestRename(t *testing.T) {
t.Fatalf("was %v", p.Was)
}
}
+
+// An id given up by a rename and taken by another provider later keeps
+// the calls recorded under it before then with the one renamed, and
+// gives the new one only its own (cybercaius: a renamed provider's usage
+// was shown under both ids).
+func TestRenamesByWhenTheIDWasTaken(t *testing.T) {
+ isolate(t)
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("USERPROFILE", t.TempDir())
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_CACHE_HOME", t.TempDir())
+ if err := Save(Provider{ID: "deepseek", Name: "DeepSeek", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m"}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := Rename("deepseek", "ds"); err != nil {
+ t.Fatal(err)
+ }
+ before := time.Now().Add(-time.Hour)
+ if r := UsageRenames(); r.Of("deepseek", before) != "ds" || r.Of("deepseek", time.Now()) != "ds" || r.Timed("deepseek") {
+ t.Fatalf("renamed: %+v", r)
+ }
+ // one added again from the list is not given the old id
+ if got := FreeID("deepseek"); got != "deepseek-2" {
+ t.Fatalf("free id %q", got)
+ }
+ // one saved under it on purpose takes it from now on
+ if err := Save(Provider{ID: "deepseek", Name: "DeepSeek again", Key: "k2", Chat: "http://127.0.0.1:2/v1", Models: []string{"m"}}); err != nil {
+ t.Fatal(err)
+ }
+ if p, _ := Find("ds"); len(p.Was) != 0 || len(p.Gave) != 1 || p.Gave[0].ID != "deepseek" {
+ t.Fatalf("ds %+v", p)
+ }
+ r := UsageRenames()
+ if got := r.Of("deepseek", before); got != "ds" {
+ t.Fatalf("a call before the id was taken went to %q", got)
+ }
+ if got := r.Of("deepseek", time.Now().Add(time.Second)); got != "deepseek" {
+ t.Fatalf("a call after went to %q", got)
+ }
+ if got := Renamed(); len(got) != 0 {
+ t.Fatalf("refs renamed %v", got)
+ }
+ if got := r.Each("deepseek"); !slices.Equal(got, []string{"deepseek", "ds"}) {
+ t.Fatalf("each %v", got)
+ }
+
+ // a rename onto it hands it over the same way
+ if err := Rename("deepseek", "ds2"); err != nil {
+ t.Fatal(err)
+ }
+ mid := time.Now()
+ if err := Save(Provider{ID: "other", Name: "Other", Key: "k3", Chat: "http://127.0.0.1:3/v1", Models: []string{"m"}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := Rename("other", "deepseek"); err != nil {
+ t.Fatal(err)
+ }
+ r = UsageRenames()
+ if r.Of("deepseek", before) != "ds" || r.Of("deepseek", mid) != "ds2" || r.Of("deepseek", time.Now().Add(time.Second)) != "deepseek" || r.Of("other", before) != "deepseek" {
+ t.Fatalf("%q %q %q %q", r.Of("deepseek", before), r.Of("deepseek", mid), r.Of("deepseek", time.Now().Add(time.Second)), r.Of("other", before))
+ }
+
+ // a providers.json that can't be read is not "nothing renamed"
+ if err := os.WriteFile(Path(), []byte("{not json"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ matches, _ := filepath.Glob(Path() + "*")
+ for _, m := range matches {
+ if m != Path() {
+ os.Remove(m)
+ }
+ }
+ if _, err := read(); err == nil {
+ t.Fatal("the broken file was read")
+ }
+ if got := UsageRenames(); got.Of("deepseek", mid) != "ds2" || got.Of("other", before) != "deepseek" {
+ t.Fatalf("unreadable: %+v", got)
+ }
+}
diff --git a/internal/usage/block_price.go b/internal/usage/block_price.go
index ca4e67d57..1743586e7 100644
--- a/internal/usage/block_price.go
+++ b/internal/usage/block_price.go
@@ -25,7 +25,7 @@ type pricedAs struct {
// names only, so they are worked out once for each set of names, not once
// per call: 750k calls name a few hundred.
type blockPricer struct {
- aliases map[string]string
+ renames provider.Renames
wires map[string]string
price func(Record) *catalog.Price
by map[[4]string]pricedAs
@@ -47,19 +47,17 @@ func (b *blockPricer) release() {
b.pooled = nil
}
-func newBlockPricer(aliases, wires map[string]string, price func(Record) *catalog.Price) *blockPricer {
- return &blockPricer{aliases: aliases, wires: wires, price: price, by: map[[4]string]pricedAs{}, agents: map[string][2]string{}}
+func newBlockPricer(renames provider.Renames, wires map[string]string, price func(Record) *catalog.Price) *blockPricer {
+ return &blockPricer{renames: renames, wires: wires, price: price, by: map[[4]string]pricedAs{}, agents: map[string][2]string{}}
}
-// as is priceRow's answer for a gateway call of these names.
+// as is priceRow's answer for a gateway call of these names, prov the
+// id the provider has now (Renames).
func (b *blockPricer) as(prov, model, served, effort string) pricedAs {
k := [4]string{prov, model, served, effort}
if a, ok := b.by[k]; ok {
return a
}
- if id, ok := b.aliases[prov]; ok {
- prov = id
- }
a := pricedAs{provider: prov, flags: swapKnown}
sent := provider.SentNameIn(b.wires, prov, model, effort)
if served != "" && Swapped(sent, served) && !(SameSpelled(model, served) || ServingName(model, served) || RelayRenamed(model, served)) {
@@ -123,19 +121,41 @@ func (b *blockPricer) block(packed *rowChunk) *rowChunk {
flags uint16
price *catalog.Price
}
- names := map[[4]uint32]ids{}
+ names := map[[5]uint32]ids{}
agents := map[uint32][2]uint32{}
- shapes := map[uint32]ids{}
+ shapes := map[[2]uint32]ids{}
+ // the provider each shape names, as it is now: one an id was given
+ // away from since has its calls told by when each was made, so its
+ // rows take the shape per provider they go to (Renames.Timed)
+ type renamedTo struct {
+ to uint32
+ timed bool
+ }
+ provs := map[uint32]renamedTo{}
for i := range c.Rows {
p := &c.Rows[i]
- got, ok := shapes[p.Shape]
+ raw := c.Shapes[p.Shape][1]
+ to, ok := provs[raw]
+ if !ok {
+ id := c.Strings[raw]
+ to = renamedTo{timed: b.renames.Timed(id)}
+ if !to.timed {
+ to.to = intern(b.renames.Of(id, p.Time), raw)
+ }
+ provs[raw] = to
+ }
+ if to.timed {
+ to.to = intern(b.renames.Of(c.Strings[raw], p.Time), raw)
+ }
+ sk := [2]uint32{p.Shape, to.to}
+ got, ok := shapes[sk]
if !ok {
t := c.Shapes[p.Shape]
- k := [4]uint32{t[1], t[5], t[7], t[8]}
+ k := [5]uint32{t[1], t[5], t[7], t[8], to.to}
named, ok := names[k]
if !ok {
- a := b.as(c.Strings[k[0]], c.Strings[k[1]], c.Strings[k[2]], c.Strings[k[3]])
- named = ids{intern(a.provider, k[0]), a.flags, a.price}
+ a := b.as(c.Strings[k[4]], c.Strings[k[1]], c.Strings[k[2]], c.Strings[k[3]])
+ named = ids{k[4], a.flags, a.price}
names[k] = named
}
agent, ok := agents[t[0]]
@@ -146,7 +166,7 @@ func (b *blockPricer) block(packed *rowChunk) *rowChunk {
}
t[0], t[1], t[rowClient] = agent[0], named.id, agent[1]
got = ids{c.shape(t), named.flags, named.price}
- shapes[p.Shape] = got
+ shapes[sk] = got
}
p.Shape = got.id
p.Flags = p.Flags&^(1|2|32) | got.flags
diff --git a/internal/usage/cache_unknown_test.go b/internal/usage/cache_unknown_test.go
index 4e03b4a19..ee4a6aa40 100644
--- a/internal/usage/cache_unknown_test.go
+++ b/internal/usage/cache_unknown_test.go
@@ -5,6 +5,7 @@ import (
"time"
"github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/provider"
)
// readBack is r as the ledger reads it back: from a chunk as written, priced
@@ -18,7 +19,7 @@ func readBack(t *testing.T, r Record) []Row {
}
return &chunk
}
- b := newBlockPricer(nil, nil, func(Record) *catalog.Price { return nil })
+ b := newBlockPricer(provider.Renames{}, nil, func(Record) *catalog.Price { return nil })
defer b.release()
raw := made()
return []Row{raw.row(0), b.block(raw).row(0), b.block(made().pack()).row(0)}
diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go
index cca0d6bdf..916e4389b 100644
--- a/internal/usage/ledger.go
+++ b/internal/usage/ledger.go
@@ -420,7 +420,7 @@ func ledgerWithShared(since, until time.Time, f Filter, recs []Record, logs []se
// ledgerMatched is ledgerWithShared with the session files' calls the
// gateway saw already told (matched, by their index in logs).
func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessions.Call, others []SharedCall, matched map[int]bool, pairs map[int]int, actors map[int]string, compactions map[int]*bool) (rows []Row, sum Totals, agents, providers []string) {
- renamed := provider.Renamed()
+ renamed := provider.UsageRenames()
// the upstream names in force now, read once for the lot: a row is
// judged by the names standing today, which is what Ledger says, and
// the rows here are what a reader compares a bill against
@@ -459,9 +459,7 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi
if !since.IsZero() && r.Time.Before(since) || after(until, r.Time) {
continue
}
- if id, ok := renamed[r.Provider]; ok {
- r.Provider = id
- }
+ r.Provider = renamed.Of(r.Provider, r.Time)
actor := ""
if call, ok := pairs[i]; ok && call >= 0 && call < len(logs) {
actor = logs[call].ThreadID
@@ -496,9 +494,7 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi
if !since.IsZero() && r.Time.Before(since) || after(until, r.Time) {
continue
}
- if id, ok := renamed[r.Provider]; ok {
- r.Provider = id
- }
+ r.Provider = renamed.Of(r.Provider, r.Time)
add(r, priceOf(r), c.Source, "")
}
// the two logs, by when each call began
@@ -557,13 +553,11 @@ func Pricer() func(Record) *catalog.Price {
// effective prices used by the ledger. Reuse it for one page of routes;
// make it again on the next read so a changed tariff re-prices history.
func NewPricer() func([]Record) Totals {
- priceOf, renamed := Pricer(), provider.Renamed()
+ priceOf, renamed := Pricer(), provider.UsageRenames()
return func(recs []Record) Totals {
var sum Totals
for _, r := range recs {
- if id, ok := renamed[r.Provider]; ok {
- r.Provider = id
- }
+ r.Provider = renamed.Of(r.Provider, r.Time)
sum.add(r, priceOf(r))
}
return sum
@@ -1115,17 +1109,18 @@ func ledgerSeriesAt(p Period, rows []Row, now time.Time) (bucket string, pts []S
// Visit calls fn with each record from since on, as the ledger's index
// reads usage.jsonl: only its blocks that reach since are decoded.
+// Each record is as it was recorded: a provider renamed since is named
+// by the id it had then, which provider.UsageRenames tells (NewCoster
+// does so itself).
func Visit(since time.Time, fn func(Record)) { readLogSnapshot().visit(since, fn) }
// NewCoster prices one record at a time at the effective prices the
// ledger uses, read once: its cost in USD, and false for a call with
// tokens but no known price.
func NewCoster() func(Record) (float64, bool) {
- priceOf, renamed := Pricer(), provider.Renamed()
+ priceOf, renamed := Pricer(), provider.UsageRenames()
return func(r Record) (float64, bool) {
- if id, ok := renamed[r.Provider]; ok {
- r.Provider = id
- }
+ r.Provider = renamed.Of(r.Provider, r.Time)
var t Totals
t.add(r, priceOf(r))
return t.Cost, t.Unpriced == 0
diff --git a/internal/usage/plan_credits_test.go b/internal/usage/plan_credits_test.go
index f069c0ef4..84ae1c539 100644
--- a/internal/usage/plan_credits_test.go
+++ b/internal/usage/plan_credits_test.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/provider"
)
// What a request said it cost in its plan's credits (#2512) is summed by
@@ -108,7 +109,7 @@ func TestPlanCreditsPacked(t *testing.T) {
}
chunk.add(Row{Record: r}, "", int64(i), false)
}
- b := newBlockPricer(nil, nil, func(Record) *catalog.Price { return nil })
+ b := newBlockPricer(provider.Renames{}, nil, func(Record) *catalog.Price { return nil })
defer b.release()
packed := chunk.pack()
if len(packed.Archive) == 0 {
diff --git a/internal/usage/probes.go b/internal/usage/probes.go
index ed9ae9c2a..cc0bf6de9 100644
--- a/internal/usage/probes.go
+++ b/internal/usage/probes.go
@@ -4,6 +4,7 @@ import (
"time"
"github.com/yetone/magpie/internal/probelog"
+ "github.com/yetone/magpie/internal/provider"
)
// SourceProbe is Record.Source for a request magpie sent a provider on its
@@ -54,7 +55,9 @@ func clipProbeError(s string) string {
// probeChunk is the probes made since since as one chunk of the request
// log's rows, each in the order its line has in the log as a gateway
// row's is; nil for none.
-func probeChunk(probes []probeRow, since time.Time) *rowChunk {
+// A provider renamed since is listed by the id it has now (Renames): the
+// Requests page's provider list named a renamed one twice (cybercaius).
+func probeChunk(probes []probeRow, since time.Time, renames provider.Renames) *rowChunk {
var c *rowChunk
for _, p := range probes {
if !since.IsZero() && p.Time.Before(since) {
@@ -63,7 +66,9 @@ func probeChunk(probes []probeRow, since time.Time) *rowChunk {
if c == nil {
c = &rowChunk{}
}
- c.add(Row{Record: p.Record, Source: SourceProbe}, "", p.off, false)
+ r := p.Record
+ r.Provider = renames.Of(r.Provider, r.Time)
+ c.add(Row{Record: r, Source: SourceProbe}, "", p.off, false)
}
if c == nil {
return nil
diff --git a/internal/usage/reasoning_stream_speed_test.go b/internal/usage/reasoning_stream_speed_test.go
index 2c4505825..6d9047399 100644
--- a/internal/usage/reasoning_stream_speed_test.go
+++ b/internal/usage/reasoning_stream_speed_test.go
@@ -5,6 +5,7 @@ import (
"time"
"github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/provider"
)
func TestVisibleReasoningSpeed(t *testing.T) {
@@ -97,7 +98,7 @@ func TestPricedRowKeepsReasoningEvidence(t *testing.T) {
for i := 0; i < 80; i++ {
chunk.add(Row{Record: c.r}, "", int64(i), false)
}
- b := newBlockPricer(nil, nil, func(Record) *catalog.Price { return nil })
+ b := newBlockPricer(provider.Renames{}, nil, func(Record) *catalog.Price { return nil })
defer b.release()
for _, from := range []*rowChunk{&chunk, chunk.pack()} {
priced := b.block(from)
@@ -139,7 +140,7 @@ func TestRowFlagsApart(t *testing.T) {
}
return &chunk
}
- b := newBlockPricer(nil, nil, func(Record) *catalog.Price { return nil })
+ b := newBlockPricer(provider.Renames{}, nil, func(Record) *catalog.Price { return nil })
defer b.release()
raw := made()
for _, row := range []Row{raw.row(0), b.block(raw).row(0), b.block(made().pack()).row(0)} {
diff --git a/internal/usage/rename_usage_test.go b/internal/usage/rename_usage_test.go
new file mode 100644
index 000000000..925924371
--- /dev/null
+++ b/internal/usage/rename_usage_test.go
@@ -0,0 +1,82 @@
+package usage
+
+import (
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/probelog"
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// A provider renamed is shown by the id it has now everywhere usage names
+// it, its calls from before the rename too: the Requests page listed it
+// twice, once by each id, its model-list rows under the old one, and the
+// Sessions tab named it by the old id (cybercaius on Discord). An id it
+// gave up and another provider took later is the new one's only from
+// then on.
+func TestRenamedProviderShownOnce(t *testing.T) {
+ reportedHome(t)
+ if err := provider.Save(provider.Provider{ID: "myrelay", Name: "My relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"gpt-9"}}); err != nil {
+ t.Fatal(err)
+ }
+ then := time.Now().Add(-time.Hour)
+ Append(Record{Time: then, Agent: "codex", Session: "s1", Provider: "myrelay", Model: "gpt-9", Input: 100, Output: 10, Status: 200})
+ probelog.Sink(probelog.Row{Time: then.Add(time.Second), Kind: probelog.KindList, Provider: "myrelay", Host: "relay.example", Endpoint: "GET /v1/models", Status: 200, Millis: 30})
+ // read once under the old id, so what is kept of it is built again
+ if p := QueryPage(All, Filter{}, 0, 50); !slices.Equal(p.Providers, []string{"myrelay"}) {
+ t.Fatalf("before: %v", p.Providers)
+ }
+ _ = Vias(time.Time{})
+ if err := provider.Rename("myrelay", "newrelay"); err != nil {
+ t.Fatal(err)
+ }
+ Append(Record{Time: then.Add(2 * time.Second), Agent: "codex", Session: "s1", Provider: "newrelay", Model: "gpt-9", Input: 100, Output: 10, Status: 200})
+
+ page := QueryPage(All, Filter{}, 0, 50)
+ if !slices.Equal(page.Providers, []string{"newrelay"}) {
+ t.Fatalf("providers %v", page.Providers)
+ }
+ for _, r := range page.Rows {
+ if r.Provider != "newrelay" {
+ t.Fatalf("a %s row under %q", r.Source, r.Provider)
+ }
+ }
+ if p := QueryPage(All, Filter{Provider: "newrelay"}, 0, 50); p.Total != 3 || p.Sum.Calls != 2 {
+ t.Fatalf("filtered: total %d sum %+v", p.Total, p.Sum)
+ }
+ vs := Vias(time.Time{}).Of("codex|s1")
+ if len(vs) != 1 || vs[0].Provider != "newrelay" || vs[0].Calls != 2 {
+ t.Fatalf("vias %+v", vs)
+ }
+
+ // a provider added under the old id afterwards takes only its own calls
+ if err := provider.Save(provider.Provider{ID: "myrelay", Name: "Another", Key: "k2", Chat: "http://127.0.0.1:2/v1", Models: []string{"gpt-9"}}); err != nil {
+ t.Fatal(err)
+ }
+ Append(Record{Time: time.Now().Add(time.Second), Agent: "codex", Session: "s2", Provider: "myrelay", Model: "gpt-9", Input: 100, Output: 10, Status: 200})
+ page = QueryPage(All, Filter{}, 0, 50)
+ if !slices.Equal(page.Providers, []string{"myrelay", "newrelay"}) {
+ t.Fatalf("providers after the id was taken %v", page.Providers)
+ }
+ got := map[string]int{}
+ for _, r := range page.Rows {
+ got[r.Provider]++
+ }
+ if got["newrelay"] != 3 || got["myrelay"] != 1 {
+ t.Fatalf("rows by provider %v", got)
+ }
+ if vs := Vias(time.Time{}).Of("codex|s1"); len(vs) != 1 || vs[0].Provider != "newrelay" {
+ t.Fatalf("vias of the renamed one %+v", vs)
+ }
+ if vs := Vias(time.Time{}).Of("codex|s2"); len(vs) != 1 || vs[0].Provider != "myrelay" {
+ t.Fatalf("vias of the new one %+v", vs)
+ }
+ calls := map[string]int{}
+ for _, g := range Summarize(All).Models {
+ calls[g.ID] += g.Calls
+ }
+ if calls["newrelay/gpt-9"] != 2 || calls["myrelay/gpt-9"] != 1 {
+ t.Fatalf("summary %v", calls)
+ }
+}
diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go
index 1b3b16ba0..bc3baa450 100644
--- a/internal/usage/request_page.go
+++ b/internal/usage/request_page.go
@@ -612,7 +612,7 @@ func readRequestState(now time.Time) requestState {
})
ids, _ := json.Marshal(provider.SessionIdentities(sessions.CodexDir()))
codexIdentityKey, _ := json.Marshal(codexIdentities)
- renamed, _ := json.Marshal(provider.Renamed())
+ renamed := provider.UsageRenames().Key()
cfg := settings.Load()
prices, _ := json.Marshal(cfg.ModelPrices)
wires, _ := json.Marshal(cfg.ModelWires)
@@ -835,7 +835,8 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti
// copy of each block kept beside it doubled the index, and over the
// cache budget every query priced the whole history again.
var gateways []*rowChunk
- priced := newBlockPricer(provider.Renamed(), cfg.ModelWires, price)
+ renames := provider.UsageRenames()
+ priced := newBlockPricer(renames, cfg.ModelWires, price)
for _, packed := range snapshot.blocks {
if !gatewaySince.IsZero() && packed.Latest.Before(gatewaySince) {
continue
@@ -844,7 +845,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti
gateways = append(gateways, c)
}
}
- if c := probeChunk(snapshot.probes, gatewaySince); c != nil {
+ if c := probeChunk(snapshot.probes, gatewaySince, renames); c != nil {
gateways = append(gateways, c) // listed, never counted (SourceProbe)
}
on := map[string]bool{}
@@ -912,7 +913,6 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti
// the other computers' days (#542), a chunk each, read again only when
// sync brought a new copy
var others []*rowChunk
- var renames map[string]string
from := ""
if !since.IsZero() { // as sharedSources reads it
from = since.AddDate(0, 0, -2).Format(time.DateOnly)
@@ -925,16 +925,11 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti
c := idx.chunks[s.path]
if reused := c != nil && c.Source.Size == s.size && c.Source.Modified.Equal(s.mod); !reused {
d, _ := readShared(s.path)
- if renames == nil {
- renames = provider.Renamed()
- }
c = &rowChunk{Source: sessions.CallSource{Path: s.path, Size: s.size, Modified: s.mod}, Computer: s.computer, Rows: make([]packedRow, 0, len(d.Calls))}
for i, call := range d.Calls {
r := call.Record
r.Computer = ""
- if id, ok := renames[r.Provider]; ok {
- r.Provider = id
- }
+ r.Provider = renames.Of(r.Provider, r.Time)
c.add(priceRow(r, call.Source), "", int64(i), false)
}
c.Bytes -= int64(32 * len(c.Strings))
diff --git a/internal/usage/summary_cache.go b/internal/usage/summary_cache.go
index 67251442f..86116d58d 100644
--- a/internal/usage/summary_cache.go
+++ b/internal/usage/summary_cache.go
@@ -134,7 +134,7 @@ func usagePriceCacheKey(now time.Time) string {
h := sha256.New()
st := settings.Load()
prices, _ := json.Marshal(st.ModelPrices)
- aliases, _ := json.Marshal(provider.Renamed())
+ 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))
diff --git a/internal/usage/usage.go b/internal/usage/usage.go
index 196e6d6c0..b6eebf19e 100644
--- a/internal/usage/usage.go
+++ b/internal/usage/usage.go
@@ -859,16 +859,15 @@ func summarize(p Period, now time.Time, recs []Record) Summary {
}
func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[string]bool, read func(func(Record))) Summary {
- renamed := provider.Renamed()
+ renamed := provider.UsageRenames()
// the names models' usage is counted under (SlouchyQuill507): a model's
// row sums its ids, each call priced by its own id first
alias := provider.UsageAlias()
normalizedKeys := map[string]bool{}
for id := range historicalKeys {
- if next, ok := renamed[id]; ok {
- id = next
+ for _, next := range renamed.Each(id) {
+ normalizedKeys[next] = true
}
- normalizedKeys[id] = true
}
historicalKeys = normalizedKeys
// a picked range's own days alone: its chart can start on the Monday
@@ -879,9 +878,7 @@ func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[
if r.Time.Before(from) || after(until, r.Time) {
return
}
- if next, ok := renamed[r.Provider]; ok {
- r.Provider = next
- }
+ r.Provider = renamed.Of(r.Provider, r.Time)
fn(r)
})
}
@@ -1069,7 +1066,9 @@ func Vias(since time.Time) ViaIndex {
return cachedVias(since)
}
-func buildVias(snapshot *logSnapshot, since time.Time) *viaLists {
+// A provider renamed since is listed by the id it has now (renames): the
+// Sessions tab named a renamed one by its old id (cybercaius).
+func buildVias(snapshot *logSnapshot, since time.Time, renames provider.Renames) *viaLists {
out := map[string][]Via{}
first := map[string]time.Time{}
keep := keptStrings{}
@@ -1077,7 +1076,7 @@ func buildVias(snapshot *logSnapshot, since time.Time) *viaLists {
if r.IsRejected() || r.IsReported() || r.Session == "" || r.Model == "" {
return
}
- r.Provider, r.Model, r.Effort = keep.of(r.Provider), keep.of(r.Model), keep.of(r.Effort)
+ r.Provider, r.Model, r.Effort = keep.of(renames.Of(r.Provider, r.Time)), keep.of(r.Model), keep.of(r.Effort)
k := ReportedAs(r.Agent) + "|" + r.Session
vs := out[k]
if t, seen := first[k]; !seen || r.Time.Before(t) {
diff --git a/internal/usage/vias_cache.go b/internal/usage/vias_cache.go
index 656019703..147e965c5 100644
--- a/internal/usage/vias_cache.go
+++ b/internal/usage/vias_cache.go
@@ -4,6 +4,8 @@ import (
"slices"
"sync"
"time"
+
+ "github.com/yetone/magpie/internal/provider"
)
// viaLists is what the gateway sent each session's calls to, and when each
@@ -23,7 +25,7 @@ type viaLists struct {
var viasCache struct {
sync.Mutex
version uint64
- clients string // the clients counted as agents (#1958)
+ clients string // the clients counted as agents (#1958), and the renames
all *viaLists
window struct {
version uint64
@@ -42,6 +44,7 @@ type ViaIndex struct {
since time.Time
snapshot *logSnapshot
clients string
+ renames provider.Renames
}
// Of is what the gateway sent one session's calls to ("agent|id") since
@@ -81,7 +84,7 @@ func (x ViaIndex) window() map[string][]Via {
if w.m != nil && w.version == x.snapshot.version && w.clients == x.clients && w.since.Equal(x.since) {
return w.m
}
- m := buildVias(x.snapshot, x.since).m
+ m := buildVias(x.snapshot, x.since, x.renames).m
if x.snapshot.complete() {
w.version, w.clients, w.since, w.m = x.snapshot.version, x.clients, x.since, m
}
@@ -90,17 +93,20 @@ func (x ViaIndex) window() map[string][]Via {
func cachedVias(since time.Time) ViaIndex {
snapshot := readLogSnapshot()
- clients := clientAgentsKey()
+ // a provider renamed is listed by the id it has now (Renames), so a
+ // rename is another index too
+ renames := provider.UsageRenames()
+ clients := clientAgentsKey() + "\x00" + renames.Key()
viasCache.Lock()
defer viasCache.Unlock()
all := viasCache.all
if all == nil || viasCache.version != snapshot.version || viasCache.clients != clients {
- all = buildVias(snapshot, time.Time{})
+ all = buildVias(snapshot, time.Time{}, renames)
if snapshot.complete() {
viasCache.version, viasCache.clients, viasCache.all = snapshot.version, clients, all
}
}
- return ViaIndex{all: all, since: since, snapshot: snapshot, clients: clients}
+ return ViaIndex{all: all, since: since, snapshot: snapshot, clients: clients, renames: renames}
}
// complete is whether the snapshot reached the end of the log, so what is
diff --git a/internal/usage/window_holds.go b/internal/usage/window_holds.go
index 6103b5976..4c340ec98 100644
--- a/internal/usage/window_holds.go
+++ b/internal/usage/window_holds.go
@@ -28,13 +28,13 @@ func init() { provider.ReckonHolds = WithWindowHolds }
func WithWindowHolds(qs []provider.SubscriptionQuota, now time.Time) []provider.SubscriptionQuota {
since, ok := holdsSince(qs, now)
if !ok { // none can be reckoned: each one only says why
- return windowHolds(qs, now, time.Time{}, nil, nil, nil, func(func(Record)) {})
+ return windowHolds(qs, now, time.Time{}, nil, provider.Renames{}, nil, func(func(Record)) {})
}
s := readLogSnapshot()
hist := provider.QuotaHistories(since, "", "")
started := withRecordedWindowStarts(qs, hist, now)
dry := dryRuns(started, hist, now)
- out := windowHolds(started, now, s.firstOwn, apiPricer(), provider.Renamed(), dry, func(fn func(Record)) { s.visit(since, fn) })
+ out := windowHolds(started, now, s.firstOwn, apiPricer(), provider.UsageRenames(), dry, func(fn func(Record)) { s.visit(since, fn) })
return withSpansOf(out, qs)
}
@@ -177,7 +177,7 @@ func dryRuns(qs []provider.SubscriptionQuota, hist []provider.QuotaHistory, now
// call in one of its account's dry runs that may have been paid otherwise:
// one where the vendor answered a call after a reading of none left, or
// where no reading with some left is known before it.
-func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf func(Record) *catalog.Price, renamed map[string]string, dry map[string][]dryRun, read func(func(Record))) []provider.SubscriptionQuota {
+func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf func(Record) *catalog.Price, renamed provider.Renames, dry map[string][]dryRun, read func(func(Record))) []provider.SubscriptionQuota {
type slot struct{ q, w int }
type span struct{ start, end time.Time }
want := map[slot]span{}
@@ -217,9 +217,7 @@ func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf
if r.IsRejected() || r.IsReported() || r.Input+r.Output == 0 {
return
}
- if next, ok := renamed[r.Provider]; ok {
- r.Provider = next
- }
+ r.Provider = renamed.Of(r.Provider, r.Time)
acct := r.Provider + "\x00" + strings.ToLower(r.Account())
var runs []runKey
for i, d := range dry[acct] {
diff --git a/internal/usage/window_holds_history.go b/internal/usage/window_holds_history.go
index 9acf94f05..25d621780 100644
--- a/internal/usage/window_holds_history.go
+++ b/internal/usage/window_holds_history.go
@@ -71,7 +71,7 @@ func HistoricalWindowHolds(cards []provider.SubscriptionQuota, hist []provider.Q
past = append(past, a)
}
s := readLogSnapshot()
- return windowHolds(snapshots, to, s.firstOwn, apiPricer(), provider.Renamed(), dryRuns(snapshots, past, to), func(fn func(Record)) {
+ return windowHolds(snapshots, to, s.firstOwn, apiPricer(), provider.UsageRenames(), dryRuns(snapshots, past, to), func(fn func(Record)) {
s.visit(since, func(r Record) {
if r.Time.Before(to) {
fn(r)
diff --git a/internal/usage/window_holds_test.go b/internal/usage/window_holds_test.go
index b6a0b0b8a..bfb8e403e 100644
--- a/internal/usage/window_holds_test.go
+++ b/internal/usage/window_holds_test.go
@@ -158,19 +158,19 @@ func TestWindowHoldsNeedsTheWholeWindowLogged(t *testing.T) {
}
}
priceOf := func(Record) *catalog.Price { return nil }
- if got := windowHolds(qs, now, now.Add(-2*24*time.Hour), priceOf, nil, nil, read); got[0].Windows[0].Holds != nil || got[0].Windows[0].HoldsWhy != provider.HoldsBeforeLog {
+ if got := windowHolds(qs, now, now.Add(-2*24*time.Hour), priceOf, provider.Renames{}, nil, read); got[0].Windows[0].Holds != nil || got[0].Windows[0].HoldsWhy != provider.HoldsBeforeLog {
t.Fatalf("the log began 2 days into the week, and the week was reckoned: %+v, why %q", got[0].Windows[0].Holds, got[0].Windows[0].HoldsWhy)
}
- got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, nil, nil, read)
+ got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, provider.Renames{}, nil, read)
if h := got[0].Windows[0].Holds; h == nil || h.Tokens != 500 || h.Priced {
t.Fatalf("logged since before the week: %+v, want 500 tokens, unpriced", h)
}
- if got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, nil, nil, func(func(Record)) {}); got[0].Windows[0].Holds != nil || got[0].Windows[0].HoldsWhy != provider.HoldsNoneRouted {
+ if got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, provider.Renames{}, nil, func(func(Record)) {}); got[0].Windows[0].Holds != nil || got[0].Windows[0].HoldsWhy != provider.HoldsNoneRouted {
t.Fatalf("nothing routed, and the week was reckoned: %+v, why %q", got[0].Windows[0].Holds, got[0].Windows[0].HoldsWhy)
}
// a provider since renamed: its calls under the old id are the account's
recs[0].Provider = "claude-old"
- if got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, map[string]string{"claude-old": "claude"}, nil, read); got[0].Windows[0].Holds == nil {
+ if got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, provider.RenamesOf(map[string]string{"claude-old": "claude"}), nil, read); got[0].Windows[0].Holds == nil {
t.Fatal("a call under the provider's old id wasn't counted")
}
}
@@ -223,7 +223,7 @@ func TestWindowHoldsLeavesOutCallsPaidOtherwise(t *testing.T) {
}
var whys [2]string
holds := func(qs []provider.SubscriptionQuota, h []provider.QuotaHistory, recs ...Record) (five, week *provider.WindowHolds) {
- got := windowHolds(qs, now, first, priceOf, nil, dryRuns(qs, h, now), reads(recs...))
+ got := windowHolds(qs, now, first, priceOf, provider.Renames{}, dryRuns(qs, h, now), reads(recs...))
whys = [2]string{got[0].Windows[0].HoldsWhy, got[0].Windows[1].HoldsWhy}
return got[0].Windows[0].Holds, got[0].Windows[1].Holds
}
@@ -288,7 +288,7 @@ func TestWindowHoldsResetBeforeRefillReading(t *testing.T) {
} {
t.Run(tc.name, func(t *testing.T) {
call := Record{Time: tc.at, Provider: providerID, ProviderAccount: "[email protected]", Model: "m", Input: 1000, Status: 200}
- got := windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, nil, dryRuns(qs, hist, now), func(fn func(Record)) { fn(call) })
+ got := windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, provider.Renames{}, dryRuns(qs, hist, now), func(fn func(Record)) { fn(call) })
h := got[0].Windows[1].Holds
if (h != nil) != tc.want {
t.Fatalf("week holds = %+v, want present %v", h, tc.want)
@@ -329,7 +329,7 @@ func TestWindowHoldsDryAgainAfterReset(t *testing.T) {
{Time: now.Add(-3 * 24 * time.Hour), Input: 1000, Status: 200},
{Time: r1.Add(time.Hour), Input: 1000, Status: 200}, // after the reset, before the next dry reading
}
- got := windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, nil, dryRuns(qs, hist, now), func(fn func(Record)) {
+ got := windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, provider.Renames{}, dryRuns(qs, hist, now), func(fn func(Record)) {
for _, c := range calls {
c.Provider, c.ProviderAccount, c.Model = "codex", "u", "m"
fn(c)