Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
provider: what a request built of the catalog stays for the next request within a second, not built again for each
yetoneed3a46d02b8e
diff --git a/internal/filememo/filememo.go b/internal/filememo/filememo.goindex 9c9a12f8d..3623f57d3 100644--- a/internal/filememo/filememo.go+++ b/internal/filememo/filememo.go@@ -9,6 +9,7 @@ import ("os""strings""sync"+ "sync/atomic""time""github.com/yetone/magpie/internal/steady"@@ -86,9 +87,17 @@ func Hold() (release func()) {func Forget() {mu.Lock()gen+++ gens.Store(gen)mu.Unlock()}+// gens is gen, read without mu.+var gens atomic.Uint64++// Gen is moved on by every Forget: what is built from files read here, and+// kept past one read, is built again when it moved.+func Gen() uint64 { return gens.Load() }+// Look has the file at path looked at on its next read, even while a// request holds what was read (Hold): another magpie may have written it,// which Forget, moved on by this one's writes alone, can't know of.diff --git a/internal/gateway/request_builds_once_test.go b/internal/gateway/request_builds_once_test.goindex 290cd75d1..63ed12f7e 100644--- a/internal/gateway/request_builds_once_test.go+++ b/internal/gateway/request_builds_once_test.go@@ -2,6 +2,7 @@ package gatewayimport ("testing"+ "time""github.com/yetone/magpie/internal/plugin""github.com/yetone/magpie/internal/provider"@@ -11,18 +12,32 @@ import (// model up on its way: each build reads every agent's sign-in, every// plugin's and the settings, and three builds a request kept magpie at// 100–350% CPU under seven agents at once (#2502). The next request,-// nothing held between them, builds afresh.+// within a second and nothing written, builds none: one request after+// another built the providers again each time. After a write it builds+// once more.func TestRequestBuildsProvidersOnce(t *testing.T) {plugin.UseCached(nil)setup(t, provider.Chat, &fake{t: t, reply: sse(`{"choices":[{"delta":{"content":"hi"}}]}`, "[DONE]")})- for i := range 2 {- n := provider.AllBuilt.Load()+ var first time.Time+ for i, want := range []int64{1, 0, 1} {+ if i == 2 {+ provider.Changed() // a provider saved+ }+ n, start := provider.AllBuilt.Load(), time.Now()+ if i == 1 && start.Sub(first) > 900*time.Millisecond {+ // what was built is held for a second: a request this late+ // (a loaded machine) builds again, rightly+ want = 1+ }+ if i == 0 {+ first = start+ }code, body := post(t, "/v1/chat/completions", `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`)if code != 200 {t.Fatalf("%d %s", code, body)}- if got := provider.AllBuilt.Load() - n; got != 1 {- t.Fatalf("request %d built the providers %d times, want 1", i+1, got)+ if got := provider.AllBuilt.Load() - n; got != want {+ t.Fatalf("request %d built the providers %d times, want %d", i+1, got, want)}}}diff --git a/internal/provider/group_serve.go b/internal/provider/group_serve.goindex 60be9496a..9ae4c4ce7 100644--- a/internal/provider/group_serve.go+++ b/internal/provider/group_serve.go@@ -55,19 +55,21 @@ func ServeGroups() (remove func()) {return holdGate(&groupGate.served)}-// holdGate holds n until the func it gives is called. Nothing built from-// the groups is kept past one call (only the file is, while a request-// holds it), so the next lookup sees the change.+// holdGate holds n until the func it gives is called. What is built from+// the groups and held across requests (heldOf) is dropped either way, so+// the next lookup sees the change.func holdGate(n *int) func() {groupGate.Lock()*n++groupGate.Unlock()+ dropHeld()var once sync.Oncereturn func() {once.Do(func() {groupGate.Lock()*n--groupGate.Unlock()+ dropHeld()})}}diff --git a/internal/provider/hold.go b/internal/provider/hold.goindex 48b2736f7..52ced4f9e 100644--- a/internal/provider/hold.go+++ b/internal/provider/hold.go@@ -1,6 +1,8 @@package providerimport (+ "hash/maphash"+ "os""slices""sync""time"@@ -22,6 +24,62 @@ var held struct {gen uint64// what was built, and when, by what it isbuilt map[string]heldValue+ // env is the environment it was built in (environSum)+ env uint64+ // fgen is filememo's generation it was built in: a write that only+ // tells filememo (settings.Save, an account's file) has it built again+ fgen uint64+ // roots is the providers' and the settings' files as last looked at+ roots [2]rootStamp+}++// rootStamp is a file's time and size, or that it wasn't there.+type rootStamp struct {+ mod time.Time+ size int64+ ok bool+}++func stampOf(path string) rootStamp {+ fi, err := os.Stat(path)+ if err != nil {+ return rootStamp{}+ }+ return rootStamp{fi.ModTime(), fi.Size(), true}+}++// heldFreshLocked drops what is built when a file was written since, by+// this process (filememo.Gen) or, for the providers' and the settings'+// files, by another (the CLI's "magpie group add", seen by the next+// request, not a second later). Called with held held.+func heldFreshLocked(look bool) {+ if g := filememo.Gen(); g != held.fgen {+ held.built, held.fgen = nil, g+ }+ if !look {+ return+ }+ for i, path := range [2]string{Path(), settings.Path()} {+ if st := stampOf(path); st != held.roots[i] {+ held.roots[i] = st+ held.built = nil+ filememo.Look(path)+ }+ }+}++var environSeed = maphash.MakeSeed()++// environSum is a hash of this process's environment: the folders every+// file and account is read from are named by it.+func environSum() uint64 {+ var h maphash.Hash+ h.SetSeed(environSeed)+ for _, kv := range os.Environ() {+ h.WriteString(kv)+ h.WriteByte(0)+ }+ return h.Sum64()}type heldValue struct {@@ -47,18 +105,35 @@ func init() {// heldFor is how long a held catalog is used before it is built again,// while one request after another keeps it held.-const heldFor = time.Second+var heldFor = time.Second// Hold keeps the catalog built once until release is called, for a// request that only reads; a write meanwhile (Changed) drops it.func Hold() (release func()) {held.Lock()+ if held.holds == 0 {+ // what was built under another environment (a HOME or config+ // folder of its own: a test's) isn't this one's+ if env := environSum(); env != held.env {+ held.built, held.env = nil, env+ }+ heldFreshLocked(true)+ }held.holds++held.Unlock()return sync.OnceFunc(func() {held.Lock()if held.holds--; held.holds == 0 {- held.built = nil+ // what is built stays for the next request within heldFor, as+ // it stays for one that overlaps this one: one request after+ // another, each built the catalog again from every provider's+ // files and accounts (a fifth of a request's CPU with 30+ // providers). Only what is past heldFor goes, for memory.+ for k, h := range held.built {+ if time.Since(h.at) >= heldFor {+ delete(held.built, k)+ }+ }}held.Unlock()})@@ -87,6 +162,7 @@ func heldOf[T any](key string, build func() T) T {held.Unlock()return build()}+ heldFreshLocked(false)if h, ok := held.built[key]; ok && time.Since(h.at) < heldFor {held.Unlock()return h.v.(T)@@ -140,6 +216,7 @@ func heldFrom[T any](key string, entries []Entry, build func([]Entry) T) T {held.Unlock()return build(entries)}+ heldFreshLocked(false)if h, ok := held.built[key]; ok && time.Since(h.at) < heldFor {if f := h.v.(fromEntries[T]); f.at == at && f.n == len(entries) {held.Unlock()diff --git a/internal/provider/hold_test.go b/internal/provider/hold_test.goindex a49a74824..a7124d289 100644--- a/internal/provider/hold_test.go+++ b/internal/provider/hold_test.go@@ -7,8 +7,10 @@ import ("slices""strings""testing"+ "time""github.com/yetone/magpie/internal/catalog"+ "github.com/yetone/magpie/internal/filememo""github.com/yetone/magpie/internal/plugin""github.com/yetone/magpie/internal/settings""github.com/yetone/magpie/internal/testenv"@@ -45,6 +47,96 @@ func TestHoldBuildsOnce(t *testing.T) {}}+// One request after another within heldFor builds the catalog once, as+// requests that overlap do: each built it again from every provider's+// files and accounts (a fifth of a request's CPU with 30 providers). A+// write between them (Changed), or another environment (a test's HOME),+// has it built again.+func TestHoldKeptForTheNextRequest(t *testing.T) {+ defer func(d time.Duration) { heldFor = d }(heldFor)+ heldFor = time.Minute // a loaded machine's pause between requests isn't the change+ t.Setenv("MAGPIE_HOLD_TEST", "1")+ n := 0+ build := func() int { n++; return n }+ for range 5 {+ release := Hold()+ heldOf("t-next", build)+ heldOf("t-next", build)+ release()+ }+ if n != 1 {+ t.Fatalf("five requests one after another: built %d times, want 1", n)+ }+ Changed()+ func() {+ defer Hold()()+ if heldOf("t-next", build); n != 2 {+ t.Fatalf("after a write: built %d times, want 2", n)+ }+ }()+ t.Setenv("MAGPIE_HOLD_TEST", "2")+ func() {+ defer Hold()()+ if heldOf("t-next", build); n != 3 {+ t.Fatalf("in another environment: built %d times, want 3", n)+ }+ }()+ if heldOf("t-next", build); n != 4 {+ t.Fatalf("unheld: built %d times, want 4", n)+ }+}++// What is held across requests is built again when anything it was built+// from may have moved: a write that only tells filememo (settings.Save, an+// account's file), the providers' or the settings' file written by+// another process (the CLI's "magpie group add"), and the groups served+// or not (GateGroups, ServeGroups).+func TestHoldKeptUntilAWrite(t *testing.T) {+ defer func(d time.Duration) { heldFor = d }(heldFor)+ heldFor = time.Minute // a loaded machine's pause between requests isn't the change+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ n := 0+ build := func() int { n++; return n }+ request := func() {+ defer Hold()()+ heldOf("t-write", build)+ }+ request()+ request()+ if n != 1 {+ t.Fatalf("two requests: built %d times, want 1", n)+ }+ for _, c := range []struct {+ what string+ write func()+ }{+ {"filememo told", filememo.Forget},+ {"providers.json written by another process", func() {+ os.MkdirAll(filepath.Dir(Path()), 0o700)+ os.WriteFile(Path(), []byte(`{"providers":[]}`), 0o600)+ }},+ {"settings.json written by another process", func() {+ os.MkdirAll(filepath.Dir(settings.Path()), 0o700)+ os.WriteFile(settings.Path(), []byte(`{}`), 0o600)+ }},+ {"the groups gated", func() { GateGroups(nil)() }},+ } {+ was := n+ c.write()+ request()+ if n != was+1 {+ t.Fatalf("%s: built %d times, want 1", c.what, n-was)+ }+ request()+ if n != was+1 {+ t.Fatalf("%s, then a request: built again", c.what)+ }+ }+}+// A change the plugin host tells (a sign-in saved, a plugin added) drops// what a request holds before it returns: a SyncCatalog running held the// plugins as they were before `magpie plugin login` saved its account,