Files
magpie/internal/gateway/affinity_fallback_test.go
T
yetone 2c89794acb gateway: a provider's fallback gives the conversation back once the provider is ready (01huadalang)
01huadalang on Discord (#feedback): once a provider's main model works
again, a conversation that went to its Fallback while it was down stayed
on the fallback, with no switch to stop it. affine treated the fallback
as any answerer: Auto kept it while its cache was worth reading (each
turn read it again, so it never went cold), Session for the session, and
a rotating provider's new turn went to the one after the fallback.

A provider's fallback is now its emergency path. When the last answerer
is a Fallback row and the provider's own model stands first in the plan,
ready (restLast put it ahead, so its rest is over), the next turn goes to
the provider (backToMain, Affinity.Why "main"), in every mode but Strict,
which the user set never to move a conversation. Within a turn the
conversation stays on the fallback until the user speaks again: the
turn's tool loop runs on reasoning the fallback sealed, which the
provider can't read, and the provider is sent the whole prompt afresh at
the next turn either way. A routing group's members are never Fallback
rows, so a group's own affinity is unchanged. No switch was added.

"Ready" is unchanged: a rest ends when restAfter set it to (a minute and
backing off for a plain failure; the vendor's reset or Retry-After for a
quota or rate limit; quotaRest 15 minutes when nothing names a time), or
earlier when renewed or a background probe lifts it.

docs/subsystems/gateway-routing.md says this beside Strict.

Run (mote, at this commit's tree on origin/main 3ce2a9819, rebased onto 774baed6d (a one-line Qoder mover min); the new tests and internal/provider run again there, then onto 13b4a29ab (Desktop tier calls in internal/gateway): go vet and TestFallback|TestAffinity|TestDesktop|the new tests ok there):
- TestFallbackGivesTheConversationBackOnceTheMainIsReady red on the old
  affinity.go: "next turn, main ready" and "..., session" answered from
  spare-key, want main. Green with the change. With !a.Within dropped by
  hand, "within the turn, main ready" goes red.
- TestGroupMemberKeepsTheConversationOnceAnotherIsBack green before and
  after (a group member stays by its cache once another is back).
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet of internal/gateway: ok.
- go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider:
  ok internal/gateway 551.7s, ok internal/provider 108.4s

Not tried: a real account. The fake upstreams answer as Anthropic does
(a 429, then cache_creation_input_tokens 3000).
2026-10-29 20:23:30 +08:00

153 lines
5.5 KiB
Go

package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// downThenUp is an Anthropic Messages upstream that refuses with a 429
// while down is set, and otherwise answers as cacheWriter does, writing
// the whole prompt to its cache.
type downThenUp struct {
cacheWriter
mu sync.Mutex
down bool
asked int
}
func (d *downThenUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
d.mu.Lock()
down := d.down
d.asked++
d.mu.Unlock()
if down {
io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
io.WriteString(w, `{"type":"error","error":{"type":"rate_limit_error","message":"rate limited"}}`)
return
}
d.cacheWriter.ServeHTTP(w, r)
}
// A provider's fallback is its emergency path: a conversation that went to
// it while the provider was down goes back to the provider at its next
// turn once the provider can serve again, however much the fallback
// cached (01huadalang on Discord: "主模型恢复后备用模型还在走缓存逻辑").
// Within a turn it stays on the fallback, whose sealed reasoning the turn
// runs on. A provider still resting keeps the conversation on the
// fallback, cached there.
func TestFallbackGivesTheConversationBackOnceTheMainIsReady(t *testing.T) {
const (
first = `{"model":"main/m","messages":[{"role":"user","content":"hi"}]}`
again = `{"model":"main/m","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"yo"},{"role":"user","content":"more"}]}`
tool = `{"model":"main/m","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"ls","arguments":"{}"}}]},{"role":"tool","tool_call_id":"c1","content":"a.go"}]}`
)
for _, c := range []struct {
name string
next string
mainBack bool
mode string
want string // who answers the next request
why string
}{
{"next turn, main ready", again, true, "", "main", "main"},
{"next turn, main ready, session", again, true, provider.AffinitySession, "main", "main"},
{"within the turn, main ready", tool, true, "", "spare", "turn"},
{"next turn, main still resting", again, false, "", "spare", "cache"},
} {
t.Run(c.name, func(t *testing.T) {
fresh(t)
main := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}, down: true}
spare := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}}
mu, su := httptest.NewServer(main), httptest.NewServer(spare)
t.Cleanup(mu.Close)
t.Cleanup(su.Close)
for _, p := range []provider.Provider{
{ID: "main", Name: "Main", Key: "main-key", Models: []string{"m"}, Anthropic: mu.URL + "/v1", Fallback: []string{"spare/s"}, Affinity: c.mode},
{ID: "spare", Name: "Spare", Key: "spare-key", Models: []string{"s"}, Anthropic: su.URL + "/v1"},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
s := New()
if code, body := postAs(t, s, "s1", first); code != 200 || !strings.Contains(body, "from spare-key") {
t.Fatalf("first turn %d %s, want the fallback's answer", code, body)
}
if c.mainBack {
// its rest over, as when the minute or the reset passes
main.mu.Lock()
main.down = false
main.mu.Unlock()
restingUntil.Lock()
for k := range restingUntil.m {
restingUntil.m[k] = time.Now().Add(-time.Second)
}
restingUntil.Unlock()
}
code, body := postAs(t, s, "s1", c.next)
if code != 200 || !strings.Contains(body, "from "+c.want+"-key") {
t.Fatalf("next request %d %s, want %s's answer", code, body, c.want)
}
a := s.trace.routes[len(s.trace.routes)-1].Affinity
if a == nil || a.Why != c.why {
t.Fatalf("affinity %+v, want why %q", a, c.why)
}
})
}
}
// A routing group keeps its own affinity: of two members, the one that
// answered while the other was down keeps the conversation, cached, once
// the other is back. Only a provider's fallback gives it back.
func TestGroupMemberKeepsTheConversationOnceAnotherIsBack(t *testing.T) {
fresh(t)
const (
first = `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`
again = `{"model":"group/g","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"yo"},{"role":"user","content":"more"}]}`
)
a := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}, down: true}
b := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}}
au, bu := httptest.NewServer(a), httptest.NewServer(b)
t.Cleanup(au.Close)
t.Cleanup(bu.Close)
for _, p := range []provider.Provider{
{ID: "pa", Name: "A", Key: "a-key", Models: []string{"m"}, Anthropic: au.URL + "/v1"},
{ID: "pb", Name: "B", Key: "b-key", Models: []string{"m"}, Anthropic: bu.URL + "/v1"},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: []string{"pa/m", "pb/m"}}); err != nil {
t.Fatal(err)
}
s := New()
if code, body := postAs(t, s, "s1", first); code != 200 || !strings.Contains(body, "from b-key") {
t.Fatalf("first turn %d %s, want b's answer", code, body)
}
a.mu.Lock()
a.down = false
a.mu.Unlock()
restingUntil.Lock()
for k := range restingUntil.m {
restingUntil.m[k] = time.Now().Add(-time.Second)
}
restingUntil.Unlock()
code, body := postAs(t, s, "s1", again)
if code != 200 || !strings.Contains(body, "from b-key") {
t.Fatalf("next turn %d %s, want b kept", code, body)
}
if aff := s.trace.routes[len(s.trace.routes)-1].Affinity; aff == nil || aff.Why != "cache" {
t.Fatalf("affinity %+v, want cache", aff)
}
}