gateway: an account rate limited till a time its vendor named is not asked again before it (hsjzg58958 on X)

hsjzg58958 on X: a vendor limited an account for 300 seconds, and magpie
asked it again about every half a second as the agent retried, until the
vendor flagged two accounts.

Cause: a candidate resting on a 429 was still "tried all the same" when
it was the last one left (restLast/probeOne), and the last one left was
never rested at all, so every client retry went upstream. Codex on its
own sign-in is relayed by codexUpstreamOn outside the candidate loop and
had no hold at all.

Fix:
- timedHeld/vendorTimed (fallback.go): when every candidate left rests on
  a 429 whose time the vendor named (Retry-After, anthropic-ratelimit-*-
  reset, x-ratelimit-reset-*, resets_in_seconds/resets_at), none is asked;
  the agent gets 429 with Retry-After = when the first is back. A ChatGPT
  account out of its allowance is answered as the backend's
  usage_limit_reached with its x-codex-* windows (Rest.out/outHeader).
- The last one left now rests too on such a 429 (vendorSaidWhen); a 429
  naming no time rests nobody, as before.
- codexHolds (codex_held.go): Codex's own relayed sign-in is held till the
  vendor's time; its retries are answered locally with the stored body,
  x-codex-* headers and Retry-After. Lifted by restarted() for quota holds.
