Files
magpie/internal/gateway/plugin_stream_admit_test.go
T
yetone f8cd964aec plugin: a fetch past the host's 128 streams waits for one, not a local 502 (#3890)
The plugin host holds streamBudget/streamWindow = 128 streaming calls'
windows. begin(true) failed the 129th at once with errTooManyCalls, before
anything reached the plugin child, and the gateway counted it as a 502
try and sent the request again. The reporter's 192 concurrent MiniMax
streams through one plugin all came back 200, but over 298 local 502
tries that never reached MiniMax (65 requests retried).

Fetch now takes its window through beginStream: when all 128 are held
it waits for one to come free, outside h.mu (the transition that frees
one takes it), while its request's context lives, the host is up, and
for streamWait (1 minute) at most, past which it is errTooManyCalls as
before. RPCs keep their reserve and still never wait; begin(false) and
begin(true) are unchanged for their other callers.

Tests:
- TestHostFetchWaitsForAStreamWindow (internal/plugin): one window;
  a second fetch waits, runs once the first is released, gives up on
  a cancelled context and after streamWait, and leaves no window taken.
- TestPluginStreamsPastTheBudgetWait (internal/gateway, new file): 192
  concurrent streams through the real Bun plugin host to a local vendor
  that holds each open until 128 are live. Every request is 200 on one
  try, the vendor sees 192 requests and never more than 128 at once.

Run at this head (on ff7048dec):
- gofmt -l internal/plugin internal/gateway: clean
- go vet -tags nogui ./internal/plugin/ ./internal/gateway/ for GOOS
  linux, windows, darwin: ok
- go test -timeout 45m ./internal/plugin/: ok (99.0s, before the rebase
  over two usage/provider commits that don't touch plugin or gateway)
- go test -timeout 45m -run Plugin ./internal/gateway/: ok (52.0s, same)
- After the rebase: TestHostFetchWaitsForAStreamWindow,
  TestHostAdmission*, TestPluginStreamsPastTheBudgetWait: ok
- Broken by hand (beginStream returning errTooManyCalls at once, as
  begin did): TestHostFetchWaitsForAStreamWindow fails ("want it
  waiting"); TestPluginStreamsPastTheBudgetWait fails with 960 lines
  of "a try 502 too many plugin calls are in flight".
- Real account: a sandbox HOME with only the ZCode plugin and its
  account, this head's build on 127.0.0.1:3581, 8 concurrent streaming
  zcode/GLM-5.3-Flash requests: 8 of 8 200, each with its [DONE].

Not tried: 192 real concurrent streams against a vendor (the reporter's
MiniMax setup); the full gateway package (only its Plugin tests).
2026-10-28 00:58:50 +08:00

104 lines
3.1 KiB
Go

package gateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// #3890: 192 streams at once through one plugin. The plugin host holds 128
// streams' windows; the rest used to be refused locally at once ("too many
// plugin calls are in flight"), each refusal a 502 try the gateway sent
// again. Now they wait for a window: every request is answered on its
// first try, and the vendor sees each once.
func TestPluginStreamsPastTheBudgetWait(t *testing.T) {
const n = 192
var hits, live, most atomic.Int64
release := make(chan struct{})
pid := besideFake(t, "stream-admit", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
hits.Add(1)
now := live.Add(1)
defer live.Add(-1)
for m := most.Load(); now > m && !most.CompareAndSwap(m, now); m = most.Load() {
}
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(200)
w.(http.Flusher).Flush()
select {
case <-release:
case <-r.Context().Done():
return
}
io.WriteString(w, `data: {"id":"a","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":null}]}`+"\n\n")
io.WriteString(w, `data: {"id":"a","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\n")
io.WriteString(w, "data: [DONE]\n\n")
}))
s := New()
gw := httptest.NewServer(s.Handler())
t.Cleanup(gw.Close)
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.Proxy, tr.MaxIdleConnsPerHost = nil, n
t.Cleanup(tr.CloseIdleConnections)
client := &http.Client{Transport: tr, Timeout: 2 * time.Minute}
model := pid + "/fake-1"
var wg sync.WaitGroup
errs := make(chan string, n)
for range n {
wg.Add(1)
go func() {
defer wg.Done()
res, err := client.Post(gw.URL+"/v1/chat/completions", "application/json", strings.NewReader(pluginReplyRequest(model, true)))
if err != nil {
errs <- err.Error()
return
}
b, _ := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode != 200 || !strings.Contains(string(b), "ok") {
errs <- res.Status + " " + string(b)
}
}()
}
// the host's windows are all held by streams the vendor keeps open
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
for live.Load() < 128 && ctx.Err() == nil {
time.Sleep(10 * time.Millisecond)
}
if live.Load() < 128 {
t.Fatalf("the vendor holds %d streams, want the host's 128", live.Load())
}
time.Sleep(300 * time.Millisecond) // the other 64 reach the host meanwhile
close(release)
wg.Wait()
close(errs)
for e := range errs {
t.Error(e)
}
if h := hits.Load(); h != n {
t.Errorf("the vendor saw %d requests, want %d", h, n)
}
if m := most.Load(); m > 128 {
t.Errorf("the vendor held %d streams at once, past the host's 128", m)
}
routes := routesOf(s, model)
if len(routes) == 0 {
t.Fatal("no routes traced")
}
for _, r := range routes {
if len(r.Tries) != 1 || r.Tries[0].Status != 200 {
for _, tr := range r.Tries {
t.Errorf("route %d: a try %d %s", r.ID, tr.Status, tr.Error)
}
}
}
}