groups: the user's own routing groups are the groups plugin's, served only while it is on (P3 router strategy)

The groups plugin now owns the user's own routing groups at the router
strategy point. The groups magpie finds (auto-<model>, one model several
providers serve) stay core, as Smart does: a new install has groups off
under Essentials, and taking those would silently drop cross-provider
failover. planGroup and the walk over a group's members stay core too.

- provider.GateGroups / ServeGroups (group_serve.go): the gateway holds
  the gate while it serves; the plugin holds ServeGroups while on. Gated
  with none served, groupsIn drops every group not Auto, so FindGroup,
  GroupFor, the catalog and /v1/models go without them. The CLI and TUI
  are never gated. Nothing derived from groups is cached past a call, so
  a flip is seen by the next lookup.
- Gated and off, a lookup that finds a user group asks the gate's refresh
  (pluginrt.Refresh in the gateway) at most once a second, never
  re-entrantly, then looks again. Without this, `magpie group add` was
  404 for up to 2s until KeepFresh turned the plugin on (seen in the
  sandbox).
- plugins/groups and plugins/routing: InUse is provider.NamedGroups, the
  file's non-Auto, non-hidden groups read past the gate; an unreadable
  providers.json is an error, so the plugin stays on.

Run before rebasing onto 707fbb249:
- go test -count=1 -timeout 40m ./... : all ok (59 packages)
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean
- sandbox, real nogui binary + `magpie serve` + two fake upstreams:
  before add: group/auto-m listed, group/mine 404; right after
  `magpie group add Mine models=pa/x,pb/m`: group/mine listed and 200;
  after `group rm`: 404, auto-m still served.

After the rebase onto 707fbb249: vets (3 OSes) and go test of
internal/provider, internal/gateway, internal/pluginrt and plugins/...
all ok.

Broken by hand, each went red:
- groupsIn filter removed: TestOwnGroupsWaitOnThePlugin,
  TestGroupsOnAndOff/off
- NamedGroups swallowing the read error: TestNamedGroupsUnreadable,
  plugins/groups TestInUse
- Apply not serving: TestOnServesOffDoesNot
- refresh not called / not throttled / asked for Auto groups too:
  TestOwnGroupRefreshesTheGate
