gateway: a group's last member out of quota sends the request back to a relay that blipped, and rests

dbydd on Discord: an in-order group of sub2api relays with a Codex (or
OpenCode Zen) subscription last. Once that last member's quota answers
429, requests still landed on it, the 429 reached the agent and broke
its loop, and a new conversation stayed stuck there.

Two causes, both in serve:

- A relay that failed for a moment (503/502/429/500) went on to the last
  member; its quota 429 is not busy(), so the patience/replan block
  (#1418) never ran and the agent got the 429 while the relay could
  answer. Now a group's last member refused out of quota or credit
  (lastSpent: failQuota/failCredit, not passing, an earlier member busy
  this request) replans like a busy one: the earlier member is asked
  again, and the spent one rests with restAfterMarked.
- The last one asked was never rested for quota when it was an account
  (#1772 rested keys only), so each later request asked it again. The
  #1772 block now rests the last account out of quota or credit too;
  quotaHeld still holds keys alone, and a Codex autoReset unrests the
  account whose reset it spends.

Tests (internal/gateway/group_spent_last_test.go):
- TestGroupRelayBlipDoesNotEndOnSpentLast: usage_limit_reached /
  rate_limit_exceeded / bare 429 on Codex, crossed with relay blips
  503/502/429/500; every turn must be 200 from the relay, Codex asked at
  most once when spent. Red on the old code (turn 0 got the 429).
- TestGroupSpentLastAccountRests: Patience off; Codex asked at most once.
  Red on the old code ("Codex asked 2 times").
- TestGroupLastMemberSpentGoesBackToEarlier: the reporter's stick case
  (on Codex, relay back, Codex spent); passed on the old code as well.

Broken by hand: lastSpent forced false -> the blip test red; the #1772
block back to keys only -> TestGroupSpentLastAccountRests red.

Not tried: a real OpenCode Zen or ChatGPT quota 429 body (the tests use
Codex's usage_limit_reached shape, rate_limit_exceeded and a bare 429),
and real sub2api relays.
This commit is contained in:
yetone
2026-10-30 11:55:36 +08:00
parent 37527c7ad3
commit 3f91b98eac
3 changed files with 300 additions and 6 deletions
File diff suppressed because one or more lines are too long
+21 -4
View File
@@ -3733,7 +3733,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// (a plain provider's: not ChatGPT's reset of a large request,
// which Codex is told at its 503 with what may help, as Codex's
// own one-account relay leaves it, codexBusy)
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()) &&
// The last one left out of its allowance, after a member before it
// failed in a way that passes, has those asked again as well, and
// rests as they did: the relay's moment of 503 had the agent told
// it, or the last one's 429, while the relay would answer a moment
// on (dbydd on Discord: an in-order group of sub2api relays, a
// Codex account out of its quota last)
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()))
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) &&
(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,
@@ -3750,7 +3758,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
if waitFrom.IsZero() {
waitFrom = time.Now()
}
if waitsOf(c.patience, patienceFallback) > 0 {
if waitsOf(c.patience, patienceFallback) > 0 && !lastSpent {
busyNow = noteBusy(busyNow, c, hw.header)
}
// nor once Codex would hang up in the pause, for want of an
@@ -3761,6 +3769,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
if next, wait, ok := replan(busyNow, rounds, waitFrom, patienceFallback); ok && !kept.tooQuiet(wait) {
try.Fail, try.Again = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds()
if lastSpent {
rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool)
try.Fail, try.Rest = rest.Why, &rest
}
if isGroup {
// a plain provider's is told as the last one left
// asked again: it has no members taking turns
@@ -3856,10 +3868,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
continue
}
}
if last && !held && !hw.passing && hw.failed() && c.p.Account == nil && quotaStatus(hw.code()) && (try.Fail == failQuota || try.Fail == failCredit || failure(hw.code(), hw.errBody()) == failQuota || failure(hw.code(), hw.errBody()) == failCredit) {
if last && !held && !hw.passing && hw.failed() && quotaStatus(hw.code()) && (try.Fail == failQuota || try.Fail == failCredit || failure(hw.code(), hw.errBody()) == failQuota || failure(hw.code(), hw.errBody()) == failCredit) {
// the last key left is out of its allowance: it rests as the
// ones before it did, for the next request to be answered
// from the rests until the first of them is back (#1772)
// from the rests until the first of them is back (#1772). An
// account too: not resting, it stayed the one a relay's moment
// of failure went on to, and its 429 the agent's, request
// after request, while the relay before it would answer
// (dbydd on Discord). quotaHeld still holds keys alone, and
// autoReset lifts the rest of an account it spends a reset of
rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool)
try.Fail, try.Rest = rest.Why, &rest
}
+277
View File
@@ -0,0 +1,277 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// dbydd on Discord: an in-order group whose first members are relays
// (sub2api) that are up, and whose last is a Codex subscription. Once a
// conversation has landed on Codex (its relays failed for a moment), and
// Codex's quota then answers 429, the request goes on to the relays, the
// agent never sees the 429, and the conversation stays off Codex.
func TestGroupLastMemberSpentGoesBackToEarlier(t *testing.T) {
for _, x := range []struct {
name string
refuse func(w http.ResponseWriter)
}{
{"usage_limit_reached", func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(429)
io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_in_seconds":7200}}`)
}},
{"rate_limit_exceeded", func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(429)
io.WriteString(w, `{"error":{"type":"rate_limit_exceeded","message":"Rate limit reached. Please try again later."}}`)
}},
{"bare 429", func(w http.ResponseWriter) {
w.WriteHeader(429)
}},
} {
t.Run(x.name, func(t *testing.T) {
codexSignedIn(t)
sticks.Lock()
sticks.m = map[string]stick{}
sticks.Unlock()
// the ChatGPT backend: answers until the quota is gone
var mu sync.Mutex
spent, codexN := false, 0
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
mu.Lock()
codexN++
out := spent
mu.Unlock()
if out {
x.refuse(w)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
`data: {"type":"response.output_text.delta","delta":"pong"}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7000,"output_tokens":1,"input_tokens_details":{"cached_tokens":6000}}}}`))
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
// the relay: down for a moment, then up
relayDown, relayN := true, 0
relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
mu.Lock()
relayN++
down := relayDown
mu.Unlock()
if down {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(503)
io.WriteString(w, `{"error":{"message":"upstream busy"}}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, grokAnswer)
}))
t.Cleanup(relay.Close)
if err := provider.Save(provider.Provider{ID: "xai", Name: "XAI", Key: "k", Models: []string{"m"}, Chat: relay.URL + "/v1"}); err != nil {
t.Fatal(err)
}
refusalGroup(t, "xai/m", "codex/gpt-5.5")
s := New()
ask := func() (int, string) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(codexAsk))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
req.Header.Set("session_id", "thread-dbydd")
s.Handler().ServeHTTP(rec, req)
return rec.Code, rec.Body.String()
}
// the relay busy: Codex answers, and the conversation is on it
for turn := range 2 {
if code, body := ask(); code != 200 || !strings.Contains(body, "pong") {
t.Fatalf("turn %d on Codex: %d %s (%+v)", turn, code, body, lastRoute(s).Tries)
}
}
// the relay is up again, and Codex's quota is gone
mu.Lock()
spent, relayDown = true, false
codexN = 0
mu.Unlock()
for turn := range 4 {
code, body := ask()
if code != 200 || !strings.Contains(body, "hello") {
r := lastRoute(s)
t.Fatalf("turn %d after the quota ran out: %d %s\naffinity %+v\ntries %+v", turn, code, body, r.Affinity, r.Tries)
}
}
mu.Lock()
defer mu.Unlock()
if codexN > 1 {
t.Fatalf("Codex asked %d times once out (relay %d); it is asked once at most", codexN, relayN)
}
})
}
}
// The same group with the relay failing now and then, as relays do: a
// request it fails goes on to Codex, out of its quota, and then back to
// the relay, which answers; the agent never sees Codex's 429 nor the
// relay's moment of failure. Out of its quota, Codex rests, and the
// relay's next failure has it asked again rather than Codex. Rate
// limited for a moment, it is asked as a resting member is (probeOne).
func TestGroupRelayBlipDoesNotEndOnSpentLast(t *testing.T) {
for _, x := range []struct {
name string
spent bool // out of its quota, not limited for a moment
refuse func(w http.ResponseWriter)
}{
{"usage_limit_reached", true, func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(429)
io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_in_seconds":7200}}`)
}},
{"rate_limit_exceeded", false, func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(429)
io.WriteString(w, `{"error":{"type":"rate_limit_exceeded","message":"Rate limit reached. Please try again later."}}`)
}},
{"bare 429", false, func(w http.ResponseWriter) {
w.WriteHeader(429)
}},
} {
for _, blip := range []int{503, 502, 429, 500} {
t.Run(x.name+" "+http.StatusText(blip), func(t *testing.T) {
codexSignedIn(t)
sticks.Lock()
sticks.m = map[string]stick{}
sticks.Unlock()
var mu sync.Mutex
codexN, relayN := 0, 0
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
mu.Lock()
codexN++
mu.Unlock()
x.refuse(w)
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
mu.Lock()
relayN++
fail := relayN%2 == 1
mu.Unlock()
if fail {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(blip)
io.WriteString(w, `{"error":{"message":"upstream error"}}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, grokAnswer)
}))
t.Cleanup(relay.Close)
if err := provider.Save(provider.Provider{ID: "xai", Name: "XAI", Key: "k", Models: []string{"m"}, Chat: relay.URL + "/v1"}); err != nil {
t.Fatal(err)
}
refusalGroup(t, "xai/m", "codex/gpt-5.5")
s := New()
for turn := range 4 {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(codexAsk))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
req.Header.Set("session_id", "thread-dbydd")
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hello") {
r := lastRoute(s)
t.Fatalf("turn %d: %d %s\naffinity %+v\ntries %+v", turn, rec.Code, rec.Body.String(), r.Affinity, r.Tries)
}
}
mu.Lock()
defer mu.Unlock()
if x.spent && codexN > 1 {
t.Fatalf("Codex asked %d times (relay %d); out of its quota, it is asked once", codexN, relayN)
}
})
}
}
}
// With the group's Patience off, nobody is asked again within a request:
// the request the relay failed has the agent told so. Codex, out of its
// quota as the last one asked, rests all the same, as a key does (#1772),
// and the relay's next failure has the relay asked again, not Codex.
func TestGroupSpentLastAccountRests(t *testing.T) {
codexSignedIn(t)
sticks.Lock()
sticks.m = map[string]stick{}
sticks.Unlock()
var mu sync.Mutex
codexN, relayN := 0, 0
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
mu.Lock()
codexN++
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(429)
io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_in_seconds":7200}}`)
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
mu.Lock()
relayN++
fail := relayN%2 == 1
mu.Unlock()
if fail {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(503)
io.WriteString(w, `{"error":{"message":"upstream error"}}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, grokAnswer)
}))
t.Cleanup(relay.Close)
if err := provider.Save(provider.Provider{ID: "xai", Name: "XAI", Key: "k", Models: []string{"m"}, Chat: relay.URL + "/v1"}); err != nil {
t.Fatal(err)
}
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"xai/m", "codex/gpt-5.5"}, Routing: provider.Ordered, Patience: provider.PatienceOff}); err != nil {
t.Fatal(err)
}
s := New()
for turn := range 5 {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(codexAsk))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
req.Header.Set("session_id", "thread-dbydd")
s.Handler().ServeHTTP(rec, req)
if turn > 0 && (rec.Code != 200 || !strings.Contains(rec.Body.String(), "hello")) {
r := lastRoute(s)
t.Fatalf("turn %d: %d %s\ntries %+v", turn, rec.Code, rec.Body.String(), r.Tries)
}
}
mu.Lock()
defer mu.Unlock()
if codexN > 1 {
t.Fatalf("Codex asked %d times (relay %d); out of its quota, it is asked once", codexN, relayN)
}
}