From 739b3bebe3707f06a3a45fabd791b7e9bc5ab4e0 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 12:54:17 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20a=20rate=20limit=20on=20the=20last?= =?UTF-8?q?=20provider=20left=20is=20waited=20out=20even=20when=20it=20doe?= =?UTF-8?q?sn't=20say=20for=20how=20long=20(#503,=20ynky007)=20=E2=80=94?= =?UTF-8?q?=20a=20429=20was=20tried=20again=20only=20when=20it=20came=20wi?= =?UTF-8?q?th=20a=20Retry-After=20(or=20a=20ratelimit-reset=20header)=20of?= =?UTF-8?q?=208=20s=20at=20most,=20so=20a=20relay's=20429=20that=20says=20?= =?UTF-8?q?nothing=20of=20when=20("Rate=20limit=20exceeded,=20please=20try?= =?UTF-8?q?=20again=20later",=20"=E5=BD=93=E5=89=8D=E5=88=86=E7=BB=84?= =?UTF-8?q?=E4=B8=8A=E6=B8=B8=E8=B4=9F=E8=BD=BD=E5=B7=B2=E9=A5=B1=E5=92=8C?= =?UTF-8?q?=EF=BC=8C=E8=AF=B7=E7=A8=8D=E5=90=8E=E5=86=8D=E8=AF=95")=20went?= =?UTF-8?q?=20straight=20to=20the=20agent.=20Where=20another=20member,=20k?= =?UTF-8?q?ey=20or=20account=20is=20left=20a=20429=20already=20moves=20on?= =?UTF-8?q?=20to=20it,=20as=20before;=20on=20the=20last=20one=20left=20(or?= =?UTF-8?q?=20the=20last=20that=20may=20answer,=20the=20others=20out=20of?= =?UTF-8?q?=20their=20allowance)=20a=20429=20failure()=20reads=20as=20a=20?= =?UTF-8?q?rate=20limit=20is=20now=20asked=20again=20up=20to=203=20times?= =?UTF-8?q?=20(rateRetries;=20busy=205xx/529=20keep=20lastRetries=20=3D=20?= =?UTF-8?q?2),=20after=201,=202=20and=204=20s=20or=20what=20Retry-After=20?= =?UTF-8?q?says=20(each=208=20s=20at=20most,=20under=20half=20a=20minute?= =?UTF-8?q?=20in=20all),=20while=20nothing=20has=20been=20sent=20to=20the?= =?UTF-8?q?=20agent=20and=20only=20until=20it=20goes=20away.=20A=20429=20t?= =?UTF-8?q?hat=20says=20the=20plan=20is=20used=20up=20(usage=20limit,=20re?= =?UTF-8?q?sets=20in=20hours:=20failQuota),=20that=20the=20money=20is=20go?= =?UTF-8?q?ne=20(creditWords),=20or=20a=20Retry-After=20past=208=20s=20(Ch?= =?UTF-8?q?atGPT's=20resets=5Fat=20goes=20on=20as=20one)=20is=20passed=20o?= =?UTF-8?q?n=20at=20once,=20as=20before.=20passing()=20now=20takes=20the?= =?UTF-8?q?=20error=20body=20and=20the=20try=20count,=20and=20the=20last?= =?UTF-8?q?=20one's=20reply=20is=20held=20for=20as=20many=20tries=20as=20a?= =?UTF-8?q?=20rate=20limit=20gets.=20TestRateLimitIsWaitedOut=20(no=20Retr?= =?UTF-8?q?y-After,=20a=20relay's=20own=20words,=20three=20in=20a=20row,?= =?UTF-8?q?=20then=20200;=20four=20in=20a=20row=20=E2=86=92=20429=20after?= =?UTF-8?q?=204=20tries;=20usage=20limit,=20=E4=BD=99=E9=A2=9D=E4=B8=8D?= =?UTF-8?q?=E8=B6=B3,=20Retry-After:=203600=20=E2=86=92=20429=20after=20on?= =?UTF-8?q?e=20try,=20at=20once)=20fails=20without=20the=20change=20(429?= =?UTF-8?q?=20after=201=20try=20in=20the=20first=20three,=203=20tries=20in?= =?UTF-8?q?=20the=20fourth);=20TestLastOneLeftIsTriedAgain=20still=20passe?= =?UTF-8?q?s.=20go=20vet=20./internal/...,=20go=20build=20-tags=20nogui=20?= =?UTF-8?q?(darwin,=20GOOS=3Dlinux),=20GOOS=3Dwindows=20go=20build,=20go?= =?UTF-8?q?=20test=20-tags=20nogui=20./internal/gateway/=20./internal/prov?= =?UTF-8?q?ider/=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/fallback.go | 14 ++++++++--- internal/gateway/gateway.go | 6 ++--- internal/gateway/retry_test.go | 46 ++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 7 deletions(-) diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 3edc1acf2..0d215fc8e 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -533,6 +533,10 @@ const ( // lastRetries is how many times the last one left is tried again after // a failure that passes — a busy vendor, a dropped connection. lastRetries = 2 + // rateRetries is as many for a rate limit, which takes longer to + // clear than a busy moment: pauses of 1, 2 and 4s, or what Retry-After + // says, under half a minute in all + rateRetries = 3 // longestPause is the longest the vendor's Retry-After is waited for // before that; longer, and the agent gets the error. longestPause = 8 * time.Second @@ -543,8 +547,8 @@ const ( var retryPause = time.Second // passing says whether a failure is one that may be gone a moment later, -// and how long to wait before trying the same one again. -func passing(status int, header http.Header, again int) (time.Duration, bool) { +// and how long to wait before trying the same one again, the again'th time. +func passing(status int, header http.Header, body []byte, again int) (time.Duration, bool) { wait := retryPause << again if d := retryAfter(header, time.Now()); d > 0 { wait = d @@ -553,9 +557,11 @@ func passing(status int, header http.Header, again int) (time.Duration, bool) { case wait > longestPause: return 0, false case status == 408, status == 500, status == 502, status == 503, status == 504, status == 529: - return wait, true + return wait, again < lastRetries case status == 429: - return wait, retryAfter(header, time.Now()) > 0 // a rate limit says when + // a relay's 429 often says nothing of when (#503: "负载已饱和,请稍 + // 后再试"); a plan used up or no money left won't clear in seconds + return wait, again < rateRetries && failure(status, body) == failRate && !creditWords.Match(body) } return 0, false } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index f79eba1e2..f812ad524 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1086,7 +1086,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro last := i == len(cands)-1 // the last one's failure is held too when an earlier one failed, // for its allowance running out to be told as that one's error - hw := newHoldWriter(w, !last || again < lastRetries || other != nil) + hw := newHoldWriter(w, !last || again < max(lastRetries, rateRetries) || other != nil) hw.thinkingShown = !refusesAfterThinking(c.model) call.Provider, call.To, call.Usage = c.p.ID, "", Usage{} model = c.model @@ -1279,7 +1279,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro skipped = append(skipped, c.label()+": "+call.Error) continue } - if wait, ok := passing(hw.code(), hw.header, again); ok && !last && again < lastRetries && hw.failed() && spentAfter(cands[i+1:]) { + if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !last && hw.failed() && spentAfter(cands[i+1:]) { // the others left are out of their allowance (Discord, waroy: a // Codex account run out, Grok busy a moment): this one is the // last that may answer, and is tried again as the last is @@ -1306,7 +1306,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro skipped = append(skipped, c.label()+": "+call.Error) continue } - if wait, ok := passing(hw.code(), hw.header, again); ok && again < lastRetries && hw.failed() { + if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && hw.failed() { // nobody else is left: the same one again, after a moment try.Fail, try.Again = failure(hw.code(), hw.errBody()), wait.Milliseconds() s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) diff --git a/internal/gateway/retry_test.go b/internal/gateway/retry_test.go index 44d70e5a5..6377b8e82 100644 --- a/internal/gateway/retry_test.go +++ b/internal/gateway/retry_test.go @@ -20,6 +20,7 @@ type scripted struct { replies []reply n int hang chan struct{} // when set, the first request waits on it + limited http.Header // headers each 429 goes with } type reply struct { @@ -40,6 +41,11 @@ func (s *scripted) ServeHTTP(w http.ResponseWriter, r *http.Request) { x.ctype = "application/json" } w.Header().Set("Content-Type", x.ctype) + if x.code == http.StatusTooManyRequests { + for k, vs := range s.limited { + w.Header()[k] = vs + } + } if x.code != 0 { w.WriteHeader(x.code) } @@ -199,6 +205,46 @@ func TestLastOneLeftIsTriedAgain(t *testing.T) { } } +// A rate limit on the last one left is waited out, a moment, whether the +// vendor says how long or not (#503: a relay's 429 with no Retry-After went +// straight to the agent); one that won't clear in seconds — a plan used up, +// no money left, a Retry-After an hour away — is the agent's at once. +func TestRateLimitIsWaitedOut(t *testing.T) { + limited := `{"error":{"message":"Rate limit exceeded, please try again later"}}` + for _, x := range []struct { + name string + said string + header http.Header + times int // how many times it is limited first + code, n int + }{ + {"retry-after", limited, http.Header{"Retry-After": {"1"}}, 1, 200, 2}, + {"no retry-after", limited, nil, 1, 200, 2}, + {"relay's own words", `{"error":{"message":"当前分组上游负载已饱和,请稍后再试"}}`, nil, 2, 200, 3}, + {"thrice", limited, nil, 3, 200, 4}, + {"too long", limited, nil, 9, 429, 1 + rateRetries}, + {"usage limit", `{"error":{"message":"You've hit your usage limit. Your limit resets in 5 hours."}}`, nil, 9, 429, 1}, + {"no balance", `{"error":{"message":"余额不足"}}`, nil, 9, 429, 1}, + {"an hour away", limited, http.Header{"Retry-After": {"3600"}}, 9, 429, 1}, + } { + fresh(t) + a := &scripted{limited: x.header} + for range x.times { + a.replies = append(a.replies, reply{429, "", x.said}) + } + a.replies = append(a.replies, reply{200, "", chatOK}) + scriptedOn(t, "a", provider.Chat, a) + start := time.Now() + code, body := postAs(t, New(), "", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`) + if code != x.code || a.n != x.n { + t.Errorf("%s: %d after %d tries: %s", x.name, code, a.n, body) + } + if x.n == 1 && time.Since(start) > time.Second { + t.Errorf("%s: passed on after %v", x.name, time.Since(start)) + } + } +} + // An agent that goes away mid-request isn't a provider failing: nobody // rests for it and nobody else is asked. func TestCanceledRequestRestsNobody(t *testing.T) {