Files
magpie/internal/gateway/session_spread_test.go
T
yetone 06d36d4142 gateway: Stays: Session spreads new sessions over the accounts (connor_yang)
connor_yang on Discord: three sessions on one provider's three accounts,
Stays: Session (整个会话), ended up on two accounts. Under Smart routing a
conversation nobody had answered yet went wherever routing put first,
whatever other sessions were on; only In turn counted the sessions each
account holds (leastHeld, #946).

Kept for the whole session (Stays: Session or Strict) under a routing that
picks by what is left (Smart, Least used first, Weekly pace;
spreadsSessions), a new conversation now goes to the key, account or
group member the fewest other conversations of the last 30 minutes are on.
It passes over one routing keeps new conversations off (readyForNew:
resting, an aside key, a fallback while the provider's own model leads,
one used past lowShare), counts leads only, and keeps routing's order on a
tie. A Claude Code subagent's first request goes to its lead's account
(withLead), not to another as a session of its own. An answered
conversation is kept as before, and resting, spent and the rest/quota
fallback are unchanged. In order, By weight, Free first, Speed first,
Cheapest, Manual and plugin routings keep their order. Docs: reference,
gateway-routing, site start.html (en, zh, ja).

Run (mote, at this head on 2604d68db): go test ./internal/gateway -run
'TestWholeSession|TestInOrderKeepsNew|TestSpreadsSessionsOnly|
TestRotateSpreads|Affinity|Strict|Subagent|Lone|LoginSwitch|ChatGPT' ok;
GOOS=linux and GOOS=windows go vet ./internal/gateway ok; gofmt clean.
The full Go suite (-timeout 45m) was started at this head after the push.

Broken by hand: spreadsSessions always false (the old code's behaviour):
TestWholeSessionSpreadsNewSessions red, "s2 went to k1, which s1 is on"
for session and strict. Subagent sent through leastHeld instead of
withLead: red, "s2's subagent went to k1, not s2's k2". readyForNew
without the fallback and lowShare checks: TestWholeSessionSpreadLeaves
TheNearlyUsedAndFallbacks red.

Not tried: real subscription accounts (the tests use three API keys on one
provider, the same candidate path); a group of different providers end to
end (leastHeld's group path is the one In turn has used); the reporter's
exact provider and agent; sessions idle more than 30 minutes no longer
count as holding their account.
2026-10-31 01:05:44 +08:00

175 lines
6.1 KiB
Go

package gateway
import (
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/routes"
)
// connor_yang on Discord: three sessions on a provider with three accounts,
// Stays: Session, Smart routing, ended up on two accounts. A conversation
// nobody has answered yet went where routing put it first, whatever other
// sessions were on, so two sessions shared one account while another sat
// unused. Kept for the whole session, a new session now goes to the one the
// fewest others are on (spreadsSessions, leastHeld), and each then stays
// where it began; its subagents go with it (withLead).
func TestWholeSessionSpreadsNewSessions(t *testing.T) {
for _, mode := range []string{provider.AffinitySession, provider.AffinityStrict} {
t.Run(mode, func(t *testing.T) {
fresh(t)
up := &keyed{}
serveOn(t, "sp", "k1", []string{"m1"}, up, "k2", "k3")
if err := provider.SetAffinity("sp", mode); err != nil {
t.Fatal(err)
}
routes.Forget("sp")
s := New()
post := func(session, sub, msgs string) string {
t.Helper()
n := len(up.tried)
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"sp/m1","messages":[`+msgs+`]}`))
req.Header.Set("x-session-id", session)
if sub != "" {
req.Header.Set("x-claude-code-agent-id", sub)
}
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 || len(up.tried) != n+1 {
t.Fatalf("%s: %d %s, tried %v", session, rec.Code, rec.Body.String(), up.tried[n:])
}
return up.tried[n]
}
on := map[string]string{}
seen := map[string]string{}
for _, ses := range []string{"s1", "s2", "s3"} {
k := post(ses, "", `{"role":"user","content":"start `+ses+`"}`)
if other, ok := seen[k]; ok {
t.Errorf("%s went to %s, which %s is on; a third account had none (%v)", ses, k, other, on)
}
seen[k], on[ses] = ses, k
}
// each stays where it began, turn after turn, as before
for _, ses := range []string{"s1", "s2", "s3"} {
msgs := `{"role":"user","content":"start ` + ses + `"},{"role":"assistant","content":"ok"},{"role":"user","content":"more"}`
if k := post(ses, "", msgs); k != on[ses] {
t.Errorf("%s's next turn went to %s, not %s where it began", ses, k, on[ses])
}
}
// a subagent of s2 goes with s2, not to the account fewest are on
if k := post("s2", "sub-1", `{"role":"user","content":"a subagent's task"}`); k != on["s2"] {
t.Errorf("s2's subagent went to %s, not s2's %s", k, on["s2"])
}
// a fourth session goes to one of the three, each holding one
post("s4", "", `{"role":"user","content":"start s4"}`)
})
}
}
// In order is the user's own order: every new session goes to the first
// account until it is used up or fails, Stays: Session or not.
func TestInOrderKeepsNewSessionsOnTheFirst(t *testing.T) {
fresh(t)
up := &keyed{}
serveOn(t, "so", "k1", []string{"m1"}, up, "k2", "k3")
if err := provider.SetAffinity("so", provider.AffinitySession); err != nil {
t.Fatal(err)
}
if err := provider.SetRouting("so", provider.Ordered); err != nil {
t.Fatal(err)
}
routes.Forget("so")
s := New()
for _, ses := range []string{"s1", "s2", "s3"} {
if code, out := postAs(t, s, ses, `{"model":"so/m1","messages":[{"role":"user","content":"start `+ses+`"}]}`); code != 200 {
t.Fatalf("%d %s", code, out)
}
}
for _, k := range up.tried {
if k != "k1" {
t.Fatalf("In order sent a new session to %s: %v", k, up.tried)
}
}
}
func TestSpreadsSessionsOnlyWhenKeptAndRoutedByWhatIsLeft(t *testing.T) {
for _, c := range []struct {
mode, routing string
want bool
}{
{provider.AffinitySession, "", true},
{provider.AffinityStrict, "", true},
{provider.AffinitySession, provider.LeastUsed, true},
{provider.AffinitySession, provider.Pace, true},
{"", "", false},
{provider.AffinityTurn, "", false},
{provider.AffinityOff, "", false},
{provider.AffinitySession, provider.Ordered, false},
{provider.AffinitySession, provider.Weighted, false},
{provider.AffinitySession, provider.FreeFirst, false},
{provider.AffinitySession, provider.Cheapest, false},
{provider.AffinitySession, provider.Rotate, false}, // spreads on its own
} {
if got := spreadsSessions(c.mode, c.routing); got != c.want {
t.Errorf("spreadsSessions(%q, %q) = %v, want %v", c.mode, c.routing, got, c.want)
}
}
}
// Spreading a whole session's new conversations never puts one on an
// account Smart keeps new conversations off — used past lowShare — nor on a
// provider's fallback while the provider's own model leads: those stay
// behind, and with every other account holding as many sessions, routing's
// first takes it.
func TestWholeSessionSpreadLeavesTheNearlyUsedAndFallbacks(t *testing.T) {
fresh(t)
key := func(k string) candidate {
p := provider.Provider{ID: "sx", Key: k}
return candidate{p: p, model: "m1", rest: "sx#" + k}
}
for _, c := range []struct {
name string
last Weighed
}{
{"used past lowShare", Weighed{Known: true, Used: lowShare + 5}},
{"a fallback", Weighed{Fallback: true}},
} {
t.Run(c.name, func(t *testing.T) {
scope := "sx/m1:" + c.name
cs := []candidate{key("k1"), key("k2"), key("k3")}
sticks.Lock()
for i, ses := range []string{"a", "b"} {
sticks.m[scope+"|"+ses] = stick{rest: cs[i].rest, who: cs[i].who(), model: "m1", at: time.Now()}
}
sticks.Unlock()
t.Cleanup(func() {
sticks.Lock()
for k := range sticks.m {
if strings.HasPrefix(k, scope+"|") {
delete(sticks.m, k)
}
}
for k := range sticks.opening {
if strings.HasPrefix(k, scope+"|") {
delete(sticks.opening, k)
}
}
sticks.Unlock()
})
pl := planned{order: []Weighed{{}, {}, c.last}}
got, _ := leastHeld(scope, scope+"|c", cs, pl, true)
if got[0].who() != cs[0].who() {
t.Errorf("a new session went to %s, %s", got[0].who(), c.name)
}
// in turn spreads to it as it did
got, _ = leastHeld(scope, scope+"|d", cs, planned{order: []Weighed{{}, {}, c.last}}, false)
if got[0].who() != cs[2].who() {
t.Errorf("in turn, a new conversation went to %s, not the one none are on", got[0].who())
}
})
}
}