diff --git a/internal/agent/route.go b/internal/agent/route.go index cadbf3f9d..ff114fb69 100644 --- a/internal/agent/route.go +++ b/internal/agent/route.go @@ -342,7 +342,7 @@ func buildModels(agent string) []catalog.Model { // a model magpie describes images to takes them (provider.Described) seen := describedNow() // the agent's own Long conversations, if it has one (ForAgent) - st, find := settings.Load().ForAgent(agent), provider.GroupFinder() + st, find := settings.Load().ForAgent(agent), provider.FoundOnce(provider.GroupFinder()) priceOf := provider.AgentPricer(st, find) members := func(id string) []provider.Member { _, ms, _ := find(id) diff --git a/internal/provider/least_allocs_test.go b/internal/provider/least_allocs_test.go new file mode 100644 index 000000000..2ebb202a5 --- /dev/null +++ b/internal/provider/least_allocs_test.go @@ -0,0 +1,35 @@ +package provider + +import ( + "runtime" + "testing" +) + +// leastAllocs is testing.AllocsPerRun's fewest over five rounds: it counts +// every goroutine's allocations, and another test's left running (a +// watcher, a poll) lands in one round now and then, never in all five. +func leastAllocs(runs int, f func()) float64 { + least := testing.AllocsPerRun(runs, f) + for range 4 { + least = min(least, testing.AllocsPerRun(runs, f)) + } + return least +} + +// leastBytes is the fewest bytes a run of f allocated, over five rounds of +// runs, for the reason leastAllocs gives. +func leastBytes(runs int, f func()) uint64 { + var least uint64 + for i := range 5 { + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + for range runs { + f() + } + runtime.ReadMemStats(&after) + if n := (after.TotalAlloc - before.TotalAlloc) / uint64(runs); i == 0 || n < least { + least = n + } + } + return least +} diff --git a/internal/provider/models.go b/internal/provider/models.go index 962af457c..2e2d10349 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -2726,7 +2726,7 @@ func EntryPricer(st settings.Settings, find func(string) (Group, []Member, bool) // entryPricerAt is EntryPricer with a provider's rate window taken at // now, or left out for a zero now. func entryPricerAt(st settings.Settings, find func(string) (Group, []Member, bool), now time.Time) func(Entry) (catalog.Price, bool) { - all := All() + all := sharedAll() // priceIn only reads them return func(e Entry) (catalog.Price, bool) { if e.Group == "" { return priceIn(st, all, e.Provider.ID, e.Model, now) @@ -2765,7 +2765,7 @@ func entryPricerAt(st settings.Settings, find func(string) (Group, []Member, boo // each call's window. func AgentPricer(st settings.Settings, find func(string) (Group, []Member, bool)) func(Entry) (catalog.Price, bool) { var base time.Time - same, all := entryPricerAt(st, find, base), All() + same, all := entryPricerAt(st, find, base), sharedAll() return func(e Entry) (catalog.Price, bool) { if pr, ok := same(e); ok || e.Group == "" { return pr, ok @@ -2778,6 +2778,35 @@ func AgentPricer(st settings.Settings, find func(string) (Group, []Member, bool) } } +// FoundOnce is find answering each group once: an agent's list asked a +// group's members for its compaction, its price twice and its protocols +// and tiers twice, each walking the group's members and resolving each +// (~8 MB in 2 minutes of an idle magpie's list rebuilds). What it gives +// is shared between the calls: only for reading. +func FoundOnce(find func(string) (Group, []Member, bool)) func(string) (Group, []Member, bool) { + type found struct { + g Group + ms []Member + ok bool + } + var ( + mu sync.Mutex + of = map[string]found{} + ) + return func(id string) (Group, []Member, bool) { + mu.Lock() + f, ok := of[id] + mu.Unlock() + if !ok { + f.g, f.ms, f.ok = find(id) + mu.Lock() + of[id] = f + mu.Unlock() + } + return f.g, f.ms, f.ok + } +} + // PriceRateOK says what is wrong with a provider's price rate, "" when // nothing: from 0 (none) to 1000, in steps of 0.001. func PriceRateOK(r float64) string { @@ -3396,8 +3425,8 @@ func resolveIn(entries []Entry, id string) (Provider, string, bool) { if pid, model, ok := strings.Cut(id, "/"); ok { // the providers a request holds (All): an agent's value of a // model not listed lands here - if p := lookIn(All(), pid); p != nil && p.On() && !p.ServesNone() { - return *p, model, true + if p := lookIn(sharedAll(), pid); p != nil && p.On() && !p.ServesNone() { + return p.clone(), model, true } } for i := range entries { diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 293630f60..2918b5d25 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -797,20 +797,38 @@ func store(f file) error { // item or a CLI's among them, and Codex's /models asked for it seven times // over, past the 5 s Codex waits for the list (#746). func All() []Provider { + shared := sharedAll() + out := make([]Provider, len(shared)) + for i, p := range shared { + out[i] = p.clone() // callers change theirs, Keys[i] and Headers included + } + return out +} + +// sharedAll is All without its copies, only for reading: the providers a +// request holds, less the accounts discovery off leaves out. Find, a +// model's price and a value resolved each copied every provider, every +// account's keys and headers, to read one (~15 MB in 2 minutes of an +// idle magpie with its window open). +func sharedAll() []Provider { held := heldOf("all", allProviders) - out := make([]Provider, 0, len(held)) // asked once, from the settings a held look has read already: asked for // each account, settings.json was parsed for every account of every // model's price (agent.magpieModels, the GUI's drift every 15s and dsh's // round every 30s), most of an idle magpie's CPU (xsw on Discord) off := sync.OnceValue(func() bool { return settings.AccountDiscoveryOffIn(heldSettings()) }) - for _, p := range held { + for i, p := range held { if p.Account != nil && off() && !p.publicAccount() { - continue + out := held[:i:i] // the first append copies + for _, p := range held[i+1:] { + if p.Account == nil || p.publicAccount() { + out = append(out, p) + } + } + return out } - out = append(out, p.clone()) // callers change theirs, Keys[i] and Headers included } - return out + return held } // clone is p with its settings unshared: slices, maps and pointers copied. @@ -1006,7 +1024,12 @@ func find(ps []Provider, id string) (Provider, bool) { // Find looks a provider up by id (or name, case-insensitively). func Find(id string) (*Provider, error) { - return findIn(All(), id) + p, err := findIn(sharedAll(), id) + if p != nil { + c := p.clone() // the caller's to change, as All's are + p = &c + } + return p, err } func findIn(all []Provider, id string) (*Provider, error) { diff --git a/internal/provider/shared_all_test.go b/internal/provider/shared_all_test.go new file mode 100644 index 000000000..c8845ec94 --- /dev/null +++ b/internal/provider/shared_all_test.go @@ -0,0 +1,61 @@ +package provider + +import ( + "fmt" + "testing" +) + +// Find under a hold copies the provider it gives, and no other: it copied +// every provider, every account's keys and headers, to give one. What it +// gives is still the caller's to change. +func TestFindCopiesTheOneItGives(t *testing.T) { + isolate(t) + for i := range 40 { + p := Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Chat: "http://127.0.0.1:1/v1", + Models: []string{"m1", "m2", "m3"}, Keys: []KeyAccount{{Key: "k1"}, {Key: "k2"}}, Headers: map[string]string{"X-A": "1", "X-B": "2"}} + if err := Save(p); err != nil { + t.Fatal(err) + } + } + defer Hold()() + p, err := Find("p7") + if err != nil || p.ID != "p7" { + t.Fatalf("Find: %v %v", p, err) + } + p.Keys[0].Key, p.Models[0], p.Headers["X-A"] = "changed", "changed", "changed" + again, _ := Find("p7") + if again.Keys[0].Key != "k1" || again.Models[0] != "m1" || again.Headers["X-A"] != "1" { + t.Fatalf("a change to what Find gave reached the next: %v %v %v", again.Keys, again.Models, again.Headers) + } + for _, q := range All() { + if q.ID == "p7" && q.Keys[0].Key != "k1" { + t.Fatalf("a change to what Find gave reached All: %v", q.Keys) + } + } + n := leastAllocs(20, func() { Find("p7") }) + if n > 60 { + t.Fatalf("Find of one of 40 providers made %v allocations, want at most 60", n) + } +} + +// FoundOnce walks each group once, however often an agent's list asks. +func TestFoundOnceAsksEachGroupOnce(t *testing.T) { + asked := map[string]int{} + find := FoundOnce(func(id string) (Group, []Member, bool) { + asked[id]++ + return Group{ID: id}, []Member{{ID: id + "-m"}}, id != "group:none" + }) + for range 5 { + for _, id := range []string{"group:a", "group:b", "group:none"} { + g, ms, ok := find(id) + if g.ID != id || len(ms) != 1 || ms[0].ID != id+"-m" || ok != (id != "group:none") { + t.Fatalf("%s: %v %v %v", id, g, ms, ok) + } + } + } + for id, n := range asked { + if n != 1 { + t.Fatalf("%s walked %d times, want once", id, n) + } + } +}