Files
magpie/internal/gateway/affinity_fallback_test.go
T
yetone 5bfa9f0762 gateway: a group's backup gives the conversation back once the member listed ahead of it is ready again (01huadalang on Discord)
01huadalang on Discord, after 76e4494db: Codex on several accounts in a
group with mimo2.6pro as the backup, Stays on Auto. Once Codex had quota
again, requests kept going to mimo.

The cause: when Codex couldn't answer, the turn fell over to mimo and the
session was stuck to mimo. On the next turns affine kept it there by
"cache", because only In order had a way back (backToFirst, Why "order").
A Smart group (and the other routings) never gave the conversation back to
the member ahead, however long Codex had been ready.

The fix: at the answer, the gateway records whether the member that
answered stood in for one listed ahead of it in the group: one that was
resting, or known all but used up (Used >= SpentShareOf). planGroup now
gives each candidate its member and its place in the group (placed), and
standsInFor reads the plan made before the tries. The flag is the stick's
stoodIn, inherited while the same who and model keep answering, and saved
in affinity.json (stoodIn). With Stays on Auto, a stick that stood in goes
back to the group's first member once that one is ready and not set aside
(backFromStandIn), with the new Why "back" and its Routing page line in
all five languages. A member put first on its merits (not a stand-in)
keeps its cache as before; Off, Session, Strict, Turn and In order keep
their own rules.

Not changed, by design: Smart and Least used count a key with unknown
usage (mimo) as unused, so with every Codex account at 90% or more of a
window a new session can go to mimo first. In order keeps a backup last;
the routing doc says so.

Tests (internal/gateway/group_stand_in_test.go, new):
- TestGroupBackupGivesTheConversationBack: smart auto with usage known
  and unknown go back ("back"); in order auto "order"; in turn and smart
  turn "new-turn"; smart off "off"; smart session, smart strict and in
  order session stay on mimo.
- TestGroupBackupStandingInWhileTheFirstIsBackAndBehind,
  TestGroupMemberPutFirstOnItsMeritsKeepsItsCache,
  TestGroupStandInStaysWithinATurn, TestGroupStandInSurvivesARestart.
- affinity_fallback_test's TestGroupMemberKeepsTheConversationOnceAnother
  IsBack pinned the old behaviour; it is now
  TestGroupMemberGivesTheConversationBackOnceTheOneAheadIsBack.
- routing-affinity-order.test.cjs gains the "back" line.

Run, all on mote:
- With the non-test changes stashed (old code): both smart auto cases,
  StandingInWhileTheFirstIsBackAndBehind, SurvivesARestart and
  GivesTheConversationBackOnceTheOneAheadIsBack are red. Green with the fix.
- Broken by hand, each red: the "back" case off (smart cases,
  StandingInWhileBehind); no inherit (StandingInWhileBehind); rest/spent
  check off (usage-known case, StandingInWhileBehind); stoodIn check
  dropped from the back case (PutFirstOnItsMerits); StoodIn not loaded
  (SurvivesARestart). A check of failed tries stayed green when turned
  off, since a failed try rests what failed, so it was removed.
- go test -tags nogui -count=1 -timeout 45m ./... at 80bcef18f + this:
  every package ok except internal/gui, whose two reds are red on
  origin/main d714c4216 too: TestSettingsSaveKeepsWhatItDoesNotSend
  (#4514) and TestColdTurnsTaken (#4510).
- Rebased on 5a56bc7d7: internal/gateway, internal/provider and
  internal/catalog ok; internal/gui has only the same two reds (#4514,
  #4510). Main then moved three provider-only commits; at the pushed
  parent f856d381a, internal/provider ok and internal/gateway -run
  'Group|Affinity|Fallback|Ordered|Strict|Rotating|Stick' ok.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/gateway ok.
- GUI (Chromium and WebKit): routing-affinity-order, routing-js,
  i18n-keys, gui-zh-tw and gui-de pass; gui-ja's one red is #4580
  (a7b47d57e's string, not this one).
- Every routing-*.test.cjs file on mote (2050 tests, both engines, five
  languages) at load 140 to 200 from other sessions' suites: 35 red in 10
  files, all timeouts or moves under load. The same 10 files run alone,
  serially, at this head and at origin/main 41b5c0f19 are red in the same
  tests (27 and 30, differing only in which language flaked). All filed:
  #4585, #3789, #3096, #3094, #3799, #3412, #1804, #4560, #3593, #4082,
  #4627, #4628, #3954, #4629.

Not tried: no real Codex or MiMo account; the case was reproduced with a
fake upstream only. A stick saved before this change has no stoodIn, so a
conversation already stuck to the backup stays there until it goes cold
(5 minutes idle) or a new session starts.
2026-11-01 05:59:05 +08:00

156 lines
5.8 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 member of a Smart group that answered while the one listed ahead of
// it was down stood in for it: once that one is back, the next turn goes
// to it, whatever the stand-in cached, as a provider's fallback gives it
// back (01huadalang on Discord, a Codex session kept on the group's MiMo
// backup by its cache). Before, the stand-in kept it for good. One put
// first on its merits keeps it (TestGroupMemberPutFirstOnItsMeritsKeepsItsCache).
func TestGroupMemberGivesTheConversationBackOnceTheOneAheadIsBack(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 a-key") {
t.Fatalf("next turn %d %s, want a's answer", code, body)
}
if aff := s.trace.routes[len(s.trace.routes)-1].Affinity; aff == nil || aff.Why != "back" {
t.Fatalf("affinity %+v, want back", aff)
}
}