This commit is contained in:
yetone
2026-10-15 10:42:23 +08:00
parent 707fbb249d
commit b1d02fa612
12 changed files with 435 additions and 24 deletions
+6
View File
@@ -1426,6 +1426,12 @@ strategies in Plugins › Built-in). It stays on while a provider or group is
routed by one of them. Turned off, the pickers offer Smart alone, and a
provider or group still set to one of them is tried in its listed order.
Your own routing groups are the built-in plugin `groups` (Routing groups in
Plugins › Built-in), which stays on while you have one. The groups magpie
finds for a model two providers serve don't need it. Turned off, the gateway
doesn't list or serve a group of your own, and the Routing page has no New
group button; `magpie groups` still lists them.
**Make first** sets the accounts' order. How much that order counts
depends on the routing:
File diff suppressed because one or more lines are too long
+18 -2
View File
@@ -187,8 +187,18 @@ the core. The five other routings are the built-in plugin `rotation`'s.
| Off | A routing no strategy serves is its listed order. `routingOf` in the gateway reads it as `order` wherever the core asks about a routing (a turn's mark, `sinks`, a rotate group's sessions, a group's heads), so nothing of the routing is left half on. | [`routing.go`](../../internal/gateway/routing.go) |
| `plugins/rotation` | Requires `providers` and `gateway`, `Essential`. Apply registers every `routes.Builtin` and removes them when turned off. `InUse` counts the providers and groups providers.json routes by one of them (`provider.Routings`, the file alone, not the catalog); an unreadable providers.json is an error, so it stays on. The gateway's `KeepFresh` watches providers.json too, so a routing set from the CLI or the TUI turns it on within 2s. Off, the window's routing pickers (the provider editor, the Routing page's pools and groups) offer Smart alone: their options are marked `data-feature="rotation"` (`routingSegs`). | [`rotation.go`](../../plugins/rotation/rotation.go), [`provider.go`](../../internal/provider/provider.go), [`app.js`](../../internal/gui/assets/app.js) |
Groups are next on this point: `planGroup` behind it, the `groups` plugin
serving it.
The user's own routing groups are the `groups` plugin's on this point. The
groups magpie finds (a model two providers serve, `auto-<model>`) stay the
core's, as Smart does: they are how a model several providers serve is one
model with failover, which a new install has with the Essentials preset,
where `groups` is off. `planGroup` and the walk over a group's members are
the core's either way: a strategy only orders a pool, and a group off is
not offered at all.
| Part | What it does | Source |
| --- | --- | --- |
| `GateGroups`, `ServeGroups` | The gateway holds `GateGroups` while it serves (`ListenAndServe`), and the plugin holds `ServeGroups` while it is on. Gated with none served, `groupsIn` leaves out every group not `Auto`, so `Groups`, `FindGroup`, `GroupFor`, the catalog, `/v1/models` and a group's `Unlists` go without them: a request for one is a model not served. A process not serving the gateway (the CLI, the TUI) is never gated and lists them all. Nothing built from the groups is kept past a call, so a flip is seen by the next lookup. Gated and off, a lookup that finds a group of the user's own first asks the gate's refresh (the gateway's is `pluginrt.Refresh`), at most once a second and never from inside one, then looks again: a group made a moment ago turns the plugin on and is served by the request that asks for it, not after `KeepFresh`'s next look (`TestOwnGroupRefreshesTheGate`). | [`group_serve.go`](../../internal/provider/group_serve.go), [`group.go`](../../internal/provider/group.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| `plugins/groups` | Requires `window` and `providers`, not Essential. Apply holds `ServeGroups`. `InUse` is `provider.NamedGroups`: the groups providers.json holds that are neither Auto nor hidden, read from the file, never through the gate (else off would count none and stay off); an unreadable file is an error, so it stays on. The `routing` plugin's `InUse` is the same count. The gateway's `KeepFresh` watches providers.json, so a group made with `magpie group add` turns it on within 2s, and a request for it before then turns it on itself (the gate's refresh, above); the window's New group button is `data-feature="groups"`. | [`groups.go`](../../plugins/groups/groups.go), [`routing.go`](../../plugins/routing/routing.go) |
The other points follow in this order: middleware (the JS gateway middleware becomes one consumer of it, with its
place, API and fail-open policy unchanged; redaction fails closed), then
@@ -288,5 +298,11 @@ remembering its layer (`Source`):
the parity run with the plugin on; `TestRotationOnAndOff` turns it off),
and `routing-save.test.cjs` (Smart alone with it off, every width and
engine).
- P3 groups: `go test ./internal/provider/ -run 'TestOwnGroupsWaitOnThePlugin|TestNamedGroupsUnreadable'`,
`go test ./plugins/groups/` (`TestOnServesOffDoesNot`, `TestInUse`) and
`go test ./internal/gateway/` whole (its `TestMain` holds
`ServeGroups`, the parity run with the plugin on; `TestGroupsOnAndOff`
turns it off: the user's group leaves `/v1/models` and isn't served,
the found one is both).
- By hand, under a sandbox HOME: `magpie plugin builtin`, `magpie plugin
builtin on groups`, `magpie plugin dump`, and a plugins.yml broken by hand.
+9
View File
@@ -477,6 +477,15 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
// `magpie plugin builtin`) come and go here too
stopObservers := usage.ServeObservers()
defer stopObservers()
// and the user's own routing groups are served while plugins/groups is
// on (provider.GateGroups); one made a moment ago turns it on as it is
// looked up, not on KeepFresh's next look
stopGroups := provider.GateGroups(func() {
if _, err := pluginrt.Refresh(); err != nil {
log.Printf("plugins: %v", err)
}
})
defer stopGroups()
freshCtx, stopFresh := context.WithCancel(ctx)
defer stopFresh()
go pluginrt.KeepFresh(freshCtx, 2*time.Second, settings.Path(), provider.Path())
+46
View File
@@ -0,0 +1,46 @@
package gateway
import (
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// The router strategy point's groups with plugins/groups on and off: on, a
// group of the user's own is listed and answers; off, in the process
// serving the gateway, it is neither, while the group magpie found for a
// model two providers serve is listed and answers either way.
func TestGroupsOnAndOff(t *testing.T) {
fresh(t)
v := &keyed{}
serveOn(t, "pa", "ka", []string{"m", "x"}, v)
serveOn(t, "pb", "kb", []string{"m"}, v)
if err := provider.SaveGroup(provider.Group{Name: "Mine", Members: []string{"pa/x", "pb/m"}}); err != nil {
t.Fatal(err)
}
s := New()
check := func(when string, mine bool) {
t.Helper()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil))
list := rec.Body.String()
if strings.Contains(list, `"group/mine"`) != mine || !strings.Contains(list, `"group/auto-m"`) {
t.Fatalf("%s: models %s", when, list)
}
code, body := postAs(t, s, "", `{"model":"group/mine","messages":[{"role":"user","content":"hi"}]}`)
if (code == 200) != mine {
t.Fatalf("%s: group/mine %d %s", when, code, body)
}
if code, body := postAs(t, s, "", `{"model":"group/auto-m","messages":[{"role":"user","content":"hi"}]}`); code != 200 {
t.Fatalf("%s: group/auto-m %d %s", when, code, body)
}
}
check("on", true)
t.Run("off", func(t *testing.T) {
withoutGroups(t)
check("off", false)
})
check("on again", true)
}
+16
View File
@@ -19,6 +19,7 @@ const standInsEnv = "MAGPIE_GATEWAY_TEST_STAND_INS"
func TestMain(m *testing.M) {
serveRotation()
groupsServed = provider.ServeGroups()
code, err := isolatedTests(m)
if err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -135,3 +136,18 @@ func withoutRotation(t *testing.T) {
rotation = nil
t.Cleanup(serveRotation)
}
// groupsServed is plugins/groups on, as for a user with a group of their
// own: the gateway's tests serve their groups.
var groupsServed func()
// withoutGroups is plugins/groups off for t, in a process serving the
// gateway (provider.GateGroups): the user's own groups aren't served.
func withoutGroups(t *testing.T) {
groupsServed()
stop := provider.GateGroups(nil)
t.Cleanup(func() {
stop()
groupsServed = provider.ServeGroups()
})
}
+3
View File
@@ -313,6 +313,9 @@ func groupsIn(entries []Entry) []Group {
}
out = append(out, withMatches(entries, g.own()))
}
if !served(f.Groups) { // plugins/groups is off: the user's own aren't served
out = slices.DeleteFunc(out, func(g Group) bool { return !g.Auto })
}
if f.NoAutoGroups {
return orderedGroups(out, f.GroupOrder)
}
+117
View File
@@ -0,0 +1,117 @@
package provider
import (
"slices"
"sync"
"sync/atomic"
"time"
)
// The user's own routing groups — those not Auto, made on the Routing page
// or with `magpie group` — are plugins/groups' to serve (P3 of
// docs/subsystems/plugin-runtime.md). In the process serving the gateway
// (GateGroups), while that plugin is off (no ServeGroups held), they are
// neither listed nor routed: Groups, FindGroup, GroupFor and the catalog
// leave them out. The groups magpie finds (Auto) are the core's either
// way, as Smart is: they are how a model several providers serve is one
// model with failover, which a new install, the groups plugin off, has.
//
// The plugin stays on while the user has a group of their own
// (NamedGroups), so off, there is none to leave out but one added since
// the plugin last looked: a lookup that finds one asks the gate's refresh
// (the gateway's plugin runtime) first, which turns the plugin on, so a
// group made a moment ago with `magpie group add` is served at once. A
// process not serving the gateway (the CLI, the TUI) lists them all.
var groupGate struct {
sync.Mutex
gated int // GateGroups calls not yet stopped
served int // ServeGroups calls not yet removed
refresh func() // the last GateGroups' refresh
}
// groupRefreshing: a refresh is under way, so a lookup it makes (a plugin's
// InUse) doesn't start another; refreshed: when the last one began, so a
// plugins.yml that can't be read, which leaves the plugin off, is asked
// again at most once a second, not on every lookup
var (
groupRefreshing atomic.Bool
groupRefreshed atomic.Int64
)
// GateGroups makes the user's own groups wait on ServeGroups until stop:
// the gateway calls it as it starts serving. refresh, when not nil, is
// asked to bring the plugins up to date when a lookup gated finds a group
// of the user's own (served).
func GateGroups(refresh func()) (stop func()) {
groupGate.Lock()
groupGate.refresh = refresh
groupGate.Unlock()
return holdGate(&groupGate.gated)
}
// ServeGroups serves the user's own groups until remove: plugins/groups
// calls it while it is on.
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.
func holdGate(n *int) func() {
groupGate.Lock()
*n++
groupGate.Unlock()
var once sync.Once
return func() {
once.Do(func() {
groupGate.Lock()
*n--
groupGate.Unlock()
})
}
}
// GroupsServed says whether the user's own groups are served here now.
func GroupsServed() bool {
groupGate.Lock()
defer groupGate.Unlock()
return groupsServedLocked()
}
// served says whether the user's own groups among gs are served: gated and
// not, gs holding one asks the refresh once and looks again.
func served(gs []Group) bool {
groupGate.Lock()
ok, refresh := groupsServedLocked(), groupGate.refresh
groupGate.Unlock()
if ok || refresh == nil || !slices.ContainsFunc(gs, func(g Group) bool { return !g.Auto && !g.Hidden }) {
return ok
}
now := time.Now().UnixNano()
if now-groupRefreshed.Load() < int64(time.Second) || !groupRefreshing.CompareAndSwap(false, true) {
return false
}
groupRefreshed.Store(now)
refresh()
groupRefreshing.Store(false)
return GroupsServed()
}
func groupsServedLocked() bool { return groupGate.gated == 0 || groupGate.served > 0 }
// NamedGroups counts the user's own groups in providers.json, served or
// not; a file that can't be read is an error, not none.
func NamedGroups() (int, error) {
f, err := read()
if err != nil {
return 0, err
}
n := 0
for _, g := range f.Groups {
if !g.Auto && !g.Hidden {
n++
}
}
return n, nil
}
+126
View File
@@ -0,0 +1,126 @@
package provider
import (
"os"
"path/filepath"
"slices"
"testing"
)
// The user's own groups wait on plugins/groups only where the gateway is
// served: ungated (the CLI, the TUI) they are listed; gated, only while
// ServeGroups is held. The groups magpie finds are listed either way, and
// NamedGroups, which keeps the plugin on, counts the user's own regardless.
func TestOwnGroupsWaitOnThePlugin(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", "")
if err := store(file{Groups: []Group{{ID: "mine", Name: "Mine", Members: []string{"a/x", "b/y"}}}}); err != nil {
t.Fatal(err)
}
entries := []Entry{
{ID: "a/x", Model: "x", Provider: Provider{ID: "a"}}, {ID: "b/y", Model: "y", Provider: Provider{ID: "b"}},
{ID: "a/m", Model: "m", Provider: Provider{ID: "a"}}, {ID: "b/m", Model: "m", Provider: Provider{ID: "b"}},
}
listed := func() []string {
var ids []string
for _, e := range groupEntries(entries) {
ids = append(ids, e.ID)
}
slices.Sort(ids)
return ids
}
both, found := []string{"group/auto-m", "group/mine"}, []string{"group/auto-m"}
check := func(when string, want []string) {
t.Helper()
if got := listed(); !slices.Equal(got, want) {
t.Fatalf("%s: %v, want %v", when, got, want)
}
if n, err := NamedGroups(); n != 1 || err != nil {
t.Fatalf("%s: NamedGroups %d, %v", when, n, err)
}
}
check("ungated", both)
stop := GateGroups(nil)
check("gated, plugin off", found)
remove := ServeGroups()
check("plugin on", both)
remove()
remove() // once
check("plugin off again", found)
stop()
check("gateway stopped", both)
}
// A providers.json that can't be read is not "no groups": the plugin that
// counts them stays on.
func TestNamedGroupsUnreadable(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", "")
if err := os.MkdirAll(filepath.Dir(Path()), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(Path(), 0o755); err != nil { // a folder where the file goes
t.Fatal(err)
}
if _, err := NamedGroups(); err == nil {
t.Fatal("no error for a providers.json that can't be read")
}
}
// Gated and off, a lookup that finds a group of the user's own asks the
// gateway's refresh first (which turns the plugin on), so one made a
// moment ago is served at once, not on the runtime's next look; a refresh
// that leaves it off is asked at most once a second, and never for the
// groups magpie found alone.
func TestOwnGroupRefreshesTheGate(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", "")
entries := []Entry{{ID: "a/m", Model: "m", Provider: Provider{ID: "a"}}, {ID: "b/m", Model: "m", Provider: Provider{ID: "b"}}}
asked := 0
var remove func()
defer func() {
if remove != nil {
remove()
}
}()
refresh := func() {
asked++
if asked == 2 {
remove = ServeGroups() // the plugin found in use, turned on
}
}
defer GateGroups(refresh)()
groupRefreshed.Store(0)
groupEntries(entries)
// a found group the user edited is kept in the file, Auto still
if err := store(file{Groups: []Group{{ID: "auto-m", Name: "m", Auto: true, Members: []string{"b/m", "a/m"}}}}); err != nil {
t.Fatal(err)
}
groupEntries(entries)
if asked != 0 {
t.Fatalf("refreshed %d times with found groups alone", asked)
}
if err := store(file{Groups: []Group{{ID: "mine", Name: "Mine", Members: []string{"a/m"}}}}); err != nil {
t.Fatal(err)
}
has := func() bool {
return slices.ContainsFunc(groupEntries(entries), func(e Entry) bool { return e.ID == "group/mine" })
}
if has() || asked != 1 {
t.Fatalf("a refresh that leaves it off: listed %v, asked %d", has(), asked)
}
has()
if asked != 1 {
t.Fatalf("asked again within a second: %d", asked)
}
groupRefreshed.Store(0)
if !has() || asked != 2 {
t.Fatalf("a refresh that turns it on: listed %v, asked %d", has(), asked)
}
}
+15 -12
View File
@@ -1,6 +1,12 @@
// Package groups is routing groups' part of the window: several models
// agents pick as one, each request sent to the right one and on to the
// next when one fails. While the user has a group, it stays on.
// Package groups is routing groups: several models agents pick as one,
// each request sent to the right one and on to the next when one fails.
// While the user has a group, it stays on.
//
// It serves the user's own groups on the gateway's router strategy point
// (P3 of docs/subsystems/plugin-runtime.md): Apply holds
// provider.ServeGroups, and off, the gateway neither lists nor routes them.
// The groups magpie finds (one model several providers serve) are the
// core's, on or off.
package groups
import (
@@ -13,15 +19,12 @@ func init() {
ID: "groups", API: "^1", Requires: []string{"window", "providers"},
Name: "Routing groups", Sub: "Several models agents pick as one: each request goes to the right one, and to the next when one fails",
One: "1 group in use", Many: "{n} groups in use",
InUse: func() (int, error) {
n := 0
for _, g := range provider.Groups() {
if !g.Auto && !g.Hidden {
n++
}
}
return n, nil
},
// a providers.json that can't be read is not known, so it stays on
InUse: provider.NamedGroups,
Parts: []pluginrt.Part{{Slot: "part", Key: "groups"}},
Apply: func(c *pluginrt.Ctx) error {
c.OnDispose(provider.ServeGroups())
return nil
},
})
}
+77
View File
@@ -0,0 +1,77 @@
package groups
import (
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
)
func TestMain(m *testing.M) { testenv.Main(m) }
func manifest(t *testing.T) pluginrt.Manifest {
t.Helper()
for _, m := range pluginrt.Registered() {
if m.ID == "groups" {
return m
}
}
t.Fatal("groups not registered")
return pluginrt.Manifest{}
}
func sandbox(t *testing.T) {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, "cache"))
}
// Where the gateway is served, the user's own groups are served while the
// plugin is on, and not while it is off.
func TestOnServesOffDoesNot(t *testing.T) {
sandbox(t)
defer provider.GateGroups(nil)()
rt := pluginrt.New([]pluginrt.Manifest{manifest(t)})
defer rt.Stop()
served := func(want bool) {
t.Helper()
if provider.GroupsServed() != want {
t.Fatalf("served: %v, want %v (%+v)", !want, want, rt.Statuses())
}
}
served(false)
rt.Reconcile(map[string]bool{"groups": true}, nil)
served(true)
rt.Reconcile(map[string]bool{"groups": false}, nil)
served(false)
rt.Reconcile(map[string]bool{"groups": true}, nil)
served(true)
}
// It counts the user's own groups; a providers.json that can't be read
// keeps it on.
func TestInUse(t *testing.T) {
sandbox(t)
inUse := manifest(t).InUse
if n, err := inUse(); n != 0 || err != nil {
t.Fatalf("no file: %d, %v", n, err)
}
if err := provider.SaveGroup(provider.Group{Name: "Mine", Members: []string{"a/x", "b/y"}}); err != nil {
t.Fatal(err)
}
if n, err := inUse(); n != 1 || err != nil {
t.Fatalf("one group: %d, %v", n, err)
}
if err := os.WriteFile(provider.Path(), []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := inUse(); err == nil {
t.Fatal("no error for a providers.json that can't be read")
}
}
+1 -9
View File
@@ -15,15 +15,7 @@ func init() {
ID: "routing", API: "^1", Requires: []string{"window", "gateway"}, Essential: true,
Name: "Routing", Sub: "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups",
One: "1 group in use", Many: "{n} groups in use",
InUse: func() (int, error) {
n := 0
for _, g := range provider.Groups() {
if !g.Auto && !g.Hidden {
n++
}
}
return n, nil
},
InUse: provider.NamedGroups,
Parts: []pluginrt.Part{{Slot: "nav.page", Key: "routing"}},
Client: []string{"i18n.js", "routing.css", "client.js"},
})