diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 78691a596..1e4f40c53 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -235,7 +235,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 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 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`), unless the turn has fallbacks or groups to go on to (`codexFallsBack`), which take it as they took the turn that held the account (`TestCodexHeldTurnFollowsTheGroup`); 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`. @@ -257,7 +257,7 @@ recorded as a prediction failure (`noPrediction`). - A provider can be set to be used first (hzh_1119 on Discord: ChatGPT Pro and Business come with monthly API credit, to be spent on an OpenAI API key before the subscription where both serve a model). *Use first* on a provider row's right-click (GUI `provider/usefirst`, `provider.SetUseFirst`, `Provider.UseFirst`, copied onto its accounts by `accountSettings`) makes its keys and accounts `routes.Seat.Lead`, and Smart (`leadFirst`) puts those under the spent tier (`seatTier` below 2) ahead of every other seat it weighs, each side in Smart's own order. Without it an API key, which tells no allowance, goes after every account with room. It counts where Smart weighs several providers together: a model's found group (`auto/`) or a user's group routed Smart; within one provider every seat shares it, so nothing changes. One resting is passed over as any is, so a 429 `insufficient_quota` (out of credit, a half-hour rest) or a failure moves the request on to the others. Free quota by expiry orders its paid seats with Smart and so honours it too; the other strategies don't read it. Affinity still keeps a conversation on the one that answered it. The Routing page says why (`Weighed.UseFirst`, `firstWhy`), and `behindWhy` doesn't call one behind it renewing later. `TestSmartLeadFirst`, `TestUseFirstLeadsTheGroup`, `use-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). - A refusal of where the request comes from (`regionWords`: Google's 400 "User location is not supported for the API use.", as Antigravity and Code Assist pass it on, and OpenAI's `unsupported_country_region_territory` / "Country, region, or territory not supported"; `regionRefused`) is the network's and the edge's the connection reached, not the account's. It rests no account and counts no failure (`restAfterMarked` returns `Rest.By` `off`, `Until` now), and the next try goes out on a new connection: `regionFresh` (in `upstreamTransport`, around each of its three transports, so under every request the gateway sends through `s.client`) reads the head of each failed reply, and when it matches it closes the transport's idle connections as the body closes and again before the next request (`pending`), so the HTTP/2 or keep-alive connection that drew the refusal isn't reused. The last candidate is asked again after `retryPause` (`passing`). Refused a second time for the same provider and model within a request (`regionAsked` in the serve loop), it is the place, not a connection: Google serves some models to no request from where the user is while the same account's other models answer (taoxiaoxin, #5182: Antigravity's gemini-3.8-flash refused, its Claude models answered). Then none of the provider's other accounts is asked that model (`notMates`), the last isn't asked again (`protected`), another provider or model left is, and the agent is told the vendor's words with `regionNote` (through `explained`, beside `Provider.Explain`): the vendor doesn't serve that model to requests from that region, it is no account's fault, other models may answer, and a proxy in a served region or another provider gets past it. So a refused model costs two asks a request, not one per account and retries. Before, every Antigravity account was asked on the one kept-alive connection, each refused the same and rested, and the agent got a 400, while a new connection answered 12 seconds on (#5182, ggdayup; `TestRegionRefusalDropsItsConnection`, `TestAntigravityRegionRefusalAsksTheNextOnANewConnection`, `TestAntigravityRegionRefusalAsksTheLastAgain`, `TestRegionRefusalRestsNoAccount`, `TestRegionRefusalOfTheModelEndsAfterOneMoreAsk`, `TestRegionNote`). Not covered: an HTTP/2 connection carrying another stream at that moment outlives the close until it is idle, and the close drops other vendors' idle connections too (one handshake each). A user whose region is refused gets the refusal after the one more ask, a moment later than before. -- 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/` 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<` 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`). A routing group the user built with the model in it counts as one more fallback after the subscription's own (`provider.GroupsAfter` in `codexFallsBack`, and in serve for a turn handed on), so a group of the Codex subscription first and an API after it takes the spent turn (`TestCodexOneAccountSpentGoesToItsGroup`). 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/` 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<` 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`). A routing group the user built with the model in it counts as one more fallback after the subscription's own (`provider.GroupsAfter` in `codexFallsBack`, and in serve for a turn handed on), so a group of the Codex subscription first and an API after it takes the spent turn (`TestCodexOneAccountSpentGoesToItsGroup`). Codex's auto-review, on `codex-auto-review`, which no group or fallback names, goes on where its conversation's own turns go (`codexReviewAfter`, from `codexLeads`): to the fallbacks and groups of the conversation's model, or to the magpie model it is on, as `codexFallsBack` and serve's `groupsAfter` add them (riverleaf88 on X, `TestCodexReviewSpentFollowsTheGroup`, `TestCodexReviewSpentFollowsMagpieModel`). 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. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 7fbdb1e60..dfd055cc2 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -994,6 +994,15 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st if r.Method == http.MethodPost && (rest == "/responses" || rest == "/responses/compact") { holdKey = codexHoldKey(base, on) if h, ok := codexHeld(holdKey, start); ok { + if rest == "/responses" && base == provider.CodexBase && on == nil && s.codexFallsBack(r, body0) { + // Codex's own sign-in held, and somewhere for the turn to + // go on to: the fallbacks answer, as they did the refusal + // that held it, not Codex handed that refusal again while + // it lasts (riverleaf88 on X: the turn after went on to + // the group no more, nor did the auto-review) + s.codexFallBack(w0, r, body0, &keptAlive{proto: provider.Responses, told: start, streams: streamOf(body0)}) + return + } s.writeCodexHeld(w, r, h, base, on, modelOf(body), start) return } @@ -1423,7 +1432,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st // 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) { + if overload && codexBusy(res.StatusCode, msg) && s.codexFallsBack(r, body) { // still too busy once asked again: the fallbacks answer said := provider.APIError(msg, res.Status) handOn(res.StatusCode, said, 0) @@ -1431,7 +1440,7 @@ 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) { + if overload && codexAccountOut(res.StatusCode, msg) && s.codexFallsBack(r, 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 @@ -1461,7 +1470,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st // 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)) { + if overload && streams && (busyAgain < lastRetries || kept.sent || s.codexFallsBack(r, 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 @@ -1542,7 +1551,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st } continue } - if s.codexFallsBack(modelOf(body), body) { + if s.codexFallsBack(r, body) { res.Body.Close() handOn(hw.failure, said, 0) end(hw.failure, said, 0, 0) @@ -1550,7 +1559,7 @@ 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) { + if hw.mayAskAgain() && hw.failure != 0 && !hw.refused && codexAccountOut(hw.failure, hw.errBody()) && r.Context().Err() == nil && s.codexFallsBack(r, body) { // the account out of its allowance, said on its stream before // any of the reply: the fallbacks answer said := "OpenAI: " + string(hw.errBody()) @@ -1689,7 +1698,14 @@ func codexAccountOut(status int, body []byte) bool { // least one of them found, or a routing group the user built with the // model in it (provider.GroupsAfter). A turn compacting natively is the backend's to // answer, and goes nowhere else. -func (s *Server) codexFallsBack(model string, body []byte) bool { +// +// Codex's auto-review on codex-auto-review falls back too where its +// conversation's turns would (codexReviewAfter): no group has that model, +// so with the account out and Codex routed on through a group, every +// review was handed the refusal and failed while the turns went on +// (riverleaf88 on X). +func (s *Server) codexFallsBack(r *http.Request, body []byte) bool { + model := modelOf(body) if model == "" || strings.Contains(model, "/") || compactionTriggerIn(body) { return false } @@ -1697,7 +1713,54 @@ func (s *Server) codexFallsBack(model string, body []byte) bool { if !ok || p.Account == nil || p.Account.Agent != "codex" { return false } - return len(provider.FallbackModels(p)) > 0 || len(provider.GroupsAfter(p.ID+"/"+model)) > 0 + return len(provider.FallbackModels(p)) > 0 || len(provider.GroupsAfter(p.ID+"/"+model)) > 0 || + len(s.codexReviewAfter(r, p, model, body)) > 0 +} + +// codexReviewAfter is where Codex's auto-review on codex-auto-review goes +// on to when the Codex subscription can't take it (the account out of its +// allowance, every account held at its cap), after the subscription's own +// fallbacks: where the turns of the conversation it reviews go on to. +// That conversation on one of magpie's models, the model itself, when +// magpie serves it to this caller (servedSession); on one of Codex's own, +// the routing groups the user built with that model in them +// (provider.GroupsAfter), which a turn on it goes on to. Codex asks its +// reviewer by OpenAI's name whatever the conversation is on (codex-rs +// guardian reviewer_config.rs, approval_review_preferred_model), and only +// the ChatGPT backend serves it. nil for any other request. +func (s *Server) codexReviewAfter(r *http.Request, p provider.Provider, model string, body []byte) []string { + lead := s.codexReviewLead(r, p, model, body) + if lead == "" { + return nil + } + if strings.Contains(lead, "/") { + to := s.servedSession(r, lead) + if to == "" { + return nil + } + if q, _, ok := provider.Resolve(to); ok && q.ID == p.ID && !provider.IsGroupRef(to) { + // the subscription itself, under another name: out too + return nil + } + return []string{to} + } + return provider.GroupsAfter(p.ID + "/" + lead) +} + +// codexReviewLead is the model the conversation Codex's auto-review on +// codex-auto-review through p, the Codex subscription, reviews is on: one +// of Codex's own by its bare name, or one of magpie's ids; "" for any +// other request, or a conversation magpie has seen no turn of. +func (s *Server) codexReviewLead(r *http.Request, p provider.Provider, model string, body []byte) string { + if p.ID != "codex" || p.Account == nil || p.Account.Agent != "codex" || !strings.EqualFold(strings.TrimSpace(model), provider.CodexAutoReview) { + return "" + } + lead, _, _ := s.codexLeads.lookup(r, body) + lead = strings.TrimPrefix(lead, "codex/") + if strings.EqualFold(lead, model) { + return "" + } + return lead } // codexFallBack serves Codex's turn on its own sign-in, which the backend diff --git a/internal/gateway/codex_review_spent_test.go b/internal/gateway/codex_review_spent_test.go new file mode 100644 index 000000000..e0874ff1c --- /dev/null +++ b/internal/gateway/codex_review_spent_test.go @@ -0,0 +1,129 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// Codex's auto-review of an approval, as codex-rs's guardian sends it: on +// its reviewer model, codex-auto-review, whatever the conversation is on, +// under x-openai-subagent: guardian and x-codex-guardian: reviewer. +const reviewTurn = `{"model":"codex-auto-review","stream":true,"input":"review this approval"}` + +// reviewOn posts body to s's Codex route as Codex's guardian does (guardian +// true) or as one of the conversation's own turns. +func reviewOn(s *Server, body string, guardian bool) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + if guardian { + req.Header.Set("x-openai-subagent", "guardian") + req.Header.Set("x-codex-guardian", "reviewer") + } + s.Handler().ServeHTTP(rec, req) + return rec +} + +// Codex's one ChatGPT account out of its allowance, and Codex routed on +// through a routing group of the user's with Codex's model first and an +// API after it: the conversation's turns go on to the API, and so does +// its auto-review, which asks codex-auto-review, a model no group has +// (riverleaf88 on X: "在codex耗尽额度时,即使路由到别的模型,在codex中自动审查会失败"). +// Before, the review was handed the backend's refusal, and Codex failed it. +func TestCodexReviewSpentFollowsTheGroup(t *testing.T) { + for _, x := range codexSpent { + t.Run(x.name, func(t *testing.T) { + b := &spentBackend{refuse: x.refuse} + spentAccount(t, b, false) + a := &scripted{replies: []reply{{200, "", chatSSEReply("from the group")}}} + scriptedOn(t, "a", provider.Chat, a) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"codex/gpt-5.5", "a/m"}}); err != nil { + t.Fatal(err) + } + s := New() + if rec := reviewOn(s, oneAccountTurn, false); rec.Code != 200 || !strings.Contains(rec.Body.String(), "from the group") { + t.Fatalf("turn: %d %q", rec.Code, rec.Body.String()) + } + rec := reviewOn(s, reviewTurn, true) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from the group") || strings.Contains(rec.Body.String(), "usage_limit_reached") { + t.Fatalf("review: %d %q", rec.Code, rec.Body.String()) + } + if a.n != 2 { + t.Fatalf("the group's API asked %d times, ChatGPT %d", a.n, b.n.Load()) + } + if b.n.Load() > 2 { + // the spent account isn't asked again for the review on + // the conversation's model, the group's first member + t.Fatalf("ChatGPT asked %d times", b.n.Load()) + } + }) + } +} + +// The conversation on one of magpie's models, picked in the Codex app +// beside the spent ChatGPT sign-in: its auto-review, on codex-auto-review +// through the sign-in, goes on to that model when the account is out. +func TestCodexReviewSpentFollowsMagpieModel(t *testing.T) { + for _, x := range codexSpent { + t.Run(x.name, func(t *testing.T) { + b := &spentBackend{refuse: x.refuse} + spentAccount(t, b, false) + a := &scripted{replies: []reply{{200, "", chatSSEReply("from magpie's model")}}} + scriptedOn(t, "a", provider.Chat, a) + s := New() + if rec := reviewOn(s, `{"model":"a/m","stream":true,"input":"ping"}`, false); rec.Code != 200 || b.n.Load() != 0 { + t.Fatalf("turn: %d %q, ChatGPT asked %d", rec.Code, rec.Body.String(), b.n.Load()) + } + rec := reviewOn(s, reviewTurn, true) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from magpie's model") || b.n.Load() != 1 || a.n != 2 { + t.Fatalf("review: %d %q, ChatGPT asked %d, a %d", rec.Code, rec.Body.String(), b.n.Load(), a.n) + } + }) + } +} + +// With nowhere else for the conversation to go (no fallback, no group, no +// turn of magpie's to follow), the review still has the backend's own +// refusal, as it had. +func TestCodexReviewSpentNowhereElseRelayed(t *testing.T) { + b := &spentBackend{refuse: codexSpent[0].refuse} + spentAccount(t, b, false) + a := &scripted{replies: []reply{{200, "", chatSSEReply("never")}}} + scriptedOn(t, "a", provider.Chat, a) + rec := reviewOn(New(), reviewTurn, true) + if rec.Code != 429 || !strings.Contains(rec.Body.String(), "usage_limit_reached") || b.n.Load() != 1 || a.n != 0 { + t.Fatalf("%d %q, ChatGPT asked %d, a %d", rec.Code, rec.Body.String(), b.n.Load(), a.n) + } +} + +// The account held after ChatGPT's 429 named when it is back +// (codexHolds): the next turn, and the review after it, go on to the +// group as the turn that held it did, never handed the refusal again from +// the hold while it lasts. +func TestCodexHeldTurnFollowsTheGroup(t *testing.T) { + for _, x := range codexSpent[:2] { + t.Run(x.name, func(t *testing.T) { + b := &spentBackend{refuse: x.refuse} + spentAccount(t, b, false) + a := &scripted{replies: []reply{{200, "", chatSSEReply("from the group")}}} + scriptedOn(t, "a", provider.Chat, a) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"codex/gpt-5.5", "a/m"}}); err != nil { + t.Fatal(err) + } + s := New() + for i, body := range []string{oneAccountTurn, oneAccountTurn, reviewTurn} { + rec := reviewOn(s, body, body == reviewTurn) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from the group") { + t.Fatalf("request %d: %d %q", i, rec.Code, rec.Body.String()) + } + } + if b.n.Load() != 1 || a.n != 3 { + t.Fatalf("ChatGPT asked %d times, the group's API %d", b.n.Load(), a.n) + } + }) + } +} diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 1f14e0cdf..ca0570e20 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -583,12 +583,13 @@ func (s *Server) planPaused(p provider.Provider, model string, from provider.Pro } // groupsAfter is p with the routing groups the user built that have p's -// model in them (provider.GroupsAfter) added after its own fallbacks, -// those it has already left out; ok is false when there are none to add. -func groupsAfter(p provider.Provider, model string) (provider.Provider, bool) { +// model in them (provider.GroupsAfter), then also, added after its own +// fallbacks, those it has already left out; ok is false when there are +// none to add. +func groupsAfter(p provider.Provider, model string, also ...string) (provider.Provider, bool) { var add []string - for _, id := range provider.GroupsAfter(p.ID + "/" + model) { - if !slices.Contains(p.Fallback, id) { + for _, id := range append(provider.GroupsAfter(p.ID+"/"+model), also...) { + if !slices.Contains(p.Fallback, id) && !slices.Contains(add, id) { add = append(add, id) } } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 8cdb74f34..7f5307873 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2931,7 +2931,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // the groups the user built with this model in them go on from // it, as a request to the group would (the Codex app asks // Codex's own model, never the group) - if q, ok := groupsAfter(p, model); ok { + // Codex's auto-review on codex-auto-review, which no group has, + // goes on where its conversation's turns go (codexReviewAfter) + if q, ok := groupsAfter(p, model, s.codexReviewAfter(r, p, model, body)...); ok { cands, pl = s.planPaused(q, model, from, pausedIn) } } @@ -2939,6 +2941,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // 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 lead := s.codexReviewLead(r, p, model, body); lead != "" && !strings.Contains(lead, "/") { + // and an auto-review's, on the conversation's model through + // that same sign-in, in a group it goes on to + cands, pl = fallbacksOnly(cands, pl, p.ID, lead) + } } if provider.IsFastPick(agent, p.ID+"/"+model) { // the agent's pick of it is sent in its vendor's fast mode