diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 9b6096eff..55fdd0b58 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -232,7 +232,7 @@ recorded as a prediction failure (`noPrediction`). - The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A biggest window its next one can't use up before it renews is passed over (`Allowance.Unreached`, `Seat.Unreached`, the trace's `unreached`): when what it has left is more than the next window, a day or longer and counted in the same unit, lets through between its own reset and the biggest one's (`Of` × the time between ÷ `Span`), what the next leaves at its reset is lost, so it ranks the account. A month holding less than its weeks add up to still ranks it while they can carry it (#1778); a Volcengine Agent Plan, 20,000 a month and 7,000 a week, goes by its week from about two weeks before its month renews (#5639, louisgreen0726; `TestMonthOutOfReachRanksByWeek`, `TestSmartSpendsAWeekTheMonthCantWait`, `TestSmartPassesAnUnreachedWindow`). Windows that tell only a share, and Ark replies with `Percent` alone, are never compared. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). When the renewals tie to the hour, Smart goes by that moment once more (`Allowance.Lapse`, `Seat.Lapse`), so of accounts renewing together (WorkBuddy's free accounts all reset at the month's end, plugin 0.1.35) the one whose credits left lapse first, after that end, goes first, and one telling none goes after (zhaocai_83020 on Discord). The trace carries both keys as Smart sorted by them, `soon` (`Allowance.Renewal`) and `lapse` (`Allowance.Lapse`) beside each window's own `renews` (`Weighed.Soon`, `Weighed.Lapse`), and the Routing page's story and rows compare those (`renewsBy`, `cmpRenews`, `firstWhy`, `behindWhy`): a credit pack ending before the month another account renews with is told as its credits expiring first, a tie broken by the lapse as that, and the order given only where every key ties (#5646, louisgreen0726; `TestTraceCarriesSmartSortKeys`, `routing-story-credits-expire.test.cjs`). A route from before `soon` is read from `renews` and `restarts`. Only Smart reads the lapse; Use before expiry, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered. - A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`. - A request's masking record is told to the app for the "Masking alert" notification (Must2333 on X, `OnMasked` in [`masked.go`](../../internal/gateway/masked.go), set by the GUI; nil under `magpie serve`), after `maskrec.Hold` and with its text around placeholders (`Snips`, `Back`) taken out. [`mask_alert.go`](../../internal/gui/mask_alert.go) keeps the records while `settings.MaskAlert` is on (off until turned on, in Settings → Usage, hidden with masking) and says only the values a record masked for the first time (`maskrec.Fresh`, [`first.go`](../../internal/maskrec/first.go): each placeholder by the key of the first record that had it, read from memory and the days kept, so a conversation's history sent again each turn, or after a restart, is not news; a value sent as written is not one masked). A burst is gathered for `maskGather` (3s) and said as one, and one is said at most every `maskGap` (1 minute), what came in between said after it. It says each kind with its count and up to two agents, never a value nor its hint; a click opens the Masking page on the latest record (`clickView`, `masking&key=`). A held-back request (`noteBlocked`) is not said; a value whose records have all aged out (30 days) is new again. `TestFreshOnlyTheFirstTime`, `TestMaskAlertFirstTimeOnly`, `TestMaskAlertNeverSaysTheValue`, `TestMaskAlertCoalesces`, `mask-alert.test.cjs`. -- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (`heldClock`: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (`creditRest`, or `quotaRest` with no `Provider.OwnQuotaRest`), is held so only once it was refused so twice in a row (`Rest.first`): a single refusal may be a moment's, and the next request, the agent's retry first, asks it again (zoecats on Discord: a local aggregator said 429 `insufficient_quota` "quota exhausted" for the moment it switched upstreams, and every request was answered from its rest of 15 or 30 minutes, which only the provider's "Rests" switch, `LimitRestOff`, let through before). Held, it is asked again a minute on (`Rest.askAt`, `fallbackCooldown`), once, and held again if refused (`Rest.asksAt`); a time the vendor named, or the user set, holds it from the first refusal to then. The rest itself stays as long as before, so the order still passes it over for a candidate that is ready. The last key left rests too when it is refused so, as the keys before it do, and so does the last account left (a Codex or other subscription account; `quotaHeld` still holds keys alone, and `autoReset` lifts the rest of an account it spends a reset of): before, an account last in an in-order group, out of its quota, was never rested, so every request a relay ahead of it failed for a moment went on to it and ended on its 429 (dbydd on Discord; `TestGroupSpentLastAccountRests`). Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (`soonestBack`, by `asksAt`), none after a key's first refusal. `TestRetryAfterALimitIsAsked`, `TestHeldLimitAskedAgainInAMinute`. A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`. +- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (`heldClock`: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (`creditRest`, or `quotaRest` with no `Provider.OwnQuotaRest`), is held so only once it was refused so twice in a row (`Rest.first`): a single refusal may be a moment's, and the next request, the agent's retry first, asks it again (zoecats on Discord: a local aggregator said 429 `insufficient_quota` "quota exhausted" for the moment it switched upstreams, and every request was answered from its rest of 15 or 30 minutes, which only the provider's "Rests" switch, `LimitRestOff`, let through before). Held, it is asked again a minute on (`Rest.askAt`, `fallbackCooldown`), once, and held again if refused (`Rest.asksAt`); a time the vendor named, or the user set, holds it from the first refusal to then. The rest itself stays as long as before, so the order still passes it over for a candidate that is ready. The last key left rests too when it is refused so, as the keys before it do, and so does the last account left (a Codex or other subscription account; `quotaHeld` still holds keys alone, and `autoReset` lifts the rest of an account it spends a reset of): before, an account last in an in-order group, out of its quota, was never rested, so every request a relay ahead of it failed for a moment went on to it and ended on its 429 (dbydd on Discord; `TestGroupSpentLastAccountRests`). Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (`soonestBack`, by `asksAt`), none after a key's first refusal. `TestRetryAfterALimitIsAsked`, `TestHeldLimitAskedAgainInAMinute`. A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key or an account resting on a 429 for the time its vendor named (`Rest.By` "retry-after" or "resets": a `Retry-After`, an `anthropic-ratelimit-*-reset` or `x-ratelimit-reset-*` header, or a refusal's `resets_in_seconds` / `resets_at`), rate limited or out of its allowance, is held the same way when every candidate left rests so (`timedHeld`, `vendorTimed`): none is asked, not even the soonest back or a lone one, and the agent is answered with the first one's error and a `Retry-After` until the first of them is back, set on the held answer too, so neither the same-one retry (`passing`) nor the patience's rounds take it for a moment's limit. Not a Codex account that spends its resets by itself (`autoReset`), nor another computer's model (`Rest.there`), nor a provider with `LimitRestOff`, which never rests for a limit. The last one left rests on such a 429 too (`vendorSaidWhen`); one naming no time rests nobody, as before. Before, a key or account limited for 300 seconds was asked again every time the agent retried, about every half a second, until the vendor flagged the accounts (hsjzg58958 on X). Codex's own sign-in, and the account a compaction goes to, are relayed outside the candidate loop (`codexUpstreamOn`): a 429 there that names its time holds that account in `codexHolds` (`noteCodexHold`), and Codex's retries are answered with ChatGPT's own refusal and a `Retry-After` till then (`writeCodexHeld`); a reset spent or a window started again lifts a hold out of allowance (`restarted`). Codex's API key isn't held: OpenAI's platform answers it. `TestRateLimitedKeysHeldUntilTheirReset`, `TestRateLimitedCodexAccountsHeldUntilTheirReset`. A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`. - A model its plugin reports busier than the user's *Busy models last* (`settings.BusyLoad`, 1 to 9999 (`BusyLoadMost`-1), past 100 for a vendor that queues, its Custom… field taking any of them, off by default; axelburks on Discord) goes behind the ready candidates, ahead of the resting ones (`restLast`, `busyOf`), and its trace row has `busy` with the load. The load comes from the plugin through `plugin.ModelLoad` (see [provider plugins](provider-plugins.md#a-models-load)); one not reported in the last 5 minutes is unknown and keeps its place. A lone candidate is asked whatever its load. A conversation it answered moves, at its next turn, to the ready one that leads (`affine`'s Why `busy`, `busyBehind`); within a turn it stays. A turn going round (`after`), a new conversation spread (`readyForNew`) or In turn (`leastHeld`) never lands on it past a ready one. When every candidate is busy, nothing moves. - A key resting after an outage that names no time is asked again in the background (`rest_probe.go`, heatonz on Discord). Behind ready keys, `probeOne` never asks it before its rest ends, though its vendor may be back in a minute. `restAfterMarked` marks the rest `Probed` when it is a key's own (not an account's or a plugin's, not one model's `restID`), `failOther` by `backoff` after a 5xx, a 408 or no connection, with no Retry-After or reset header, at a provider whose `List` asks over the network (`Provider.ListAsks`), and long enough for a first ask. `keepProbingRests`, started in `ListenAndServe`, then asks the vendor's model list with that key through its proxy (`Provider.List`, which saves nothing) 1, 2, 5 and then every 10 minutes into the rest, while it is the same rest. When the list answers, the rest is lifted as Try now lifts it (`liftedLocked`, `unsink`, the trace's lift). Not asked: rate limits (a list answers while the chat endpoint still refuses, and lifting one early would undo Sink), quota, credit, a Retry-After or reset, a refused key (401, 403, 400), restrictions and verification, each of which ends on its own time or the vendor's. A key a probe lifted that fails again within 30 minutes isn't asked again until it answers a request (`probeMissed`, `probeAnswered` in `served`): the list answered for the vendor, not for its chat. Only the loop's own `Server` asks (`restProbes.asking`), so a test's `Server` never reaches the network. The cost is one list per resting key per step, never one per request. The key list (`KeyRest.Probed`) and Routing's words for the try (`restHow`) add "checked in the background, back as soon as it answers". `TestRestProbeLiftsAKeyBackUp`, `TestRestProbeLeavesOtherRests`, `TestRestProbeOnlyByARunningLoop`, `rest-probed.test.cjs`. - A provider whose keys are on different plans (`KeyAccount.Plan`, `PlansMixed`; yckonnnn on X) sends each key to its plan's endpoints: every key path takes its copy through `WithKey`, which moves it there (`atKeyPlan`), on the first try and on a failover alike. `perKeyBarred` leaves out a key whose plan's list lacks the model (`PlanServing`: a pay-as-you-go model id at the Agent Plan's endpoint only answers 404), not shown in the trace; only when no key's plan has it are those keys asked. Embeddings and drawing go through the same `perKeyBarred` and `WithKey`; a video started on a mixed provider names its key in the task id (`videoStart.onKey`, `keyMark`) so its poll goes to that key's plan. `TestKeyPlansEachToItsOwnEndpoint`. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index e260c0669..e89403703 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -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) diff --git a/internal/gateway/codex_held.go b/internal/gateway/codex_held.go new file mode 100644 index 000000000..dc050548b --- /dev/null +++ b/internal/gateway/codex_held.go @@ -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())}) +} diff --git a/internal/gateway/codex_leaving_model_test.go b/internal/gateway/codex_leaving_model_test.go index 8bc8d4b21..df1977564 100644 --- a/internal/gateway/codex_leaving_model_test.go +++ b/internal/gateway/codex_leaving_model_test.go @@ -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) diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index f2cef2e93..34ecff207 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -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 diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index d412a5ca5..3bde346cc 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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 diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index 3ff4c8a8e..497c08367 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -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) { diff --git a/internal/gateway/group_test.go b/internal/gateway/group_test.go index 191d3d266..e8c4345ba 100644 --- a/internal/gateway/group_test.go +++ b/internal/gateway/group_test.go @@ -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() diff --git a/internal/gateway/rate_held_test.go b/internal/gateway/rate_held_test.go new file mode 100644 index 000000000..08ac05b02 --- /dev/null +++ b/internal/gateway/rate_held_test.go @@ -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) + }) + } + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 24040a0d8..39514ff8b 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -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 diff --git a/internal/gateway/strict_affinity_test.go b/internal/gateway/strict_affinity_test.go index 8197bc5a4..f4d3f43b3 100644 --- a/internal/gateway/strict_affinity_test.go +++ b/internal/gateway/strict_affinity_test.go @@ -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)