- Not held: LimitRestOff accounts (the user's setting), auto-reset weeks,
  rests "there" (answered by the vendor's own hold), Codex's API key.

Run:
- New TestRateLimitedKeysHeldUntilTheirReset (4 signals x 1 and 2 keys)
  and TestRateLimitedCodexAccountsHeldUntilTheirReset (3 refusals x 1 and
  2 accounts): red at fc9ce34d8 (each key/account asked on every retry),
  green after.
- Broken by hand: held branch off -> every case red (4 extra hits);
  last-one rest off -> 1-key cases red, Retry-After lost; codexHeld off ->
  1-account Codex cases red.
- mote: go test ./internal/gateway -run 'TestRateLimited|TestAllResting|
  TestQuotaHeld|TestGroupSpent|TestCodex|TestRetryAfter|TestHeldLimit'
  ok; TestCodexLeavingModelCompactsLocally updated (the used-up account is
  now asked once, then held) and ok.
- gofmt -l clean; go vet, GOOS=linux -tags nogui and GOOS=windows go vet
  and build ok.
- mote, whole internal/gateway package at the rebased head 46199a6ae
  (on 80161247a): ok but for TestStrictAffinityPassesTheErrorOn, which
  asserted the bug itself ("resting now, it is still the one asked"). A
  strict conversation's account resting till ChatGPT's named reset now
  gets its own usage-limit 429 from the rest, with nobody asked; updated,
  and with TestRateLimited|TestCodexLeavingModel|TestCodexEveryAccountOut
  ok at this head.
- The full ./... suite was queued behind six other sessions' suites on
  mote's lock and not run before the push; queued again at this head.

Not tried: a real vendor account limited live (no account was rate
limited to test on); Codex API-key relay is not held (OpenAI's platform
headers are Codex's own to read); plugin providers are held only through
the shared candidate loop; a held Codex passthrough body's
resets_in_seconds is stale by the time elapsed (Retry-After is exact).
This commit is contained in:
yetone
2026-11-10 00:58:01 +08:00
parent 7db3478275
commit 803d7747e7
11 changed files with 478 additions and 9 deletions
File diff suppressed because one or more lines are too long
+13
View File
@@ -986,6 +986,16 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
if apiKey(r.Header) && rest != "/models" {
base = codexAPIBase
}
// the account ChatGPT limited till a time it named is not asked again
// before it: Codex's retries are answered here (codexHolds)
holdKey := ""
if r.Method == http.MethodPost && (rest == "/responses" || rest == "/responses/compact") {
holdKey = codexHoldKey(base, on)
if h, ok := codexHeld(holdKey, start); ok {
s.writeCodexHeld(w, r, h, base, on, modelOf(body), start)
return
}
}
var maskedHits maskHits
// the ChatGPT sign-in the user set to go unmasked, and its fallbacks
// (codexFallBack masks for its own route), gets the turn as written
@@ -1408,6 +1418,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
if (rest == "/responses" || rest == "/responses/compact") && res.StatusCode >= 400 {
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body = io.NopCloser(bytes.NewReader(msg))
// its credits and resets looked at above, a 429 that names
// when the account is back holds it till then (codexHolds)
noteCodexHold(holdKey, res.StatusCode, res.Header, msg)
if overload && codexBusy(res.StatusCode, msg) && s.codexFallsBack(modelOf(body), body) {
// still too busy once asked again: the fallbacks answer
said := provider.APIError(msg, res.Status)
+136
View File
@@ -0,0 +1,136 @@
package gateway
import (
"cmp"
"net/http"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/provider"
)
// codexHolds are the ChatGPT accounts Codex's turns are relayed on as they
// came (codexUpstreamOn: Codex's own sign-in, or the account a compaction
// goes to) that ChatGPT refused with a 429 naming when they are back. The
// accounts loop rests and holds its own (timedHeld); a relayed turn has no
// candidate to rest, so it is held here: hsjzg58958 on X, an account
// limited for 300 seconds was asked again every time Codex tried again,
// till ChatGPT flagged it. Keyed by the account's user, lower case.
var codexHolds struct {
sync.Mutex
m map[string]codexHold
}
// codexHold is a refusal given again without asking until it ends.
type codexHold struct {
until time.Time
status int
why string // failRate, failQuota or failCredit
body []byte // as ChatGPT said it, for Codex to show as it would
ctype string
codex http.Header // its x-codex-* windows, which Codex reads beside it
}
// codexHoldKey is who a turn relayed to base on on goes to, for its hold;
// "" for one not held: Codex's API key, which OpenAI's platform limits
// by its own headers Codex reads, or a sign-in magpie can't name.
func codexHoldKey(base string, on *provider.Provider) string {
if base != provider.CodexBase {
return ""
}
if on != nil {
if on.Account == nil || on.LimitRestOff {
return ""
}
return strings.ToLower(on.Account.User)
}
who, ok := provider.CodexSignedIn()
if !ok {
return ""
}
return strings.ToLower(who)
}
// noteCodexHold holds who after ChatGPT refused a turn with res's 429,
// when it named for how long (vendorSaidWhen), as rateRest reads it.
func noteCodexHold(who string, status int, header http.Header, body []byte) {
if who == "" || status != http.StatusTooManyRequests || !vendorSaidWhen(header, body) {
return
}
why := failure(status, body)
if why != failRate && why != failQuota && why != failCredit {
return
}
now := time.Now()
d := retryAfter(header, now)
d = max(d, min(resetsNoted(header, now), longestQuota), min(resetsAt(body, now), longestQuota))
if d <= 0 {
return
}
codexHolds.Lock()
defer codexHolds.Unlock()
if codexHolds.m == nil {
codexHolds.m = map[string]codexHold{}
}
if h, ok := codexHolds.m[who]; ok && h.until.After(now.Add(d)) {
return // a longer hold stands
}
windows := http.Header{}
for k, vs := range header {
if strings.HasPrefix(strings.ToLower(k), "x-codex-") {
windows[k] = slices.Clone(vs)
}
}
codexHolds.m[who] = codexHold{until: now.Add(d), status: status, why: why, body: append([]byte(nil), body...), ctype: header.Get("Content-Type"), codex: windows}
}
// codexHeld is who's hold, while it lasts.
func codexHeld(who string, now time.Time) (codexHold, bool) {
if who == "" {
return codexHold{}, false
}
codexHolds.Lock()
defer codexHolds.Unlock()
h, ok := codexHolds.m[who]
if ok && !now.Before(h.until) {
delete(codexHolds.m, who)
ok = false
}
return h, ok
}
// liftCodexHold ends user's hold out of its allowance or credits: a reset
// spent for it, or its window started again (restarted). A rate limit's
// stands: a new window says nothing of it.
func liftCodexHold(user string) {
codexHolds.Lock()
defer codexHolds.Unlock()
who := strings.ToLower(user)
if h, ok := codexHolds.m[who]; ok && h.why != failRate {
delete(codexHolds.m, who)
}
}
// writeCodexHeld answers a turn on a held account as ChatGPT did, with
// when it is back as Retry-After, and says so in the request log.
func (s *Server) writeCodexHeld(w http.ResponseWriter, r *http.Request, h codexHold, base string, on *provider.Provider, model string, start time.Time) {
wait := time.Until(h.until)
for k, vs := range h.codex {
w.Header()[k] = vs
}
w.Header().Set("Content-Type", cmp.Or(h.ctype, "application/json"))
w.Header().Set("Retry-After", strconv.Itoa(int((wait+time.Second-1)/time.Second)))
w.WriteHeader(h.status)
w.Write(h.body)
what := "rate limited"
if h.why != failRate {
what = "out of its allowance"
}
said := provider.APIError(h.body, http.StatusText(h.status)) + " (" + what + ": not asked again before " + heldClock(h.until, time.Now()) + ")"
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: model,
Provider: "openai", Agent: callerOf(r).agent, Kind: callKind(r.Header), Status: h.status,
Millis: time.Since(start).Milliseconds(), Error: codexWho(base, on) + ": " + said, headers: headerLogOf(r.Context())})
}
+9 -2
View File
@@ -83,8 +83,15 @@ func TestCodexLeavingModelCompactsLocally(t *testing.T) {
if code != 200 {
t.Fatalf("%s (header %v): %d %s", c.reason, c.header, code, out)
}
if strings.Join(tried, ",") != "acct-1" {
t.Fatalf("%s: the old model was asked of %v, want acct-1 once", c.reason, tried)
// asked once; refused with the time it is back, it is held till
// then, and the next compactions are answered from that refusal
// without asking it again (timedHeld, hsjzg58958 on X)
want := "acct-1"
if c.reason != "model_downshift" || !c.header {
want = ""
}
if strings.Join(tried, ",") != want {
t.Fatalf("%s: the old model was asked of %v, want %q", c.reason, tried, want)
}
if s := summary(out); !strings.Contains(s, "build the parser") || !strings.Contains(s, "the parser is built") {
t.Fatalf("%s: no local summary of the thread: %q\n%s", c.reason, s, out)
+50
View File
@@ -1380,6 +1380,56 @@ func quotaHeld(cs []candidate) (Rest, time.Time, bool) {
return first, back, len(cs) > 0
}
// timedHeld is, when every candidate of cs rests on a 429 for as long as
// its vendor said (vendorTimed), the rest of the first, and when the first
// of them is back. Asked before then, each is refused the same, and asked
// every time the agent tries again it is the vendor's to judge: hsjzg58958
// on X, two accounts each limited for 300 seconds were asked again about
// every half a second, as the agent retried, until the vendor flagged them
// both. A key or an account alike, out of its rate or its allowance: the
// time is the vendor's own, not one magpie guessed (quotaHeld's first
// refusal asked again). Not a subscription account that spends its resets
// by itself (autoReset), nor another computer's model (Rest.there).
func timedHeld(cs []candidate) (Rest, time.Time, bool) {
var first Rest
var back time.Time
now := time.Now()
for i, c := range cs {
r, ok := restingOf(c)
if !ok || !vendorTimed(c, r) {
return Rest{}, time.Time{}, false
}
at := r.asksAt(now)
if !now.Before(at) {
return Rest{}, time.Time{}, false
}
if i == 0 {
first = r
}
if back.IsZero() || at.Before(back) {
back = at
}
}
return first, back, len(cs) > 0
}
// vendorTimed says whether r, c's rest, is a 429's for the time its vendor
// named: its Retry-After or rate-limit reset headers, or the reset its
// refusal gave (rateRest, Rest.By "retry-after" or "resets").
func vendorTimed(c candidate, r Rest) bool {
if r.there || r.Status != http.StatusTooManyRequests || r.By != "retry-after" && r.By != "resets" {
return false
}
switch r.Why {
case failRate:
return true
case failQuota, failCredit:
a := c.p.Account
return a == nil || !provider.AutoResetsWeek(a.Agent, a.User)
}
return false
}
// quotaStatus is a status a vendor says a key is out of its allowance with.
func quotaStatus(status int) bool {
return status == http.StatusTooManyRequests || status == http.StatusPaymentRequired
+46 -3
View File
@@ -3388,10 +3388,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
continue
}
if i < len(cands)-1 {
if _, _, ok := quotaHeld(cands[i:]); ok {
_, _, spent := quotaHeld(cands[i:])
if _, _, timed := timedHeld(cands[i:]); spent || timed {
// every key left is out of its allowance, resting until it
// is back: none is asked, and the agent is told so at once
// (#1772)
// is back, or every one left is limited till a time its
// vendor named: none is asked, and the agent is told so at
// once (#1772; hsjzg58958 on X)
cands = cands[:i+1]
}
}
@@ -3875,6 +3877,38 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// using this one rests that model of it alone (remoteModelRest)
noteMember(hw, r, c.p, c.model)
writeError(hw, from, call.Status, msg)
} else if rested, back, ok := timedHeld(cands[i:]); ok && last {
// it rests on a 429 till the time its vendor named, and so
// does every one that was left (hsjzg58958 on X: limited for
// 300 seconds, each account was asked again about every half a
// second as the agent retried, until the vendor flagged them):
// the agent is answered here, with when the first of them is
// back as Retry-After. Set on the held answer too, so it isn't
// taken for a moment's limit and asked again in a second
// (passing) or in the patience's rounds (busy)
said := rested.Error
if said == "" {
said = http.StatusText(rested.Status)
}
what := "rate limited"
if rested.Why != failRate {
what = "out of its allowance"
}
msg := fmt.Sprintf("%s (%s: not asked again before %s)", said, what, heldClock(back, time.Now()))
held, heldBack, call.Status, call.Error = true, back, rested.Status, c.p.Name+": "+msg
if wait := time.Until(back); wait > 0 {
hw.Header().Set("Retry-After", strconv.Itoa(int((wait+time.Second-1)/time.Second)))
}
noteMember(hw, r, c.p, c.model)
if rested.out != nil && from == provider.Responses {
// a ChatGPT account used up: Codex is told as the backend
// told it, usage_limit_reached with its plan, reset and
// windows, which it shows and doesn't retry
// (TestCodexEveryAccountOutToldAsTheBackend)
writeCodexOut(hw, rested.outHeader, call.Status, msg, rested.out)
} else {
writeError(hw, from, call.Status, msg)
}
} else {
// a stream that fails before anything is said is let go at
// once (hw.stop), not read on until the vendor hangs up
@@ -5050,6 +5084,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// 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
} else if last && !held && !hw.passing && hw.failed() && hw.code() == http.StatusTooManyRequests && !hw.turnedAway && try.Fail != failPrompt && failure(hw.code(), hw.errBody()) == failRate && vendorSaidWhen(hw.header, hw.errBody()) {
// the last one left is rate limited till a time its vendor
// named: it rests till then too, for the agent's retries to be
// answered from the rest (timedHeld) rather than sent on to
// the vendor, which flags an account asked so (hsjzg58958 on
// X). A 429 naming no time rests nobody, as before: a relay's
// moment of saturation is asked again
rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool)
try.Fail, try.Rest = rest.Why, &rest
}
if !hw.passing && hw.code() == http.StatusTooManyRequests && hw.header.Get("Retry-After") == "" {
// the vendor said nothing of when: the agent is told when
+3
View File
@@ -105,6 +105,9 @@ func noRests() {
restingUntil.m = map[string]time.Time{}
restingUntil.note = map[string]Rest{}
restingUntil.Unlock()
codexHolds.Lock()
codexHolds.m = nil
codexHolds.Unlock()
}
func post(t *testing.T, path, body string) (int, string) {
+3
View File
@@ -43,6 +43,9 @@ func fresh(t *testing.T) {
restingUntil.Lock()
restingUntil.m = map[string]time.Time{}
restingUntil.Unlock()
codexHolds.Lock()
codexHolds.m = nil
codexHolds.Unlock()
sticks.Lock()
sticks.m = map[string]stick{}
sticks.Unlock()
+187
View File
@@ -0,0 +1,187 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// limitedUp is a vendor that has every key or account it serves over its
// rate limit for the next five minutes, and says so as refuse does. It
// counts what it was asked.
type limitedUp struct {
refuse func(w http.ResponseWriter)
n atomic.Int32
}
func (u *limitedUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
u.n.Add(1)
w.Header()["Content-Type"] = nil
u.refuse(w)
}
// limitedFor is the 300 seconds hsjzg58958's vendor named.
const limitedFor = 300 * time.Second
// rateRefusals are the ways a vendor says an account or key is rate
// limited for limitedFor: the Retry-After header, Anthropic's
// anthropic-ratelimit-*-reset and OpenAI's x-ratelimit-reset-* headers
// with no Retry-After, and ChatGPT's resets_in_seconds in the error.
var rateRefusals = []struct {
name string
refuse func(w http.ResponseWriter)
}{
{"Retry-After", func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Retry-After", "300")
w.WriteHeader(429)
io.WriteString(w, `{"error":{"message":"Rate limit reached for requests","type":"rate_limit_error"}}`)
}},
{"anthropic-ratelimit reset", func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("anthropic-ratelimit-requests-remaining", "0")
w.Header().Set("anthropic-ratelimit-requests-reset", time.Now().Add(limitedFor).UTC().Format(time.RFC3339))
w.WriteHeader(429)
io.WriteString(w, `{"type":"error","error":{"type":"rate_limit_error","message":"This request would exceed your account's rate limit. Please try again later."}}`)
}},
{"x-ratelimit reset", func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("x-ratelimit-remaining-requests", "0")
w.Header().Set("x-ratelimit-reset-requests", "5m0s")
w.WriteHeader(429)
io.WriteString(w, `{"error":{"message":"Rate limit reached for gpt-5.5 on requests per min (RPM): Limit 3, Used 3, Requested 1.","type":"requests","code":"rate_limit_exceeded"}}`)
}},
{"resets_in_seconds", 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.","resets_in_seconds":300}}`)
}},
}
// clientRetries is an agent asking again every half a second after a
// 429, as Codex and Claude Code do on their own; it returns the last
// answer.
func clientRetries(t *testing.T, n int, ask func() *httptest.ResponseRecorder) *httptest.ResponseRecorder {
t.Helper()
var rec *httptest.ResponseRecorder
for range n {
time.Sleep(500 * time.Millisecond)
rec = ask()
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("retry answered %d: %s", rec.Code, rec.Body)
}
}
return rec
}
// heldRetryAfter checks that an answer given while every candidate is
// limited tells the agent when it is back, within the vendor's time.
func heldRetryAfter(t *testing.T, rec *httptest.ResponseRecorder) {
t.Helper()
ra, err := strconv.Atoi(rec.Header().Get("Retry-After"))
if err != nil || ra < int(limitedFor/time.Second)-30 || ra > int(limitedFor/time.Second) {
t.Errorf("Retry-After %q, want about %v", rec.Header().Get("Retry-After"), limitedFor)
}
}
// hsjzg58958 on X: a vendor rate limited the account for 300 seconds, and
// magpie asked it again about every half second, as the agent retried,
// till the vendor flagged two accounts. A key or account the vendor named
// a time for is not asked again before it: the agent's retries are
// answered here, 429 with when the first of them is back.
func TestRateLimitedKeysHeldUntilTheirReset(t *testing.T) {
for _, x := range rateRefusals {
for _, keys := range [][]string{{"k-a"}, {"k-a", "k-b"}} {
t.Run(x.name+"/"+strconv.Itoa(len(keys))+" keys", func(t *testing.T) {
fresh(t)
up := &limitedUp{refuse: x.refuse}
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
p := provider.Provider{ID: "lim", Name: "lim", Chat: srv.URL + "/v1", Models: []string{"m"}, Key: keys[0]}
for _, k := range keys[1:] {
p.Keys = append(p.Keys, provider.KeyAccount{Key: k})
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
s := New()
ask := func() *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"lim/m","messages":[{"role":"user","content":"hi"}]}`))
req.Header.Set("Content-Type", "application/json")
s.Handler().ServeHTTP(rec, req)
return rec
}
if rec := ask(); rec.Code != http.StatusTooManyRequests {
t.Fatalf("first: %d %s", rec.Code, rec.Body)
}
first := int(up.n.Load())
if first != len(keys) {
t.Errorf("first request asked %d times, want each key once", first)
}
rec := clientRetries(t, 4, ask)
if n := int(up.n.Load()); n != first {
t.Errorf("the agent's 4 retries reached the vendor %d times while every key was limited for %v", n-first, limitedFor)
}
heldRetryAfter(t, rec)
})
}
}
}
// The same for ChatGPT accounts behind Codex, one or two (the thread
// hsjzg58958 replied in): each refused for five minutes is asked once,
// whether ChatGPT says it is rate limited or out of its allowance till
// then.
func TestRateLimitedCodexAccountsHeldUntilTheirReset(t *testing.T) {
cases := append([]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":300}}`)
}}}, rateRefusals[0], rateRefusals[3])
for _, x := range cases {
for _, spares := range [][]string{nil, {"spare@example.com"}} {
t.Run(x.name+"/"+strconv.Itoa(len(spares)+1)+" accounts", func(t *testing.T) {
codexSignedIn(t, spares...)
up := &limitedUp{refuse: x.refuse}
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
was := provider.CodexBase
provider.CodexBase = srv.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
s := New()
ask := func() *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(oneAccountTurn))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
s.Handler().ServeHTTP(rec, req)
return rec
}
if rec := ask(); rec.Code != http.StatusTooManyRequests {
t.Fatalf("first: %d %s", rec.Code, rec.Body)
}
first := int(up.n.Load())
if first != len(spares)+1 {
t.Errorf("first request asked ChatGPT %d times, want each account once", first)
}
rec := clientRetries(t, 4, ask)
if n := int(up.n.Load()); n != first {
t.Errorf("Codex's 4 retries reached ChatGPT %d times while every account was limited for %v", n-first, limitedFor)
}
heldRetryAfter(t, rec)
})
}
}
}
+24
View File
@@ -829,6 +829,11 @@ type Rest struct {
// asked, it answers from its own hold at once, or from what it serves
// now
there bool
// out, outHeader: a ChatGPT account's refusal as the backend gave it
// (codexOutRefusal) and its x-codex-* windows, for a turn held on it
// (timedHeld) to be told as Codex is told on its own sign-in
out []byte
outHeader http.Header
}
// asksAt is when r, a key's rest out of its allowance or credit, has it
@@ -869,6 +874,9 @@ func renewed(agent, user string) {
// stands started again in fact, or a reset was spent.
func restarted(agent, user string) {
liftRests(agent, user, true)
if agent == "codex" {
liftCodexHold(user)
}
}
// liftRests lifts an account's rests out of quota, or of a window read
@@ -1478,6 +1486,15 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
// the vendor's words, for quotaHeld to give again
r.said = provider.APIError(body, http.StatusText(status))
}
if codexOutRefusal(c.p, provider.Responses, status, body) {
r.out = append([]byte(nil), body...)
r.outHeader = http.Header{}
for k, vs := range header {
if strings.HasPrefix(strings.ToLower(k), "x-codex-") {
r.outHeader[k] = slices.Clone(vs)
}
}
}
switch why {
case failCredit:
d, r.By, guessed = creditRest, "credit", true
@@ -1920,6 +1937,13 @@ func backingOff(key string, now time.Time) bool {
return ok && now.Before(until) && restingUntil.note[key].Why == failOther
}
// vendorSaidWhen says whether a 429's headers or body name a time it is
// limited till, as rateRest reads them.
func vendorSaidWhen(header http.Header, body []byte) bool {
now := time.Now()
return max(retryAfter(header, now), resetsNoted(header, now), resetsAt(body, now)) > 0
}
// rateRest is how long a rate-limited candidate sits out: as long as the
// vendor says (Retry-After, a reset header or a reset time in its error),
// and a minute when it says nothing. One limited again as soon as its rest
+6 -3
View File
@@ -87,9 +87,12 @@ func TestStrictAffinityPassesTheErrorOn(t *testing.T) {
if why := lastWhy(t, srv); why != "strict" {
t.Fatalf("traced as %q", why)
}
// resting now, it is still the one asked
if code, _, tried := strictPost(t, srv, b, "s1"); code != 429 || tried != "acct-1" {
t.Fatalf("strict, its account resting: %d tried %s", code, tried)
// resting now till the time ChatGPT named, it is still its account's
// error the agent gets, not another's answer, but given from the rest:
// asked again on every retry, an account is flagged (timedHeld,
// hsjzg58958 on X)
if code, body, tried := strictPost(t, srv, b, "s1"); code != 429 || !strings.Contains(body, "usage limit") || tried != "" {
t.Fatalf("strict, its account resting: %d %s tried %s", code, body, tried)
}
if code, body, tried := strictPost(t, srv, b, "s2"); code != 200 || !strings.Contains(body, "pong") || tried != "acct-2" {
t.Fatalf("a new conversation: %d %s tried %s", code, body, tried)