Files
magpie/internal/gateway/rate_backoff_test.go
T
yetone af0558e6d0 gateway: a 429 that says in words when it's back rests until then, in Chinese as in English (#1669, Natsumeretsu)
WorkBuddy answers a frequency limit with the time it resets, in words:
"将在 2026-10-11 20:16:02 UTC+8重置" and "your usage will reset at
2026-10-11 12:37:53 UTC+8, ...". resetsAt read neither (only Claude
Code's "limit reached|<unix>" and ChatGPT's resets_at), so the Chinese
one rested quotaRest (15 min, matched 用量) and the English one
fallbackCooldown (1 min, no word list matched): the account was asked
again long before it was back, refused, and benched again.

- resetsWritten reads a time beside the reset phrasing (resetsWhen:
  "reset(s) at", 将在/将于), in the UTC/GMT offset it is written with.
  The offset must be followed by 重置 or punctuation, so a refusal cut
  after "UTC" or "UTC+" is never read as UTC; a date that isn't real,
  one past, or more than a week off (longestWritten) isn't read; another
  vendor's date in passing ("deprecated on ...", "retry after ...") is no
  reset. resetsAt falls back to it, so keepRetry notes it too.
- failure reads such a 429 as out of quota in either language.
- One that points to the account's other models ("切换其他模型",
  "switch to the other models") rests that model alone (restID), so
  the account's other models are still asked during an hours-long rest.
- rateRest: a reset time the refusal names (resetsAt, or as keepRetry
  noted it) is believed up to longestQuota, as the quota branch does,
  and the trace says "resets"; a Retry-After or rate-limit reset header
  stays held to longestWait. Decided: the stated time is the vendor's
  statement of when the account is back, and how far it is believed
  shouldn't hang on which word list the message happened to match
  (8 days as quota vs 1 hour as rate for the same words); a Retry-After
  is generic advice and keeps the hour.

The rest is the gateway's, so it holds for moved WorkBuddy users too:
the plugin (packages/workbuddy 0.1.14, explained()) passes a 429 that
isn't "unapproved channel"/14018 on as it came.
TestPluginWrittenResetRests shows a plugin-served 429 with the
reporter's refusal resting the model until the stated time.

