Skip to content

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

provider: a request's groups are built once under its Hold, not again by each look-up

yetone627e8e7d958a
diff --git a/internal/provider/group.go b/internal/provider/group.go
index feba98c31..c83c686a0 100644
--- a/internal/provider/group.go
+++ b/internal/provider/group.go
@@ -28,6 +28,7 @@ import (
"regexp"
"slices"
"strings"
+ "sync/atomic"
"time"
"github.com/yetone/magpie/internal/catalog"
@@ -351,7 +352,50 @@ func Groups() []Group {
return groupsIn(providerEntries())
}
+// groupsIn is the groups among entries (Groups), built once while a
+// request holds the catalog: a request looked its group up by building
+// every group again, matching each pattern and finding the automatic
+// groups over every model (FindGroup, then the groups' entries). Each
+// caller gets a copy of its own to change.
func groupsIn(entries []Entry) []Group {
+ return cloneGroups(heldFrom("groups", entries, buildGroupsIn))
+}
+
+// cloneGroups is gs with nothing shared with it: no slice, map or pointer
+// of a group or its rules.
+func cloneGroups(gs []Group) []Group {
+ if gs == nil {
+ return nil
+ }
+ out := make([]Group, len(gs))
+ for i, g := range gs {
+ g.Members, g.Match, g.Matched = slices.Clone(g.Members), slices.Clone(g.Match), slices.Clone(g.Matched)
+ g.Off, g.Levels, g.Fast = slices.Clone(g.Off), slices.Clone(g.Levels), slices.Clone(g.Fast)
+ g.Weights = maps.Clone(g.Weights)
+ if g.Rules != nil {
+ rs := make([]Rule, len(g.Rules))
+ for j, r := range g.Rules {
+ r.Agents, r.Folders, r.ExceptFolders = slices.Clone(r.Agents), slices.Clone(r.Folders), slices.Clone(r.ExceptFolders)
+ if r.Time != nil {
+ t := *r.Time
+ t.Days = slices.Clone(t.Days)
+ r.Time = &t
+ }
+ rs[j] = r
+ }
+ g.Rules = rs
+ }
+ out[i] = g
+ }
+ return out
+}
+
+// groupsBuilt counts buildGroupsIn, for the test that a held request
+// builds the groups once.
+var groupsBuilt atomic.Int64
+
+func buildGroupsIn(entries []Entry) []Group {
+ groupsBuilt.Add(1)
f := heldOf("file", load)
var out []Group
hidden := map[string]bool{}
diff --git a/internal/provider/group_held_test.go b/internal/provider/group_held_test.go
index 819447c43..88828cdf7 100644
--- a/internal/provider/group_held_test.go
+++ b/internal/provider/group_held_test.go
@@ -3,7 +3,9 @@ package provider
import (
"fmt"
"path/filepath"
+ "reflect"
"testing"
+ "time"
"github.com/yetone/magpie/internal/settings"
)
@@ -134,3 +136,168 @@ func BenchmarkGroupEntries(b *testing.B) {
buildGroupEntries(entries)
}
}
+
+// A request to a group looked its group up through FindGroup and the
+// other group readers, and each built every group again: reading
+// providers.json's groups, matching each pattern against every model and
+// finding the automatic groups over the catalog. While a request holds the
+// catalog the groups are built once, and each caller gets its own copy.
+func TestGroupsBuiltOnceWhileHeld(t *testing.T) {
+ groupHeldFixture(t)
+ release := Hold()
+ defer release()
+ Groups()
+ before := groupsBuilt.Load()
+ for range 20 {
+ Groups()
+ if _, _, ok := FindGroup(GroupPrefix + "g4"); !ok {
+ t.Fatal("no group g4")
+ }
+ }
+ if n := groupsBuilt.Load() - before; n != 0 {
+ t.Fatalf("the groups were built %d times more in 40 looks under one Hold, want 0", n)
+ }
+ // a caller's change to its copy is not the next caller's
+ var g4 Group
+ for _, g := range Groups() {
+ if g.ID == "g4" {
+ g4 = g
+ }
+ }
+ g4.Members[0] = "changed"
+ for _, g := range Groups() {
+ if g.ID == "g4" && g.Members[0] == "changed" {
+ t.Fatal("a change to a held group's members reached the next caller")
+ }
+ }
+ // a write builds them again
+ if err := SaveGroup(Group{ID: "g4", Name: "Renamed", Members: []string{"p0/m1", "p1/m1"}, Routing: Ordered}); err != nil {
+ t.Fatal(err)
+ }
+ if g, _, ok := FindGroup(GroupPrefix + "g4"); !ok || g.Name != "Renamed" {
+ t.Fatalf("a group saved under the Hold kept its old self: %+v", g)
+ }
+}
+
+// cloneGroups shares nothing with what it copies: every slice, map and
+// pointer of a Group and of its Rules, found by reflection, so a field
+// added later is copied too or this fails.
+func TestCloneGroupsSharesNothing(t *testing.T) {
+ var g Group
+ fillEvery(reflect.ValueOf(&g).Elem())
+ if len(g.Rules) == 0 {
+ t.Fatal("the fill made no rule")
+ }
+ c := cloneGroups([]Group{g})[0]
+ if !reflect.DeepEqual(c, g) {
+ t.Fatalf("the copy differs:\n%+v\n%+v", c, g)
+ }
+ if path := sharedRef(reflect.ValueOf(g), reflect.ValueOf(c), "Group"); path != "" {
+ t.Fatalf("%s is shared with the held group", path)
+ }
+}
+
+// fillEvery gives every field of v a value, and each slice, map and pointer one
+// element.
+func fillEvery(v reflect.Value) {
+ switch v.Kind() {
+ case reflect.Struct:
+ for i := range v.NumField() {
+ if v.Type().Field(i).IsExported() {
+ fillEvery(v.Field(i))
+ }
+ }
+ case reflect.Slice:
+ v.Set(reflect.MakeSlice(v.Type(), 1, 1))
+ fillEvery(v.Index(0))
+ case reflect.Map:
+ v.Set(reflect.MakeMap(v.Type()))
+ k, e := reflect.New(v.Type().Key()).Elem(), reflect.New(v.Type().Elem()).Elem()
+ fillEvery(k)
+ fillEvery(e)
+ v.SetMapIndex(k, e)
+ case reflect.Pointer:
+ v.Set(reflect.New(v.Type().Elem()))
+ fillEvery(v.Elem())
+ case reflect.String:
+ v.SetString("x")
+ case reflect.Bool:
+ v.SetBool(true)
+ case reflect.Int, reflect.Int64, reflect.Int32:
+ v.SetInt(1)
+ case reflect.Float64:
+ v.SetFloat(1)
+ }
+}
+
+// sharedRef names the first slice, map or pointer a and b hold in common.
+func sharedRef(a, b reflect.Value, path string) string {
+ switch a.Kind() {
+ case reflect.Struct:
+ for i := range a.NumField() {
+ if a.Type().Field(i).IsExported() {
+ if p := sharedRef(a.Field(i), b.Field(i), path+"."+a.Type().Field(i).Name); p != "" {
+ return p
+ }
+ }
+ }
+ case reflect.Slice:
+ if a.Len() > 0 && a.Pointer() == b.Pointer() {
+ return path
+ }
+ for i := range a.Len() {
+ if p := sharedRef(a.Index(i), b.Index(i), fmt.Sprintf("%s[%d]", path, i)); p != "" {
+ return p
+ }
+ }
+ case reflect.Map, reflect.Pointer:
+ if !a.IsNil() && a.Pointer() == b.Pointer() {
+ return path
+ }
+ if a.Kind() == reflect.Pointer && !a.IsNil() {
+ return sharedRef(a.Elem(), b.Elem(), path)
+ }
+ }
+ return ""
+}
+
+// BenchmarkGroupLooksHeld is the group look-ups one request to a group
+// makes under its Hold (FindGroup for the route, its members and the
+// window, and the group list), over 30 providers serving the same 60
+// models.
+func BenchmarkGroupLooksHeld(b *testing.B) {
+ isolate(b)
+ home := b.TempDir()
+ b.Setenv("HOME", home)
+ b.Setenv("USERPROFILE", home)
+ b.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
+ b.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
+ b.Setenv("MAGPIE_NO_ACCOUNTS", "1")
+ var models []string
+ for i := range 60 {
+ models = append(models, fmt.Sprintf("m%d", i))
+ }
+ for i := range 30 {
+ if err := Save(Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Models: models, Anthropic: "http://127.0.0.1:9"}); err != nil {
+ b.Fatal(err)
+ }
+ }
+ if err := SaveGroup(Group{ID: "g4", Name: "G4", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1"}, Routing: Ordered}); err != nil {
+ b.Fatal(err)
+ }
+ Changed()
+ defer func(d time.Duration) { heldFor = d }(heldFor)
+ heldFor = time.Hour // the look-ups of one request, not the Hold's age on a loaded machine
+ release := Hold()
+ defer release()
+ providerEntries()
+ b.ResetTimer()
+ for range b.N {
+ for range 4 {
+ if _, _, ok := FindGroup(GroupPrefix + "g4"); !ok {
+ b.Fatal("no group g4")
+ }
+ }
+ Groups()
+ }
+}