remote magpie: two magpies each the other's remote no longer list each other's models back without end

cdredfox (Discord) saw 100-200% CPU while magpie used a remote magpie
over Tailscale, gone with the remote off. Their providers mask anyway
and their agent asks auto/ ids, so the earlier unmasked-group lead
doesn't explain it. What does: when A and B are each other's remote,
A's /v1/models (to another magpie) lists rem/<B's models>, B fetches it
as back/rem/..., lists that back to A, and so on: one level deeper on
every 10-minute fetch, without end. Each level is another member of
the found auto/ group and another route round the two machines, masked
again on each pass. On mote, two sandbox magpies in that setup went
from A: [auto/m1 own/m1 rem/auto/m1 rem/up/m1 rem/back/own/m1] to
[... rem/back/rem/back/own/m1, rem/back/rem/auto/m1 ...] after one
more scheduled fetch, and B had back/rem/back/own/m1. A request on the
loop route (rem/back/own/m1) cost A 1.07s CPU over 10 turns against
0.69s for own/m1.

The list a magpie gives another magpie now names, as magpie_via, the
magpies each model passes through, itself last. Each process has a
random id (catalog.Self). A fetched list leaves out a model whose via
has this magpie and another one (it left here and came back), or more
than 8 magpies. A remote that is this magpie itself (via only this id,
as the in-process tests set up) is kept. A magpie older than this sends
no via, and its list is taken as before: both machines need the update.
Stamped on every list a magpie gives: models(), its deciders, and the
drawer and video lists. A routing group's via is its members'
together, so A's auto/m1 holding B's auto/m1 (which holds A's) is left
out at B, and requests no longer go A -> B -> A through groups.
What a user of A loses: B's own auto/ group of a model when it holds
A's model (it reaches A again); B's own models stay listed at A one by
one, and A's group of the model holds them. The cached list keeps Via, so a model a remote served
through others keeps its path in this magpie's list too.

Run (mote, at this tree on 6abacd46c = origin/main):
- go test -timeout 45m ./internal/catalog ./internal/provider
  ./internal/gateway -count=1: ok (catalog 0.7s, provider 120s,
  gateway 670s).
- go vet those three; GOOS=linux and GOOS=windows go vet: ok. gofmt -l
  clean.
- Two sandbox magpies (CLI, nogui build) each the other's remote:
  after two scheduled fetches (18:14, 18:24/18:25) A lists auto/m1,
  own/m1, rem/up/m1 and B auto/m1, up/m1, back/own/m1, each fetch
  taking 1 model; the old build in the same setup went 3 -> 5 models
  on B's second fetch and kept growing (rem/back/rem/back/own/m1).
- go test ./internal/gateway again after the group change: ok (715s).

Broken by hand:
- the loops check in live.go off: TestFetchLeavesOutWhatCameFromHere
  red (back/own/m1 with [self peer] and a 9-magpie model taken), and
  TestRemoteMagpieListLoopsNoMore red (the remote's back/own/m1 taken).
- models() without the magpie_via line: TestRemoteMagpieListLoopsNoMore
  red (own/m1 and rem/up/m1 listed through []).
- viaOf giving a group nil: red (auto/m1 listed through [self], not
  [peer self]).

Not tried:
- cdredfox's own two machines; it isn't confirmed yet that their remote
  also has this machine as its remote. If it doesn't, this isn't their
  cause.
- A loop through a magpie older than this one (no via: still grows
  until both are updated).
- The full suite (runs once after the push).
This commit is contained in:
yetone
2026-11-05 10:26:14 +08:00
parent 1ae48d7f4d
commit c2c991a5b3
8 changed files with 279 additions and 2 deletions
File diff suppressed because one or more lines are too long
+3
View File
@@ -84,6 +84,9 @@ type Model struct {
// provider after it (magpie_label): the name Provider in model names
// Off has here (ARNO on Discord).
Plain string `json:",omitempty"`
// Via, on a model of another magpie's list, is the magpies it passes
// through to its vendor, that one last (magpie_via.go)
Via []string `json:",omitempty"`
// Apart, in a list magpie hands Codex, is what tells the model from
// another entry Codex's picker would call the same (two providers
// named Codex each serving GPT-6.1-Sol, nb5p on Discord): its
+8
View File
@@ -633,6 +633,10 @@ func fetchPage(ctx context.Context, url, key string, anthropic bool, headers map
if id == "" {
continue
}
// one that goes from here and comes back (magpie_via.go)
if loops(r.Via) {
continue
}
// Another magpie's list is already what its user exposed. Keep
// its retrieval models too; a vendor's general list still leaves
// out models agents can't chat with.
@@ -704,6 +708,7 @@ func fetchPage(ctx context.Context, url, key string, anthropic bool, headers map
codexFacts(&m, r, codex)
}
kimiFacts(&m, r)
m.Via = slices.Clip(r.Via)
out = append(out, m)
}
return out, v.HasMore, v.LastID, nil
@@ -781,6 +786,9 @@ type liveModel struct {
// its X-Magpie-Prices header: the price its user set, else its list
// price. Raw, as an odd value mustn't lose the whole list
Price json.RawMessage `json:"magpie_price"`
// the magpies another magpie's model passes through to its vendor,
// itself last (magpie_via.go)
Via []string `json:"magpie_via"`
// the protocol family PipeLLM routes the model by: openai, anthropic
// or gemini
TypeTarget string `json:"type_target"`
+56
View File
@@ -0,0 +1,56 @@
package catalog
import (
"crypto/rand"
"encoding/hex"
"slices"
"sync"
)
// Two magpies can each be the other's Remote magpie (cdredfox on Discord:
// two computers on one Tailscale network). Each one's list to the other
// had the other's own models in it, under its Remote magpie provider, and
// each fetch, every ten minutes (provider.RemoteMagpieEvery), took a turn
// more of the loop: rem/back/own/m1, then rem/back/rem/back/own/m1, … on
// both computers, without end. Every one of them joined its model's found
// group (auto/<model>), and a request to one went round the loop, masked
// again on each computer each time it came back.
//
// So a magpie's list to another magpie names, of each model, the magpies
// it passes through on its way to its vendor (magpie_via): the one
// listing it, and those its own list had from, each by its Self. A list
// that names this magpie and another along the way is of a model that
// leaves here and comes back: it isn't taken. A magpie pointed at itself
// (the gateway's tests, which serve their remote from one process) is
// this magpie alone, and its list is taken as it was. A list from a
// magpie from before names nothing, and is taken as it was.
// MaxVia is the most magpies a model's way may pass through before a list
// is taken to loop through a magpie from before magpie_via, which
// stamps none of its own.
const MaxVia = 8
// Self is this run of magpie's name in magpie_via: random, made up once a
// run, and told only to a magpie that asks for its list.
var Self = sync.OnceValue(func() string {
b := make([]byte, 8)
rand.Read(b)
return hex.EncodeToString(b)
})
// loops reports whether a model another magpie lists by way of via leaves
// this magpie and comes back to it.
func loops(via []string) bool {
if len(via) > MaxVia {
return true
}
self := Self()
return slices.Contains(via, self) && slices.ContainsFunc(via, func(v string) bool { return v != self })
}
// ViaHere is the magpie_via a model goes out with in this magpie's list
// to another: the way it came here by, when it came from another magpie,
// then this one.
func ViaHere(came []string) []string {
return append(slices.Clip(came), Self())
}
+64
View File
@@ -0,0 +1,64 @@
package catalog
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
)
// Two magpies that are each other's remote (cdredfox on Discord) list
// each other's models back: a model that left this magpie through the
// other, and comes back, is not taken again, so neither list grows a
// level on every fetch. One only through others is kept, with the magpies
// it passes, and so is one through this magpie alone: a remote that is
// this magpie itself.
func TestFetchLeavesOutWhatCameFromHere(t *testing.T) {
self := Self()
long := make([]string, MaxVia+1)
for i := range long {
long[i] = fmt.Sprintf("p%d", i)
}
q := func(via []string) string {
s := make([]string, len(via))
for i, v := range via {
s[i] = `"` + v + `"`
}
return "[" + strings.Join(s, ",") + "]"
}
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
fmt.Fprintf(rw, `{"object":"list","data":[
{"id":"up/m1","magpie_via":["peer"]},
{"id":"back/own/m1","magpie_via":%s},
{"id":"own/m2","magpie_via":%s},
{"id":"far/m3","magpie_via":%s},
{"id":"old/m4"}]}`, q([]string{self, "peer"}), q([]string{self}), q(long))
}))
defer srv.Close()
ms, _, err := FetchAt(context.Background(), srv.URL+"/v1", "k", false, nil)
if err != nil {
t.Fatal(err)
}
got := map[string][]string{}
for _, m := range ms {
got[m.ID] = m.Via
}
if _, ok := got["back/own/m1"]; ok {
t.Errorf("a model that went out of this magpie and came back was taken: %v", got)
}
if _, ok := got["far/m3"]; ok {
t.Errorf("a model through more than %d magpies was taken: %v", MaxVia, got)
}
if v, ok := got["up/m1"]; !ok || !slices.Equal(v, []string{"peer"}) {
t.Errorf("up/m1 = %v, %v; want kept through [peer]", v, ok)
}
if v, ok := got["own/m2"]; !ok || !slices.Equal(v, []string{self}) {
t.Errorf("own/m2 = %v, %v; want kept through this magpie", v, ok)
}
if v, ok := got["old/m4"]; !ok || v != nil {
t.Errorf("an older magpie's model = %v, %v; want kept, through nothing said", v, ok)
}
}
+31 -2
View File
@@ -1428,7 +1428,8 @@ func drawerObjects(r *http.Request) []map[string]any {
name := cmp.Or(m.Name, m.ID)
o := map[string]any{"id": p.ID + "/" + m.ID, "object": "model", "type": "model", "kind": "image", "created": 0,
"owned_by": p.ID, "display_name": name, "magpie_label": name + " · " + p.Name,
"modalities": map[string]any{"input": []string{"text"}, "output": []string{"image"}}}
"modalities": map[string]any{"input": []string{"text"}, "output": []string{"image"}},
"magpie_via": catalog.ViaHere(m.Via)}
if m.Images {
o["modalities"] = map[string]any{"input": []string{"text", "image"}, "output": []string{"image"}}
}
@@ -1456,12 +1457,35 @@ func videomakerObjects(r *http.Request) []map[string]any {
name := cmp.Or(m.Name, m.ID)
out = append(out, map[string]any{"id": p.ID + "/" + m.ID, "object": "model", "type": "model", "kind": "video", "created": 0,
"owned_by": p.ID, "display_name": name, "magpie_label": name + " · " + p.Name,
"modalities": map[string]any{"input": []string{"text", "image"}, "output": []string{"video"}}})
"modalities": map[string]any{"input": []string{"text", "image"}, "output": []string{"video"}},
"magpie_via": catalog.ViaHere(m.Via)})
}
}
return out
}
// viaOf is the magpies e's model passes through after this one, as the
// remote magpie serving it listed them; nil for a provider's own model.
// A routing group's are its members' together: a group with a remote
// magpie's group in it (two magpies each the other's remote, each with an
// auto/ group of the model) reaches every magpie that one does (catalog's
// magpie_via.go).
func viaOf(e provider.Entry) []string {
if e.Group == "" {
return e.Provider.RemoteVia(e.Model)
}
_, ms, _ := provider.FindGroup(e.ID)
var via []string
for _, m := range ms {
for _, v := range m.Provider.RemoteVia(m.Model) {
if !slices.Contains(via, v) {
via = append(via, v)
}
}
}
return via
}
// catalogFor is the catalog as the agent asking is shown it.
func catalogFor(r *http.Request) []provider.Entry {
shown, _ := provider.CatalogFor(agentOf(r))
@@ -1567,6 +1591,10 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) {
if how := webSearchOf(e, searches); how != "" {
m["web_search"] = how
}
// the magpies it goes through, this one last, so a
// magpie that is this one's remote too doesn't take
// back its own models (catalog's magpie_via.go)
m["magpie_via"] = catalog.ViaHere(viaOf(e))
}
if ts := tiers[e.ID]; len(ts) > 0 {
m["service_tiers"] = ts
@@ -1610,6 +1638,7 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) {
m := modelObject(e)
m["kind"], m["magpie_label"] = "decision", labels[i]
m["native_endpoints"] = []string{"/v1/systemone"}
m["magpie_via"] = catalog.ViaHere(viaOf(e))
data = append(data, m)
}
}
+101
View File
@@ -0,0 +1,101 @@
package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// Two magpies each the other's remote (cdredfox on Discord, 100-200% CPU
// until the remote was off) listed each other's models back, one level
// more on every 10-minute fetch, without end: rem/back/own/m1, then
// rem/back/rem/back/own/m1, each another member of the found auto/ group
// and another trip round the two, masked again on each. The list magpie
// gives another magpie now says which magpies each model passes, this one
// last, a routing group the magpies its members pass, and a model of a
// remote that went out of here comes back no more.
func TestRemoteMagpieListLoopsNoMore(t *testing.T) {
self := catalog.Self()
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `{"object":"list","data":[]}`)
}))
t.Cleanup(up.Close)
// the other magpie: what it serves of its own, and this magpie's own
// m1, which it has through this one as its remote
peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"object":"list","data":[
{"id":"up/m1","object":"model","magpie_via":["peer"]},
{"id":"back/own/m1","object":"model","magpie_via":["`+self+`","peer"]}]}`)
}))
t.Cleanup(peer.Close)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "own", Name: "Own", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("own", up.URL+"/v1", []catalog.Model{{ID: "m1"}}); err != nil {
t.Fatal(err)
}
id, err := provider.Add(provider.Provider{ID: "rem", Name: "Rem", Preset: provider.RemoteMagpiePreset, Chat: strings.TrimPrefix(peer.URL, "http://")})
if err != nil {
t.Fatal(err)
}
rem, _ := provider.Find(id)
ms, err := rem.Fetch(context.Background())
if err != nil {
t.Fatal(err)
}
var ids []string
for _, m := range ms {
ids = append(ids, m.ID)
}
if slices.Contains(ids, "back/own/m1") || !slices.Contains(ids, "up/m1") {
t.Fatalf("the remote's list taken = %v; want up/m1 and not this magpie's own model back", ids)
}
srv := httptest.NewServer(New().Handler())
t.Cleanup(srv.Close)
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/v1/models", nil)
req.Header.Set(provider.DrawersHeader, "1")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var list struct {
Data []struct {
ID string `json:"id"`
Via []string `json:"magpie_via"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&list); err != nil {
t.Fatal(err)
}
via := map[string][]string{}
for _, m := range list.Data {
via[m.ID] = m.Via
}
if v, ok := via["own/m1"]; !ok || !slices.Equal(v, []string{self}) {
t.Errorf("own/m1 is listed through %v, %v; want this magpie (%s) alone; list %v", v, ok, self, via)
}
if v, ok := via["rem/up/m1"]; !ok || !slices.Equal(v, []string{"peer", self}) {
t.Errorf("rem/up/m1 is listed through %v, %v; want [peer %s]; list %v", v, ok, self, via)
}
// the auto/ group of m1 here has the remote's m1 in it, so it reaches
// the other magpie too: listed back to it, it is left out there
if v, ok := via["auto/m1"]; !ok || !slices.Equal(v, []string{"peer", self}) {
t.Errorf("auto/m1 is listed through %v, %v; want [peer %s], its members' magpies and this one; list %v", v, ok, self, via)
}
if _, ok := via["rem/back/own/m1"]; ok {
t.Errorf("this magpie's own model came back through the remote: %v", via)
}
}
+15
View File
@@ -183,3 +183,18 @@ func (p Provider) RemotePriced(model string) bool {
_, ok := p.remotePrice(model)
return ok
}
// RemoteVia is the magpies a remote magpie's model passes through to its
// vendor, as its list said, that magpie last (catalog's magpie_via.go);
// nil for another provider's, or a list from a magpie from before.
func (p Provider) RemoteVia(model string) []string {
if !p.IsRemoteMagpie() {
return nil
}
for _, m := range p.liveByID(model) {
if len(m.Via) > 0 {
return m.Via
}
}
return nil
}