Files
magpie/internal/gateway/affinity_fallback_paths_test.go
T
yetone 76e4494dbd gateway: In turn passes over a provider's fallback while the provider is ready (01huadalang)
01huadalang on Discord (#feedback, 10-31): once the main provider has
quota again, requests keep going to the fallback model, which is only
meant for emergencies.

Cause: a provider routed In turn treated its fallback rows as more of
its own keys. A new turn went to the row after the last answerer
(after), which past the provider's last key is the fallback, and a new
conversation went to the row the fewest conversations held (leastHeld),
which is the fallback nobody is on. Both happened while every key of the
provider was ready. The session spread already skipped fallbacks
(readyForNew); rotate's after and leastHeld(ready=false) did not.

Fix: standsIn(order, i) marks a fallback row when the plan's first row
is the provider's own. after, leastHeld and readyForNew all skip it, so
a fallback takes a new turn or conversation only when nothing ahead of
it can. Within one turn (tool results) a conversation still stays on
whoever answered, because of sealed reasoning.

Stays: Strict is the user's own choice and is not changed. A
conversation it keeps on the fallback stays there. The trace now names
the provider's ready first row (Affinity.Main), and the Routing page
says why: the provider is ready again, Strict never moves a
conversation, and new conversations go to the provider (en, zh, zh-TW,
ja, de).

Tests (internal/gateway/affinity_fallback_paths_test.go):
- TestRotatingProviderKeepsItsFallbackForEmergencies (1 and 2 keys)
- TestFallbackGivesBackAcrossRoutings: auto, in turn, in turn+session,
  least used+session, stays turn, and a group fallback with auto, in
  turn and session
- TestStrictKeepsTheFallbackAndSaysTheMainIsReady
On the old code, the rotate provider's new turn went to spare-key (Why
new-turn), and in turn+session's new conversation went to the fallback
(Why first). Broken by hand: with after's standsIn removed and Strict's
Main dropped, the rotate test, the in-turn cases and the Strict test go
red. session_spread_test's fallback case pinned the old In turn pick;
it now expects k2.
GUI: routing-affinity-order has a "strict" case.

