remote magpie: a request that goes round magpies pointing at each other stops after 8, and a remote that is this magpie lists its models once
Followsc2c991a5b(cdredfox's two magpies each the other's remote). hanslin1666 (Discord) has the sibling: device B uses device A through a Remote magpie provider, and S3 sync carried that provider to A too, so A has a Remote magpie pointing at itself. Sync carries every provider (backup.Collect, provider.Mirror), a Remote magpie included. Two holesc2c991a5bleft: - A remote that is this magpie lists this magpie's own models through this one alone ([self]);c2c991a5bkept any via of only self, so rem/own/m1, rem/rem/own/m1, ... still grew a level a fetch until MaxVia. A via naming this magpie is now taken only when it is exactly [self]: the remote's own models, once (what the gateway's in-process remote tests need, and what hanslin1666 sees today). - Nothing stopped a request at request time: a list fetched from a magpie older than magpie_via, or one cached before the update, could still route round. Each request magpie passes to a Remote magpie now says how many magpies it went through (X-Magpie-Hops: the count it came with + 1, 1 for an agent's own); one that arrives having passed catalog.MaxVia (8) is answered 508 Loop Detected with what to turn off, before any vendor or remote is asked. The count is read only from a magpie's request (its User-Agent, which needs the key anyway), and taken off every request as it arrives, so no vendor is sent it. It goes on every path that already passes the caller on (passOnCaller: chat, decide, draw, embeddings, video). Run (mote, at this tree onc2c991a5b): - go test -timeout 45m ./internal/catalog ./internal/provider ./internal/gateway -count=1 on Linux (wsl-run, magpie-desktop): catalog ok, gateway ok (590s), provider red only in TestClaudeAccountServesModelsListedSinceItsFetch, #3174, which this doesn't touch. - go vet, GOOS=linux and GOOS=windows go vet of catalog and gateway (mote): ok. gofmt -l clean. - The full suite atc2c991a5b(mote, -timeout 45m ./...): 86 packages ok, internal/gui red only in TestMainWindowCorners (#3949). Broken by hand: - the via rule back to c2c991a5b's: TestFetchLeavesOutWhatCameFromHere red (rem/own/m2 through [self self] taken). - no hops set in passOnCaller and no check in withCaller: TestRemoteMagpieRequestLoopStops red (the remote told [ ] passes, 200 not 508 at 8, the vendor asked). Not tried: - hanslin1666's or cdredfox's own machines. - Paths to a remote that don't go through passOnCaller (the Codex socket and native passthrough) don't count hops; a loop through them is still cut by the lists. - Hiding a Remote magpie that is this magpie, or keeping it out of sync on the machine it names: not done here (a third machine that syncs may want it); it now costs one extra local pass per request to it, and its models show twice.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -20,10 +20,13 @@ import (
|
||||
// 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.
|
||||
// leaves here and comes back: it isn't taken. A Remote magpie that is
|
||||
// this magpie itself (sync brought one to the computer it names,
|
||||
// hanslin1666 on Discord; the gateway's tests serve their remote from
|
||||
// one process) has this magpie's own models, through this one alone,
|
||||
// once: a model that went that way twice or more (rem/rem/own/m1) isn't
|
||||
// taken either. 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
|
||||
@@ -44,8 +47,7 @@ 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 })
|
||||
return len(via) > 1 && slices.Contains(via, Self())
|
||||
}
|
||||
|
||||
// ViaHere is the magpie_via a model goes out with in this magpie's list
|
||||
|
||||
@@ -14,8 +14,9 @@ import (
|
||||
// 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.
|
||||
// it passes, and so is one through this magpie alone, once: a remote that
|
||||
// is this magpie itself (hanslin1666 on Discord) has its own models once,
|
||||
// not again one level deeper on each fetch.
|
||||
func TestFetchLeavesOutWhatCameFromHere(t *testing.T) {
|
||||
self := Self()
|
||||
long := make([]string, MaxVia+1)
|
||||
@@ -34,8 +35,9 @@ func TestFetchLeavesOutWhatCameFromHere(t *testing.T) {
|
||||
{"id":"up/m1","magpie_via":["peer"]},
|
||||
{"id":"back/own/m1","magpie_via":%s},
|
||||
{"id":"own/m2","magpie_via":%s},
|
||||
{"id":"rem/own/m2","magpie_via":%s},
|
||||
{"id":"far/m3","magpie_via":%s},
|
||||
{"id":"old/m4"}]}`, q([]string{self, "peer"}), q([]string{self}), q(long))
|
||||
{"id":"old/m4"}]}`, q([]string{self, "peer"}), q([]string{self}), q([]string{self, self}), q(long))
|
||||
}))
|
||||
defer srv.Close()
|
||||
ms, _, err := FetchAt(context.Background(), srv.URL+"/v1", "k", false, nil)
|
||||
@@ -49,6 +51,9 @@ func TestFetchLeavesOutWhatCameFromHere(t *testing.T) {
|
||||
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["rem/own/m2"]; ok {
|
||||
t.Errorf("a model through this magpie twice (a remote that is this magpie) was taken: %v", got)
|
||||
}
|
||||
if _, ok := got["far/m3"]; ok {
|
||||
t.Errorf("a model through more than %d magpies was taken: %v", MaxVia, got)
|
||||
}
|
||||
|
||||
@@ -5,10 +5,12 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
@@ -27,6 +29,13 @@ import (
|
||||
const (
|
||||
AgentHeader = "X-Magpie-Agent"
|
||||
ViaHeader = "X-Magpie-Via"
|
||||
// HopsHeader is how many magpies a request was passed on through
|
||||
// before it came here. Two magpies each the other's remote (cdredfox
|
||||
// on Discord), or one that is its own (a Remote magpie provider sync
|
||||
// brought to the computer it names, hanslin1666), could pass a request
|
||||
// round and round, masked again on each pass: one passed on through
|
||||
// catalog.MaxVia magpies is answered 508 Loop Detected instead.
|
||||
HopsHeader = "X-Magpie-Hops"
|
||||
)
|
||||
|
||||
// caller is who a request is recorded as: its agent, and the computer it
|
||||
@@ -47,6 +56,9 @@ type caller struct {
|
||||
// keepTurn: another magpie asked that its Responses turn be kept
|
||||
// though it says store false (KeepTurnHeader, remote_delta.go)
|
||||
keepTurn bool
|
||||
// hops: the magpies the request was passed on through before this
|
||||
// one (HopsHeader)
|
||||
hops int
|
||||
}
|
||||
|
||||
type callerCtx struct{}
|
||||
@@ -55,7 +67,12 @@ type callerCtx struct{}
|
||||
// headers that said so off it.
|
||||
func withCaller(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := context.WithValue(r.Context(), callerCtx{}, callerFrom(r))
|
||||
c := callerFrom(r)
|
||||
if c.hops >= catalog.MaxVia {
|
||||
writeError(w, protoOfPath(r.URL.Path), http.StatusLoopDetected, "this request went round magpies that are each other's Remote magpie "+strconv.Itoa(c.hops)+" times: on one of them, turn off or remove the Remote magpie provider that points back")
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), callerCtx{}, c)
|
||||
if searchingFrom(r) {
|
||||
// another magpie's search: only the model itself searches
|
||||
ctx = context.WithValue(ctx, searchingKey{}, true)
|
||||
@@ -64,6 +81,7 @@ func withCaller(next http.Handler) http.Handler {
|
||||
r.Header.Del(ViaHeader)
|
||||
r.Header.Del(SearchingHeader)
|
||||
r.Header.Del(KeepTurnHeader)
|
||||
r.Header.Del(HopsHeader)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
@@ -87,6 +105,9 @@ func callerFrom(r *http.Request) caller {
|
||||
}
|
||||
c.keepTurn = keepTurnAsks(r)
|
||||
if magpieAsks(r) {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(r.Header.Get(HopsHeader))); err == nil && n > 0 {
|
||||
c.hops = min(n, 1<<20)
|
||||
}
|
||||
if a := label(r.Header.Get(AgentHeader)); a != "" {
|
||||
c.agent = usage.AgentOf(a)
|
||||
c.via = label(r.Header.Get(ViaHeader))
|
||||
@@ -141,6 +162,7 @@ func passOnCaller(ctx context.Context, req *http.Request) {
|
||||
req.Header.Set(KeepTurnHeader, magpieUA())
|
||||
}
|
||||
c, ok := ctx.Value(callerCtx{}).(caller)
|
||||
req.Header.Set(HopsHeader, strconv.Itoa(c.hops+1))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -99,3 +100,85 @@ func TestRemoteMagpieListLoopsNoMore(t *testing.T) {
|
||||
t.Errorf("this magpie's own model came back through the remote: %v", via)
|
||||
}
|
||||
}
|
||||
|
||||
// A request that went round magpies each the other's remote (or one that
|
||||
// is its own) is stopped once it has passed catalog.MaxVia of them, even
|
||||
// where their lists came from magpies too old to say: each magpie tells
|
||||
// the next how many it passed through (HopsHeader), and no vendor is
|
||||
// asked.
|
||||
func TestRemoteMagpieRequestLoopStops(t *testing.T) {
|
||||
var vendor int
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
vendor++
|
||||
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"}}]}`)
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
var hops []string
|
||||
peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.Method == http.MethodGet {
|
||||
io.WriteString(w, `{"object":"list","data":[{"id":"up/m1","object":"model"}]}`)
|
||||
return
|
||||
}
|
||||
hops = append(hops, r.Header.Get(HopsHeader))
|
||||
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"}}]}`)
|
||||
}))
|
||||
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)
|
||||
if _, err := rem.Fetch(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(New().Handler())
|
||||
t.Cleanup(srv.Close)
|
||||
ask := func(model, ua, hop string) int {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/v1/chat/completions", strings.NewReader(`{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", ua)
|
||||
if hop != "" {
|
||||
req.Header.Set(HopsHeader, hop)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
// an agent's request goes on as the first pass, another magpie's as
|
||||
// one more than it came with
|
||||
if code := ask("rem/up/m1", "curl/8", ""); code != http.StatusOK {
|
||||
t.Fatalf("an agent's request to the remote: %d", code)
|
||||
}
|
||||
if code := ask("rem/up/m1", "magpie/test", "3"); code != http.StatusOK {
|
||||
t.Fatalf("another magpie's request to the remote: %d", code)
|
||||
}
|
||||
if !slices.Equal(hops, []string{"1", "4"}) {
|
||||
t.Errorf("the remote was told %v passes; want [1 4]", hops)
|
||||
}
|
||||
// one that has gone round as many as a list may name is stopped here
|
||||
before := vendor
|
||||
if code := ask("own/m1", "magpie/test", strconv.Itoa(catalog.MaxVia)); code != http.StatusLoopDetected {
|
||||
t.Errorf("a request passed on through %d magpies: %d, want 508", catalog.MaxVia, code)
|
||||
}
|
||||
if vendor != before {
|
||||
t.Errorf("the vendor was asked a request that went round in a loop")
|
||||
}
|
||||
// only a magpie's count is read: an agent can't stop its own request
|
||||
if code := ask("own/m1", "curl/8", "99"); code != http.StatusOK {
|
||||
t.Errorf("an agent's request with a hops header of its own: %d, want 200", code)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user