gateway: the same 5xx from two accounts in one request rests neither (mycf_711)
mycf_711 on Discord: 127 of one provider's 128 503s in a day were
"AIError AI服务异常" word for word, all one agent's request with an empty
tool schema the upstream always refused. forbiddenAlike/unforbid
(plugins#243) only took plain 403s, so each such request walked every
account of the provider into backoff, and other agents' normal requests
then found every account resting.
A 500/502/503 that says nothing of why (plainUnavailable: failOther, not
overloaded, no proxy down, not codexReset, not the protection refusal, not
"did not stream", some words) now joins forbiddenAlike when:
- a second account of the same provider, model and reasoning gives it in
the same status and words, request/trace ids left out (refusalWords);
- and the provider answered another request within answeringLately (5m,
noted in servedCandidate as routed.answered).
Then neither rests, the first one's rest and failure count are taken back,
the other mates go last (matesLast, so a group's other members are asked
first), and the last one left isn't asked again after a moment
(sameRefusal; before, the two-account case re-sent the request 13 times).
Kept as before: one account's 503 alone rests it; 503s in other words are
each account's own; a provider that answered nothing in the last 5 minutes
may be down, and its alike 503s rest as before, so an outage is backed off
once 5 minutes have passed since its last answer. A 403 is still alike only
to a 403. Overloads keep their own short model rest.
Ran (mote, via mote-run, at this tree on 6b47bce67; after the rebase onto
186453e00, vet and TestPlain*|TestQoder* again: ok):
- TestPlain5xxOnTwoMatesRestsNeither (5 cases: alone, two alike + a third
answers, two alike nobody left, two in other words, two alike with the
provider down), TestPlainUnavailableWords, TestPlain403*: ok.
- go test -run "Plain|Forbid|Rest|Overload|Fallback|Group|Busy|Patience|
Codex|Refus|Served|Unavailable|Protection" ./internal/gateway/: ok 240s.
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet on
./internal/gateway/: ok. gofmt -l: nothing.
Broken by hand, each red with a real FAIL:
- no 5xx alike (words5xx never set, the old behaviour): acct-1 rests in
"two alike, a third answers"; "nobody left" tried acct-1,acct-2 x13.
- last one asked again (sameRefusal dropped): tried acct-1,acct-2,acct-2,
acct-1,acct-2.
- no outage guard (answeredLately always true): "provider down" case,
acct-1 not resting.
- words not compared: "two in other words", acct-1 not resting.
Not tried: the reporter's real provider and plugin (unknown here, no
account); a group with another provider failing over during the first 5
minutes of a real outage (matesLast covers it, not tested here); the full
./... suite before push (run after the tag, per the loop rules). In the
first 5 minutes of a real outage alike 503s no longer rest, so each
request asks two accounts before moving on; a gateway whose only traffic
is the refused request still rests as before (no answer lately).
This commit is contained in:
File diff suppressed because one or more lines are too long
+21
-10
@@ -3022,7 +3022,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
// the key or subscription account the last try went to (#557)
|
||||
providerKeyID, providerKeyName, providerAccount := "", "", ""
|
||||
var other *Try // the first failure that wasn't an allowance run out
|
||||
var forbade []forbidden // the plain 403s rested so far (forbiddenAlike)
|
||||
var forbade []forbidden // the plain 403s and 5xx rested so far (forbiddenAlike)
|
||||
sameRefusal := false // the last try's 5xx was a mate's word for word: the request's
|
||||
autoReset := resetFirst != nil // a Codex or Claude reset looked at, once a request
|
||||
creditsAsked := map[string]bool{} // Codex accounts asked again onto their credits, once each (creditsAgain)
|
||||
// the subscription/model pairs an account refused as a model it doesn't
|
||||
@@ -4321,11 +4322,21 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
continue
|
||||
}
|
||||
plain403 := hw.failed() && !hw.refused && plainForbidden(c, hw.code(), hw.errBody())
|
||||
if alike, others := forbiddenAlike(forbade, c); plain403 && len(alike) > 0 {
|
||||
// a mate refused this request with a plain 403 too: the
|
||||
// request is what is refused, not each account (plugins#243).
|
||||
// Neither rests, the mate's rest taken back, and its other
|
||||
// mates are asked last, as for a prompt turned away
|
||||
// a 5xx that says nothing of why, from a provider answering other
|
||||
// requests: alike from two accounts, it is the request's too
|
||||
var words5xx string
|
||||
sameRefusal = false
|
||||
if !plain403 && hw.failed() && !hw.refused && !hw.turnedAway && plainUnavailable(c, hw.code(), hw.errBody()) && answeredLately(c.p.ID) {
|
||||
words5xx = refusalWords(hw.code(), hw.errBody())
|
||||
}
|
||||
if alike, others := forbiddenAlike(forbade, c, words5xx); (plain403 || words5xx != "") && len(alike) > 0 {
|
||||
// a mate refused this request with a plain 403 too, or the
|
||||
// same 5xx in the same words: the request is what is refused,
|
||||
// not each account (plugins#243, mycf_711's 503s). Neither
|
||||
// rests, the mate's rest taken back, and its other mates are
|
||||
// asked last, as for a prompt turned away; the last one left
|
||||
// isn't asked again after a moment, as one busy is
|
||||
sameRefusal = words5xx != ""
|
||||
for _, f := range alike {
|
||||
unforbid(f)
|
||||
}
|
||||
@@ -4446,8 +4457,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
try.Fail, try.Rest = rest.Why, &rest
|
||||
at := -1
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1], at = try, len(t.Tries)-1 })
|
||||
if plain403 {
|
||||
forbade = append(forbade, forbidden{c: c, rest: rest, try: at})
|
||||
if plain403 || words5xx != "" {
|
||||
forbade = append(forbade, forbidden{c: c, rest: rest, try: at, words: words5xx})
|
||||
}
|
||||
skipped = append(skipped, c.label()+": "+call.Error)
|
||||
if waitsOf(c.patience, patienceFallback) > 0 && !hw.turnedAway && busy(hw.code(), hw.errBody()) {
|
||||
@@ -4469,7 +4480,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
// (spentAfter) and the agent is told theirs
|
||||
lastSpent := last && isGroup && len(busyNow) > 0 && !hw.passing && hw.failed() && !busy(hw.code(), hw.errBody()) &&
|
||||
slices.Contains([]string{failQuota, failCredit}, failure(hw.code(), hw.errBody())) && !spentAfter([]candidate{c})
|
||||
if _, same := passing(hw.code(), hw.header, hw.errBody(), again); last && patience > 0 && !protected && !hw.turnedAway && !hw.refused && hw.failed() && (busy(hw.code(), hw.errBody()) || lastSpent) &&
|
||||
if _, same := passing(hw.code(), hw.header, hw.errBody(), again); last && patience > 0 && !protected && !sameRefusal && !hw.turnedAway && !hw.refused && hw.failed() && (busy(hw.code(), hw.errBody()) || lastSpent) &&
|
||||
(isGroup || !codexReset(hw.code(), hw.errBody())) &&
|
||||
(len(busyNow) > 0 || waitsOf(c.patience, patienceFallback) > 0 && !same) {
|
||||
// every member has failed, each in a way that passes — busy,
|
||||
@@ -4519,7 +4530,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
break
|
||||
}
|
||||
}
|
||||
if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !hw.turnedAway && hw.failed() && waitFrom.IsZero() && !kept.tooQuiet(wait) {
|
||||
if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !sameRefusal && !hw.turnedAway && hw.failed() && waitFrom.IsZero() && !kept.tooQuiet(wait) {
|
||||
// nobody else is left: the same one again, after a moment (not
|
||||
// what Antigravity turned away: it turns it away again; nor
|
||||
// once the group's patience is spent)
|
||||
|
||||
@@ -78,7 +78,7 @@ func fresh(t *testing.T) {
|
||||
// rather than a turn on, or with a failure already counted.
|
||||
func forgetRouting() {
|
||||
routed.Lock()
|
||||
routed.used, routed.failures, routed.slow = map[string]tokenUse{}, map[string]int{}, map[string]slowRun{}
|
||||
routed.used, routed.failures, routed.slow, routed.answered = map[string]tokenUse{}, map[string]int{}, map[string]slowRun{}, map[string]time.Time{}
|
||||
routed.Unlock()
|
||||
routes.Forget()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// One request refused with the same 5xx, word for word, by two accounts
|
||||
// of a provider that answers other requests is the request refused, not
|
||||
// each account (mycf_711 on Discord: 127 of a provider's 128 503s were
|
||||
// "AIError AI服务异常", one agent's request with an empty tool schema the
|
||||
// upstream always refused; each walked every account into backoff, and
|
||||
// the other agents' requests found them all resting). Neither rests, the
|
||||
// last one left isn't asked again after a moment, and an account after
|
||||
// them answers. One account's 503 alone still rests it, 503s in other
|
||||
// words are the accounts' own, and a provider that answered nothing
|
||||
// lately may be down: its alike 503s rest as before.
|
||||
func TestPlain5xxOnTwoMatesRestsNeither(t *testing.T) {
|
||||
for _, x := range []struct {
|
||||
name string
|
||||
spares []string
|
||||
also []string // accounts after acct-1 that refuse too
|
||||
differ bool // each account says it in its own words
|
||||
cold bool // the provider answered nothing before
|
||||
resting []string // who rests after
|
||||
code int
|
||||
tried string // the accounts asked, in order
|
||||
}{
|
||||
{"alone", []string{"b@example.com"}, nil, false, false, []string{"codex@me@example.com"}, 200, "acct-1,acct-2"},
|
||||
{"two alike, a third answers", []string{"b@example.com", "c@example.com"}, []string{"acct-2"}, false, false, nil, 200, "acct-1,acct-2,acct-3"},
|
||||
{"two alike, nobody left", []string{"b@example.com"}, []string{"acct-2"}, false, false, nil, 503, "acct-1,acct-2"},
|
||||
{"two in other words", []string{"b@example.com", "c@example.com"}, []string{"acct-2"}, true, false, []string{"codex@me@example.com", "codex@b@example.com"}, 200, "acct-1,acct-2,acct-3"},
|
||||
{"two alike, provider down", []string{"b@example.com", "c@example.com"}, []string{"acct-2"}, false, true, []string{"codex@me@example.com", "codex@b@example.com"}, 200, "acct-1,acct-2,acct-3"},
|
||||
} {
|
||||
t.Run(x.name, func(t *testing.T) {
|
||||
codexSignedIn(t, x.spares...)
|
||||
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var armed atomic.Bool
|
||||
var n atomic.Int32
|
||||
unavailable := func(w http.ResponseWriter) {
|
||||
if !armed.Load() {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(
|
||||
`data: {"type":"response.created","response":{"id":"r0","model":"gpt-5.5"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"pong"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"r0","usage":{"input_tokens":7,"output_tokens":1}}}`))
|
||||
return
|
||||
}
|
||||
k := n.Add(1)
|
||||
msg := "AIError AI服务异常"
|
||||
if x.differ {
|
||||
msg = fmt.Sprintf("upstream %c failed", 'a'+rune(k))
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
// a trace id of its own each time, as a vendor's has
|
||||
fmt.Fprintf(w, `{"error":{"message":"%s (trace_id: %032x)","type":"api_error"}}`, msg, 0xabc0+int(k))
|
||||
}
|
||||
var tried []string
|
||||
chatgptRefusing(t, &tried, unavailable, x.also...)
|
||||
s := New()
|
||||
if !x.cold {
|
||||
// another request answered: the provider is up
|
||||
if code, body := codexAskOn(s, `{"model":"gpt-5.5","stream":true,"input":"hello"}`); code != 200 {
|
||||
t.Fatalf("the first request: %d %s", code, body)
|
||||
}
|
||||
}
|
||||
tried = nil
|
||||
armed.Store(true)
|
||||
code, body := codexAskOn(s, `{"model":"gpt-5.5","stream":true,"input":"ping","tools":[{"type":"function","name":"x","parameters":{}}]}`)
|
||||
if code != x.code {
|
||||
t.Fatalf("status %d: %s; tried %v", code, body, tried)
|
||||
}
|
||||
if got := strings.Join(tried, ","); got != x.tried {
|
||||
t.Fatalf("tried %s, want %s", got, x.tried)
|
||||
}
|
||||
r := lastRoute(s)
|
||||
who := []string{"codex@me@example.com"}
|
||||
for _, sp := range x.spares {
|
||||
who = append(who, "codex@"+sp)
|
||||
}
|
||||
for _, w := range who {
|
||||
_, ok := restOf(w)
|
||||
if want := slices.Contains(x.resting, w); ok != want {
|
||||
t.Fatalf("%s resting %v, want %v; tried %v; tries %+v", w, ok, want, tried, r.Tries)
|
||||
}
|
||||
if !ok {
|
||||
routed.Lock()
|
||||
f := routed.failures[w]
|
||||
routed.Unlock()
|
||||
if f != 0 {
|
||||
t.Fatalf("%s still counts %d failures", w, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if x.resting == nil && (r.Tries[0].Rest != nil || r.Tries[1].Rest != nil) {
|
||||
t.Fatalf("tries still say they rest: %+v", r.Tries)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// What two tries' 5xx are compared by: the words, ids left out, and the
|
||||
// status; a body that says nothing is never alike, nor an overload, which
|
||||
// rests the model a moment on its own path.
|
||||
func TestPlainUnavailableWords(t *testing.T) {
|
||||
c := candidate{p: provider.Provider{ID: "relay"}, model: "m"}
|
||||
a := refusalWords(503, []byte(`{"error":{"message":"AIError AI服务异常 req 9f8e7d6c5b4a3f2e1d0c"}}`))
|
||||
b := refusalWords(503, []byte(`{"error":{"message":"AIError AI服务异常 req 0a1b2c3d4e5f60718293"}}`))
|
||||
if a == "" || a != b {
|
||||
t.Fatalf("ids kept apart: %q vs %q", a, b)
|
||||
}
|
||||
if refusalWords(502, []byte(`{"error":{"message":"AIError AI服务异常"}}`)) == a {
|
||||
t.Fatal("a 502 is alike to a 503")
|
||||
}
|
||||
for _, x := range []struct {
|
||||
status int
|
||||
body string
|
||||
want bool
|
||||
}{
|
||||
{503, `{"error":{"message":"AIError AI服务异常"}}`, true},
|
||||
{500, `{"error":{"message":"Internal error"}}`, true},
|
||||
{502, `{"error":{"message":"bad upstream"}}`, true},
|
||||
{504, `{"error":{"message":"timed out"}}`, false},
|
||||
{503, ``, false},
|
||||
{503, `{"error":{"message":"The model is overloaded"}}`, false},
|
||||
{529, `{"error":{"message":"busy"}}`, false},
|
||||
{429, `{"error":{"message":"slow down"}}`, false},
|
||||
} {
|
||||
if got := plainUnavailable(c, x.status, []byte(x.body)); got != x.want {
|
||||
t.Errorf("%d %s: %v, want %v", x.status, x.body, got, x.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+76
-12
@@ -40,10 +40,11 @@ const usageHalfLife = time.Hour
|
||||
|
||||
var routed = struct {
|
||||
sync.Mutex
|
||||
used map[string]tokenUse // candidate restKey → tokens it served
|
||||
failures map[string]int // candidate restKey → failures since it last answered
|
||||
slow map[string]slowRun // candidate restID → its slow starts since it last answered (restSlow)
|
||||
}{used: map[string]tokenUse{}, failures: map[string]int{}, slow: map[string]slowRun{}}
|
||||
used map[string]tokenUse // candidate restKey → tokens it served
|
||||
failures map[string]int // candidate restKey → failures since it last answered
|
||||
slow map[string]slowRun // candidate restID → its slow starts since it last answered (restSlow)
|
||||
answered map[string]time.Time // provider ID → when one of its candidates last answered (answeringLately)
|
||||
}{used: map[string]tokenUse{}, failures: map[string]int{}, slow: map[string]slowRun{}, answered: map[string]time.Time{}}
|
||||
|
||||
// slowRun is a model's slow starts in a row on one account or key, and
|
||||
// when the last of them was.
|
||||
@@ -82,6 +83,9 @@ func served(rest, key string, tokens int) {
|
||||
// when it has one, the candidate's model-specific rest.
|
||||
func servedCandidate(c candidate, tokens int) {
|
||||
served(c.restKey(), c.restKey(), tokens)
|
||||
routed.Lock()
|
||||
routed.answered[c.p.ID] = time.Now()
|
||||
routed.Unlock()
|
||||
provider.NoteServed(c.p, time.Now())
|
||||
provider.Unretire(c.p.ID, c.model) // back in service, if it was said retired
|
||||
if id := c.restID(); id != c.restKey() {
|
||||
@@ -93,12 +97,14 @@ func servedCandidate(c candidate, tokens int) {
|
||||
}
|
||||
}
|
||||
|
||||
// forbidden is a plain 403 one request was given, and the rest it took:
|
||||
// what forbiddenAlike and unforbid read.
|
||||
// forbidden is a plain 403, or a plain 5xx (plainUnavailable), one
|
||||
// request was given, and the rest it took: what forbiddenAlike and
|
||||
// unforbid read.
|
||||
type forbidden struct {
|
||||
c candidate
|
||||
rest Rest
|
||||
try int // its index in the route's Tries, -1 untraced
|
||||
c candidate
|
||||
rest Rest
|
||||
try int // its index in the route's Tries, -1 untraced
|
||||
words string // a 5xx's status and words (refusalWords); "" for a 403
|
||||
}
|
||||
|
||||
// plainForbidden says a reply is a 403 that says nothing of why: no
|
||||
@@ -109,17 +115,75 @@ func plainForbidden(c candidate, status int, body []byte) bool {
|
||||
!modelRefused(status, body) && !codeAssistModelMissing(c.p, status, body)
|
||||
}
|
||||
|
||||
// plainUnavailable says a reply is a 500, 502 or 503 that says nothing
|
||||
// the account is at fault for, nor that the vendor is busy: no quota,
|
||||
// credit, rate, overload (vendorOverloaded), no proxy down, not ChatGPT's
|
||||
// reset (codexReset) or its protection refusal, each read on its own
|
||||
// path. Such a 5xx may be an outage or the request's: an upstream, or a
|
||||
// plugin putting its upstream's error in its own words, refusing a
|
||||
// request it will always refuse (mycf_711 on Discord: 127 of one
|
||||
// provider's 128 503s, "AIError AI服务异常" word for word, were one
|
||||
// agent's request with an empty tool schema, and each walked every
|
||||
// account into backoff). forbiddenAlike tells them apart: the same words
|
||||
// from two accounts, while the provider answers other requests.
|
||||
func plainUnavailable(c candidate, status int, body []byte) bool {
|
||||
switch carriedStatus(status, body) {
|
||||
case http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable:
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return failureOf(c, status, body) == failOther && !vendorOverloaded(status, body) &&
|
||||
!codexReset(status, body) && !protectionRefused(status, body) &&
|
||||
!bytes.Contains(body, []byte(didNotStream)) && refusalWords(status, body) != ""
|
||||
}
|
||||
|
||||
// idRun is a run in an error's words that differs from one try to the
|
||||
// next: a request or trace id, a timestamp.
|
||||
var idRun = regexp.MustCompile(`[0-9a-fA-F][0-9a-fA-F-]{11,}|\d{6,}`)
|
||||
|
||||
// refusalWords is a 5xx's status and the words it said, ids left out
|
||||
// (idRun), for two tries' to be compared; "" when it said nothing, as a
|
||||
// bare 502 from a proxy down does, which proves nothing alike.
|
||||
func refusalWords(status int, body []byte) string {
|
||||
w := strings.Join(strings.Fields(string(wordsOf(body))), " ")
|
||||
if w == "" {
|
||||
return ""
|
||||
}
|
||||
w = idRun.ReplaceAllString(w, "#")
|
||||
if len(w) > 512 {
|
||||
w = w[:512]
|
||||
}
|
||||
return strconv.Itoa(carriedStatus(status, body)) + " " + w
|
||||
}
|
||||
|
||||
// answeringLately is how recently a provider must have answered a request
|
||||
// for the same 5xx from two of its accounts to read as the request's: a
|
||||
// provider answering others is up. One that answered nothing in it may be
|
||||
// down, and rests as before, so an outage is backed off once this has
|
||||
// passed since its last answer.
|
||||
const answeringLately = 5 * time.Minute
|
||||
|
||||
// answeredLately says one of provider id's candidates answered a request
|
||||
// within answeringLately.
|
||||
func answeredLately(id string) bool {
|
||||
routed.Lock()
|
||||
at := routed.answered[id]
|
||||
routed.Unlock()
|
||||
return !at.IsZero() && time.Since(at) < answeringLately
|
||||
}
|
||||
|
||||
// forbiddenAlike is the plain 403s of c's mates earlier in the request:
|
||||
// another key or account of its provider, asked the same model at the
|
||||
// same reasoning. Two of them refusing one request alike, it is the
|
||||
// request that is refused, not each account (plugins#243,
|
||||
// zygs1083-dotcom: Factory's 403 for a Claude Code wrapper it refused
|
||||
// rested every account in turn, and the next requests found them all in
|
||||
// backoff).
|
||||
// backoff). A plain 5xx (words, refusalWords) is alike only to one of
|
||||
// the same status and words; a 403 (words "") only to a 403.
|
||||
// The rest of seen is returned beside them, for the request to keep.
|
||||
func forbiddenAlike(seen []forbidden, c candidate) (alike, others []forbidden) {
|
||||
func forbiddenAlike(seen []forbidden, c candidate, words string) (alike, others []forbidden) {
|
||||
for _, f := range seen {
|
||||
if f.c.p.ID == c.p.ID && f.c.model == c.model && f.c.effort == c.effort && f.c.who() != c.who() {
|
||||
if f.c.p.ID == c.p.ID && f.c.model == c.model && f.c.effort == c.effort && f.c.who() != c.who() && f.words == words {
|
||||
alike = append(alike, f)
|
||||
} else {
|
||||
others = append(others, f)
|
||||
|
||||
Reference in New Issue
Block a user