Files
magpie/internal/gateway/weighted_keys_test.go
T
yetone 3ec6b4da27 gateway, gui: a provider's keys can be routed by weight, a key weighing 3 taking three requests for every one a key weighing 1 takes (dengtongcai, #841) — Routing already spread requests over a provider's keys in order, in turn, least used first or by pace, but never in a set proportion: two team keys meant to split 75/25 could only go evenly or one after the other. Routing now has By weight (routing "weight") for a provider with keys: each key that's on shows its weight and its share beside it in the editor (Weight 3 · 75%), a click edits it in place and posts keys/weight (provider.SetKeyWeight, 1 to 1000; none or 0 counts as 1, kept out of the file), and providers.json takes it as "weight" on each of keys (keyWeight for the first). The gateway picks as NGINX's smooth weighted round robin does (weighted.go): 3, 1 and 4 go round in every 8 requests in that ratio, never bunched; the others follow in their order for failover. A key resting after a failure is left out of the round while it rests, the others taking its share by their weights, and goes last. A conversation still stays with its key as Stays says (cache-warm across turns by default, within a turn always), and a request kept so is counted against the key that took it, not the one the round picked, so new conversations make up the share; Stays Off gives the ratio request by request. The weight goes with its key through Make first, the editor's Save, backups and WebDAV sync. The Routing page offers By weight for key pools and explains a pick by it; sink (Goes to the back) is off for it as for In turn. zh, ja, de strings. TestWeightedKeys (3:1:4 exact in each of 50 rounds of 8 through perKey and route; with one resting the other two 75/25 and the resting one last; a kept request made up by the next picks) and TestSetKeyWeight fail on the old code (no Weighted); key-weight.test.cjs (WebKit, en and zh: By weight shows the weights and shares, a click sets one and the shares redraw, Smart hides them, no scroll) fails on the old code (no By weight). key-import, panel-routing, routing-save, rate-limited-sink, routing-reset-deadline, account-arrange, gui-ja, gui-de and click-scroll pass on WebKit. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass.
2026-10-05 08:50:57 +08:00

149 lines
4.5 KiB
Go

package gateway
import (
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// Weighted routing (#841): a provider's keys weighing 3 and 1 take three
// requests to one, held over every few requests rather than only on
// average, and a key resting is left out of the round, the others taking
// its share by their weights.
func TestWeightedKeys(t *testing.T) {
p := provider.Provider{ID: "wk", Chat: "https://wk.example/v1", Key: "ka", KeyName: "team-a", KeyWeight: 3,
Keys: []provider.KeyAccount{{Name: "team-b", Key: "kb"}, {Name: "team-c", Key: "kc", Weight: 4}, {Name: "spare", Key: "kd", Off: true, Weight: 9}},
Routing: provider.Weighted}
a, b, c := "wk#"+provider.KeyID("ka"), "wk#"+provider.KeyID("kb"), "wk#"+provider.KeyID("kc")
t.Cleanup(func() {
wrr.Lock()
delete(wrr.m, p.ID)
wrr.Unlock()
restingUntil.Lock()
delete(restingUntil.m, c)
restingUntil.Unlock()
})
pick := func() string {
cs := route(p, perKey(p, "m", provider.Chat), "m", provider.Chat)
if len(cs) != 3 {
t.Fatalf("%d candidates: %s", len(cs), restsOf(cs))
}
return cs[0].rest
}
// 3 : 1 : 4 over every round of 8, smoothly: never the same key more
// than twice running when another weighs as much
got := map[string]int{}
var seq []string
for range 8 * 50 {
k := pick()
got[k]++
seq = append(seq, k)
if len(seq)%8 == 0 {
round := map[string]int{}
for _, s := range seq[len(seq)-8:] {
round[s]++
}
if round[a] != 3 || round[b] != 1 || round[c] != 4 {
t.Fatalf("round %d: a %d b %d c %d, want 3 1 4", len(seq)/8, round[a], round[b], round[c])
}
}
}
if got[a] != 150 || got[b] != 50 || got[c] != 200 {
t.Fatalf("over 400: a %d b %d c %d", got[a], got[b], got[c])
}
if run := strings.Count(strings.Join(seq[:8], " "), c+" "+c+" "+c); run > 0 {
t.Fatalf("not smooth: %v", seq[:8])
}
// c resting: a and b share its requests 3 : 1, and c is tried last
restingUntil.Lock()
restingUntil.m[c] = time.Now().Add(time.Hour)
restingUntil.Unlock()
got = map[string]int{}
for range 4 * 25 {
cs := route(p, perKey(p, "m", provider.Chat), "m", provider.Chat)
cs, _ = restLast(cs, planned{order: make([]Weighed, len(cs))})
if cs[len(cs)-1].rest != c {
t.Fatalf("the resting key isn't last: %s", restsOf(cs))
}
got[cs[0].rest]++
}
if got[a] != 75 || got[b] != 25 || got[c] != 0 {
t.Fatalf("with c resting: a %d b %d c %d", got[a], got[b], got[c])
}
// a conversation kept on b counts against b: the next picks make it up
restingUntil.Lock()
delete(restingUntil.m, c)
restingUntil.Unlock()
wrr.Lock()
delete(wrr.m, p.ID)
wrr.Unlock()
got = map[string]int{}
for i := range 8 * 10 {
cs := route(p, perKey(p, "m", provider.Chat), "m", provider.Chat)
k := cs[0]
if i%8 == 0 { // every round, one request stays with b
for _, x := range cs {
if x.rest == b {
weightedKept(k, x)
k = x
}
}
}
got[k.rest]++
}
if got[a] != 30 || got[b] != 10 || got[c] != 40 {
t.Fatalf("with b kept: a %d b %d c %d", got[a], got[b], got[c])
}
}
// A key's weight is saved with it, the first key's too, and 1 is the
// default left out of the file.
func TestSetKeyWeight(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", home+"/.config")
if err := provider.Save(provider.Provider{ID: "wk", Name: "WK", Chat: "https://wk.example/v1", Key: "ka", Keys: []provider.KeyAccount{{Key: "kb"}}, Routing: provider.Weighted}); err != nil {
t.Fatal(err)
}
if err := provider.SetKeyWeight("wk", provider.KeyID("ka"), 3); err != nil {
t.Fatal(err)
}
if err := provider.SetKeyWeight("wk", provider.KeyID("kb"), 5); err != nil {
t.Fatal(err)
}
if err := provider.SetKeyWeight("wk", provider.KeyID("kb"), -1); err == nil {
t.Fatal("a weight below 0 was taken")
}
p, err := provider.Find("wk")
if err != nil {
t.Fatal(err)
}
if p.Routing != provider.Weighted {
t.Fatalf("routing %q", p.Routing)
}
ks := p.KeyList()
if ks[0].Weight != 3 || ks[1].Weight != 5 {
t.Fatalf("weights %d %d", ks[0].Weight, ks[1].Weight)
}
// the weight goes with its key when another goes first
if err := provider.UseKey("wk", provider.KeyID("kb")); err != nil {
t.Fatal(err)
}
p, _ = provider.Find("wk")
if p.KeyWeight != 5 || p.Keys[0].Weight != 3 {
t.Fatalf("after Make first: first %d, other %d", p.KeyWeight, p.Keys[0].Weight)
}
if err := provider.SetKeyWeight("wk", provider.KeyID("kb"), 1); err != nil {
t.Fatal(err)
}
p, _ = provider.Find("wk")
if p.KeyWeight != 0 {
t.Fatalf("1 kept as %d", p.KeyWeight)
}
}