diff --git a/internal/agent/dsh.go b/internal/agent/dsh.go index f8c16f569..a925414ae 100644 --- a/internal/agent/dsh.go +++ b/internal/agent/dsh.go @@ -207,7 +207,7 @@ func dshOn(at place, dir, list string, fresh, lead func() string) *Agent { if len(files) == 0 { return false } - _, items, err := dshRead(files[0]) + _, items, err := dshLook(files[0]) // dshOver changes a copy return err == nil && dshWired(dshOver(dir, items)) }, // connected so, Disconnect takes the route out, the start magpie @@ -728,9 +728,12 @@ func dshNode(it dshItem) (*yaml.Node, error) { // An entry's text is parsed once and its node shared, so whoever gets it // only reads it; a caller changing the node takes dshNode's own copy. func dshNodeShared(it dshItem) (*yaml.Node, error) { - text := strings.Join(it.lines, "\n") + // keyed by a hash of the lines, checked against a copy of them, so a + // look that finds the entry allocates nothing: joining the lines into a + // key each time was most of what the drift poll's dsh check still made + key := dshLinesHash(it.lines) dshNodes.Lock() - n, ok := dshNodes.m[text] + n, ok := dshNodes.find(key, it.lines) dshNodes.Unlock() if !ok { var err error @@ -738,10 +741,13 @@ func dshNodeShared(it dshItem) (*yaml.Node, error) { n = nil } dshNodes.Lock() - if dshNodes.m == nil || len(dshNodes.m) >= dshNodesMax { - dshNodes.m = map[string]*yaml.Node{} + if dshNodes.m == nil || dshNodes.size >= dshNodesMax { + dshNodes.m, dshNodes.size = map[uint64][]dshNodeEntry{}, 0 + } + if _, there := dshNodes.find(key, it.lines); !there { + dshNodes.m[key] = append(dshNodes.m[key], dshNodeEntry{slices.Clone(it.lines), n}) + dshNodes.size++ } - dshNodes.m[text] = n dshNodes.Unlock() } if n == nil { @@ -754,11 +760,42 @@ func dshNodeShared(it dshItem) (*yaml.Node, error) { // entries, with room for the old text of ones just changed. const dshNodesMax = 512 -var dshNodes struct { - sync.Mutex - m map[string]*yaml.Node +var dshNodeSeed = maphash.MakeSeed() + +// dshLinesHash hashes an entry's lines as the text they make. +func dshLinesHash(lines []string) uint64 { + var h maphash.Hash + h.SetSeed(dshNodeSeed) + for _, l := range lines { + h.WriteString(l) + h.WriteByte('\n') + } + return h.Sum64() } +type dshNodeEntry struct { + lines []string // a copy: a caller may change its own slice later + n *yaml.Node +} + +type dshNodeCache struct { + sync.Mutex + m map[uint64][]dshNodeEntry + size int +} + +// find is the node parsed from these lines; the caller holds the lock. +func (c *dshNodeCache) find(key uint64, lines []string) (*yaml.Node, bool) { + for _, e := range c.m[key] { + if slices.Equal(e.lines, lines) { + return e.n, true + } + } + return nil, false +} + +var dshNodes dshNodeCache + // dshNodeLines writes an entry read with dshNode back as lines. func dshNodeLines(n *yaml.Node) ([]string, error) { var buf bytes.Buffer diff --git a/internal/agent/dsh_shared_test.go b/internal/agent/dsh_shared_test.go index dd3ab7546..659d70880 100644 --- a/internal/agent/dsh_shared_test.go +++ b/internal/agent/dsh_shared_test.go @@ -21,6 +21,21 @@ func TestDshLookParsesAnEntryOnce(t *testing.T) { if n := testing.AllocsPerRun(20, func() { dshConfig(it); dshConfigIndex([]dshItem{it}, dshPiRow) }); n > 50 { t.Errorf("a look at an unchanged entry: %.0f allocations, want a few", n) } + // the lookup itself: no key built from the 1200 lines + if n := testing.AllocsPerRun(20, func() { dshNodeShared(it) }); n != 0 { + t.Errorf("finding a parsed entry: %.0f allocations, want 0", n) + } + // the cache keeps its own copy of the lines: a caller changing its + // slice in place gets the new text, not the node of the old + own := append([]string{}, lines...) + mine := dshItem{id: dshPiRow, lines: own} + if got := dshConfig(mine)["model"]; got != "m1" { + t.Fatalf("copy: %q", got) + } + own[3] = " model: m3" + if got := dshConfig(mine)["model"]; got != "m3" { + t.Errorf("lines changed in place: %q, want m3", got) + } w, err := dshNode(it) if err != nil { t.Fatal(err) diff --git a/internal/gui/api.go b/internal/gui/api.go index e708c9382..c43096a03 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -2961,7 +2961,7 @@ func state() stateJSON { } if ps, err := profile.Load(); err == nil { for _, n := range profile.Names(ps) { - pj := profileJSON{Name: n, Summary: profile.Summary(ps[n]), Agents: profile.Details(ps[n]), InUse: profile.InUse(ps[n], detected, now)} + pj := profileJSON{Name: n, Summary: profile.Summary(ps[n]), Agents: profile.DetailsIn(ps[n], all), InUse: profile.InUse(ps[n], detected, now)} if l := ps[n].Library; l != nil { servers, skills := l.On() pj.Library = &profileLibraryJSON{Servers: servers, Skills: skills, Instructions: l.GivesInstructions()} diff --git a/internal/profile/details.go b/internal/profile/details.go index 8ffb3b372..e40c12b1e 100644 --- a/internal/profile/details.go +++ b/internal/profile/details.go @@ -66,10 +66,15 @@ func secret(key, label, value string) bool { // follows: Claude Code's four tiers are all there, one that follows the main // model saying so (#480: opus and fable, following it, were missing, and // read as not set). What applying the profile writes is unchanged. -func Details(p Profile) []Group { - known := map[string]*agent.Agent{} - var order []string - for _, a := range agent.All() { +func Details(p Profile) []Group { return DetailsIn(p, agent.All()) } + +// DetailsIn is Details over all, the agents a page already built for its +// request: the state route lists every profile, and building the agents +// again for each one was the page's largest single cost after its own. +func DetailsIn(p Profile, all []*agent.Agent) []Group { + known := make(map[string]*agent.Agent, len(all)) + order := make([]string, 0, len(all)) + for _, a := range all { known[a.ID] = a order = append(order, a.ID) } diff --git a/internal/provider/rename.go b/internal/provider/rename.go index 883dff3ba..f867c9d9e 100644 --- a/internal/provider/rename.go +++ b/internal/provider/rename.go @@ -14,6 +14,7 @@ import ( "golang.org/x/net/publicsuffix" "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/settings" ) @@ -407,8 +408,23 @@ func (r Renames) Key() string { // 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. +// UsageRenames are the renames of providers.json as it is now, worked +// out once each time the file changes and shared, so read only: each +// profile's in-use check on every state poll parsed the whole file again +// for them, 5 MB of forty polls with real accounts. func UsageRenames() Renames { + if r, err := filememo.Read("provider renames", Path(), func(b []byte) (Renames, error) { + f, err := parseProviders(b) + if err != nil { + return Renames{}, err + } + return renamesOf(f.Providers, f.Deleted), nil + }); err == nil { + lastRenames.Store(&r) + return r + } + // missing, or a file that doesn't decode: read's own way, its last + // good generation f, err := read() if err != nil { if r := lastRenames.Load(); r != nil { diff --git a/internal/provider/usage_renames_memo_test.go b/internal/provider/usage_renames_memo_test.go new file mode 100644 index 000000000..11b0cbdd0 --- /dev/null +++ b/internal/provider/usage_renames_memo_test.go @@ -0,0 +1,38 @@ +package provider + +import ( + "fmt" + "testing" + "time" +) + +// Each profile's in-use check on a state poll asks for the renames; with +// providers.json unchanged they are worked out once, not parsed from the +// whole file again, and a rename after still shows at once. +func TestUsageRenamesParsedOnceAChange(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()) + for i := range 60 { + if err := Save(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{"a", "b", "c"}}); err != nil { + t.Fatal(err) + } + } + if err := Rename("p1", "one"); err != nil { + t.Fatal(err) + } + if got := UsageRenames().Of("p1", time.Now()); got != "one" { + t.Fatalf("p1 went to %q", got) + } + if n := testing.AllocsPerRun(20, func() { UsageRenames() }); n > 10 { + t.Errorf("renames of an unchanged file: %.0f allocations, want a few", n) + } + if err := Rename("p2", "two"); err != nil { + t.Fatal(err) + } + if got := UsageRenames().Of("p2", time.Now()); got != "two" { + t.Errorf("a rename since: p2 went to %q", got) + } +}