Run (via mote-run unless noted):
- go test -tags nogui -count=1 -timeout 45m ./... at b08f35fcc (this
  change on 7428f3229): every package ok except two reds, both filed
  and the same on main: internal/gui TestSettingsSaveKeepsWhatItDoesNotSend
  (SearchAll, #4514) and internal/usage TestRequestChunksFromDisk
  (TempDir cleanup, #4390).
- Rebased onto 0fe9f97c1, at this head: go test ./internal/gateway -run
  'Affinity|Rotat|Fallback|Strict|Spread|Turn|Stick|Lead|Order': ok;
  go vet -tags nogui ./internal/gateway: ok
- go vet ./internal/gateway; GOOS=linux and GOOS=windows go vet -tags
  nogui ./internal/gateway ./internal/gui: ok
- gofmt -l: clean
- GUI in WSL (wsl-run), routing-affinity-order, routing-affinity-cache-
  write and i18n-keys in chromium and webkit: 43 of 44. The red is
  i18n-keys' "Unmarked", the same on main (#4524).

Not tried: a real account. This was reproduced with fake upstreams only.
2026-11-01 01:59:59 +08:00

189 lines
7.5 KiB
Go

package gateway
import (
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// chatTurns builds the Chat Completions body of a conversation's n-th user
// turn (n from 1), each earlier turn answered.
func chatTurns(model string, n int) string {
var b strings.Builder
b.WriteString(`{"model":"` + model + `","messages":[`)
for i := 1; i <= n; i++ {
if i > 1 {
b.WriteString(`{"role":"assistant","content":"yo"},`)
}
b.WriteString(`{"role":"user","content":"turn ` + itoa(i) + `"}`)
if i < n {
b.WriteString(",")
}
}
b.WriteString(`]}`)
return b.String()
}
// mainReady ends every rest, as when the minute or the reset passes, and
// has the upstream answer again.
func mainReady(d *downThenUp) {
d.mu.Lock()
d.down = false
d.mu.Unlock()
restingUntil.Lock()
for k := range restingUntil.m {
restingUntil.m[k] = time.Now().Add(-time.Second)
}
restingUntil.Unlock()
}
// A provider's fallback is for when none of the provider's own keys or
// accounts can take a request (01huadalang on Discord, again on 10-31:
// "主供应商有额度后请求还是一直走备用模型,备用只是应急"). A provider routed
// In turn went round its fallbacks as if they were more of its keys: a
// new turn went to the one after the last answerer (after), which past
// the provider's last key is its fallback, and a new conversation to the
// one the fewest conversations were on (leastHeld), which is the fallback
// nobody is on — while every key of the provider was ready.
func TestRotatingProviderKeepsItsFallbackForEmergencies(t *testing.T) {
for _, keys := range []int{1, 2} {
t.Run(itoa(keys)+" keys", func(t *testing.T) {
fresh(t)
main := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}}
spare := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}}
mu, su := httptest.NewServer(main), httptest.NewServer(spare)
t.Cleanup(mu.Close)
t.Cleanup(su.Close)
mp := provider.Provider{ID: "main", Name: "Main", Key: "main-key", Models: []string{"m"}, Anthropic: mu.URL + "/v1",
Fallback: []string{"spare/s"}, Routing: provider.Rotate}
if keys == 2 {
mp.Keys = []provider.KeyAccount{{Key: "main2-key"}}
}
for _, p := range []provider.Provider{mp,
{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()
for _, sess := range []string{"s1", "s2", "s3"} {
for n := 1; n <= 4; n++ {
code, body := postAs(t, s, sess, chatTurns("main/m", n))
if code != 200 || strings.Contains(body, "from spare-key") || !strings.Contains(body, "from main") {
a := s.trace.routes[len(s.trace.routes)-1].Affinity
t.Fatalf("%s turn %d: %d %s (affinity %+v), want a key of main's while main is ready", sess, n, code, body, a)
}
}
}
})
}
}
// The same with the provider down for one turn: the fallback answers it,
// and once the provider is ready the next turn and a new conversation go
// to the provider, in every routing and Stays but Strict.
func TestFallbackGivesBackAcrossRoutings(t *testing.T) {
for _, c := range []struct {
name, routing, mode string
group bool // the fallback is a routing group
}{
{"auto", "", "", false},
{"in turn", provider.Rotate, "", false},
{"in turn, session", provider.Rotate, provider.AffinitySession, false},
{"least used, session", provider.LeastUsed, provider.AffinitySession, false},
{"stays turn", "", provider.AffinityTurn, false},
{"group fallback", "", "", true},
{"group fallback, in turn", provider.Rotate, "", true},
{"group fallback, session", "", provider.AffinitySession, true},
} {
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)
fb := "spare/s"
if c.group {
if err := provider.SaveGroup(provider.Group{ID: "fb", Name: "FB", Members: []string{"spare/s", "spare2/s"}}); err != nil {
t.Fatal(err)
}
fb = provider.GroupPrefix + "fb"
}
for _, p := range []provider.Provider{
{ID: "main", Name: "Main", Key: "main-key", Keys: []provider.KeyAccount{{Key: "main2-key"}}, Models: []string{"m"}, Anthropic: mu.URL + "/v1",
Fallback: []string{fb}, Routing: c.routing, Affinity: c.mode},
{ID: "spare", Name: "Spare", Key: "spare-key", Models: []string{"s"}, Anthropic: su.URL + "/v1"},
{ID: "spare2", Name: "Spare2", Key: "spare2-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", chatTurns("main/m", 1)); code != 200 || !strings.Contains(body, "from spare") {
t.Fatalf("first turn %d %s, want the fallback's answer", code, body)
}
mainReady(main)
for n := 2; n <= 4; n++ {
code, body := postAs(t, s, "s1", chatTurns("main/m", n))
if code != 200 || !strings.Contains(body, "from main") {
a := s.trace.routes[len(s.trace.routes)-1].Affinity
t.Fatalf("turn %d %d %s (affinity %+v), want main's answer", n, code, body, a)
}
}
for _, sess := range []string{"s2", "s3", "s4"} {
code, body := postAs(t, s, sess, chatTurns("main/m", 1))
if code != 200 || !strings.Contains(body, "from main") {
a := s.trace.routes[len(s.trace.routes)-1].Affinity
t.Fatalf("new conversation %s: %d %s (affinity %+v), want main's answer", sess, code, body, a)
}
}
})
}
}
// Stays: Strict is the user's own: a conversation it keeps on the fallback
// stays there once the provider is ready again, and the trace names the
// provider's ready key (Affinity.Main) for the Routing page to say why.
// A new conversation goes to the provider.
func TestStrictKeepsTheFallbackAndSaysTheMainIsReady(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: provider.AffinityStrict},
{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", chatTurns("main/m", 1)); code != 200 || !strings.Contains(body, "from spare-key") {
t.Fatalf("first turn %d %s, want the fallback's answer", code, body)
}
mainReady(main)
code, body := postAs(t, s, "s1", chatTurns("main/m", 2))
if code != 200 || !strings.Contains(body, "from spare-key") {
t.Fatalf("next turn %d %s, want the fallback kept (Strict)", code, body)
}
a := s.trace.routes[len(s.trace.routes)-1].Affinity
if a == nil || a.Why != "strict" || a.Main == nil || a.Main.Provider != "main" {
t.Fatalf("affinity %+v, want strict naming main as ready", a)
}
if code, body := postAs(t, s, "s2", chatTurns("main/m", 1)); code != 200 || !strings.Contains(body, "from main-key") {
t.Fatalf("new conversation %d %s, want main's answer", code, body)
}
if a := s.trace.routes[len(s.trace.routes)-1].Affinity; a == nil || a.Main != nil {
t.Fatalf("new conversation's affinity %+v, want no main named", a)
}
}