Files
magpie/internal/gateway/concurrency_test.go
T
yetone 987d72c133 providers: Max concurrent requests — over it, an agent's requests wait in line and go out in the order they came (Lemon on Discord: 希望 provider 或者插件能够支持一个参数类似 max_concurrency,如果超过上限,放到无界队列里面依序请求; Memo: ChatGPT/Codex subscriptions' risk control trips at about 5-6 requests at once) — the gateway sent every request to its provider the moment it came, so a few agents (or one agent's subagents) on one subscription could have any number out at the vendor at once, and nothing in magpie could hold them to what an account takes. A provider now has maxConcurrency (providers.json; nil or 0 is no limit, a negative one is saved as 0), and a signed-in agent's accounts keep theirs with their picks. The limit is per key or account, as the gateway already tells them apart (candidate.who(): provider#keyid, provider@user, else the provider), so a subscription pooling several accounts lets each one have that many out. Before a try is forwarded it takes a slot in that lane (internal/gateway/concurrency.go); with none free it waits in a FIFO queue with no bound, and is let in, first come first served, as one before it ends. The slot is held for the whole try (attempt reads the vendor's reply to its end or until the agent hangs up, and its body is closed when it returns) and given back once whatever happens (sync.Once), and a lane with nothing out and no one waiting is dropped. An agent that hangs up while waiting leaves the queue at once, is never sent and takes no slot (a slot granted in the same instant is handed on), and goes the way of any canceled request (499, nothing recorded). Waiting is not a failure: a request in line stays for its provider and is not moved on to a fallback or another group member, the account isn't rested, and the time it waited is told in its route's try (Try.Queued, ms). A plugin can say how many each of its accounts takes, as its own field: the auth hook's maxConcurrency, else package.json's magpie.maxConcurrency (a whole number over 0, at most 1000); the user's setting on the provider goes over it. GET /v1/magpie/concurrency (local or shared callers, as quotas) gives each lane's out, waiting and limit. The provider editor (keys, custom, signed-in accounts) has "Max concurrent requests" / 最大并发请求数 under Proxy, "超出时排队,按顺序发出;0 或留空为不限制" below it (with a plugin's own number as its placeholder), refuses anything but a whole number from 0 to 1000 before anything is posted, and an empty field saves none (the plugin's, if it has one); a save that doesn't send the field keeps what the provider had. No coloured left border, and a click in the field leaves the page where it is. TestMaxConcurrency (limit 2, five streams: never more than 2 at the vendor, 3 waiting, let in a..e in order; one canceled while waiting leaves the queue, takes no slot and never reaches the vendor; slots given back when each stream ends and when an agent hangs up mid-stream; the next one served at once) fails without the change (all five reach the vendor at once, no lane), as do TestLanesLimitLifted, TestProviderConcurrency and the updated TestPluginOwnIconAndKeyHint (the auth hook's 3, package.json's 5 when the hook's is 2.5); provider-concurrency.test.cjs (chromium and webkit, en and zh: typed and saved, 2.5 refused with nothing posted, empty saved as null, an account opening on its 5 and saving 0, a plugin's 4 as the placeholder, every string translated, no stripe, no scroll on click) passes. No vendor was asked. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... (under a temp HOME) and go test -race on the new tests pass. provider-proxy.test.cjs's account test fails the same on HEAD without the change (its editor redrawn under it).
2026-10-02 13:38:23 +08:00

271 lines
8.0 KiB
Go

package gateway
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// slowVendor streams a reply's first chunk at once and its end only when
// the test lets that request go (or its caller hangs up), counting how many
// it has out at once and the order they came in.
type slowVendor struct {
mu sync.Mutex
order []string
out int
most int
release map[string]chan struct{}
quit chan struct{} // closed when the test ends, so nothing is left waiting
}
func (v *slowVendor) gate(tag string) chan struct{} {
v.mu.Lock()
defer v.mu.Unlock()
if v.release[tag] == nil {
v.release[tag] = make(chan struct{})
}
return v.release[tag]
}
func (v *slowVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var req struct {
Messages []struct {
Content string `json:"content"`
} `json:"messages"`
}
json.Unmarshal(b, &req)
tag := req.Messages[0].Content
v.mu.Lock()
v.order = append(v.order, tag)
v.out++
v.most = max(v.most, v.out)
v.mu.Unlock()
defer func() {
v.mu.Lock()
v.out--
v.mu.Unlock()
}()
gate := v.gate(tag)
w.Header().Set("Content-Type", "text/event-stream")
chunk := func(s string) {
fmt.Fprintf(w, "data: {\"id\":\"x\",\"choices\":[{\"index\":0,\"delta\":{\"content\":%q}}]}\n\n", s)
w.(http.Flusher).Flush()
}
chunk("from " + tag)
select {
case <-gate:
case <-v.quit:
return
case <-r.Context().Done():
return
}
chunk(" done")
io.WriteString(w, "data: {\"id\":\"x\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")
}
func (v *slowVendor) seen() []string {
v.mu.Lock()
defer v.mu.Unlock()
return slices.Clone(v.order)
}
// within waits for cond, failing the test after a few seconds.
func within(t *testing.T, what string, cond func() bool) {
t.Helper()
for end := time.Now().Add(5 * time.Second); time.Now().Before(end); time.Sleep(5 * time.Millisecond) {
if cond() {
return
}
}
t.Fatalf("timed out waiting for %s", what)
}
// A provider's MaxConcurrency (Discord, Lemon) is how many requests are out
// at the vendor at once: with 2, five sent together never have more than
// two out, the rest go in the order they came as each one before them is
// read to its end, an agent that hangs up while waiting leaves the queue
// without taking a slot or reaching the vendor, and one that hangs up
// mid-stream gives its slot back.
func TestMaxConcurrency(t *testing.T) {
fresh(t)
v := &slowVendor{release: map[string]chan struct{}{}, quit: make(chan struct{})}
up := httptest.NewServer(v)
t.Cleanup(up.Close)
two := 2
if err := provider.Save(provider.Provider{ID: "slow", Name: "Slow", Key: "k", Models: []string{"m"}, Chat: up.URL + "/v1", MaxConcurrency: &two}); err != nil {
t.Fatal(err)
}
s := New()
gw := httptest.NewServer(s.Handler())
t.Cleanup(gw.Close)
t.Cleanup(func() { close(v.quit) }) // runs first: a failed test leaves no handler waiting
// a provider with a key has a lane per key
lane := func() Lane { return s.Lanes()["slow#"+provider.KeyID("k")] }
type reply struct {
tag, body string
err error
}
replies := make(chan reply, 10)
send := func(ctx context.Context, tag string) {
body := `{"model":"slow/m","stream":true,"messages":[{"role":"user","content":"` + tag + `"}]}`
go func() {
req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+"/v1/chat/completions", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
replies <- reply{tag: tag, err: err}
return
}
b, err := io.ReadAll(res.Body)
res.Body.Close()
replies <- reply{tag, string(b), err}
}()
}
// two out at once, three waiting in the order they came
tags := []string{"a", "b", "c", "d", "e"}
for i, tag := range tags {
send(context.Background(), tag)
if i < 2 {
within(t, tag+" at the vendor", func() bool { return len(v.seen()) == i+1 })
} else {
within(t, tag+" queued", func() bool { return lane().Waiting == i-1 })
}
}
if l := lane(); l.Busy != 2 || l.Waiting != 3 || l.Limit != 2 {
t.Fatalf("lane = %+v, want 2 out, 3 waiting", l)
}
// one more, gone while it waits: out of the queue, never sent, no slot
ctx, cancel := context.WithCancel(context.Background())
send(ctx, "gone")
within(t, "gone queued", func() bool { return lane().Waiting == 4 })
cancel()
within(t, "gone out of the queue", func() bool { return lane().Waiting == 3 })
if r := <-replies; r.tag != "gone" || r.err == nil {
t.Fatalf("the canceled request answered: %+v", r)
}
if l := lane(); l.Busy != 2 {
t.Fatalf("lane after a cancel in the queue = %+v, want 2 out", l)
}
// each one done lets the next in, first come first served
for i, tag := range tags {
close(v.gate(tag))
r := <-replies
if r.err != nil || r.tag != tag || !strings.Contains(r.body, "from "+tag) || !strings.Contains(r.body, "[DONE]") {
t.Fatalf("reply %d = %+v, want %s's whole stream", i, r, tag)
}
if next := i + 2; next < len(tags) {
within(t, tags[next]+" at the vendor", func() bool { return len(v.seen()) == next+1 })
}
}
if got := v.seen(); !slices.Equal(got, tags) {
t.Fatalf("vendor saw %v, want %v in order", got, tags)
}
if v.most != 2 {
t.Fatalf("most out at once = %d, want 2", v.most)
}
within(t, "every slot given back", func() bool { return len(s.Lanes()) == 0 })
// an agent hanging up mid-stream gives its slot back
ctx, cancel = context.WithCancel(context.Background())
body := `{"model":"slow/m","stream":true,"messages":[{"role":"user","content":"hangup"}]}`
req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+"/v1/chat/completions", strings.NewReader(body))
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
line, _ := bufio.NewReader(res.Body).ReadString('\n')
if !strings.Contains(line, "from hangup") {
t.Fatalf("first line = %q", line)
}
if l := lane(); l.Busy != 1 {
t.Fatalf("lane mid-stream = %+v, want 1 out", l)
}
cancel()
res.Body.Close()
within(t, "the hung-up slot given back", func() bool { return len(s.Lanes()) == 0 })
// and the next is served at once
send(context.Background(), "after")
within(t, "after at the vendor", func() bool { return slices.Contains(v.seen(), "after") })
close(v.gate("after"))
if r := <-replies; r.err != nil || !strings.Contains(r.body, "[DONE]") {
t.Fatalf("after = %+v", r)
}
}
// A queued request's wait is told in its route's try, and a limit lifted
// lets whoever waits go at once.
func TestLanesLimitLifted(t *testing.T) {
var l lanes
r1, ok := l.acquire(context.Background(), "p", 1)
if !ok {
t.Fatal("first slot refused")
}
got := make(chan func(), 1)
go func() {
r, _ := l.acquire(context.Background(), "p", 1)
got <- r
}()
within(t, "second queued", func() bool {
l.mu.Lock()
defer l.mu.Unlock()
return l.m["p"] != nil && len(l.m["p"].queue) == 1
})
if _, ok := l.acquire(context.Background(), "p", 0); !ok {
t.Fatal("no limit refused")
}
select {
case r2 := <-got:
r2()
case <-time.After(2 * time.Second):
t.Fatal("lifting the limit left the queue waiting")
}
r1()
r1() // twice is once
l.mu.Lock()
defer l.mu.Unlock()
if len(l.m) != 0 {
t.Fatalf("lanes left: %+v", l.m["p"])
}
}
// Concurrency is the user's setting, else none; 0 set is none, and a
// negative one saved is 0.
func TestProviderConcurrency(t *testing.T) {
n := 3
if c := (provider.Provider{MaxConcurrency: &n}).Concurrency(); c != 3 {
t.Fatalf("Concurrency = %d, want 3", c)
}
if c := (provider.Provider{}).Concurrency(); c != 0 {
t.Fatalf("Concurrency unset = %d, want 0", c)
}
fresh(t)
neg := -4
if err := provider.Save(provider.Provider{ID: "neg", Name: "Neg", Key: "k", Chat: "https://example.invalid/v1", MaxConcurrency: &neg}); err != nil {
t.Fatal(err)
}
p, err := provider.Find("neg")
if err != nil {
t.Fatal(err)
}
if p.MaxConcurrency == nil || *p.MaxConcurrency != 0 {
t.Fatalf("saved %v, want 0", p.MaxConcurrency)
}
}