Files
magpie/internal/gateway/concurrency_account_test.go
T
yetone 62ffc40169 gateway: a waiting request goes to an account back from rest (01huadalang)
01huadalang on Discord (11-01): three ZCode accounts, three requests at
once each. The first two got a 405 and rested, so every request went to
the third, and those over its three waited in its lane. Once the first two
were back, the waiting ones stayed on the third, behind its long turns,
until its requests were cut by hand. Same under Smart, In turn and Stays
off.

Cause: a request that queued in a lane (lanes.take) waited only for that
lane's turn. Nothing looked again when another lane gave a slot back or a
rest ended. With ZCode's maxAccounts 2, the third took a seat while the
first two rested and was a reserve again once they were back, but the
requests already waiting for it stayed. laneMate also gave way to a mate
resting, because ready() checks only lane and RPM room.

Change:
- lanes.take takes a move func. While waiting (lanes.await), it looks
  again when any lane gives a slot back, when a rest is lifted (Unrest,
  UnrestAll signal lanes.freed), when the soonest rest among the others
  ends, and at least every 5s (laneRecheck). waitMate finds the first
  candidate after it in the planned order (then those probeOne left out
  for resting) of the same provider, or any member of a group, that has
  a free slot with no queue (tryTake), minute room, isn't resting, didn't
  give way, and isn't a reserve as keepAtOnce stands now. The request
  then leaves its queue (errMoved) and serve runs that candidate with the
  slot already taken for it. A fallback provider is never one. Strict
  stays leave no other candidate, so nothing changes there.
- laneMate skips resting mates.
- docs/subsystems/gateway-routing.md Limits row says so.

Tests:
- TestWaitingRequestGoesToAccountBackFromRest: 3 keys, cap 3, MaxAccounts
  2, k1 and k2 resting (405), 9 requests. 3 go to k3, 6 wait for it, and
  none reach the resting two. Then the rests are lifted (Unrest) or run
  out (300ms), and the six go to k1 and k2 while k3's three are still
  out (9 at once). Run under Smart and Rotate, with Stays default and
  off.
- TestWaitingRequestTakesSlotGivenBackElsewhere: 2 keys, cap 1. A third
  request waiting for one key goes to the other when that one's request
  ends, under default, order, rotate and usage routing.
- TestFullMemberGivesWay updated. c, waiting for first, now goes to second
  once second's b ends. d (first's fallback is second) still waits for
  first.

Run on mote (mote-run), rebased on e65bc8473:
- go test -count=1 -timeout 45m ./internal/gateway: every test ok
  except TestCodexPoolSaysTheClientsVersion (608s; #4807, below)
- go vet ./internal/gateway, GOOS=linux (-tags nogui), GOOS=windows: ok
- gofmt -l: clean
- go test -race -count=10 on the three tests above: ok
- That red is #4807, also the only red in an earlier full run (it passes alone,
  here and on origin/main e65bc8473; another test's Codex version reaches
  it).

Rebased again on 6b3a6d42c (VS Code agent host, gateway.go): at this
head, vet for darwin, linux and windows ok, gofmt clean, and go test -run
'Lane|Waiting|FullMember|AtOnce|VSCode|Vscode|AgentHost|Concurrency|
Queue|Rest|Probe|Affinity' ./internal/gateway ok (44s).

Broken by hand:
- On origin/main's code, the new tests and the updated
  TestFullMemberGivesWay are red. The rest test fails at "six waiting for
  k3" because laneMate handed requests to the resting keys.
- With waitMate's move ignored (if ok && false), every case is red at
  "the waiting ones at k1 and k2", and so is TestWaitingRequestTakesSlot-
  GivenBackElsewhere.
- With the rest's end ignored for the recheck timer (only laneRecheck),
  the four "ran out" cases are red.
- Two test races were found under -race and fixed in the test: the rest
  was timed from before the nine were sent, and the concurrency count was
  read before the ninth reached the fake vendor.

Not tried: real ZCode accounts or the ZCode plugin. The plugin's own 405
handling and maxAccounts are as before. Not run on Windows or Linux
machines; vet only.
2026-11-02 04:17:24 +08:00

318 lines
12 KiB
Go

