Files
magpie/internal/gateway/first_token_test.go
T
yetone 6f64956f27 routing: a group can let a member go that hasn't begun answering after a set time and ask the next, and a request's detail splits its first token into magpie's time and the vendor's (Chen on X: answers through magpie felt slow, with no way to tell whether magpie or the vendor was the wait) — a group's editor has a Slow to start row (Wait, 30 s, 1 min, 2 min; Wait, the default, keeps today's behaviour). With a time set, a streamed request to a member that has sent no text, reasoning or tool call by then is cancelled before any of its bytes reach the agent (the held start is dropped; keepalives go on meanwhile) and the next member is asked; the try is marked slow ("slow to start", narrated in the route), and the member doesn't rest, since nothing is wrong with it. The last member left is always waited for. The card says "Next after 1 min without a first token". Each request now records when it went to the vendor (httptrace WroteRequest, sent_ms), and its detail shows In magpie and Vendor's first token beside First token; after a failover In magpie includes the time spent on the members let go. With the owner's real DeepSeek key in a sandbox, a group [a local member that sends its role chunk then stalls 60 s, deepseek-flash] with 3 s: the answer came from DeepSeek in 4.4 s, none of the stalled member's stream reached the client, its try read slow / "no first token in 3s" with no rest, and the ledger had ttft 3622, sent 3003. TestGroupFirstTokenFailsOver (failover, the last one waited for, one in time kept; passes -race) and group-first-token.test.cjs and usage-ledger-detail.test.cjs (WebKit, en and zh) fail on the old code. group-from-model-add's narrow-window case fails the same on origin/main; Chromium doesn't launch in this sandbox. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass (TestProvidersAnswerWhileListsComeIn flaked once, passes alone).
2026-10-04 19:33:55 +08:00

104 lines
3.7 KiB
Go

package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// slowStart streams the role chunk at once and its text only after wait,
// or never when the request goes first.
type slowStart struct {
wait time.Duration
n int
}
func (s *slowStart) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
s.n++
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(200)
io.WriteString(w, `data: {"id":"s","choices":[{"index":0,"delta":{"role":"assistant"}}]}`+"\n\n")
w.(http.Flusher).Flush()
select {
case <-r.Context().Done():
return
case <-time.After(s.wait):
}
io.WriteString(w, `data: {"id":"s","choices":[{"index":0,"delta":{"content":"slow answer"},"finish_reason":"stop"}]}`+"\n\n"+"data: [DONE]\n\n")
}
const chatStreamOK = `data: {"id":"b","choices":[{"index":0,"delta":{"role":"assistant","content":"from b"},"finish_reason":"stop"}]}` + "\n\n" + "data: [DONE]\n\n"
func slowOn(t *testing.T, id string, h http.Handler) {
t.Helper()
up := httptest.NewServer(h)
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: id, Name: strings.ToUpper(id), Key: "k", Models: []string{"m"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
}
// A member that hasn't begun its answer within the group's first-token
// time is let go before any of it reaches the agent, and the next one
// answers; the slow one doesn't rest. The last one is always waited for.
func TestGroupFirstTokenFailsOver(t *testing.T) {
fresh(t)
a := &slowStart{wait: 10 * time.Second}
b := &scripted{replies: []reply{{200, "text/event-stream", chatStreamOK}}}
slowOn(t, "a", a)
scriptedOn(t, "b", provider.Chat, b)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered, FirstToken: 1}); err != nil {
t.Fatal(err)
}
s := New()
began := time.Now()
code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
if took := time.Since(began); took > 5*time.Second {
t.Fatalf("took %s", took)
}
if code != 200 || !strings.Contains(body, "from b") || strings.Contains(body, "slow answer") || a.n != 1 || b.n != 1 {
t.Fatalf("%d %s (a %d, b %d)", code, body, a.n, b.n)
}
r := s.trace.routes[len(s.trace.routes)-1]
if len(r.Tries) != 2 || r.Tries[0].Fail != failSlow || r.Tries[0].Rest != nil || r.Tries[1].Status != 200 {
t.Fatalf("tries: %+v", r.Tries)
}
recs := usage.Load(time.Time{})
if len(recs) == 0 {
t.Fatal("no record")
}
last := recs[len(recs)-1]
if last.Sent <= 0 || last.TTFT <= 0 || last.Sent > last.TTFT {
t.Fatalf("sent %d, ttft %d", last.Sent, last.TTFT)
}
// the last one left is waited for
fresh(t)
a = &slowStart{wait: 2 * time.Second}
slowOn(t, "a", a)
provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m"}, Routing: provider.Ordered, FirstToken: 1})
s = New()
if code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`); code != 200 || !strings.Contains(body, "slow answer") {
t.Fatalf("last: %d %s", code, body)
}
// a member that answers in time is kept
fresh(t)
a = &slowStart{wait: 100 * time.Millisecond}
b = &scripted{replies: []reply{{200, "text/event-stream", chatStreamOK}}}
slowOn(t, "a", a)
scriptedOn(t, "b", provider.Chat, b)
provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered, FirstToken: 1})
s = New()
if code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`); code != 200 || !strings.Contains(body, "slow answer") || b.n != 0 {
t.Fatalf("in time: %d %s (b %d)", code, body, b.n)
}
}