Files
magpie/internal/gateway/busy_test.go
T
yetone 3a4df527f5 plugin, provider, gateway, upstream: a test whose check fails while its fake vendor holds a reply ends with a FAIL, not a package hung until -timeout (#1808)
TestNPMInfoDeadline's fake npm held slow-one's reply on <-release, closed only
on the happy path. A check firing first under load (on the issue's machine,
the quick ones missing at npmAll = 300ms) left the handler held, and
httptest.Server.Close, run in the test's cleanup, waited for it forever:
the whole internal/plugin package hung to -timeout and lost every result.

- TestNPMInfoDeadline: a t.Cleanup registered after fakeNPM (so it runs
  before the fake's Close) lets the handler go once (sync.OnceFunc). Its
  timing assumptions, all listed: the 2s wall-clock bound on Info is gone
  (slow-one is held and npmEach is an hour, so Info coming back at all is
  npmAll at work; a minute only turns a wait into a FAIL); npmAll is 5s,
  the quick ones' time to answer on a loaded machine, not 300ms; the slow
  one's kept answer is polled for 30s, not 3s.
- The same pattern in its siblings, each fake handler blocked on a channel
  only the happy path closed, now let go by a cleanup/defer that runs
  before the server's Close: TestRestartFinishesTheReply (plugin),
  TestPastedAddressAndCallbackFinishOnce, TestPartnersFetchedLastIsHeld
  (provider), TestBusy (before gw.Close too, whose request waits on it),
  TestLaneReleasedOnFailure (gateway), TestReadOnceInFresh (upstream; its
  100ms bound on Of goes the same way as the 2s one: the page is held, so
  Of coming back is its not waiting, 10s being short of the read's 15s).
- Audited, already right: grok_accounts, quota_refresh_order,
  quota_history_waiter, subscription_usage, sub2api_usage, qoder, routing,
  github_test, session_route, request_encoding, key_limits, vertex (quit),
  plugin_usage (r.Context).

Run, in a sandbox HOME with pinned caches:
- Old TestNPMInfoDeadline with its check forced (took > 0): "httptest.Server
  blocked in Close", panic at -timeout 30s. With a 500ms delay injected into
  the fake's answers (a loaded machine): FAIL at the quick-ones check, then
  the same hang. New test: with the delay injected, PASS (5.55s); with the
  check forced, FAIL in 5.5s and the package's other tests run; with
  npmAll an hour (the deadline broken), "Info waited for the slow package"
  and the package ends.
- Each sibling with t.Fatal injected while its handler is held: old code,
  all five httptest siblings hang to -timeout 90s ("blocked in Close"),
  upstream's stalls ~56s; new code, each ends at once with FAIL.
- go test -race -count=5 of every touched test: pass.
- gofmt -l (nothing), go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean, before and after rebasing onto
  a3f2097ed. go test -tags nogui ./... (darwin): all 49 packages ok before
  the rebase; after it, all ok but internal/proc's
  TestFindToolKeepsWrapperWhenMiseDoesntSay/hangs ("mise wasn't asked",
  a 300ms miseWait under load; passes 20 of 20 alone), filed as #1838.
Not run: the Windows box, Linux tests.
2026-10-12 23:24:22 +08:00

89 lines
2.9 KiB
Go

package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// What a restart would cut short (#577): a reply streaming counts until
// it has ended, a GET (the model list) never does, and a Claude Code turn
// waiting on its caller's tool results counts until it has them or ends.
func TestBusy(t *testing.T) {
fresh(t)
started, release := make(chan struct{}), make(chan struct{})
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"hel"}}]}`+"\n\n")
w.(http.Flusher).Flush()
close(started)
<-release
io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
}))
defer up.Close()
if err := provider.Save(provider.Provider{ID: "up", Name: "Up", Key: "k", Chat: up.URL + "/v1", Models: []string{"m"}}); err != nil {
t.Fatal(err)
}
s := New()
gw := httptest.NewServer(s.Handler())
defer gw.Close()
// deferred after both Closes, so it runs first: each waits for the held
// stream (the gateway's request on it), which a failed check would
// leave held (#1808)
let := sync.OnceFunc(func() { close(release) })
defer let()
if b := s.Busy(); b.Any() || !b.Last.IsZero() {
t.Fatalf("before any request: %+v", b)
}
done := make(chan struct{})
go func() {
defer close(done)
res, err := http.Post(gw.URL+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"up/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`))
if err == nil {
io.Copy(io.Discard, res.Body)
res.Body.Close()
}
}()
<-started
if res, err := http.Get(gw.URL + "/v1/models"); err == nil {
res.Body.Close()
}
if b := s.Busy(); b.Requests != 1 || b.Tools != 0 || !b.Any() {
t.Fatalf("streaming: %+v, want one request", b)
}
let()
<-done
deadline := time.Now().Add(2 * time.Second)
for s.Busy().Requests != 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if b := s.Busy(); b.Any() || time.Since(b.Last) > 5*time.Second {
t.Fatalf("after the stream: %+v", b)
}
// a Claude Code turn parked on its caller's tools
run := &subscriptionRun{bridge: s.subscription, token: "t", pending: map[string]chan mcpToolResult{}}
s.subscription.mu.Lock()
s.subscription.runs["t"] = run
s.subscription.mu.Unlock()
if b := s.Busy(); b.Tools != 0 {
t.Fatalf("a run not waiting: %+v", b)
}
run.park()
if b := s.Busy(); b.Tools != 1 || !b.Any() {
t.Fatalf("a run waiting on tool results: %+v", b)
}
run.finish()
if b := s.Busy(); b.Tools != 0 {
t.Fatalf("a run ended: %+v", b)
}
}