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) {