gateway: Codex's one account used up goes on to the Codex subscription's fallbacks
adorable_piglet on Discord: once the ChatGPT (Plus) account's quota ran
out, the Codex app couldn't send at all, and magpie never moved the turn
to the fallback they had set (their own API key, another provider).
Cause: with one ChatGPT account and nothing to route, a turn on Codex's
own sign-in is relayed as it came (codexUpstreamOn). The relay handed an
overload on to the subscription's fallbacks (codexFallBack), but a
quota, credit or rate refusal went to Codex as the backend said it, the
429 usage_limit_reached with its x-codex headers. Codex then stops.
Change: codexAccountOut names the refusals that are the account's, not
the request's: failure() quota, credit or rate, as a status or as a
stream's failure before any reply (response.failed, an error event, a
stream without Content-Type), and a 403 usage_not_included. Never a 401:
Codex renews its own sign-in on it. When the subscription has fallbacks
(codexFallsBack, never a compaction), such a refusal now goes on to them
once the credits retry and the automatic reset have been looked at, as
an overload does; the trace keeps the try's real failure kind. With no
fallback set, Codex still gets the backend's refusal.
What Codex's own client does: it greys Send from its own /wham usage
read. magpie already gets past that once the usage reading says used up
(codex.out with the app-server restart, #540, 9f641daea); this change is
the turn itself.
docs/subsystems/gateway-routing.md says it.
Run (mote, at this tree):
- go test -tags nogui ./internal/gateway -run 'TestCodexOneAccount|TestCodexOwnModel|TestCodexSpent': ok.
- New TestCodexOneAccountSpentFallsBack: all 7 codexSpent shapes red on
the old code (Codex got the 429/403 or the failed stream), green now.
TestCodexOneAccountSpentNoFallbackRelayed and
TestCodexOneAccountSignInRefusedNotFallenBack hold the no-fallback and
401 cases.
- GOOS=linux and GOOS=windows go vet ./internal/gateway: ok. gofmt clean.
- The whole internal/gateway package (-timeout 45m) was still running at
push; the result is reported separately.
Broken by hand: codexAccountOut returning false: the 7 subtests red again.
Not tried: a real used-up ChatGPT account in the real Codex app.
This commit is contained in:
@@ -225,7 +225,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- A third way, set per account, spends the credits only after everything else (gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then the subscription's credits): *Only after every other account, key and fallback* under the Usage card's *Use credits*, `magpie quota credits <account> last`, `settings.CodexCreditsLast` (`provider.CodexCreditsLast`, `SetCodexCreditsMode`; on or off clears it, and an account never in it keeps its place, so a setting saved before keeps its order). Such an account is `creditsLast` while it goes on on its credits (`spendsCredits`) and a window for the model is used up where *off* would hold it (`Allowance.CapHeld` at `WindowCaps{Credits: true}`; a call ChatGPT counts in no window, `freeOnChatGPT`, stays). `restLast` then puts it behind every candidate of the plan, the provider's fallbacks and groups included: ready, then resting, then the credits-last ones in their own order (`Weighed.CreditsLast`). Affinity doesn't keep a conversation on one while one not on its credits leads (`Affinity.Why` `credits`, `lastBehind`), within a turn too, and In turn's next pick and Smart/Pace/Least used's spreading of new sessions never bring one forward (`after`, `leastHeld`, `readyForNew`). Strict affinity keeps it, as a rule, an `X-Magpie-Account` pin and a sealed task's lead (`leadFirst`) still put theirs first. A reset is still spent before its credits when the try reaches it (`resetBeforeCredits`). Codex's own sign-in's relay has the one account and nothing to put first, so there it is as *on*. The Routing page tells each: behind the rest, first when every one is, and the conversation moved. `TestCodexCreditsLastAfterTheOthers`, `TestCodexCreditsLastAfterTheFallback`, `TestCodexCreditsLastNotKept`, `TestCodexCreditsLastMode`, `codex-credits-last.test.cjs`.
|
||||
- A fourth, set per account, spends the credits before moving to another account (jojonas_xyz on X: the account ran out, magpie moved to another by itself, and no setting kept the first one's credits in use). *On* alone lets the vendor answer on credits, but Smart and Pace still put an account at `LowShare` (90%) or `SpentShare` (98%) behind every account with room (`tier`), Drain counts it used up at `SpentShareOf(Drain)`, and `NextLogin` moves Codex's own sign-in at the spent share, credits or not. *Before moving to another account* under *Use credits* (the Usage card, the menu bar panel, and the account's ⋯ in its provider's editor), `magpie quota credits <account> first`, `settings.CodexCreditsFirst` (`provider.CodexCreditsFirst`; one of first and last at most, on or off clears it) makes an account that spends credits (`spendsCredits`) a `routes.Seat.First`: Smart, Pace and Fastest weigh it at tier 0 (`seatTier`), Drain doesn't count it spent, affinity doesn't move a conversation off it as `spent`, and `readyForNew`/`standsInFor` treat it as having room (`Weighed.CreditsFirst`). `NextLogin` keeps Codex signed in to it while one of its windows says it holds credits (`spendsFirst`); with the credits gone it moves as before. The account magpie moved Codex off says where the setting is, on its *First again once it has room* tag. `TestCodexCreditsFirstKeepsItsPlace`, `TestCodexCreditsFirstDrainStays`, `TestCodexCreditsFirstMode`, `TestCodexStaysOnAnAccountSpendingCreditsFirst`, `codex-credits-first.test.cjs`.
|
||||
- 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, and the sign-in not known to be out of its allowance, `provider.CodexUsedUpKnown`, which routes the turn as `codex/<model>` as a restarted Codex's goes) 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. The reply's `x-codex-*` windows are kept as the sign-in's usage and a `usage_limit_reached` refusal has it read again at once (`heardCodexLimits`, `codexMayBeUsedUp`), as on the accounts path. 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)).
|
||||
- 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, and the sign-in not known to be out of its allowance, `provider.CodexUsedUpKnown`, which routes the turn as `codex/<model>` as a restarted Codex's goes) 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. The account out of its allowance goes on to the same fallbacks at once, after the credits retry and the automatic reset are looked at (`codexAccountOut`: a quota, credit or rate refusal, as a status or as a stream's failure before any reply, and a 403 `usage_not_included`; never a 401, which Codex renews its sign-in on). Before that, Codex was handed the 429 with its fallbacks unused (adorable_piglet on Discord, `TestCodexOneAccountSpentFallsBack`); with none set it still is (`TestCodexOneAccountSpentNoFallbackRelayed`). Each try is a `HandedOn` usage record and a try in the trace. The reply's `x-codex-*` windows are kept as the sign-in's usage and a `usage_limit_reached` refusal has it read again at once (`heardCodexLimits`, `codexMayBeUsedUp`), as on the accounts path. 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 ChatGPT 401 that says the token sent has expired and asks for a refresh (`provider.SignInExpired`, #2973) while its `exp` is ahead renews the account's sign-in once (`provider.NoteExpiredSignIn` from `noteSignIn`), keyed on the token sent, so the next request goes with a fresh one; nothing is marked, and the request fails over as any 401 does ([Providers and accounts](providers-accounts.md), A token called expired).
|
||||
- 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.
|
||||
|
||||
@@ -1139,6 +1139,12 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
appendUsage(r, rec)
|
||||
tried = append(tried, fmt.Sprintf("openai: %d %s", status, msg))
|
||||
}
|
||||
// handOut is handOn for a try the account was out for (codexAccountOut),
|
||||
// the trace saying why as a routed try's does
|
||||
handOut := func(status int, msg string, body []byte) {
|
||||
handOn(status, msg, 0)
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1].Fail = failure(status, body) })
|
||||
}
|
||||
// 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 {
|
||||
@@ -1375,6 +1381,17 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
s.codexFallBack(w0, r, body0, kept)
|
||||
return
|
||||
}
|
||||
if overload && codexAccountOut(res.StatusCode, msg) && s.codexFallsBack(modelOf(body), body) {
|
||||
// the account out of its allowance (its credits and resets
|
||||
// looked at above): the fallbacks answer, as they do for a
|
||||
// turn through magpie's accounts, rather than Codex handed
|
||||
// the refusal (adorable_piglet on Discord)
|
||||
said := provider.APIError(msg, res.Status)
|
||||
handOut(res.StatusCode, said, msg)
|
||||
end(res.StatusCode, said, 0, 0)
|
||||
s.codexFallBack(w0, r, body0, kept)
|
||||
return
|
||||
}
|
||||
if said, ok := codexSaidNothing(rest, modelOf(body), codexWho(base, on), res, msg); ok {
|
||||
// a failure with nothing said of it, which Codex shows as
|
||||
// "Unknown error" alone (#409), or a web page Codex shows
|
||||
@@ -1483,6 +1500,16 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
return
|
||||
}
|
||||
}
|
||||
if hw.mayAskAgain() && hw.failure != 0 && !hw.refused && codexAccountOut(hw.failure, hw.errBody()) && r.Context().Err() == nil && s.codexFallsBack(modelOf(body), body) {
|
||||
// the account out of its allowance, said on its stream before
|
||||
// any of the reply: the fallbacks answer
|
||||
said := "OpenAI: " + string(hw.errBody())
|
||||
res.Body.Close()
|
||||
handOut(hw.failure, said, hw.errBody())
|
||||
end(hw.failure, said, 0, 0)
|
||||
s.codexFallBack(w0, r, body0, kept)
|
||||
return
|
||||
}
|
||||
hw.release()
|
||||
break
|
||||
}
|
||||
@@ -1587,6 +1614,25 @@ func codexRouteUnmasked(on *provider.Provider) bool {
|
||||
return unredactedRoute(*p, false, nil)
|
||||
}
|
||||
|
||||
// codexAccountOut says the ChatGPT backend turned away a turn on Codex's
|
||||
// own sign-in for the account, not the request: out of its allowance
|
||||
// (usage_limit_reached, a plan without Codex), of its credits, or rate
|
||||
// limited — what a turn through magpie's accounts goes on past to the
|
||||
// next. A 401 is never one: Codex renews its own sign-in on it.
|
||||
func codexAccountOut(status int, body []byte) bool {
|
||||
if status == http.StatusUnauthorized {
|
||||
return false
|
||||
}
|
||||
if status == http.StatusForbidden && bytes.Contains(body, []byte("usage_not_included")) {
|
||||
return true
|
||||
}
|
||||
switch failure(status, body) {
|
||||
case failQuota, failCredit, failRate:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@@ -184,9 +184,10 @@ func TestCodexOneAccountOverloadFallsBack(t *testing.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.
|
||||
// A usage limit isn't an overload: it isn't asked again, and with no
|
||||
// fallback it goes to Codex as the backend said it, asked once
|
||||
// (TestCodexOwnModelOneAccountRelayed; with a fallback,
|
||||
// TestCodexOneAccountSpentFallsBack). 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)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// spentBackend is the ChatGPT backend turning every turn away as refuse
|
||||
// does, counting what it was asked.
|
||||
type spentBackend struct {
|
||||
refuse func(w http.ResponseWriter)
|
||||
n atomic.Int32
|
||||
}
|
||||
|
||||
func (b *spentBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
b.n.Add(1)
|
||||
// no Content-Type unless refuse says one, as the backend streams
|
||||
w.Header()["Content-Type"] = nil
|
||||
b.refuse(w)
|
||||
}
|
||||
|
||||
// spentAccount is Codex signed in to ChatGPT with its one account, the
|
||||
// ChatGPT backend b, and the Codex subscription falling back to fb/m
|
||||
// when fallback is set.
|
||||
func spentAccount(t *testing.T, b *spentBackend, fallback bool) *scripted {
|
||||
t.Helper()
|
||||
codexSignedIn(t)
|
||||
up := httptest.NewServer(b)
|
||||
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 fallback {
|
||||
responsesOn(t, "fb", fb)
|
||||
if err := provider.Save(provider.Provider{ID: "codex", Fallback: []string{"fb/m"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if id, routed := codexAccounts(httptest.NewRequest("POST", CodexPath+"/responses", nil), "gpt-5.5"); routed {
|
||||
t.Fatalf("one account goes through routing as %s", id)
|
||||
}
|
||||
return fb
|
||||
}
|
||||
|
||||
// Codex's one ChatGPT account out of its allowance, the Codex subscription
|
||||
// with a fallback set in magpie (the user's own API key, another
|
||||
// provider): the turn Codex relays on its sign-in goes on to the fallback,
|
||||
// in every shape the backend says the account is out, as a turn through
|
||||
// magpie's accounts does (adorable_piglet on Discord: the Plus account's
|
||||
// quota ran out and Codex was handed the refusal, never the fallback).
|
||||
// The account is asked once; the refusal never reaches Codex.
|
||||
func TestCodexOneAccountSpentFallsBack(t *testing.T) {
|
||||
for _, x := range codexSpent {
|
||||
t.Run(x.name, func(t *testing.T) {
|
||||
b := &spentBackend{refuse: x.refuse}
|
||||
fb := spentAccount(t, b, true)
|
||||
code, body := codexPost(t, oneAccountTurn)
|
||||
if code != 200 || !strings.Contains(body, "from the fallback") || strings.Contains(body, "usage_limit_reached") ||
|
||||
strings.Contains(body, "rate_limit_exceeded") || strings.Contains(body, "usage_not_included") {
|
||||
t.Fatalf("%d %q", code, body)
|
||||
}
|
||||
if b.n.Load() != 1 || fb.n != 1 {
|
||||
t.Fatalf("ChatGPT asked %d times, the fallback %d", b.n.Load(), fb.n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// With no fallback set, Codex still has the backend's own refusal, as it
|
||||
// had (TestCodexOwnModelOneAccountRelayed): nowhere else to go.
|
||||
func TestCodexOneAccountSpentNoFallbackRelayed(t *testing.T) {
|
||||
b := &spentBackend{refuse: codexSpent[0].refuse}
|
||||
spentAccount(t, b, false)
|
||||
code, body := codexPost(t, oneAccountTurn)
|
||||
if code != 429 || !strings.Contains(body, "usage_limit_reached") || b.n.Load() != 1 {
|
||||
t.Fatalf("%d %q, asked %d", code, body, b.n.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// A sign-in the backend refuses (401) goes to Codex as it came, fallback
|
||||
// or not: Codex renews its own token on it, which a fallback's answer
|
||||
// would keep it from doing.
|
||||
func TestCodexOneAccountSignInRefusedNotFallenBack(t *testing.T) {
|
||||
b := &spentBackend{refuse: func(w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(401)
|
||||
w.Write([]byte(`{"error":{"message":"Provided authentication token is expired. Please try signing in again.","code":"token_expired"}}`))
|
||||
}}
|
||||
fb := spentAccount(t, b, true)
|
||||
code, body := codexPost(t, oneAccountTurn)
|
||||
if code != 401 || !strings.Contains(body, "token_expired") || fb.n != 0 {
|
||||
t.Fatalf("%d %q, fallback asked %d", code, body, fb.n)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user