小八 on Discord (2026-10-23): a WorkBuddy plugin account answered magpie's
own 504 "no first token in 30s" 58 times on kimi-k3-1 and glm-5.3 (the
vendor's per-model token limit, which it never names, it just stalls).
The group went on each time, then asked the same account first on the
next request: 15 slow starts in 17 minutes in one session.
Cause: gateway.go's hw.slow branch (the group's FirstToken let a member
go) never rested anything, by design ("a long prompt being slow to start
anywhere"), and nothing counted slow starts. So every request waited out
the whole FirstToken on the stalled member before falling back.
Now restSlow (routing.go) counts slow starts per restID (provider,
account or key, model). Once rests nothing, as before. The second in a
row, within slowForget (30m) of the last, rests that model on that
account: 1 minute, doubling each time after, capped by the provider's
RestCapOr(longestRetry), never for a provider whose rest cap is off. An
answer clears the count (servedCandidate). A client-cancelled request
never reaches the slow branch, so it counts nothing. A longer rest
already there is kept. The rest carries Rest.Model, so the Routing page
shows it on that model's rows only. The Routing story of a rested slow
try says so, and the group editor's slow-to-start hint no longer says
"It doesn't rest" (en, zh, zh-TW, ja, de).
Tests: TestSlowStartsRestTheModelOnItsAccount (once: no rest; an answer
in between restarts the count; twice: the model rests on k1 with Key
a#k1/m, Model m, under a minute; k1's whole key and k2/m don't rest; the
next request asks k2/m first; a/n still goes to k1; a third slow start
backs off longer; an answer ends it). TestCanceledSlowStartRestsNothing
(three client cancels during the first-token wait: no rest, no count).
routing-went-on.test.cjs gains a rested slow try in five languages;
group-first-token.test.cjs's i18n list has the new strings.
Broken by hand: restSlow's result ignored in gateway.go -> the first test
red at "twice in a row" (Rest nil); servedCandidate not clearing
routed.slow -> red at "an answer in between starts the count again";
restSlow called in the cancel branch -> the cancel test red at "cancel
2: k1/m wasn't asked (rested?)". All restored, green.
Run at the worktree on base 7aad6a50e: gofmt -l clean; go vet darwin,
GOOS=linux -tags nogui, GOOS=windows: ok. The two new tests -race
-count=3: ok. TestGroupFirstTokenFailsOver, TestNestedGroupFirstToken:
ok. GUI: the 125 routing-*, group-* and i18n-* files, Chromium and
WebKit: 1428 of 1429; the one red, routing-rule-remove de (menu focus
after ArrowUp, the #3094 symptom), passed 20 of 20 alone. Full suite:
set -o pipefail; go test -tags nogui -timeout 45m ./... : 69 packages ok, none failed (gateway 544s, agent 430s, provider 234s).
Not tried: a real WorkBuddy account stalling on its token limit; the
fixture stalls by holding its stream after the role chunk.
Rebased on origin/main ecd983500 (no gateway or routing plugin change in between) and run again there: gofmt, the three go vets, internal/gui (budgets) ok, the four first-token gateway tests ok, i18n-keys, routing-went-on and group-first-token in both engines 43 of 43.
184 lines
5.7 KiB
Go
184 lines
5.7 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// keyedSlow is slow to start on one key's one model while slow is set,
|
|
// and answers at once otherwise. It says who it was asked as, key/model.
|
|
type keyedSlow struct {
|
|
key, model string
|
|
slow atomic.Bool
|
|
arrived chan struct{} // told of each slow request, when set
|
|
mu sync.Mutex
|
|
asked []string
|
|
}
|
|
|
|
func (k *keyedSlow) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
body, _ := io.ReadAll(r.Body)
|
|
key, model := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "), modelOf(body)
|
|
k.mu.Lock()
|
|
k.asked = append(k.asked, key+"/"+model)
|
|
k.mu.Unlock()
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.WriteHeader(200)
|
|
if key == k.key && model == k.model && k.slow.Load() {
|
|
io.WriteString(w, `data: {"id":"s","choices":[{"index":0,"delta":{"role":"assistant"}}]}`+"\n\n")
|
|
w.(http.Flusher).Flush()
|
|
if k.arrived != nil {
|
|
k.arrived <- struct{}{}
|
|
}
|
|
<-r.Context().Done()
|
|
return
|
|
}
|
|
io.WriteString(w, chatStreamOK)
|
|
}
|
|
|
|
func (k *keyedSlow) first() string {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
if len(k.asked) == 0 {
|
|
return ""
|
|
}
|
|
return k.asked[0]
|
|
}
|
|
|
|
func (k *keyedSlow) reset() {
|
|
k.mu.Lock()
|
|
k.asked = nil
|
|
k.mu.Unlock()
|
|
}
|
|
|
|
// A model that keeps failing to start on one account rests there (小八 on
|
|
// Discord: a WorkBuddy account's kimi-k3-1 stalled 58 times, past the
|
|
// group's first-token time, and magpie asked it first again each time, 15
|
|
// times in 17 minutes). Once nobody rests; twice in a row, that model on
|
|
// that account rests, and a success in between starts the count again.
|
|
// The same model on another key and another model on the same key are
|
|
// asked as before.
|
|
func TestSlowStartsRestTheModelOnItsAccount(t *testing.T) {
|
|
fresh(t)
|
|
up := &keyedSlow{key: "k1", model: "m"}
|
|
up.slow.Store(true)
|
|
serveOn(t, "a", "k1", []string{"m", "n"}, up, "k2")
|
|
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m"}, Routing: provider.Ordered, FirstToken: 1}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s := New()
|
|
k1m, k1, k2m := "a#"+provider.KeyID("k1")+"/m", "a#"+provider.KeyID("k1"), "a#"+provider.KeyID("k2")+"/m"
|
|
ask := func(model string) Try {
|
|
t.Helper()
|
|
up.reset()
|
|
code, body := postAs(t, s, "", `{"model":"`+model+`","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
|
if code != 200 || !strings.Contains(body, "from b") {
|
|
t.Fatalf("%s: %d %s", model, code, body)
|
|
}
|
|
r := s.trace.routes[len(s.trace.routes)-1]
|
|
return r.Tries[0]
|
|
}
|
|
|
|
if tr := ask("group/g"); up.first() != "k1/m" || tr.Fail != failSlow || tr.Rest != nil {
|
|
t.Fatalf("once: first %s, %+v", up.first(), tr)
|
|
}
|
|
up.slow.Store(false)
|
|
if tr := ask("group/g"); up.first() != "k1/m" || tr.Status != 200 {
|
|
t.Fatalf("answered: first %s, %+v", up.first(), tr)
|
|
}
|
|
up.slow.Store(true)
|
|
if tr := ask("group/g"); tr.Fail != failSlow || tr.Rest != nil {
|
|
t.Fatalf("an answer in between starts the count again: %+v", tr)
|
|
}
|
|
tr := ask("group/g")
|
|
if tr.Fail != failSlow || tr.Rest == nil || tr.Rest.Why != failSlow || tr.Rest.Model != "m" || tr.Rest.Key != k1m || tr.Rest.Failures != 2 {
|
|
t.Fatalf("twice in a row: %+v (rest %+v)", tr, tr.Rest)
|
|
}
|
|
if d := time.Until(tr.Rest.Until); d <= 0 || d > fallbackCooldown {
|
|
t.Fatalf("rests %s, want up to %s", d, fallbackCooldown)
|
|
}
|
|
if _, ok := restOf(k1); ok {
|
|
t.Fatal("the whole key rests")
|
|
}
|
|
if _, ok := restOf(k2m); ok {
|
|
t.Fatal("the model rests on the other key")
|
|
}
|
|
if ask("group/g"); up.first() != "k2/m" {
|
|
t.Fatalf("the resting model was asked first: %s", up.first())
|
|
}
|
|
if ask("a/n"); up.first() != "k1/n" {
|
|
t.Fatalf("another model on the key: first %s", up.first())
|
|
}
|
|
|
|
// a third slow start (asked again once its rest is over) rests longer
|
|
restingUntil.Lock()
|
|
restingUntil.m[k1m] = time.Now().Add(-time.Second)
|
|
restingUntil.Unlock()
|
|
tr = ask("group/g")
|
|
if tr.Rest == nil || tr.Rest.By != "backoff" || tr.Rest.Failures != 3 || time.Until(tr.Rest.Until) <= fallbackCooldown {
|
|
t.Fatalf("again: %+v (rest %+v)", tr, tr.Rest)
|
|
}
|
|
// and an answer ends it
|
|
restingUntil.Lock()
|
|
restingUntil.m[k1m] = time.Now().Add(-time.Second)
|
|
restingUntil.Unlock()
|
|
up.slow.Store(false)
|
|
ask("group/g")
|
|
up.slow.Store(true)
|
|
if tr := ask("group/g"); tr.Rest != nil {
|
|
t.Fatalf("after an answer: rest %+v", tr.Rest)
|
|
}
|
|
}
|
|
|
|
// A request its client gives up on while the model hasn't begun counts no
|
|
// slow start, however often.
|
|
func TestCanceledSlowStartRestsNothing(t *testing.T) {
|
|
fresh(t)
|
|
up := &keyedSlow{key: "k1", model: "m", arrived: make(chan struct{}, 1)}
|
|
up.slow.Store(true)
|
|
serveOn(t, "a", "k1", []string{"m"}, up, "k2")
|
|
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m"}, Routing: provider.Ordered, FirstToken: 60}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s := New()
|
|
for i := range 3 {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`)).WithContext(ctx)
|
|
s.Handler().ServeHTTP(httptest.NewRecorder(), req)
|
|
}()
|
|
select {
|
|
case <-up.arrived:
|
|
case <-done: // answered by another: the slow one wasn't asked
|
|
cancel()
|
|
t.Fatalf("cancel %d: k1/m wasn't asked (rested?)", i)
|
|
}
|
|
cancel()
|
|
<-done
|
|
up.mu.Lock()
|
|
asked := append([]string(nil), up.asked...)
|
|
up.mu.Unlock()
|
|
if len(asked) != i+1 {
|
|
t.Fatalf("cancel %d: asked %v", i, asked)
|
|
}
|
|
}
|
|
if _, ok := restOf("a#" + provider.KeyID("k1") + "/m"); ok {
|
|
t.Fatal("a canceled request rests the model")
|
|
}
|
|
routed.Lock()
|
|
defer routed.Unlock()
|
|
if len(routed.slow) != 0 {
|
|
t.Fatalf("counted: %v", routed.slow)
|
|
}
|
|
}
|