Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: Codex's own turn on one ChatGPT account is asked again on an overload, then its fallbacks (夜松云 on Discord)

yetone5f73537f5b02
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index cc807e91f..352583e8e 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -125,6 +125,7 @@ recorded as a prediction failure (`noPrediction`).
- In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models.
- A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits <account> off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again.
- Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873).
+- One of Codex's own models on the backend path with no routing to do (`codexAccounts` false: one ChatGPT account, no usage cap, no key holds, nothing pinned) is relayed as Codex sent it, on Codex's own sign-in, its bytes and headers unchanged and its reply streamed as it comes (`codexUpstreamOn` with no account): routing was built for more than one account, and that path also keeps the turn's native compaction with the backend. Before, nothing was asked again on it, so an overload went straight to Codex, which doesn't retry the backend's `server_is_overloaded` itself (夜松云 on Discord). Now a transient overload (`codexBusy`: what `busy` calls busy, a 529, a 503 saying overloaded, the backend's in-stream `response.failed` with `server_is_overloaded` (#1418); never a 429, a usage limit, an edge's drop of the connection (`edgeSaidDrop`) or a reset (`codexReset`)) is asked again of the same account, the same body and headers, up to `lastRetries` times after `retryPause<<n`, as the accounts loop asks its last account, and only before any of the reply has reached Codex. A stream is held for it through a `holdWriter` with its reasoning let through (`thinkingShown`), kept alive past `keepHeldAfter` across the tries (one `keptAlive`), so Codex sees the stream's headers and comments, never a failed try's frames. Nothing rests for an overload. Once the retries are spent, a turn whose codex subscription has fallbacks (`codexFallsBack`; never a compaction) goes on to them (`codexFallBack`: the turn served as `codex/<model>` with the account left out of the candidates, `fallbacksOnly`, and the same keepalive carried in `handedOnKey`); without fallbacks Codex gets the last try's failure as the backend said it. Each try is a `HandedOn` usage record and a try in the trace. A success is relayed as before, with nothing held when no retry or fallback is left (`TestCodexOneAccountOverloadAskedAgain`, `…StreamOverloadAskedAgain`, `…OverloadBounded`, `…OverloadFallsBack`, `…OverloadKeptAlive`, `…RefusalNotAskedAgain` in [`codex_one_account_overload_test.go`](../../internal/gateway/codex_one_account_overload_test.go)).
- A subscription account whose sign-in its vendor revoked (`provider.SignInRevoked`: 401 `token_revoked` and the like, #1793) fails as `failAuth`: the next member is asked at once, nothing rests, and the account is marked (`noteSignIn` in [`signin_revoked.go`](../../internal/gateway/signin_revoked.go)). Its later requests aren't sent while it has that credential: `forwardOnce` answers them with a 401 of magpie's own (`revokedReply`), so they too pass on. Compaction on an account of magpie's (`compactOn`) picks a marked one last. A key's provider answering the same words rests as before.
- A sub2api key out of its own limit answers 429 `api key 7天限额已用完` (or `日限额`, `5小时限额`) as `rate_limit_exceeded`. It is out of quota (`plannedWords`), not rate limited: it rests till the window it filled renews when its windows as last read say so, else `quotaRest`, and its windows are read again (`staleKeyAllowance`). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (`renewed`, told through `provider.OnRenewed`), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (`restingOf`, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503 `No available accounts`, or a later version's 429 `All available accounts are currently rate-limited`) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows.
- A 5xx is a server error, not quota, unless the vendor's own quota code says so (`quotaCodes`: `usage_limit_reached`, `RESOURCE_EXHAUSTED`, Claude Code's `usage limit reached|<unix>`). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota by `usedUpWords` (上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (`usedUpWords`) still apply to a 4xx.
diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go
index b783f9be7..07e4e654e 100644
--- a/internal/gateway/codex_backend.go
+++ b/internal/gateway/codex_backend.go
@@ -829,6 +829,7 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri
func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest string, body []byte, on *provider.Provider) {
start := time.Now()
usage.Saw(agentOf(r))
+ w0, body0 := w, body // as they came, for the fallbacks (codexFallBack)
if r.Method == http.MethodPost {
var unmask func()
var err error
@@ -852,6 +853,18 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
if r.URL.RawQuery != "" {
u += "?" + r.URL.RawQuery
}
+ // Codex's turn on its own sign-in, the one account it has, with
+ // nobody else to ask (codexAccounts): an overload of the backend's —
+ // a busy status, or server_is_overloaded on a stream that has said
+ // nothing yet (#1418), which Codex doesn't ask again for — is asked
+ // again of it, as the accounts loop asks its last account, the same
+ // bytes with the same sign-in, and then of the subscription's
+ // fallbacks; nobody rests for it (夜松云 on Discord)
+ overload := r.Method == http.MethodPost && rest == "/responses" && base == provider.CodexBase && on == nil
+ streams := streamOf(body)
+ kept := &keptAlive{proto: provider.Responses, told: start, streams: streams}
+ busyAgain := 0 // times the turn was asked again for an overload
+ var tried []string // what each of those said, for the request log
// a turn goes in the Routing view's live trace as the others do, to
// the one it can go to: Codex's own sign-in, or its key
var tr *Route
@@ -904,10 +917,12 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
window = cmp.Or(provider.CodexWindow(user, model), catalog.ContextOf(model))
}
s.trace.update(tr, func(t *Route) {
- t.Tries[0].Done, t.Tries[0].Status, t.Tries[0].Millis, t.Tries[0].Error = true, status, ms, msg
- t.Tries[0].TTFT, t.Tries[0].FirstText = ttft, text
+ // the last try: the turn asked again for an overload has one each
+ try := &t.Tries[len(t.Tries)-1]
+ try.Done, try.Status, try.Millis, try.Error = true, status, time.Since(try.Start).Milliseconds(), msg
+ try.TTFT, try.FirstText = ttft, text
t.ReasoningHidden = first.hidesReasoning(provider.Responses)
- t.Tries[0].ReasoningHidden = t.ReasoningHidden
+ try.ReasoningHidden = t.ReasoningHidden
t.Done, t.Status, t.Error, t.Millis, t.Tokens = true, status, msg, ms, tokens
if t.TitleLink != nil && isTitleKind(kind) && status < 400 && msg == "" && !titleReply.truncated {
link := *t.TitleLink
@@ -916,13 +931,13 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
}
t.Output, t.Reasoning, t.TTFT, t.FirstText = out, uu.Reasoning, ttft, text
flow := first.flowFor(uu.Reasoning)
- t.Flow, t.Tries[0].Flow = flow, flow
+ t.Flow, try.Flow = flow, flow
t.Usage = routeUsage("openai", model, uu)
if prompt != nil {
t.Prompt = prompt.calibrated(promptCounted(t.Usage), window)
}
- t.Tries[0].Served, t.Tries[0].Swapped = served, swapped(model, served)
- t.Served, t.Swapped = t.Tries[0].Served, t.Tries[0].Swapped
+ try.Served, try.Swapped = served, swapped(model, served)
+ t.Served, t.Swapped = try.Served, try.Swapped
})
}
}
@@ -931,188 +946,311 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
resetNote := "" // what spending it did, for the request log
resets := 0 // times a large request ChatGPT closed on was asked again (#1628)
sent := len(body) // the bytes that went, compressed (provider.CodexCompressed)
- for tries := 0; ; tries++ {
- ctx := provider.ViaSignedIn(r.Context(), "codex")
- if on != nil {
- ctx = on.Via(r.Context())
- }
- req, err := http.NewRequestWithContext(ctx, r.Method, u, bytes.NewReader(body))
- if err != nil {
- writeError(w, provider.Responses, 502, err.Error())
- end(502, err.Error(), 0, 0)
+ began := start // when the try now going began
+ // failWith tells Codex of a failure before any reply: as the stream's
+ // error once it was sent the stream's headers while it waited
+ failWith := func(status int, msg string) {
+ if kept.sent {
+ streamError(w, provider.Responses, status, msg)
return
}
- copyHeaders(req.Header, r.Header)
- if on != nil {
- // the account's own token and id in place of the sign-in's;
- // what Codex said it takes back stays as it said it
- accept := req.Header.Values("Accept")
- if err := on.Sign(ctx, req, provider.Responses, body); err != nil {
- msg := "OpenAI (" + on.Account.User + "): " + err.Error()
- writeError(w, provider.Responses, 502, msg)
- end(502, msg, 0, 0)
+ writeError(w, provider.Responses, status, msg)
+ }
+ // handOn notes a try that failed for an overload, which the turn goes
+ // on from, after wait: in the trace, and as a row handed on, as the
+ // accounts loop notes one
+ handOn := func(status int, msg string, wait time.Duration) {
+ s.trace.update(tr, func(t *Route) {
+ try := &t.Tries[len(t.Tries)-1]
+ try.Done, try.Status, try.Error, try.Fail = true, status, msg, failOther
+ try.Millis, try.Again = time.Since(try.Start).Milliseconds(), wait.Milliseconds()
+ })
+ servedProvider, servedAccount := codexServed(base, r.Header, on)
+ rec := usage.Record{RouteID: tr.ID, Time: began, Agent: agentOf(r), Provider: servedProvider, Host: provider.HostOf(base),
+ ProviderAccount: servedAccount, Model: modelOf(body), Requested: modelOf(body), Effort: effort,
+ Millis: time.Since(began).Milliseconds(), Status: status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header),
+ Kind: kind, Endpoint: r.URL.Path, HandedOn: true}
+ failedWith(&rec, status, msg, "")
+ appendUsage(r, rec)
+ tried = append(tried, fmt.Sprintf("openai: %d %s", status, msg))
+ }
+ // askAgain pauses wait, Codex kept alive meanwhile, for the turn to be
+ // asked again; false when Codex went away in it
+ askAgain := func(status int, msg string, wait time.Duration) bool {
+ handOn(status, msg, wait)
+ busyAgain++
+ if !pauseAlive(r.Context(), w, kept, streams, start, wait) {
+ s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1].Gone = true })
+ end(status, msg, 0, 0)
+ return false
+ }
+ began = time.Now()
+ s.trace.update(tr, func(t *Route) {
+ again := t.Tries[0]
+ t.Tries = append(t.Tries, Try{ID: again.ID, Model: again.Model, Effort: again.Effort, Start: began})
+ })
+ first, titleReply = firstToken{start: start}, capturedBody{}
+ return true
+ }
+ var sniff *usageSniffer
+ var refusal []byte // what OpenAI said, of a request it turned away
+ for {
+ // the try's own, which a stream that failed before its reply ends
+ // (holdWriter.stop)
+ attempt, cancel := context.WithCancel(r.Context())
+ defer cancel()
+ for tries := 0; ; tries++ {
+ ctx := provider.ViaSignedIn(attempt, "codex")
+ if on != nil {
+ ctx = on.Via(attempt)
+ }
+ req, err := http.NewRequestWithContext(ctx, r.Method, u, bytes.NewReader(body))
+ if err != nil {
+ failWith(502, err.Error())
+ end(502, err.Error(), 0, 0)
return
}
- // a sign-in its vendor revoked isn't sent again (#1793)
- if why, ok := provider.RevokedSignIn(on.Account, req); ok {
- writeError(w, provider.Responses, 401, why)
- end(401, why, 0, 0)
+ copyHeaders(req.Header, r.Header)
+ if on != nil {
+ // the account's own token and id in place of the sign-in's;
+ // what Codex said it takes back stays as it said it
+ accept := req.Header.Values("Accept")
+ if err := on.Sign(ctx, req, provider.Responses, body); err != nil {
+ msg := "OpenAI (" + on.Account.User + "): " + err.Error()
+ writeError(w, provider.Responses, 502, msg)
+ end(502, msg, 0, 0)
+ return
+ }
+ // a sign-in its vendor revoked isn't sent again (#1793)
+ if why, ok := provider.RevokedSignIn(on.Account, req); ok {
+ writeError(w, provider.Responses, 401, why)
+ end(401, why, 0, 0)
+ return
+ }
+ req.Header.Del("Accept")
+ for _, v := range accept {
+ req.Header.Add("Accept", v)
+ }
+ }
+ // left to the transport, the reply comes back plain for the usage in it
+ req.Header.Del("Accept-Encoding")
+ // a turn to ChatGPT goes zstd-compressed again, as Codex sent it
+ // before magpie read it (ylorn on X); an API key's goes plain
+ sent = provider.CodexCompressed(req, body)
+ if res, err = s.client.Do(req); err != nil {
+ msg := "OpenAI: " + err.Error()
+ if rest == "/responses" {
+ msg = codexUnreached(modelOf(body), err)
+ }
+ failWith(502, msg)
+ end(502, msg, 0, 0)
return
}
- req.Header.Del("Accept")
- for _, v := range accept {
- req.Header.Add("Accept", v)
+ if on != nil {
+ // one of magpie's accounts: a revoked sign-in shows on its
+ // row, to sign in again (#1793)
+ noteSignIn(ctx, on.Account, req, res)
}
- }
- // left to the transport, the reply comes back plain for the usage in it
- req.Header.Del("Accept-Encoding")
- // a turn to ChatGPT goes zstd-compressed again, as Codex sent it
- // before magpie read it (ylorn on X); an API key's goes plain
- sent = provider.CodexCompressed(req, body)
- if res, err = s.client.Do(req); err != nil {
- msg := "OpenAI: " + err.Error()
- if rest == "/responses" {
- msg = codexUnreached(modelOf(body), err)
- }
- writeError(w, provider.Responses, 502, msg)
- end(502, msg, 0, 0)
- return
- }
- if on != nil {
- // one of magpie's accounts: a revoked sign-in shows on its
- // row, to sign in again (#1793)
- noteSignIn(ctx, on.Account, req, res)
- }
- if !autoReset && rest == "/responses" && base != codexAPIBase && res.StatusCode == http.StatusTooManyRequests {
- // the account is out of its allowance: one it lets spend its
- // resets by itself, its week used up, spends one and is asked
- // again — nobody else is there to ask
- autoReset = true
+ if !autoReset && rest == "/responses" && base != codexAPIBase && res.StatusCode == http.StatusTooManyRequests {
+ // the account is out of its allowance: one it lets spend its
+ // resets by itself, its week used up, spends one and is asked
+ // again — nobody else is there to ask
+ autoReset = true
+ msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
+ res.Body.Close()
+ res.Body = io.NopCloser(bytes.NewReader(msg))
+ if failure(res.StatusCode, msg) == failQuota {
+ if who, out, ok := s.autoResetSignedIn(r.Context()); ok {
+ s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1].Reset = &AutoReset{Who: who, Text: out.Text()} })
+ resetNote = "openai (" + who + "): used one of its resets by itself (" + out.Text() + ")"
+ continue
+ }
+ }
+ }
+ if rest == "/responses" && base != codexAPIBase && edgeMayDrop(res.StatusCode, sent) && resets < lastRetries {
+ // ChatGPT closed the connection before answering a large
+ // request, which often passes (#1628), or its front couldn't
+ // retry one that large (#2034): asked again after a moment,
+ // as the accounts loop asks its last one again
+ head, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10))
+ res.Body.Close()
+ res.Body = io.NopCloser(bytes.NewReader(head))
+ if edgeSaidDrop(res.StatusCode, head) {
+ wait := retryPause << resets
+ resets++
+ select {
+ case <-time.After(wait):
+ continue
+ case <-r.Context().Done():
+ }
+ }
+ }
+ if overload && busyAgain < lastRetries && res.StatusCode >= 400 {
+ // the backend too busy for the turn, said as its status
+ msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
+ res.Body.Close()
+ res.Body = io.NopCloser(bytes.NewReader(msg))
+ if codexBusy(res.StatusCode, msg) {
+ if wait, ok := passing(res.StatusCode, res.Header, msg, busyAgain); ok {
+ if !askAgain(res.StatusCode, provider.APIError(msg, res.Status), wait) {
+ return
+ }
+ continue
+ }
+ }
+ }
+ if rest != "/responses" || tries >= 3 || (res.StatusCode != 400 && res.StatusCode != 404) {
+ break
+ }
+ // an item OpenAI can't take — sealed by another account, or
+ // another vendor's that it looks up and doesn't have — is taken
+ // out and the rest asked again, rather than the conversation
+ // stuck on it for good
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
res.Body = io.NopCloser(bytes.NewReader(msg))
- if failure(res.StatusCode, msg) == failQuota {
- if who, out, ok := s.autoResetSignedIn(r.Context()); ok {
- s.trace.update(tr, func(t *Route) { t.Tries[0].Reset = &AutoReset{Who: who, Text: out.Text()} })
- resetNote = "openai (" + who + "): used one of its resets by itself (" + out.Text() + ")"
- continue
- }
+ b, ok := withoutUnreadable(body, msg)
+ if !ok {
+ break
}
+ body = b
}
- if rest == "/responses" && base != codexAPIBase && edgeMayDrop(res.StatusCode, sent) && resets < lastRetries {
- // ChatGPT closed the connection before answering a large
- // request, which often passes (#1628), or its front couldn't
- // retry one that large (#2034): asked again after a moment,
- // as the accounts loop asks its last one again
- head, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10))
- res.Body.Close()
- res.Body = io.NopCloser(bytes.NewReader(head))
- if edgeSaidDrop(res.StatusCode, head) {
- wait := retryPause << resets
- resets++
- select {
- case <-time.After(wait):
- continue
- case <-r.Context().Done():
- }
+ if rest == "/responses" {
+ // a web page or nothing at all, served 200, is the 502 it stands
+ // for (#1012)
+ res = notAnAPIReply(res, "OpenAI: ")
+ if base != codexAPIBase {
+ // still closed on after that: Codex is told what may help,
+ // at the 503 it asks again for (#1628)
+ res = codexDropped(res, sent)
}
}
- if rest != "/responses" || tries >= 3 || (res.StatusCode != 400 && res.StatusCode != 404) {
- break
- }
- // an item OpenAI can't take — sealed by another account, or
- // another vendor's that it looks up and doesn't have — is taken
- // out and the rest asked again, rather than the conversation
- // stuck on it for good
- msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
- res.Body.Close()
- res.Body = io.NopCloser(bytes.NewReader(msg))
- b, ok := withoutUnreadable(body, msg)
- if !ok {
- break
- }
- body = b
- }
- if rest == "/responses" {
- // a web page or nothing at all, served 200, is the 502 it stands
- // for (#1012)
- res = notAnAPIReply(res, "OpenAI: ")
- if base != codexAPIBase {
- // still closed on after that: Codex is told what may help,
- // at the 503 it asks again for (#1628)
- res = codexDropped(res, sent)
- }
- }
- defer res.Body.Close()
- if base == codexAPIBase && res.StatusCode == http.StatusUnauthorized {
- // Codex signed in with an API key OpenAI refuses — often one a
- // relay issued, left in ~/.codex/auth.json — and one of Codex's own
- // models was picked, which goes out with Codex's own sign-in
- msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
- writeError(w, provider.Responses, res.StatusCode, codexKeyRefused(msg))
- s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
- Provider: "openai", Agent: agentOf(r), Status: res.StatusCode,
- Millis: time.Since(start).Milliseconds(), Error: res.Status})
- end(res.StatusCode, res.Status, 0, 0)
- return
- }
- if rest == "/responses" && res.StatusCode >= 400 {
- msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
- res.Body = io.NopCloser(bytes.NewReader(msg))
- if len(bytes.TrimSpace(msg)) == 0 {
- // a failure with nothing said of it, which Codex shows as
- // "Unknown error" alone (#409): said where the turn went
- said := codexFailedEmpty(modelOf(body), res.Status)
- writeError(w, provider.Responses, res.StatusCode, said)
+ defer res.Body.Close()
+ if base == codexAPIBase && res.StatusCode == http.StatusUnauthorized {
+ // Codex signed in with an API key OpenAI refuses — often one a
+ // relay issued, left in ~/.codex/auth.json — and one of Codex's own
+ // models was picked, which goes out with Codex's own sign-in
+ msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
+ writeError(w, provider.Responses, res.StatusCode, codexKeyRefused(msg))
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
- Provider: "openai", Agent: agentOf(r), Kind: callKind(r.Header), Status: res.StatusCode,
- Millis: time.Since(start).Milliseconds(), Error: said})
- end(res.StatusCode, said, 0, 0)
+ Provider: "openai", Agent: agentOf(r), Status: res.StatusCode,
+ Millis: time.Since(start).Milliseconds(), Error: res.Status})
+ end(res.StatusCode, res.Status, 0, 0)
return
}
- }
- for k, vs := range res.Header {
- if !hopHeader(k) {
- w.Header()[k] = vs
- }
- }
- modelsEtag(w.Header())
- w.WriteHeader(res.StatusCode)
- var sniff *usageSniffer
- if rest == "/responses" {
- ct := res.Header.Get("Content-Type")
- if ct == "" && streamOf(body) { // the ChatGPT backend streams without saying so
- ct = "text/event-stream"
+ if rest == "/responses" && res.StatusCode >= 400 {
+ msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
+ res.Body = io.NopCloser(bytes.NewReader(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)
+ handOn(res.StatusCode, said, 0)
+ end(res.StatusCode, said, 0, 0)
+ s.codexFallBack(w0, r, body0, kept)
+ return
+ }
+ if len(bytes.TrimSpace(msg)) == 0 {
+ // a failure with nothing said of it, which Codex shows as
+ // "Unknown error" alone (#409): said where the turn went
+ said := codexFailedEmpty(modelOf(body), res.Status)
+ failWith(res.StatusCode, said)
+ s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
+ Provider: "openai", Agent: agentOf(r), Kind: callKind(r.Header), Status: res.StatusCode,
+ Millis: time.Since(start).Milliseconds(), Error: said})
+ end(res.StatusCode, said, 0, 0)
+ return
+ }
}
- sniff = newSniffer(provider.Responses, ct)
- }
- f, _ := w.(http.Flusher)
- buf := make([]byte, 32<<10)
- var refusal []byte // what OpenAI said, of a request it turned away
- for {
- n, err := res.Body.Read(buf)
- if n > 0 {
- if captureTitle {
- titleReply.add(buf[:n])
+ // a stream that may still be asked again, or whose Codex has the
+ // stream's headers already, goes through a holdWriter: the frames
+ // before a reply held, its reasoning and text let through as they
+ // come, an error before them held for the turn to be asked again
+ out := w
+ var hw *holdWriter
+ if overload && streams && (busyAgain < lastRetries || kept.sent || s.codexFallsBack(modelOf(body), body)) {
+ hw = newHoldWriter(w, true)
+ hw.alive, hw.streams, hw.ctx, hw.stop = kept, true, r.Context(), cancel
+ // reasoning goes to Codex at once, as it always went
+ hw.thinkingShown = true
+ out = hw
+ }
+ for k, vs := range res.Header {
+ if !hopHeader(k) {
+ out.Header()[k] = vs
}
- if sniff != nil {
- sniff.write(buf[:n])
- first.see(buf[:n])
- tools.add(buf[:n])
+ }
+ if hw != nil && res.StatusCode < 400 && res.Header.Get("Content-Type") == "" {
+ // the ChatGPT backend streams without saying so: held as the
+ // stream it is
+ out.Header().Set("Content-Type", "text/event-stream")
+ }
+ modelsEtag(out.Header())
+ out.WriteHeader(res.StatusCode)
+ stopWatch := func() {}
+ if hw != nil {
+ stopWatch = hw.watch()
+ }
+ if rest == "/responses" {
+ ct := res.Header.Get("Content-Type")
+ if ct == "" && streams { // the ChatGPT backend streams without saying so
+ ct = "text/event-stream"
}
- if res.StatusCode >= 400 && len(refusal) < 8<<10 {
- refusal = append(refusal, buf[:n]...)
+ sniff = newSniffer(provider.Responses, ct)
+ }
+ f, _ := out.(http.Flusher)
+ buf := make([]byte, 32<<10)
+ refusal = nil
+ for {
+ n, err := res.Body.Read(buf)
+ if n > 0 {
+ if captureTitle {
+ titleReply.add(buf[:n])
+ }
+ if sniff != nil {
+ sniff.write(buf[:n])
+ first.see(buf[:n])
+ tools.add(buf[:n])
+ }
+ if res.StatusCode >= 400 && len(refusal) < 8<<10 {
+ refusal = append(refusal, buf[:n]...)
+ }
+ if _, werr := out.Write(buf[:n]); werr != nil {
+ break
+ }
+ if f != nil {
+ f.Flush()
+ }
}
- if _, werr := w.Write(buf[:n]); werr != nil {
+ if err != nil {
break
}
- if f != nil {
- f.Flush()
- }
}
- if err != nil {
+ stopWatch()
+ if hw == nil {
break
}
+ hw.settle()
+ if hw.mayAskAgain() && hw.failure != 0 && !hw.refused && codexBusy(hw.failure, hw.errBody()) && r.Context().Err() == nil {
+ // the backend too busy for the turn, said on its stream before
+ // any of the reply (#1418)
+ said := "OpenAI: " + string(hw.errBody())
+ if wait, ok := passing(hw.failure, res.Header, hw.errBody(), busyAgain); ok {
+ res.Body.Close()
+ if !askAgain(hw.failure, said, wait) {
+ return
+ }
+ continue
+ }
+ if s.codexFallsBack(modelOf(body), body) {
+ res.Body.Close()
+ handOn(hw.failure, said, 0)
+ end(hw.failure, said, 0, 0)
+ s.codexFallBack(w0, r, body0, kept)
+ return
+ }
+ }
+ hw.release()
+ break
}
if sniff == nil {
return
@@ -1120,6 +1258,11 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
call := Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
Provider: "openai", Agent: agentOf(r), Kind: kind, Status: res.StatusCode,
Millis: time.Since(start).Milliseconds(), Fallback: resetNote}
+ if len(tried) > 0 {
+ // the overloads it was asked again for, before the one that answered
+ call.Fallback = strings.Join(append(tried, call.Fallback), "; ")
+ call.Fallback = strings.TrimSuffix(call.Fallback, "; ")
+ }
call.TTFT, call.FirstText = first.ms()
call.ReasoningHidden = first.hidesReasoning(provider.Responses)
uu.add(sniff.usage())
@@ -1148,6 +1291,91 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
appendUsage(r, rec)
}
+// codexBusy says a failure of the ChatGPT backend's, said as a status or
+// on a stream before any reply, is it too busy for the turn (busy): no
+// fault of the account's, nor of the request's. Its front closing on the
+// request is no overload: a large request's has its own retries
+// (edgeSaidDrop, codexDropped), and a small one's goes to Codex as the
+// 503 it asks again for (TestCodexResetJudgedByTheBytesSent). A 429 is
+// the account's allowance or rate, which isn't outwaited in seconds.
+func codexBusy(status int, msg []byte) bool {
+ if status == http.StatusTooManyRequests || edgeSaidDrop(status, msg) || codexReset(status, msg) {
+ return false
+ }
+ return busy(status, msg)
+}
+
+// codexFallsBack says Codex's turn on one of its own models has fallbacks
+// to go on to (codexFallBack): the Codex subscription's, set in magpie, at
+// least one of them found. A turn compacting natively is the backend's to
+// answer, and goes nowhere else.
+func (s *Server) codexFallsBack(model string, body []byte) bool {
+ if model == "" || strings.Contains(model, "/") || compactionTriggerIn(body) {
+ return false
+ }
+ p, _, ok := provider.Resolve("codex/" + model)
+ if !ok || p.Account == nil || p.Account.Agent != "codex" {
+ return false
+ }
+ for _, id := range p.Fallback {
+ if _, _, ok := provider.Resolve(id); ok {
+ return true
+ }
+ }
+ return false
+}
+
+// codexFallBack serves Codex's turn on its own sign-in, which the backend
+// was too busy for however often it was asked again, from the Codex
+// subscription's fallbacks, as serve goes on to them for a turn through
+// magpie's accounts; the account itself is not asked again (handedOnOf).
+// kept is what Codex was sent while it waited: the stream's headers, once
+// it had them, which the fallback's reply follows.
+func (s *Server) codexFallBack(w http.ResponseWriter, r *http.Request, body []byte, kept *keptAlive) {
+ id := "codex/" + modelOf(body)
+ body, _ = codexInputAs(withModel(body, id), true, s.nativeCompactionFor(id))
+ s.serve(w, r.WithContext(context.WithValue(r.Context(), handedOnKey{}, kept)), provider.Responses, body)
+}
+
+// handedOnKey carries, in a request codexFallBack hands on, what its
+// agent was sent while it waited.
+type handedOnKey struct{}
+
+// handedOnOf is what the agent of a request codexFallBack handed on was
+// sent while it waited, nil for any other request.
+func handedOnOf(r *http.Request) *keptAlive {
+ k, _ := r.Context().Value(handedOnKey{}).(*keptAlive)
+ return k
+}
+
+// fallbacksOnly is cands without model's own on provider id, pl with
+// them: a request handed on to the fallbacks (codexFallBack) after the
+// account was asked as often as it is asked.
+func fallbacksOnly(cands []candidate, pl planned, id, model string) ([]candidate, planned) {
+ own := func(c candidate) bool { return c.p.ID == id && c.model == model }
+ var kept []candidate
+ var order []Weighed
+ for i, c := range cands {
+ if !own(c) {
+ kept = append(kept, c)
+ order = append(order, pl.order[i])
+ }
+ }
+ cands, pl.order = kept, order
+ pl.held = slices.DeleteFunc(slices.Clone(pl.held), own)
+ pl.capped = slices.DeleteFunc(slices.Clone(pl.capped), own)
+ var unlisted []candidate
+ var unlistedW []Weighed
+ for i, c := range pl.unlisted {
+ if !own(c) {
+ unlisted = append(unlisted, c)
+ unlistedW = append(unlistedW, pl.unlistedW[i])
+ }
+ }
+ pl.unlisted, pl.unlistedW = unlisted, unlistedW
+ return cands, pl
+}
+
// codexServed is who a relay through codexUpstreamOn is recorded as.
// Codex's own ChatGPT sign-in is the codex account, and a compaction
// signed by another of its accounts (compactOn) is that account, so the
diff --git a/internal/gateway/codex_one_account_overload_test.go b/internal/gateway/codex_one_account_overload_test.go
new file mode 100644
index 000000000..8fd149771
--- /dev/null
+++ b/internal/gateway/codex_one_account_overload_test.go
@@ -0,0 +1,244 @@
+package gateway
+
+import (
+ "bytes"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// overloadedStatus is the ChatGPT backend's overload said as a status.
+const overloadedStatus = `{"error":{"type":"server_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`
+
+// codexAnswer is a turn the ChatGPT backend answers, its frames first.
+var codexAnswer = sse(append(slices.Clone(overloadedLead),
+ `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"hello"}`,
+ `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":9,"output_tokens":2}}}`)...)
+
+// overloadedBackend stands in for the ChatGPT backend, answering the n-th
+// request (from 0) with replies[n], the last one after that; it keeps
+// every request's body and headers. A 200 goes with no Content-Type, as
+// the backend sends it.
+type overloadedBackend struct {
+ replies []reply
+ mu sync.Mutex
+ bodies [][]byte
+ heads []http.Header
+}
+
+func (o *overloadedBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ o.mu.Lock()
+ i := min(len(o.bodies), len(o.replies)-1)
+ o.bodies = append(o.bodies, b)
+ o.heads = append(o.heads, r.Header.Clone())
+ o.mu.Unlock()
+ x := o.replies[i]
+ if x.ctype != "" {
+ w.Header().Set("Content-Type", x.ctype)
+ } else {
+ w.Header()["Content-Type"] = nil
+ }
+ w.WriteHeader(x.code)
+ io.WriteString(w, x.body)
+}
+
+func (o *overloadedBackend) asked() int {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ return len(o.bodies)
+}
+
+// oneCodexAccount is Codex signed in to ChatGPT with its one account and
+// nothing else on in magpie, the ChatGPT backend o: a turn on one of
+// Codex's own models is relayed as it came (codexAccounts), nobody else
+// to ask.
+func oneCodexAccount(t *testing.T, o *overloadedBackend) {
+ t.Helper()
+ codexSignedIn(t)
+ up := httptest.NewServer(o)
+ t.Cleanup(up.Close)
+ was := provider.CodexBase
+ provider.CodexBase = up.URL + "/backend-api/codex"
+ t.Cleanup(func() { provider.CodexBase = was })
+ pause := retryPause
+ retryPause = time.Millisecond
+ t.Cleanup(func() { retryPause = pause })
+ if id, routed := codexAccounts(httptest.NewRequest("POST", CodexPath+"/responses", nil), "gpt-5.5"); routed {
+ t.Fatalf("one account goes through routing as %s", id)
+ }
+}
+
+const oneAccountTurn = `{"model":"gpt-5.5","stream":true,"input":"ping"}`
+
+// noneResting says nothing rests after an overload: no account is at
+// fault for it.
+func noneResting(t *testing.T) {
+ t.Helper()
+ restingUntil.Lock()
+ defer restingUntil.Unlock()
+ if len(restingUntil.m) > 0 {
+ t.Fatalf("rested for an overload: %v", restingUntil.m)
+ }
+}
+
+// With one ChatGPT account, Codex's own turn the backend says it is too
+// busy for (529) is asked again of the same account, after the pause the
+// accounts loop takes, as Codex sent it (夜松云 on Discord): the answer
+// reaches Codex, nothing of the failure.
+func TestCodexOneAccountOverloadAskedAgain(t *testing.T) {
+ o := &overloadedBackend{replies: []reply{{529, "application/json", overloadedStatus}, {200, "", codexAnswer}}}
+ oneCodexAccount(t, o)
+ code, body := codexPost(t, oneAccountTurn)
+ if code != 200 || !strings.Contains(body, "hello") || strings.Contains(body, "overloaded") || o.asked() != 2 {
+ t.Fatalf("%d %q, asked %d times", code, body, o.asked())
+ }
+ // the turn goes again as it went: the same bytes, the same sign-in
+ if !bytes.Equal(o.bodies[0], o.bodies[1]) {
+ t.Fatalf("asked again with another body:\n%s\n%s", o.bodies[0], o.bodies[1])
+ }
+ for _, k := range []string{"Authorization", "Chatgpt-Account-Id"} {
+ if o.heads[0].Get(k) == "" || o.heads[0].Get(k) != o.heads[1].Get(k) {
+ t.Fatalf("%s: %q then %q", k, o.heads[0].Get(k), o.heads[1].Get(k))
+ }
+ }
+ noneResting(t)
+}
+
+// The ChatGPT backend's overload as it says it on a turn (#1418): a 200,
+// the frames before a reply, then server_is_overloaded. Codex doesn't ask
+// again for it; held while it has only those frames, the turn is asked
+// again, and Codex has the answer and nothing of the failure.
+func TestCodexOneAccountStreamOverloadAskedAgain(t *testing.T) {
+ failed := reply{200, "", sse(append(slices.Clone(overloadedLead), overloadedFailed)...)}
+ o := &overloadedBackend{replies: []reply{failed, {200, "", codexAnswer}}}
+ oneCodexAccount(t, o)
+ code, body := codexPost(t, oneAccountTurn)
+ if code != 200 || !strings.Contains(body, "hello") || strings.Contains(body, "server_is_overloaded") || o.asked() != 2 {
+ t.Fatalf("%d %q, asked %d times", code, body, o.asked())
+ }
+ // the answer's frames go with it, once
+ if strings.Count(body, "event: response.created") != 1 {
+ t.Fatalf("frames: %q", body)
+ }
+ noneResting(t)
+}
+
+// An overload that lasts is asked again as often as the accounts loop
+// asks its last account (lastRetries), and then Codex has the backend's
+// own failure, as it had before.
+func TestCodexOneAccountOverloadBounded(t *testing.T) {
+ for name, failed := range map[string]reply{
+ "status": {529, "application/json", overloadedStatus},
+ "stream": {200, "", sse(append(slices.Clone(overloadedLead), overloadedFailed)...)},
+ } {
+ t.Run(name, func(t *testing.T) {
+ o := &overloadedBackend{replies: []reply{failed}}
+ oneCodexAccount(t, o)
+ code, body := codexPost(t, oneAccountTurn)
+ if o.asked() != 1+lastRetries || !strings.Contains(body, "server_is_overloaded") {
+ t.Fatalf("%d %q, asked %d times", code, body, o.asked())
+ }
+ if code != failed.code {
+ t.Fatalf("status %d, the backend's %d", code, failed.code)
+ }
+ noneResting(t)
+ })
+ }
+}
+
+// With fallbacks set on the Codex subscription, an overload that lasts
+// goes on to them once the account was asked again, as a turn through
+// magpie's accounts does; without the account asked any more.
+func TestCodexOneAccountOverloadFallsBack(t *testing.T) {
+ for name, failed := range map[string]reply{
+ "status": {529, "application/json", overloadedStatus},
+ "stream": {200, "", sse(append(slices.Clone(overloadedLead), overloadedFailed)...)},
+ } {
+ t.Run(name, func(t *testing.T) {
+ o := &overloadedBackend{replies: []reply{failed}}
+ oneCodexAccount(t, o)
+ fb := &scripted{replies: []reply{{200, "text/event-stream", sse(
+ `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"from the fallback"}`,
+ `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"f1","status":"completed","output":[]}}`)}}}
+ responsesOn(t, "fb", fb)
+ if err := provider.Save(provider.Provider{ID: "codex", Fallback: []string{"fb/m"}}); err != nil {
+ t.Fatal(err)
+ }
+ code, body := codexPost(t, oneAccountTurn)
+ if code != 200 || !strings.Contains(body, "from the fallback") || strings.Contains(body, "server_is_overloaded") {
+ t.Fatalf("%d %q", code, body)
+ }
+ if o.asked() != 1+lastRetries || fb.n != 1 {
+ t.Fatalf("ChatGPT asked %d times, the fallback %d", o.asked(), fb.n)
+ }
+ noneResting(t)
+ })
+ }
+}
+
+// A usage limit isn't an overload: with one account it still goes to
+// Codex as the backend said it, asked once (TestCodexOwnModelOneAccountRelayed),
+// and so does a refusal of the request.
+func TestCodexOneAccountRefusalNotAskedAgain(t *testing.T) {
+ o := &overloadedBackend{replies: []reply{{400, "application/json", `{"error":{"type":"invalid_request_error","message":"Unsupported parameter: foo"}}`}}}
+ oneCodexAccount(t, o)
+ code, body := codexPost(t, oneAccountTurn)
+ if code != 400 || !strings.Contains(body, "Unsupported parameter") || o.asked() != 1 {
+ t.Fatalf("%d %q, asked %d times", code, body, o.asked())
+ }
+}
+
+// A backend that is slow to say it is overloaded (#1418: 36s after its
+// frames) has Codex kept alive meanwhile with the stream's headers and
+// comments, none of the failed tries; what follows goes on in that
+// stream: the last try's failure as it was said, or the fallback's reply.
+func TestCodexOneAccountOverloadKeptAlive(t *testing.T) {
+ k, w := keepHeldAfter, watchEvery
+ keepHeldAfter, watchEvery = 20*time.Millisecond, 5*time.Millisecond
+ t.Cleanup(func() { keepHeldAfter, watchEvery = k, w })
+ for _, withFallback := range []bool{false, true} {
+ codexSignedIn(t)
+ slow := &slowFrames{wait: 150 * time.Millisecond, then: func(int) string { return sse(overloadedFailed) }}
+ up := httptest.NewServer(slow)
+ t.Cleanup(up.Close)
+ was := provider.CodexBase
+ provider.CodexBase = up.URL + "/backend-api/codex"
+ t.Cleanup(func() { provider.CodexBase = was })
+ pause := retryPause
+ retryPause = time.Millisecond
+ t.Cleanup(func() { retryPause = pause })
+ fb := &scripted{replies: []reply{{200, "text/event-stream", sse(
+ `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"from the fallback"}`,
+ `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"f1","status":"completed","output":[]}}`)}}}
+ if withFallback {
+ responsesOn(t, "fb", fb)
+ if err := provider.Save(provider.Provider{ID: "codex", Fallback: []string{"fb/m"}}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ code, body := codexPost(t, oneAccountTurn)
+ slow.mu.Lock()
+ asked := slow.n
+ slow.mu.Unlock()
+ if code != 200 || !strings.Contains(body, ": keepalive") || asked != 1+lastRetries {
+ t.Fatalf("fallback %v: %d %q, asked %d times", withFallback, code, body, asked)
+ }
+ if withFallback {
+ if !strings.Contains(body, "from the fallback") || strings.Contains(body, "server_is_overloaded") || fb.n != 1 {
+ t.Fatalf("fallback: %q, asked %d times", body, fb.n)
+ }
+ } else if strings.Count(body, "server_is_overloaded") != 1 || strings.Count(body, "event: response.created") != 1 {
+ // the last try's own failure, once, and none of the others'
+ t.Fatalf("no fallback: %q", body)
+ }
+ noneResting(t)
+ }
+}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index b42a67796..dcd6568df 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -1977,6 +1977,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
} else {
cands, pl = s.plan(p, model, from)
+ if handedOnOf(r) != nil {
+ // Codex's own sign-in, asked as often as it is asked: only
+ // the fallbacks are left (codexFallBack)
+ cands, pl = fallbacksOnly(cands, pl, p.ID, model)
+ }
if provider.IsFastPick(agent, p.ID+"/"+model) {
// the agent's pick of it is sent in its vendor's fast mode
// (#954), as a group's member may be; its fallbacks, other
@@ -2278,6 +2283,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
autoReset := resetFirst != nil // a Codex or Claude reset looked at, once a request
// what the tries' held streams sent the agent ahead of a reply (#751)
kept := &keptAlive{proto: from, told: start}
+ if k := handedOnOf(r); k != nil {
+ // Codex's own sign-in waited for first, with Codex kept alive
+ kept = k
+ }
var sentMs int64 // ms from the request to its answering try going to the vendor
// of it, magpie's own, the tries that failed first and the wait for a
// slot (usage.Record.Own, Retried, Queued: #1532)