Tests: TestResetsWritten (reporter's bytes in both languages, other
offsets, cut-short, garbled, past, >7 days, other vendors' dates),
TestWrittenResetRestsUntilThen (both languages rest the model by
"resets", noted path, cut-short falls back, other vendors' 429s
unchanged), TestRateLimitBelievesItsReset, TestPluginWrittenResetRests.
Broke each piece by hand (reader, classification, rate cap, model
scope, offset, the terminator) and each made one of them fail.
TestRateLimitBacksOffWhenItComesBack now expects "resets" for a noted
reset. go test -tags nogui ./... under a temp HOME, rebased
on 498b77fbc, passes but internal/provider's
TestCopilotSecretToolUsername, which this doesn't touch: it is #1627
(5s secret-tool bound under load) and fails alone 3 of 5 on this head
too. internal/gateway rerun after rebasing on 6ebe481f8; gofmt -l, go
vet for darwin, GOOS=linux and GOOS=windows on internal/gateway.
Not tried against WorkBuddy itself: its raw 429 JSON shape isn't
known beyond the message (err_type 6004), and a body that escapes the
Chinese as \uXXXX wouldn't be read (the reporter's classification by
用量 shows theirs isn't escaped).
2026-10-12 03:23:27 +08:00

93 lines
3.9 KiB
Go

package gateway
import (
"net/http"
"strconv"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// A rate limit that comes back as soon as its rest is over rests twice as
// long each time, up to half an hour, until the account answers; a vendor's
// own word of when (a header, or a reset time in its error) is kept; and
// an account whose usage says it has credits left still waits its rest out
// behind the others (01huadalang: a WorkBuddy free model 429 while the
// account had credits was asked again every minute).
func TestRateLimitBacksOffWhenItComesBack(t *testing.T) {
old := allowances
defer func() { allowances = old }()
allowances = func(string) map[string]provider.Allowance {
return map[string]provider.Allowance{"a@x.com": {{Used: 5, Span: 30 * 24 * time.Hour}}}
}
s := &Server{}
c := candidate{p: provider.Provider{ID: "workbuddy", Account: &provider.Account{Agent: "workbuddy", User: "a@x.com"}}, model: "free-model", rest: "workbuddy#a"}
id := c.restKey()
body := []byte(`{"error":{"message":"Too many requests","type":"rate_limit_error"}}`)
near := func(d, want time.Duration) bool { return d > want-5*time.Second && d <= want }
// its rest runs out: the next 429 comes as soon as it is back
expire := func() {
restingUntil.Lock()
restingUntil.m[id] = time.Now().Add(-time.Second)
restingUntil.Unlock()
}
for i, want := range []time.Duration{time.Minute, 2 * time.Minute, 4 * time.Minute, 8 * time.Minute, 16 * time.Minute, 30 * time.Minute, 30 * time.Minute} {
r := s.restAfter(c, 429, http.Header{}, body)
if r.Why != failRate || !near(time.Until(r.Until), want) || r.Failures != i+1 {
t.Fatalf("429 #%d: rests %v by %s, %d failures; want %v", i+1, time.Until(r.Until), r.By, r.Failures, want)
}
if i > 0 && r.By != "backoff" {
t.Fatalf("429 #%d by %s", i+1, r.By)
}
// a usage that says it has credits doesn't put it before the others
other := candidate{p: provider.Provider{ID: "next"}, model: "m", rest: "next"}
out, _ := restLast([]candidate{c, other}, planned{order: make([]Weighed, 2)})
if out[0].rest != "next" {
t.Fatalf("429 #%d: resting account tried first", i+1)
}
expire()
}
// tried anyway while resting (the last one left, again and again in one
// request): it doesn't stretch the rest further
servedCandidate(c, 1)
s.restAfter(c, 429, http.Header{}, body)
expire()
s.restAfter(c, 429, http.Header{}, body) // 2m
r := s.restAfter(c, 429, http.Header{}, body)
if !near(time.Until(r.Until), 2*time.Minute) || r.Failures != 2 {
t.Fatalf("failed again while resting: %v, %d failures", time.Until(r.Until), r.Failures)
}
// an answer starts it over
servedCandidate(c, 1)
if r := s.restAfter(c, 429, http.Header{}, body); !near(time.Until(r.Until), time.Minute) || r.By != "cooldown" {
t.Fatalf("after an answer: %v by %s", time.Until(r.Until), r.By)
}
// the vendor's Retry-After, when longer than the backoff, is what it waits
servedCandidate(c, 1)
h := http.Header{}
h.Set("Retry-After", "600")
if r := s.restAfter(c, 429, h, body); !near(time.Until(r.Until), 10*time.Minute) || r.By != "retry-after" {
t.Fatalf("Retry-After 600: %v by %s", time.Until(r.Until), r.By)
}
// and a reset time in the error, as keepRetry notes it
servedCandidate(c, 1)
h = http.Header{}
h.Set(resetsHeader, strconv.FormatInt(time.Now().Add(20*time.Minute).Unix(), 10))
if r := s.restAfter(c, 429, h, body); !near(time.Until(r.Until), 20*time.Minute) || r.By != "resets" {
t.Fatalf("reset noted: %v by %s", time.Until(r.Until), r.By)
}
// a rate limit long after the last one's rest ended is a new one
restingUntil.Lock()
restingUntil.m[id] = time.Now().Add(-rateForget - time.Minute)
restingUntil.Unlock()
if r := s.restAfter(c, 429, http.Header{}, body); !near(time.Until(r.Until), time.Minute) || r.Failures != 1 {
t.Fatalf("long after: %v, %d failures", time.Until(r.Until), r.Failures)
}
servedCandidate(c, 1)
}