diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 37810a609..39c4c4ef3 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -172,7 +172,7 @@ recorded as a prediction failure (`noPrediction`). - A rule's hours and days (`Rule.Time`, `provider.TimeWindow`) are read on `ruleClock` in the zone they were set in (`TimeWindow.Zone`, an IANA name; gaubeebangeel on X: magpie on a cloud server in UTC, its user in Beijing, the hours 8 off). The GUI saves the browser's zone when the hours or days are changed in the editor and leaves a rule's zone alone otherwise; the CLI (`magpie group rule add … time=09:00-18:00@Asia/Shanghai` or `tz=`) and the TUI save the one typed, or this computer's (`provider.LocalZone`: `$TZ`, `time.Local`, the `/etc/localtime` link) when it has an IANA name. A window with no zone, every one saved before zones were kept, stays on magpie's own clock. A zone magpie doesn't know is refused on save (`TimeWindow.clean`), and one in a file edited by hand makes the window never hold (`zoneOf`): the rule is as if absent, never always on and never hours off. Zones come from Go's embedded tzdata, so Windows knows them too. `/api/groups` gives magpie's clock (`clock`: its zone and offset in seconds), and when it differs from the hours' zone the Routing page tells the zone beside them, on the group's rules and in the editor (`zoneNote` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)): the zone's name, or the server's offset for hours with none. `TestRuleTimeWindowInItsZone`, `TestRuleTimeWindowInItsZoneAtTurnStart`, `TestRuleTimeWindowUnknownZone`, `TestParseRuleTimeZone`, `TestGroupRuleTimeZoneCmd`, `routing-time-zone.test.cjs`. 3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`); a Free plan's call is capped as any other (`TestAccountCapHoldsAutoReviewOnAFreePlan`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`). A Codex account let spend its credits is never held or refused for its week, so before a try goes to one whose week its last reading says is used up and that spends a reset when its week runs out, `resetBeforeCredits` spends one first, one a week at most, in routing and in the relay (`resetBeforeCreditsOn`); a reset is free and credits cost money (tongzhenbao on X, `TestCodexResetBeforeCredits`). Otherwise a capped or barred set returns `cappedError` or `barredError`. A provider with Stop at the caps on (`CapStop`, plugins#349) answers that 429 instead of going on to its fallbacks when every primary account is held (`plan`, `TestCapStopSkipsTheFallbacks`); off, the default, the fallbacks take it as before. A careful provider (`CapCareful`, plugins#349, off by default, `cap_careful.go`) has `readCareful` read a capped account's usage again before planning when its reading is over 15s old within 5 points of a cap, or over 5m old at all, waiting at most 10s and asking a failed account again at most every 15s; `capHold` then holds an account whose usage was never read, whose last read failed or whose reading is still that old (`carefulDoubt`, `Weighed.Unread` in the trace), as one at its cap is: unknown is not spent (`TestCarefulHoldsWhatItCantTell`, `TestCarefulReadsAgainNearTheCap`, `TestCarefulEveryAccountUnread`, `TestCarefulOffByDefault`). Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. 4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats: doubled each time, up to `longestRetry` (10 minutes) for a failure and `longestRateRest` (30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's own `restCap` in minutes (`Provider.RestCapOr`, at most `MaxQuotaRest`; `magpie provider rest-cap 4h`, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (`TestOwnRestCap`). An error `failure` reads as out of credit is `retryable` at any 4xx, so the next account or member is asked and this one rests as credit; before, a 400 or 422 counted only by `quotaWords`, and SuperMagic's 400 「您的可用积分已不足…通过「充值」通道补充积分」 went to the agent with another account of 6,467 points unasked, the empty one never rested (#4095, mycf_711; `TestCredit400MovesToTheNextAccount`). A shape refusal that also says so (`creditWords` in `shapeRefused`) is the credit it says. The failure count is kept per key or account (`restKey`), and any of its models' answers clears it (`served`). Each model's own count (`restID`) is kept beside it and cleared only by that model's answer (`servedCandidate`): once it is past the account's, a sibling model answered since it last did, so the failure is the model's and it climbs its own ladder and rests alone, its siblings still served (#2241, weizsw: an Antigravity seat's gemini-3.5-flash-lite rested a minute 41 times of 43 while gemini-3.8-flash kept answering; `TestModelLadderClimbsPastSiblingAnswers`). Every model failing with no answer between still climbs the account's ladder and rests the account, and a candidate naming no model has the account's count alone. `rest-cap off` (`provider.RestCapOff`, `restCap: -1`) is for a relay or account pool whose unknown errors come now and then and pass by the next request (Kismet Alan on Discord): a failure that says nothing of why (`failOther`: a 5xx, a dropped connection) then rests nobody and isn't counted, its trace rest `by: "off"` with no time left. A 401 or 403, a model not served, an account's window full, a rate limit (magpie's own 30-minute cap), quota, credit and a restriction still rest it as before (`TestRestCapOff`). A provider the user added can be set never to rest for a limit instead (`provider.LimitRestOff`, `limitRestOff` in providers.json; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default): a refusal `restAfterMarked` reads as out of quota, out of credit or rate limited, and any 429, then rests nothing, isn't counted or sunk, and is `by: "off"`; `restDrawer` rests no image model of it. The next request is sent to it as usual. It is for a relay whose limits pass in a moment (zoecats on Discord: a local aggregator said "quota exhausted" while it switched upstreams, and magpie answered itself for 30 minutes; `TestLimitRestOffKeepsAsking`, `TestLimitRestOffRestsNothingForALimit`). A 401, a model not served and a plain failure still rest it. The shortest cap otherwise is a minute, the first rest; `rest-cap 30s` is turned away and names `off`. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A Google account's Code Assist (the Antigravity and Gemini CLI built-ins) answering 404 `NOT_FOUND` ("Requested entity was not found.") rests its model the same way, as its endpoint is the same for every model (`codeAssistModelMissing`; Packing1 on Discord: Argon, listed for a Google AI Pro account, answered 404 and rested the whole account; `TestCodeAssistMissingModelRestsTheModel`). A refusal for want of quota, credit or rate, for an account its vendor restricted, or for a verify it asks of its account there, from another computer's magpie (a Remote magpie provider, LAN share) rests only the model it was about (`remoteModelRest`, keyed by `restID`, in `restAfterMarked` and `rateRest`): that magpie serves each of its models from its own providers and rests them itself, so one out of quota there says nothing of the others (bigsteven on Discord: a 429 for one model rested every model on the remote for the 3 hours it named, so a group never moved on to the remote's other models; `TestRemoteMagpieQuotaRestsTheModel`, `TestRemoteMagpieRestrictedRestsTheModel`). Another magpie added by hand, as an OpenAI-compatible provider of the user's own name rather than the preset, is read as one by its reply: a magpie names the provider that answered or held it (`X-Magpie-Provider`, `providerHeader`; `noteMember`, also on a `quotaHeld` or `verifyHeld` answer), as no vendor does, and `keepRetry` notes it as `answeredThereHeader`, since this magpie writes its own provider into the same header of its reply and the note is kept from the client (lagrangepoint1813 on Discord: "Remote Magpie: Claude Code: You've hit your session limit" answered every model of it, from `quotaHeld`, for the five hours it named; `TestAnotherMagpieAddedByHandRestsTheModel`, asked there and held there). Its key refused, the computer unreachable, or the key's own limit there (`keyLimited`'s 429, which carries `X-Magpie-Limit-Reset`, `remoteKeyLimitHeader`), still rests it whole: #2077's reporter had a Claude Code session limit on the other magpie refuse its Qoder models here (`TestRemoteMagpieRestsTheModel`, two gateways over HTTP; `TestRemoteMagpieKeyLimitRestsTheKey`). The held try keeps that marker only as a note of magpie's own (`keepRetry` sets `keyLimitThereHeader`, which `holdWriter` never passes on), so the rest is whole however the 429 came, and the marker never reaches the agent or a magpie this one answers, which would read it as this magpie's own key limit (#2791, ggbdpq; `TestRemoteMagpieKeyLimitRestsTheRemote`, `TestRemoteMagpieKeyLimitMarkerStaysHere`). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A 400 or 422 that says this upstream's API can't take the request's shape (`shapeWords`: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870), or that it is served on another API than the one asked (`wrongEndpoint`, once the member has tried every API it has a URL for: #2670, a relay with a Chat URL alone refusing tools with reasoning and `none` too), rests nobody: the next candidate is asked once (`shapeRefused`, `failShape`), and the last one's error reaches the agent. A request missing what every API requires ("field required") isn't one, nor is a 200 that mentions it. Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: ","type":"invalid_request_error"}`, a 400, or a 422 before) is handled the same way: it turns away a request whose history and asked-for output together are over a limit below the model's listed context (the reporter's A/B: one ~748K-token agent conversation answered 200 with `max_completion_tokens` 64000 and this 400 with 384000, the model's listed max output), which another member's model may take, and the key is fine (#2313, `TestGroupFailsOverCommandCodesBare400`). Its overflow, which names the model's context length before the trace id, and an error that names a `param`, aren't one. A relay's own cap on one request's input that says so (`tooLongRe`: B.ai's 400 "Input token exceed the limit", on a 380K request under the model's 1M window; #2445, worksyang) is taken as an overflow (`overflowed`), which no word list of `retryable` matched: a group's next member that may hold the request is asked (`withRoom`, `failOverflow`), nobody rests, another account of the same model isn't asked, and with no member left the agent is told the conversation is too long, so it compacts. A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. A 401 or 403 is the exception: one that names a quota is out of quota already (`usedUpWords`), and one that doesn't is about the key or the request, so it rests on the backoff ladder whatever the reading says (plugins#243, zygs1083-dotcom: a Factory account read at 98% sat out its week over one plain 403; `TestPlain403DoesNotRestUntilTheWindow`). A plain 403 (`plainForbidden`: no quota, credit, rate, verification, restriction or model not served) from a second key or account of the same provider, model and reasoning in one request is the request refused, not each account: neither rests, the first one's rest and counted failure are taken back (`forbiddenAlike`, `unforbid`), and the provider's other mates are asked last (`matesLast`). Before, that one request walked every account of the provider into backoff (`TestPlain403OnTwoMatesRestsNeither`). One account's plain 403 alone still rests it. Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. A WorkBuddy account the vendor restricted (#1849: 403 `{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}`) rests `restrictedRest` (2 hours) as `restricted` (`failRestricted`), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's `wbExplain` and the plugin's `explained()` (0.1.17, the mover's `min`) end the error with `provider.WBRestrictedHint` (`restrictedSaid`), and the vendor's own body, its code 11140 or its words (`provider.WBRestricted`), counts only from a WorkBuddy candidate (`restrictedRefused`, `isWorkBuddy`), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. WorkBuddy's 11128 channel refusal stays `promptRefused` and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (`/api/gateway/unrest`) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest, and with Sink on puts the key back from the back of the order; the backoff count stays, and a refusal after it rests the key again the usual way. Every lift before its time (Try now, `UnrestAll` for a replaced key, `renewed` for windows that renewed) is noted by its rest key (`restingUntil.lifted`) and handed to the Routing page in the trace (`TraceState.Lifted`, `lifted` in `/api/gateway/trace`), and a lift wakes a page waiting on the trace though no route changed (`trace.lifted`). The page stops showing a rest or a sink found before its lift, wherever the lift was asked for (zoecats on Discord: Try now in the provider's editor left Routing at 429 until a restart; `TestTryNowToldToTheRoutingPage`, `routing-lifted-elsewhere.test.cjs`). With another magpie serving the gateway, Try now lifts nothing (#3555). The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). So does one said in a stream a client is answered whole from (a Codex account is streamed upstream for a `stream:false` Responses, Chat or Messages request): each decoder gives the refusal's error event status 400 and its code (`filterRefused`), a whole reply it cut is answered the refusal rather than its words so far, and Anthropic's error shape, which has no code, carries it in `refusedHeader`; before, it was answered 502 `api_error`, asked again, and each account rested (#3274). `restAfterMarked` itself rests nobody, and counts no failure, for a 400 whose error object `policyRefusal` reads as a refusal, by its code, never by words a body may echo of the request. Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. How many more candidates a refusal before any of the reply is asked of is Settings' `RefusalRetries` (`refusalAsksAgain`, counted per request in the candidate loop; a group's other members count too): unset, every one left (#248); 0, none (#1925, DD on Discord). When nobody is left, an agent on Anthropic's Messages API gets the held refusal itself, the vendor's 200 with `stop_reason` `refusal` and its `stop_details`, streamed or whole (`holdWriter.handBack`), since that is what Claude Code switches to its fallback model on; a 400 is only an API error to it. Codex and Chat clients still get `failTo`'s 400 (`refusedStatus`), which they don't ask again for. `TestRefusalRetries*` in [`refusal_retries_test.go`](../../internal/gateway/refusal_retries_test.go) cover keys, a group and the Claude subscription. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged; Codex's own `web.run` (a function in the `web` namespace, which Codex offers in place of the hosted tool on a Responses Lite model or with its standalone web search on, and runs through `/alpha/search`) counts as declaring it, since the backend refuses a request carrying both `web.run` and the hosted `web_search` (Savin on Discord, Codex 0.163.0-alpha; `TestSearchedConversationUnderWebRun`). siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. Command Code turning a model away for its Zero Data Retention setting (its plugin's switch, 0.1.14, which sends `x-cmd-zdr: 1`; magpie-community/plugins#246) is a refusal of that request's setting, not of the model or the account: the Provider API's 422 with `"code":"cmd_zdr_no_providers"` and the 400 the plugin makes of Go's error line with `"type":"cmd_zdr_no_providers"` (`zdrCoded`, matched as the error's code or type, never by its words, whose "…a different model.","type":"invalid_request_error" read as a model unserved and rested the model on the account). `keepRetry` notes it beside the error (`zdrHeader`), since the error the agent gets may keep no code (Anthropic's shape, or the 400's numeric code). It rests nobody, anywhere (`restAfterMarked` returns `by: "off"`), so the model answers as soon as the switch is off; it isn't asked of the provider's other accounts at that model, which carry the same header (`notMates`), nor again after a moment; another member, the provider's other models among them, is asked once, and with none left the agent gets Command Code's words (`TestCommandCodeZDRRefusalRestsNothing`, `TestZDRRefusalNeverRests`). Another vendor's refusal in the same words, without the code, still rests the model (`TestZDRRefusalIsCommandCodesCodeOnly`). -5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`), which a plain provider shares once its same-one retries are spent (below). When every member has failed in a way that passes (`busy`: 408, 500, 502, 503, 504 or 529 that isn't a proxy, a quota, response protection, or an upstream that answered a stream request with a whole reply, which fails the same however often it is asked (`didNotStream`; the same-one retries of `passing` leave it alone too, `TestStreamlessMemberIsAskedOnce`), or a 429 that is a short rate limit, not a plan or credit), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest()` (30 times `retryPause`, 30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on while the group's `Patience` lasts. A member of a group in the group uses the innermost that sets `Patience` (`innerPatience`, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an inner `PatienceOff` skips replan for that member (`TestNestedGroupPatienceThroughOuter`, `TestNestedGroupPatienceInnerOff`, `TestNestedGroupPatienceFallsBackToOuter`). `replanRounds` (12) is only a backstop that never comes first: the pauses alone add up to `PatienceLongest` in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; `TestPatienceIsUsedUp`). The budget is the group's `Patience`, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 is `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error; a member the vendor said is back within a second past its budget (read in whole seconds) is asked as the budget ends (`TestReporterResetFitsTheDefaultPatience`). While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider (a `provider/model` request, its accounts and fallbacks the candidates) first takes the same-one retries `passing` gives the last one left: `lastRetries` for a busy vendor, `rateRetries` for a rate limit, each pause `retryPause< patience=2m|off|default`; the provider editor shows no row for it and its save keeps it, `TestProviderSaveKeepsPatience`), unset `singlePatience` (`PatienceDefault`, 60s), counted from when the agent would have had the error, so it works with no setting and the user's value wins either way (`TestSingleProviderOwnPatienceWins`; ChatGPT's reset of a large request, `codexReset`, is left out: Codex is told it at its 503 with what may help, as `codexBusy` leaves it). A provider's own Patience is for a request to it alone: a group it is in, set or unset, keeps the group's (zoecats on Discord: a local relay's short 429 went straight to Claude Code once the few retries were spent). So a 429 whose Retry-After is 20s is waited out, the stream kept alive past `keepHeldAfter`; one of an hour, a quota, credit or plan limit, a 401 or 403, a refusal, response protection's 502 and `didNotStream` are not `busy` or don't fit the budget, and reach the agent at once as the vendor said them. Its tries are traced with `Again` alone, no `Replan` or `Patience`, so the Routing page tells it as the last one left asked again rather than as a group's members (`TestSingleProviderWaitsOutAShortRateLimit`, `TestSingleProviderPassesALongLimitThrough`, `TestSingleProviderAgentGoneInTheWait` in [`single_busy_test.go`](../../internal/gateway/single_busy_test.go)). Codex's own one-account relay (`codexUpstreamOn`, below) doesn't join it: its request is relayed unchanged outside the candidate loop, and the backend's 429 is always the plan's usage limit (`codexBusy` never retries one), so the short rate limit this waits out doesn't arise there; its overloads keep their `lastRetries` and then the subscription's fallbacks. An agent that goes away in either pause (the same-one retry's or a group's replan) ends the request there with 499: nobody is asked again, and the try whose pause it was is marked `Gone` (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (`TestAgentGoneInTheRetryPause`, `routing-agent-gone.test.cjs`). A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. A try is added to the route's `Tries` only as it is asked, so a later try is the record that the gateway went on from this one, and the Routing page tells what came of a try from that, never from where it stood in the order (#2281, xishuchkui-code: an Antigravity 502 empty reply that went on to the next account was told as "an error another account wouldn't fix, so Claude Code gets it"). The one case the record can't show is the last try left out of its allowance after an earlier failure that wasn't one, where the agent is told the earlier error: that try is marked `Earlier` (`routing-went-on.test.cjs`). +5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`), which a plain provider shares once its same-one retries are spent (below). When every member has failed in a way that passes (`busy`: 408, 500, 502, 503, 504 or 529 that isn't a proxy, a quota, response protection, or an upstream that answered a stream request with a whole reply, which fails the same however often it is asked (`didNotStream`; the same-one retries of `passing` leave it alone too, `TestStreamlessMemberIsAskedOnce`), or a 429 that is a short rate limit, not a plan or credit), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest()` (30 times `retryPause`, 30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on while the group's `Patience` lasts. A member of a group in the group uses the innermost that sets `Patience` (`innerPatience`, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an inner `PatienceOff` skips replan for that member (`TestNestedGroupPatienceThroughOuter`, `TestNestedGroupPatienceInnerOff`, `TestNestedGroupPatienceFallsBackToOuter`). `replanRounds` (12) is only a backstop that never comes first: the pauses alone add up to `PatienceLongest` in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; `TestPatienceIsUsedUp`). The budget is the group's `Patience`, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 is `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error; a member the vendor said is back within a second past its budget (read in whole seconds) is asked as the budget ends (`TestReporterResetFitsTheDefaultPatience`). The last member out of its quota or credit (not `busy`), after an earlier member failed in a way that passes, has those earlier ones asked again the same way, and rests as they did (`lastSpent`): before, the agent had the relay's moment of 503 while the relay would answer a moment on (`TestGroupRelayBlipDoesNotEndOnSpentLast`). While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider (a `provider/model` request, its accounts and fallbacks the candidates) first takes the same-one retries `passing` gives the last one left: `lastRetries` for a busy vendor, `rateRetries` for a rate limit, each pause `retryPause< patience=2m|off|default`; the provider editor shows no row for it and its save keeps it, `TestProviderSaveKeepsPatience`), unset `singlePatience` (`PatienceDefault`, 60s), counted from when the agent would have had the error, so it works with no setting and the user's value wins either way (`TestSingleProviderOwnPatienceWins`; ChatGPT's reset of a large request, `codexReset`, is left out: Codex is told it at its 503 with what may help, as `codexBusy` leaves it). A provider's own Patience is for a request to it alone: a group it is in, set or unset, keeps the group's (zoecats on Discord: a local relay's short 429 went straight to Claude Code once the few retries were spent). So a 429 whose Retry-After is 20s is waited out, the stream kept alive past `keepHeldAfter`; one of an hour, a quota, credit or plan limit, a 401 or 403, a refusal, response protection's 502 and `didNotStream` are not `busy` or don't fit the budget, and reach the agent at once as the vendor said them. Its tries are traced with `Again` alone, no `Replan` or `Patience`, so the Routing page tells it as the last one left asked again rather than as a group's members (`TestSingleProviderWaitsOutAShortRateLimit`, `TestSingleProviderPassesALongLimitThrough`, `TestSingleProviderAgentGoneInTheWait` in [`single_busy_test.go`](../../internal/gateway/single_busy_test.go)). Codex's own one-account relay (`codexUpstreamOn`, below) doesn't join it: its request is relayed unchanged outside the candidate loop, and the backend's 429 is always the plan's usage limit (`codexBusy` never retries one), so the short rate limit this waits out doesn't arise there; its overloads keep their `lastRetries` and then the subscription's fallbacks. An agent that goes away in either pause (the same-one retry's or a group's replan) ends the request there with 499: nobody is asked again, and the try whose pause it was is marked `Gone` (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (`TestAgentGoneInTheRetryPause`, `routing-agent-gone.test.cjs`). A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. A try is added to the route's `Tries` only as it is asked, so a later try is the record that the gateway went on from this one, and the Routing page tells what came of a try from that, never from where it stood in the order (#2281, xishuchkui-code: an Antigravity 502 empty reply that went on to the next account was told as "an error another account wouldn't fix, so Claude Code gets it"). The one case the record can't show is the last try left out of its allowance after an earlier failure that wasn't one, where the agent is told the earlier error: that try is marked `Earlier` (`routing-went-on.test.cjs`). ## Constraints and failure behavior @@ -198,7 +198,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 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). Only Smart reads it; Weekly pace, 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. 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 listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`. - 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`. - A subscription's account whose own model list lacks the model (`Account.Lists`: an Antigravity account's `fetchAvailableModels`, a plugin account's `models`) isn't planned while another of its accounts lists it (`perKeyBarred`'s `left`, `planned.unlisted`, the Routing page's "unlisted, skipped"). It is the next asked when every account of the subscription that lists the model has been asked and one refused it as a model it doesn't serve (`unservedTry`: `modelRefused`, or Code Assist's 404 NOT_FOUND, `codeAssistModelMissing`), before any later member or fallback (`unlistedNext`, `askUnlisted` moves its row from the route's left to its order after the one that refused). A list is fetched once and can be stale: 01huadalang's Gemini 4 was served by one Antigravity account of several, and the one whose list named it refused it with a 404 the agent got while the other could answer. The one that refused rests for that model alone. Not for another refusal (a 403, a quota), a request pinned to an account, a native compaction sealed to one, or a conversation kept strictly on one; a gateway key held to some accounts narrows the unlisted ones too (`allowedCandidates`). `TestUnlistedAccountAskedAfterModelRefused`, `TestUnlistedAccountNotAskedForOtherRefusals`. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 3245e094a..2eea83923 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3733,7 +3733,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // (a plain provider's: not ChatGPT's reset of a large request, // which Codex is told at its 503 with what may help, as Codex's // own one-account relay leaves it, codexBusy) - if _, same := passing(hw.code(), hw.header, hw.errBody(), again); last && patience > 0 && !protected && !hw.turnedAway && !hw.refused && hw.failed() && busy(hw.code(), hw.errBody()) && + // The last one left out of its allowance, after a member before it + // failed in a way that passes, has those asked again as well, and + // rests as they did: the relay's moment of 503 had the agent told + // it, or the last one's 429, while the relay would answer a moment + // on (dbydd on Discord: an in-order group of sub2api relays, a + // Codex account out of its quota last) + lastSpent := last && isGroup && len(busyNow) > 0 && !hw.passing && hw.failed() && !busy(hw.code(), hw.errBody()) && + slices.Contains([]string{failQuota, failCredit}, failure(hw.code(), hw.errBody())) + if _, same := passing(hw.code(), hw.header, hw.errBody(), again); last && patience > 0 && !protected && !hw.turnedAway && !hw.refused && hw.failed() && (busy(hw.code(), hw.errBody()) || lastSpent) && (isGroup || !codexReset(hw.code(), hw.errBody())) && (len(busyNow) > 0 || waitsOf(c.patience, patienceFallback) > 0 && !same) { // every member has failed, each in a way that passes — busy, @@ -3750,7 +3758,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if waitFrom.IsZero() { waitFrom = time.Now() } - if waitsOf(c.patience, patienceFallback) > 0 { + if waitsOf(c.patience, patienceFallback) > 0 && !lastSpent { busyNow = noteBusy(busyNow, c, hw.header) } // nor once Codex would hang up in the pause, for want of an @@ -3761,6 +3769,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } if next, wait, ok := replan(busyNow, rounds, waitFrom, patienceFallback); ok && !kept.tooQuiet(wait) { try.Fail, try.Again = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds() + if lastSpent { + rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool) + try.Fail, try.Rest = rest.Why, &rest + } if isGroup { // a plain provider's is told as the last one left // asked again: it has no members taking turns @@ -3856,10 +3868,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro continue } } - if last && !held && !hw.passing && hw.failed() && c.p.Account == nil && quotaStatus(hw.code()) && (try.Fail == failQuota || try.Fail == failCredit || failure(hw.code(), hw.errBody()) == failQuota || failure(hw.code(), hw.errBody()) == failCredit) { + if last && !held && !hw.passing && hw.failed() && quotaStatus(hw.code()) && (try.Fail == failQuota || try.Fail == failCredit || failure(hw.code(), hw.errBody()) == failQuota || failure(hw.code(), hw.errBody()) == failCredit) { // the last key left is out of its allowance: it rests as the // ones before it did, for the next request to be answered - // from the rests until the first of them is back (#1772) + // from the rests until the first of them is back (#1772). An + // account too: not resting, it stayed the one a relay's moment + // of failure went on to, and its 429 the agent's, request + // after request, while the relay before it would answer + // (dbydd on Discord). quotaHeld still holds keys alone, and + // autoReset lifts the 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 } diff --git a/internal/gateway/group_spent_last_test.go b/internal/gateway/group_spent_last_test.go new file mode 100644 index 000000000..41c0d0a1e --- /dev/null +++ b/internal/gateway/group_spent_last_test.go @@ -0,0 +1,277 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// dbydd on Discord: an in-order group whose first members are relays +// (sub2api) that are up, and whose last is a Codex subscription. Once a +// conversation has landed on Codex (its relays failed for a moment), and +// Codex's quota then answers 429, the request goes on to the relays, the +// agent never sees the 429, and the conversation stays off Codex. +func TestGroupLastMemberSpentGoesBackToEarlier(t *testing.T) { + for _, x := range []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":7200}}`) + }}, + {"rate_limit_exceeded", 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."}}`) + }}, + {"bare 429", func(w http.ResponseWriter) { + w.WriteHeader(429) + }}, + } { + t.Run(x.name, func(t *testing.T) { + codexSignedIn(t) + sticks.Lock() + sticks.m = map[string]stick{} + sticks.Unlock() + // the ChatGPT backend: answers until the quota is gone + var mu sync.Mutex + spent, codexN := false, 0 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + mu.Lock() + codexN++ + out := spent + mu.Unlock() + if out { + x.refuse(w) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`, + `data: {"type":"response.output_text.delta","delta":"pong"}`, + `data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7000,"output_tokens":1,"input_tokens_details":{"cached_tokens":6000}}}}`)) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + // the relay: down for a moment, then up + relayDown, relayN := true, 0 + relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + mu.Lock() + relayN++ + down := relayDown + mu.Unlock() + if down { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(503) + io.WriteString(w, `{"error":{"message":"upstream busy"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, grokAnswer) + })) + t.Cleanup(relay.Close) + if err := provider.Save(provider.Provider{ID: "xai", Name: "XAI", Key: "k", Models: []string{"m"}, Chat: relay.URL + "/v1"}); err != nil { + t.Fatal(err) + } + refusalGroup(t, "xai/m", "codex/gpt-5.5") + s := New() + ask := func() (int, string) { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(codexAsk)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + req.Header.Set("session_id", "thread-dbydd") + s.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.String() + } + // the relay busy: Codex answers, and the conversation is on it + for turn := range 2 { + if code, body := ask(); code != 200 || !strings.Contains(body, "pong") { + t.Fatalf("turn %d on Codex: %d %s (%+v)", turn, code, body, lastRoute(s).Tries) + } + } + // the relay is up again, and Codex's quota is gone + mu.Lock() + spent, relayDown = true, false + codexN = 0 + mu.Unlock() + for turn := range 4 { + code, body := ask() + if code != 200 || !strings.Contains(body, "hello") { + r := lastRoute(s) + t.Fatalf("turn %d after the quota ran out: %d %s\naffinity %+v\ntries %+v", turn, code, body, r.Affinity, r.Tries) + } + } + mu.Lock() + defer mu.Unlock() + if codexN > 1 { + t.Fatalf("Codex asked %d times once out (relay %d); it is asked once at most", codexN, relayN) + } + }) + } +} + +// The same group with the relay failing now and then, as relays do: a +// request it fails goes on to Codex, out of its quota, and then back to +// the relay, which answers; the agent never sees Codex's 429 nor the +// relay's moment of failure. Out of its quota, Codex rests, and the +// relay's next failure has it asked again rather than Codex. Rate +// limited for a moment, it is asked as a resting member is (probeOne). +func TestGroupRelayBlipDoesNotEndOnSpentLast(t *testing.T) { + for _, x := range []struct { + name string + spent bool // out of its quota, not limited for a moment + refuse func(w http.ResponseWriter) + }{ + {"usage_limit_reached", true, 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":7200}}`) + }}, + {"rate_limit_exceeded", false, 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."}}`) + }}, + {"bare 429", false, func(w http.ResponseWriter) { + w.WriteHeader(429) + }}, + } { + for _, blip := range []int{503, 502, 429, 500} { + t.Run(x.name+" "+http.StatusText(blip), func(t *testing.T) { + codexSignedIn(t) + sticks.Lock() + sticks.m = map[string]stick{} + sticks.Unlock() + var mu sync.Mutex + codexN, relayN := 0, 0 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + mu.Lock() + codexN++ + mu.Unlock() + x.refuse(w) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + mu.Lock() + relayN++ + fail := relayN%2 == 1 + mu.Unlock() + if fail { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(blip) + io.WriteString(w, `{"error":{"message":"upstream error"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, grokAnswer) + })) + t.Cleanup(relay.Close) + if err := provider.Save(provider.Provider{ID: "xai", Name: "XAI", Key: "k", Models: []string{"m"}, Chat: relay.URL + "/v1"}); err != nil { + t.Fatal(err) + } + refusalGroup(t, "xai/m", "codex/gpt-5.5") + s := New() + for turn := range 4 { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(codexAsk)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + req.Header.Set("session_id", "thread-dbydd") + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hello") { + r := lastRoute(s) + t.Fatalf("turn %d: %d %s\naffinity %+v\ntries %+v", turn, rec.Code, rec.Body.String(), r.Affinity, r.Tries) + } + } + mu.Lock() + defer mu.Unlock() + if x.spent && codexN > 1 { + t.Fatalf("Codex asked %d times (relay %d); out of its quota, it is asked once", codexN, relayN) + } + }) + } + } +} + +// With the group's Patience off, nobody is asked again within a request: +// the request the relay failed has the agent told so. Codex, out of its +// quota as the last one asked, rests all the same, as a key does (#1772), +// and the relay's next failure has the relay asked again, not Codex. +func TestGroupSpentLastAccountRests(t *testing.T) { + codexSignedIn(t) + sticks.Lock() + sticks.m = map[string]stick{} + sticks.Unlock() + var mu sync.Mutex + codexN, relayN := 0, 0 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + mu.Lock() + codexN++ + mu.Unlock() + 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":7200}}`) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + mu.Lock() + relayN++ + fail := relayN%2 == 1 + mu.Unlock() + if fail { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(503) + io.WriteString(w, `{"error":{"message":"upstream error"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, grokAnswer) + })) + t.Cleanup(relay.Close) + if err := provider.Save(provider.Provider{ID: "xai", Name: "XAI", Key: "k", Models: []string{"m"}, Chat: relay.URL + "/v1"}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"xai/m", "codex/gpt-5.5"}, Routing: provider.Ordered, Patience: provider.PatienceOff}); err != nil { + t.Fatal(err) + } + s := New() + for turn := range 5 { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(codexAsk)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + req.Header.Set("session_id", "thread-dbydd") + s.Handler().ServeHTTP(rec, req) + if turn > 0 && (rec.Code != 200 || !strings.Contains(rec.Body.String(), "hello")) { + r := lastRoute(s) + t.Fatalf("turn %d: %d %s\ntries %+v", turn, rec.Code, rec.Body.String(), r.Tries) + } + } + mu.Lock() + defer mu.Unlock() + if codexN > 1 { + t.Fatalf("Codex asked %d times (relay %d); out of its quota, it is asked once", codexN, relayN) + } +}