Files
magpie/internal/gateway/rest_all_test.go
T
yetone be7f174677 gateway: a key out of a guessed quota is asked again after one refusal, and held a minute (zoecats)
zoecats (Discord #feedback, 10-25): a local aggregator answers 429
insufficient_quota "quota exhausted" for the moment it switches
upstreams, and the agent's retry and every request after it were
answered by magpie itself, "out of its allowance: not asked again
before …", Retry-After 900. v0.1.1488 (c6768f06f) let it through only
when the user unticks the provider's new "Rests" switch; by default it
was still held (checked on origin/main 4dfd88206 below). The owner's
zero-config rule wants it to just work.

Cause: quotaHeld (#1772) answers from the rest, without asking, as soon
as every key left rests out of its allowance or credit, from the first
refusal on, for as long as the rest: 15 minutes (quotaRest) or 30
(creditRest) that magpie guessed when the vendor named no time.

Now (Rest.first, Rest.askAt, Rest.asksAt), for a rest whose length
magpie guessed (creditRest, or quotaRest with no OwnQuotaRest):
- The key is held only once it was refused so twice in a row. The first
  refusal still rests it (the order passes it over for a ready
  candidate), but the next request, the agent's retry first, asks it
  again; served, its rest is cleared as before.
- Held, it is asked again a minute on (fallbackCooldown), once, and
  held again if refused.
- A time the vendor named (resets, Retry-After, a window) or the user
  set (quotaRest, QuotaResetAt) holds it from the first refusal to
  then, as before. A first version gave every refusal one more ask;
  the full gateway suite turned it down in TestClineFreeLimitLeaves-
  OtherModels and TestZhipuRestsUntilItsReset (a named reset asked
  again), so it is limited to the guess.
  #1772's keys out for the week are asked at most once a minute each
  while requests come, not on every request.
- soonestBack, the Retry-After a 429 without one gets, says when the
  first of them is asked again: none after a first refusal, about 60s
  for a guessed hold (was 900 or 1800). That narrows #3556 for a
  guessed hold; a vendor-named or user-set one is as before.
- A rate limit was already asked again (restLast, retries within the
  request) and is unchanged; the new test holds it there, Retry-After
  0 and every key resting included.
- The "Rests" switch (LimitRestOff) stays: unticked, nothing rests at
  all.
docs/subsystems/gateway-routing.md says so.

Run (worktree at origin/main 4dfd88206 plus this change):
- Reproduced first on the old code with tests:
  TestRetryAfterALimitIsAsked (new; 429 insufficient_quota, a usage
  limit with no reset, the same with Retry-After: 0, 402, every key of
  two; plus two rate-limit cases): the five limit cases red on
  4dfd88206 ("request 2 after the refusal: 429 … not asked again before
  14:34"), green now; the rate cases green on both.
  TestHeldLimitAskedAgainInAMinute (new) red on the old code (Retry-After
  900, not asked a minute on), green now. TestAllRestingAnswersFromRest,
  TestOwnQuotaRest and TestQuotaHeldOnlyForKeysOutOfAllowance changed to
  the new rule (each key asked once more, then held; held Retry-After
  about 60s; a user-set week held from the first refusal); red on the
  old code. TestRemoteMagpieRestsTheModel (#2077) asks Claude Code once
  more before its hold: the other magpie can't read "resets 8:10pm
  (America/Los_Angeles)", so its 15 minutes there are a guess.
- Broken by hand, each red, then restored: r.first always false ->
  TestRetryAfterALimitIsAsked's five limit cases; askAt never set ->
  TestHeldLimitAskedAgainInAMinute and TestAllRestingAnswersFromRest
  (Retry-After 900).
- Sandbox HOME, a nogui build of 4dfd88206 and of this tree, `serve` on
  127.0.0.1:3481 over a Python fake answering 429 insufficient_quota
  "quota exhausted" once, then 200: old: 429, then 429 "not asked again
  before 14:41", 429 again, Retry-After 900, 1 upstream POST. New: 429
  (no Retry-After), 200, 200, 3 upstream POSTs (rerun on the final tree). The fake refusing every
  time, new: 429, 429 Retry-After 60, then held "not asked again before
  14:27" Retry-After 60, 2 upstream POSTs.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway/ at
  4dfd88206 plus this tree, through suite-lock (after the DSH run):
  ok 446.6s. The first full run, before the rule was limited to a
  guess, was red in the three tests named above.
- gofmt -l clean; go vet ./internal/gateway/ (darwin); GOOS=linux go
  vet -tags nogui ./...; GOOS=windows go vet -tags nogui
  ./internal/gateway/: ok.

Not tried: zoecats' own aggregator; a real vendor's out-of-credit key
(OpenAI insufficient_quota) to see the once-a-minute ask in use; the
GUI (no GUI file changed; the Routing page reads the same rests);
Windows box (Windows CI compiles the tests only).
2026-10-25 15:02:12 +08:00

226 lines
8.2 KiB
Go

package gateway
import (
"io"
"net/http"
"net/http/httptest"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// deadKeys answers as #1772's mock did: a key starting with "dead" is
// out of its weekly allowance, in a 429 that names no reset; any other
// is served.
type deadKeys struct {
mu sync.Mutex
keys []string
}
func (d *deadKeys) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
d.mu.Lock()
d.keys = append(d.keys, key)
d.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
if strings.HasPrefix(key, "dead") {
w.WriteHeader(http.StatusTooManyRequests)
io.WriteString(w, `{"error":{"message":"you have reached your weekly usage limit","type":"rate_limit_error"}}`)
return
}
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
}
func (d *deadKeys) took() []string {
d.mu.Lock()
defer d.mu.Unlock()
out := d.keys
d.keys = nil
return out
}
func deadChain(t *testing.T, keys ...string) (*deadKeys, *Server) {
t.Helper()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
restingUntil.Lock()
restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}
restingUntil.Unlock()
t.Cleanup(func() {
restingUntil.Lock()
restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}
restingUntil.Unlock()
})
d := &deadKeys{}
up := httptest.NewServer(d)
t.Cleanup(up.Close)
p := provider.Provider{ID: "mockdead", Name: "mockdead", Chat: up.URL + "/v1", Models: []string{"glm-5.3-flash"}, Routing: provider.Ordered}
p.Key = keys[0]
for _, k := range keys[1:] {
p.Keys = append(p.Keys, provider.KeyAccount{Key: k})
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
return d, New()
}
func postDead(t *testing.T, srv *Server) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"mockdead/glm-5.3-flash","messages":[{"role":"user","content":"hi"}]}`))
req.Header.Set("Content-Type", "application/json")
srv.Handler().ServeHTTP(rec, req)
return rec
}
// #1772 (a fleet on four Ollama Cloud keys): every key out of its weekly
// allowance, each new request had asked each key again (the first twice)
// and answered 429 with no Retry-After, so a client that waits as told
// asked again at once. A key is held once it was refused so twice in a
// row (a single refusal may be a moment's, zoecats on Discord), and, its
// vendor naming no time, asked again a minute on, which Retry-After says.
func TestAllRestingAnswersFromRest(t *testing.T) {
d, srv := deadChain(t, "dead-a", "dead-b")
rec := postDead(t, srv)
if rec.Code != 429 {
t.Fatalf("first: %d %s", rec.Code, rec.Body)
}
if got := d.took(); strings.Join(got, ",") != "dead-a,dead-b" {
t.Errorf("first request asked %v, want each key once", got)
}
if ra := rec.Header().Get("Retry-After"); ra != "" {
t.Errorf("first: Retry-After %q, while each key is asked again at once", ra)
}
// each asked once more, the soonest back first, one a request as
// every candidate resting has it (restLast)
var again []string
for i := 0; i < 2; i++ {
if rec = postDead(t, srv); rec.Code != 429 {
t.Fatalf("confirming: %d %s", rec.Code, rec.Body)
}
again = append(again, d.took()...)
}
if slices.Sort(again); strings.Join(again, ",") != "dead-a,dead-b" {
t.Errorf("asked again %v, want each key once", again)
}
for i := 0; i < 2; i++ {
rec = postDead(t, srv)
if rec.Code != 429 {
t.Fatalf("again: %d %s", rec.Code, rec.Body)
}
if got := d.took(); len(got) != 0 {
t.Errorf("again: asked %v while every key rests", got)
}
ra, err := strconv.Atoi(rec.Header().Get("Retry-After"))
if err != nil || ra < 50 || ra > int(fallbackCooldown/time.Second) {
t.Errorf("again: Retry-After %q, want about %v", rec.Header().Get("Retry-After"), fallbackCooldown)
}
if !strings.Contains(rec.Body.String(), "weekly usage limit") {
t.Errorf("again: the vendor's reason is gone: %s", rec.Body)
}
}
}
// A provider whose keys are out for the week, its vendor saying nothing of
// when, rests them as long as the user set (quotaRest), not 15 minutes.
func TestOwnQuotaRest(t *testing.T) {
d, srv := deadChain(t, "dead-a", "dead-b")
if err := provider.SetQuotaRest("mockdead", 7*24*60); err != nil {
t.Fatal(err)
}
rec := postDead(t, srv)
if got := d.took(); rec.Code != 429 || len(got) != 2 {
t.Fatalf("%d after %v: %s", rec.Code, got, rec.Body)
}
// the user's rest is no guess: held from the first refusal, and not
// asked again a minute on
rec = postDead(t, srv)
if got := d.took(); rec.Code != 429 || len(got) != 0 {
t.Fatalf("held: %d after %v: %s", rec.Code, got, rec.Body)
}
week := int(7 * 24 * time.Hour / time.Second)
if ra, _ := strconv.Atoi(rec.Header().Get("Retry-After")); ra < week-5 || ra > week {
t.Errorf("Retry-After %q, want a week", rec.Header().Get("Retry-After"))
}
for _, c := range []candidate{{p: provider.Provider{ID: "mockdead"}, rest: "mockdead#" + provider.KeyID("dead-a")}} {
if r, ok := restingOf(c); !ok || time.Until(r.Until) < 7*24*time.Hour-time.Minute {
t.Errorf("rests %v until %v", ok, r.Until)
}
}
// a time the vendor names stands over it
p, _ := provider.Find("mockdead")
c := candidate{p: *p, model: "glm-5.3-flash", rest: "mockdead#x"}
h := http.Header{"Retry-After": {"120"}}
if r := srv.restAfter(c, 429, h, []byte(`{"error":{"message":"you have reached your weekly usage limit"}}`)); r.By != "retry-after" || time.Until(r.Until) > 3*time.Minute {
t.Errorf("a vendor's Retry-After lost to the provider's own rest: %+v", r)
}
}
// Only a 429 or a 402 out of quota is answered from the rest: a 403 whose
// words read as quota (a key's plan, a region) is asked again as before,
// and so is a subscription account, whose resets may be spent for it.
func TestQuotaHeldOnlyForKeysOutOfAllowance(t *testing.T) {
deadChain(t, "dead-a")
srv := New()
body := []byte(`{"error":{"message":"you have reached your weekly usage limit"}}`)
key := candidate{p: provider.Provider{ID: "k1"}, rest: "k1"}
srv.restAfter(key, 429, nil, body)
if _, _, ok := quotaHeld([]candidate{key}); ok {
t.Error("a key refused once is held: its retry isn't asked")
}
srv.restAfter(key, 429, nil, body)
if _, _, ok := quotaHeld([]candidate{key}); !ok {
t.Error("a key out of its allowance twice in a row isn't held")
}
forbidden := candidate{p: provider.Provider{ID: "k2"}, rest: "k2"}
srv.restAfter(forbidden, 403, nil, []byte(`{"error":{"message":"quota exceeded for this region"}}`))
if _, _, ok := quotaHeld([]candidate{key, forbidden}); ok {
t.Error("a 403 held")
}
acct := candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "a@b"}}, rest: "codex"}
srv.restAfter(acct, 429, nil, body)
if _, _, ok := quotaHeld([]candidate{acct}); ok {
t.Error("an account held")
}
fresh := candidate{p: provider.Provider{ID: "k3"}, rest: "k3"}
if _, _, ok := quotaHeld([]candidate{key, fresh}); ok {
t.Error("held with a key not resting")
}
}
// #1772's providers.json named its first key in "keys" as well as in
// "key": each key is one candidate, asked once.
func TestFirstKeyListedTwiceAskedOnce(t *testing.T) {
d, srv := deadChain(t, "dead-1", "dead-1", "dead-2", "ok-3")
if rec := postDead(t, srv); rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if got := d.took(); strings.Join(got, ",") != "dead-1,dead-2,ok-3" {
t.Errorf("cold walk asked %v", got)
}
}
// A chain whose last key is served walks past the dead ones once each.
func TestDeadChainWalksEachOnce(t *testing.T) {
d, srv := deadChain(t, "dead-1", "dead-2", "ok-3")
if rec := postDead(t, srv); rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if got := d.took(); strings.Join(got, ",") != "dead-1,dead-2,ok-3" {
t.Errorf("cold walk asked %v", got)
}
if rec := postDead(t, srv); rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if got := d.took(); strings.Join(got, ",") != "ok-3" {
t.Errorf("warm walk asked %v", got)
}
}