package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// laneRig is a gateway in front of slow vendors, and a way to send it
// requests that answer on a channel.
type laneRig struct {
t *testing.T
s *Server
gw *httptest.Server
replies chan laneReply
ctx context.Context // ended when the test ends: nothing is left waiting in a lane
}
type laneReply struct {
tag, body string
status int
header http.Header
err error
}
func newLaneRig(t *testing.T) *laneRig {
s := New()
gw := httptest.NewServer(s.Handler())
t.Cleanup(gw.Close)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel) // runs before gw.Close, which waits for every request
return &laneRig{t: t, s: s, gw: gw, replies: make(chan laneReply, 20), ctx: ctx}
}
func slowUp(t *testing.T) (*slowVendor, string) {
v := &slowVendor{release: map[string]chan struct{}{}, quit: make(chan struct{})}
up := httptest.NewServer(v)
t.Cleanup(up.Close)
t.Cleanup(func() { close(v.quit) }) // runs first: a failed test leaves no handler waiting
return v, up.URL
}
// send asks for model with a chat completions stream whose message is tag,
// or with Anthropic's Messages when path says so.
func (g *laneRig) send(ctx context.Context, path, model, tag string) {
body := `{"model":"` + model + `","stream":true,"messages":[{"role":"user","content":"` + tag + `"}]}`
if path == "/v1/messages" {
body = `{"model":"` + model + `","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"` + tag + `"}]}`
}
ctx, stop := context.WithCancel(ctx)
context.AfterFunc(g.ctx, stop)
go func() {
defer stop()
req, _ := http.NewRequestWithContext(ctx, "POST", g.gw.URL+path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
g.replies <- laneReply{tag: tag, err: err}
return
}
b, err := io.ReadAll(res.Body)
res.Body.Close()
g.replies <- laneReply{tag, string(b), res.StatusCode, res.Header, err}
}()
}
func (g *laneRig) reply() laneReply {
g.t.Helper()
select {
case r := <-g.replies:
return r
case <-time.After(5 * time.Second):
g.t.Fatal("no reply")
}
return laneReply{}
}
// An account's or key's own limit (#892) is over the provider's, and its
// count is one whatever asks for it: a request for the model and requests
// through two routing groups, each with the key in it, wait for the one
// slot the key has, never more out at the vendor than that.
func TestAccountLimitSharedAcrossGroups(t *testing.T) {
fresh(t)
v, up := slowUp(t)
five := 5
if err := provider.Save(provider.Provider{ID: "slow", Name: "Slow", Key: "k", Models: []string{"m"}, Chat: up + "/v1",
MaxConcurrency: &five, AccountConcurrency: map[string]int{provider.KeyID("k"): 1}}); err != nil {
t.Fatal(err)
}
for _, id := range []string{"one", "two"} {
if err := provider.SaveGroup(provider.Group{ID: id, Name: id, Members: []string{"slow/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
}
g := newLaneRig(t)
lane := func() Lane { return g.s.Lanes()["slow#"+provider.KeyID("k")] }
g.send(context.Background(), "/v1/chat/completions", "group/one", "a")
within(t, "a at the vendor", func() bool { return len(v.seen()) == 1 })
g.send(context.Background(), "/v1/chat/completions", "group/two", "b")
within(t, "b queued", func() bool { return lane().Waiting == 1 })
g.send(context.Background(), "/v1/chat/completions", "slow/m", "c")
within(t, "c queued", func() bool { return lane().Waiting == 2 })
if l := lane(); l.Busy != 1 || l.Limit != 1 {
t.Fatalf("lane = %+v, want 1 out of a limit of 1 (the key's own, not the provider's 5)", l)
}
for i, tag := range []string{"a", "b", "c"} {
close(v.gate(tag))
if r := g.reply(); r.err != nil || r.tag != tag || !strings.Contains(r.body, "[DONE]") {
t.Fatalf("reply %d = %+v, want %s whole", i, r, tag)
}
}
if v.most != 1 {
t.Fatalf("most out at once = %d, want 1", v.most)
}
within(t, "every slot given back", func() bool { return len(g.s.Lanes()) == 0 })
// set to none, the key takes no slot at all, the provider's 5 or not
if err := provider.SetAccountConcurrency("slow", provider.KeyID("k"), new(int)); err != nil {
t.Fatal(err)
}
p, _ := provider.Find("slow")
if n := p.LaneLimit(); n != 0 {
t.Fatalf("limit set to none = %d", n)
}
// and given the provider's again, it has 5
if err := provider.SetAccountConcurrency("slow", provider.KeyID("k"), nil); err != nil {
t.Fatal(err)
}
p, _ = provider.Find("slow")
if n := p.LaneLimit(); n != 5 {
t.Fatalf("limit given back to the provider's = %d, want 5", n)
}
}
// A provider's QueueLimit turns away one more than it holds at once, and
// QueueWait one that waited that long: each with a 429 in the API's own
// shape, Retry-After, the queue left as it was, and the vendor never asked.
func TestQueueFullAndWaitedOut(t *testing.T) {
fresh(t)
v, up := slowUp(t)
one := 1
if err := provider.Save(provider.Provider{ID: "slow", Name: "Slow", Key: "k", Models: []string{"m"}, Chat: up + "/v1", Anthropic: up,
MaxConcurrency: &one, QueueLimit: 1, QueueWait: 1}); err != nil {
t.Fatal(err)
}
g := newLaneRig(t)
lane := func() Lane { return g.s.Lanes()["slow#"+provider.KeyID("k")] }
g.send(context.Background(), "/v1/chat/completions", "slow/m", "a")
within(t, "a at the vendor", func() bool { return len(v.seen()) == 1 })
g.send(context.Background(), "/v1/chat/completions", "slow/m", "b")
within(t, "b queued", func() bool { return lane().Waiting == 1 })
// the queue full: c turned away at once, as OpenAI says a 429
began := time.Now()
g.send(context.Background(), "/v1/chat/completions", "slow/m", "c")
r := g.reply()
if r.tag != "c" || r.status != 429 || r.header.Get("Retry-After") == "" || time.Since(began) > 900*time.Millisecond {
t.Fatalf("c = %+v, want an immediate 429 with Retry-After", r)
}
var oe struct {
Error struct{ Message, Type string } `json:"error"`
}
if json.Unmarshal([]byte(r.body), &oe) != nil || !strings.Contains(oe.Error.Message, "queue is full") || oe.Error.Type == "" {
t.Fatalf("c's body = %s, want OpenAI's error saying the queue is full", r.body)
}
// in Anthropic's shape on its Messages
g.send(context.Background(), "/v1/messages", "slow/m", "d")
r = g.reply()
var ae struct {
Type string `json:"type"`
Error struct{ Type, Message string } `json:"error"`
}
if r.status != 429 || json.Unmarshal([]byte(r.body), &ae) != nil || ae.Type != "error" || ae.Error.Type != "rate_limit_error" || !strings.Contains(ae.Error.Message, "queue is full") {
t.Fatalf("d = %d %s, want Anthropic's rate_limit_error", r.status, r.body)
}
// b waits its second and is turned away, out of the queue
r = g.reply()
if r.tag != "b" || r.status != 429 || !strings.Contains(r.body, "waited") {
t.Fatalf("b = %+v, want a 429 for waiting too long", r)
}
if l := lane(); l.Busy != 1 || l.Waiting != 0 {
t.Fatalf("lane after b waited out = %+v, want a alone", l)
}
if got := v.seen(); !slices.Equal(got, []string{"a"}) {
t.Fatalf("vendor saw %v, want a alone", got)
}
close(v.gate("a"))
if r := g.reply(); r.tag != "a" || !strings.Contains(r.body, "[DONE]") {
t.Fatalf("a = %+v", r)
}
within(t, "every slot given back", func() bool { return len(g.s.Lanes()) == 0 })
}
// A slot is given back when the vendor fails the request, and the next
// one waiting is sent.
func TestLaneReleasedOnFailure(t *testing.T) {
fresh(t)
var mu sync.Mutex
calls := 0
gate := make(chan struct{})
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
calls++
n := calls
mu.Unlock()
if n == 1 {
<-gate
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
io.WriteString(w, `{"error":{"message":"bad request","type":"invalid_request_error"}}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "data: {\"id\":\"x\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")
}))
t.Cleanup(up.Close)
// runs before up.Close, which waits for a's held request: a check that
// fails before the gate opens below doesn't leave it held (#1808)
let := sync.OnceFunc(func() { close(gate) })
t.Cleanup(let)
one := 1
if err := provider.Save(provider.Provider{ID: "slow", Name: "Slow", Key: "k", Models: []string{"m"}, Chat: up.URL + "/v1", MaxConcurrency: &one}); err != nil {
t.Fatal(err)
}
g := newLaneRig(t)
lane := func() Lane { return g.s.Lanes()["slow#"+provider.KeyID("k")] }
g.send(context.Background(), "/v1/chat/completions", "slow/m", "a")
within(t, "a out", func() bool { return lane().Busy == 1 })
g.send(context.Background(), "/v1/chat/completions", "slow/m", "b")
within(t, "b queued", func() bool { return lane().Waiting == 1 })
let()
got := map[string]laneReply{}
for range 2 {
r := g.reply()
got[r.tag] = r
}
if got["a"].status != 400 || got["b"].status != 200 || !strings.Contains(got["b"].body, "ok") {
t.Fatalf("a = %+v, b = %+v: want a's failure, then b served", got["a"], got["b"])
}
within(t, "every slot given back", func() bool { return len(g.s.Lanes()) == 0 })
}
// A full member of a routing group gives way to one with a slot free (no
// waiting while another member has room), and a request of the group
// waiting for one goes to another once that one has room again (waitMate),
// while a provider's fallback is never asked for want of a slot: the
// request waits for its own.
func TestFullMemberGivesWay(t *testing.T) {
fresh(t)
v1, up1 := slowUp(t)
v2, up2 := slowUp(t)
one := 1
if err := provider.Save(provider.Provider{ID: "first", Name: "First", Key: "k1", Models: []string{"m"}, Chat: up1 + "/v1", MaxConcurrency: &one, Fallback: []string{"second/m"}}); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "second", Name: "Second", Key: "k2", Models: []string{"m"}, Chat: up2 + "/v1", MaxConcurrency: &one}); err != nil {
t.Fatal(err)
}
if err := provider.SaveGroup(provider.Group{ID: "pair", Name: "Pair", Members: []string{"first/m", "second/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
g := newLaneRig(t)
firstLane := func() Lane { return g.s.Lanes()["first#"+provider.KeyID("k1")] }
g.send(context.Background(), "/v1/chat/completions", "group/pair", "a")
within(t, "a at first", func() bool { return len(v1.seen()) == 1 })
// first is full: b goes to second at once
g.send(context.Background(), "/v1/chat/completions", "group/pair", "b")
within(t, "b at second", func() bool { return slices.Contains(v2.seen(), "b") })
if l := firstLane(); l.Waiting != 0 {
t.Fatalf("first's lane = %+v, want nobody waiting", l)
}
// both full: c waits for first, the group's first member
g.send(context.Background(), "/v1/chat/completions", "group/pair", "c")
within(t, "c queued at first", func() bool { return firstLane().Waiting == 1 })
// asked for first/m itself, d waits for first rather than going to its
// fallback
g.send(context.Background(), "/v1/chat/completions", "first/m", "d")
within(t, "d queued at first", func() bool { return firstLane().Waiting == 2 })
close(v2.gate("b"))
if r := g.reply(); r.tag != "b" || !strings.Contains(r.body, "from b") {
t.Fatalf("b = %+v", r)
}
// second has room again: c, waiting for first, goes there (waitMate);
// d, which second is only the fallback of, waits on for first
within(t, "c at second", func() bool { return slices.Contains(v2.seen(), "c") })
if l := firstLane(); l.Waiting != 1 {
t.Fatalf("first's lane = %+v, want d alone waiting", l)
}
if slices.Contains(v2.seen(), "d") {
t.Fatal("d went to first's fallback for want of a slot")
}
close(v2.gate("c"))
if r := g.reply(); r.tag != "c" || !strings.Contains(r.body, "[DONE]") {
t.Fatalf("c = %+v", r)
}
for _, tag := range []string{"a", "d"} {
close(v1.gate(tag))
if r := g.reply(); r.tag != tag || !strings.Contains(r.body, "[DONE]") {
t.Fatalf("%s = %+v", tag, r)
}
}
within(t, "every slot given back", func() bool { return len(g.s.Lanes()) == 0 })
}