Skip to content

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

gateway: a single provider's busy or briefly rate-limited reply is waited out, for its own Patience (zoecats)

yetoned56c14e953e6
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 46cde46f2..dbd4f692f 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -149,7 +149,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`); otherwise a capped or barred set returns `cappedError` or `barredError`. 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 <id> 4h`, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (`TestOwnRestCap`). 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 <id> 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 <id> 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`). 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: <hex>","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`). 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. 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 keeps only the same-one retries `passing` gives the last one left. 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. 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<<n` or a Retry-After of at most `longestPause` (8s). Past those, or for a Retry-After longer than `longestPause`, it is replanned the same way, its accounts taking turns as members do, for the provider's own `Patience` (`Provider.Patience`, the same values as a group's, set with `magpie provider set <id> 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
diff --git a/internal/cli/patience_cli_test.go b/internal/cli/patience_cli_test.go
new file mode 100644
index 000000000..bed79e140
--- /dev/null
+++ b/internal/cli/patience_cli_test.go
@@ -0,0 +1,30 @@
+package cli
+
+import (
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// patience= sets how long a request to the provider alone is kept while it
+// is busy (zoecats on Discord): a time up to four minutes, off, or default;
+// anything else is refused and leaves what was set.
+func TestPatiencePair(t *testing.T) {
+ var p provider.Provider
+ for _, c := range []struct {
+ v string
+ want int
+ }{
+ {"2m", 120}, {"90", 90}, {"45s", 45}, {"4m", 240}, {"off", provider.PatienceOff}, {"0", provider.PatienceOff}, {"default", 0},
+ } {
+ if err := applyPairs(&p, []string{"patience=" + c.v}); err != nil || p.Patience != c.want {
+ t.Fatalf("patience=%s: %v, got %d, want %d", c.v, err, p.Patience, c.want)
+ }
+ }
+ p.Patience = 30
+ for _, bad := range []string{"5m", "-3", "soon", "1h"} {
+ if err := applyPairs(&p, []string{"patience=" + bad}); err == nil || p.Patience != 30 {
+ t.Fatalf("patience=%s taken: %v, %d", bad, err, p.Patience)
+ }
+ }
+}
diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go
index 4ae01511d..1f5272a27 100644
--- a/internal/cli/providers_cli.go
+++ b/internal/cli/providers_cli.go
@@ -47,6 +47,10 @@ const providerUsage = `usage:
additional-tools=on sends a tool Claude Code's tool search loads to its
Responses API where it was loaded (an additional_tools item, which
keeps the cache); additional-tools=default puts it with the other tools
+ patience=2m keeps a request to it alone (not through a group) that long
+ while it is busy or briefly rate limited, asking again after a pause
+ (at most 4m); patience=off hands the agent the error at once;
+ patience=default, 1m
magpie provider key <id> <key> change the API key
magpie provider icon <id> <file|name> give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon
magpie provider fallback <id> <provider/model>… where requests go when it's out of quota or down (none clears)
@@ -1102,6 +1106,14 @@ func applyPairs(p *provider.Provider, pairs []string) error {
default:
return fmt.Errorf("additional-tools=on|default, not %q", v)
}
+ case "patience":
+ // how long a request to the provider alone is kept while it
+ // is busy, as a group's Patience (zoecats on Discord)
+ n, err := patienceArg(v)
+ if err != nil {
+ return err
+ }
+ p.Patience = n
case "user-agent", "ua":
// agent: a request goes with the User-Agent the agent that
// sent it gave, for a coding plan that serves only agents it
@@ -2028,3 +2040,30 @@ func autoIncludeCmd(rest []string) error {
fmt.Printf("%s · a newly listed model is exposed when one of these matches its id: %s\n", p.Name, strings.Join(p.AutoInclude, " "))
return nil
}
+
+// patienceArg reads patience=: off, default, or a time up to
+// provider.PatienceLongest seconds, as 90, 90s or 2m.
+func patienceArg(v string) (int, error) {
+ v = strings.ToLower(strings.TrimSpace(v))
+ switch v {
+ case "off", "no", "none", "0":
+ return provider.PatienceOff, nil
+ case "default", "":
+ return 0, nil
+ }
+ d, err := time.ParseDuration(v)
+ if err != nil {
+ n, nerr := strconv.Atoi(v)
+ if nerr != nil {
+ return 0, fmt.Errorf("patience=off|default|<time, e.g. 2m>, not %q", v)
+ }
+ d = time.Duration(n) * time.Second
+ }
+ if d == 0 {
+ return provider.PatienceOff, nil
+ }
+ if d < 0 || d > provider.PatienceLongest*time.Second {
+ return 0, fmt.Errorf("patience is at most %s, not %q", provider.PatienceLongest*time.Second, v)
+ }
+ return int((d + time.Second - 1) / time.Second), nil
+}
diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go
index b9996687b..fa4a64429 100644
--- a/internal/gateway/fallback.go
+++ b/internal/gateway/fallback.go
@@ -1446,11 +1446,13 @@ const (
// clear than a busy moment: pauses of 1, 2 and 4s, or what Retry-After
// says, under half a minute in all
rateRetries = 3
- // longestPause is the longest the vendor's Retry-After is waited for
- // before that; longer, and the agent gets the error.
- longestPause = 8 * time.Second
)
+// longestPause is the longest the vendor's Retry-After is waited for by
+// the same-one retries; longer, and a plain provider or a group waits it
+// out within its patience (replan), else the agent gets the error.
+var longestPause = 8 * time.Second
+
// retryPause is the first pause before the last one left is tried again;
// each pause after is twice the one before.
var retryPause = time.Second
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index bdbce20e3..5ac0c27c6 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -2455,8 +2455,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
var patience, patienceFallback time.Duration
if isGroup {
patienceFallback = g.Waits()
- patience = maxWaits(cands, patienceFallback)
+ } else {
+ // one provider asked for, not a group: its accounts busy are kept
+ // for its own Patience, as long by default as a group that sets
+ // none (zoecats on Discord: a relay's short 429 went straight to
+ // the agent once the few same-one retries were spent)
+ patienceFallback = waitsOf(p.Patience, singlePatience)
}
+ patience = maxWaits(cands, patienceFallback)
var busyNow []busyTry // the members of this round that failed so
rounds := 0 // the rounds they were asked again in
var waitFrom time.Time // when every member had first failed so
@@ -3486,7 +3492,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
continue
}
+ // (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()) &&
+ (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,
// overloaded, rate limited for a moment — with nothing of a
@@ -3512,7 +3522,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
memberWait = patience
}
if next, wait, ok := replan(busyNow, rounds, waitFrom, patienceFallback); ok && !kept.tooQuiet(wait) {
- try.Fail, try.Again, try.Replan, try.Patience = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds(), len(next), int(memberWait/time.Second)
+ try.Fail, try.Again = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds()
+ if isGroup {
+ // a plain provider's is told as the last one left
+ // asked again: it has no members taking turns
+ try.Replan, try.Patience = len(next), int(memberWait/time.Second)
+ }
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
skipped = append(skipped, c.label()+": "+call.Error)
rounds, busyNow = rounds+1, nil
diff --git a/internal/gateway/patience.go b/internal/gateway/patience.go
index 8c5fe4394..94a1e9e61 100644
--- a/internal/gateway/patience.go
+++ b/internal/gateway/patience.go
@@ -27,8 +27,17 @@ const didNotStream = "did not stream"
// alone, as the last one left of a plain provider is (passing), while
// another member is busy too. A streaming agent is kept alive with SSE
// comments through the pause, as through a held stream. A plain provider,
-// which the agent picked as itself, keeps the retries passing gives the
-// last one left.
+// which the agent picked as itself, is kept the same way once the retries
+// passing gives the last one left are spent, its accounts its members,
+// for its own Patience, unset singlePatience.
+
+// singlePatience is how long a request to one provider, not a group, is
+// kept once it has failed in a way that passes and the same-one retries
+// (passing) are spent: as long as a group that sets no Patience waits
+// (zoecats on Discord), unless the provider sets its own Patience (magpie
+// provider set <id> patience=), which wins. A group's, set or not, is the
+// group's.
+var singlePatience = provider.PatienceDefault * time.Second
// replanRounds is how many times the members are asked again, at most:
// a backstop that never comes before the patience does. The pauses alone
diff --git a/internal/gateway/queue_keepalive_test.go b/internal/gateway/queue_keepalive_test.go
index 6601f5928..b3b61e966 100644
--- a/internal/gateway/queue_keepalive_test.go
+++ b/internal/gateway/queue_keepalive_test.go
@@ -454,7 +454,9 @@ func TestQueuedStreamFailureIsTheStreamsError(t *testing.T) {
for _, a := range queueAsks {
t.Run(a.name, func(t *testing.T) {
one := 1
- v := &streamVendor{fail: 10, block: make(chan struct{})}
+ // failing every time it is asked: past the same-one retries
+ // and the plain provider's patience (singlePatience) too
+ v := &streamVendor{fail: 1000, block: make(chan struct{})}
gw := queueGateway(t, v, func(p *provider.Provider) { p.MaxConcurrency = &one })
first := holdSlot(t, gw, v, a.path, a.body)
code, body, _, err := askHeard(gw, a.path, a.body, first.free)
diff --git a/internal/gateway/retry_test.go b/internal/gateway/retry_test.go
index efd6d5289..5c0cb6233 100644
--- a/internal/gateway/retry_test.go
+++ b/internal/gateway/retry_test.go
@@ -197,7 +197,10 @@ func TestLastOneLeftIsTriedAgain(t *testing.T) {
fresh(t)
a = &scripted{replies: []reply{{503, "", `{"error":{"message":"down"}}`}}}
scriptedOn(t, "a", provider.Chat, a)
- if code, _ := postAs(t, New(), "", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`); code != 503 || a.n != 1+lastRetries {
+ // down for good: the same-one retries, then the rounds of its
+ // patience (singlePatience; with retryPause at 1ms the rounds'
+ // backstop comes first), then the agent has the 503
+ if code, _ := postAs(t, New(), "", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`); code != 503 || a.n != 1+lastRetries+replanRounds {
t.Fatalf("gave up with %d after %d tries", code, a.n)
}
@@ -226,7 +229,11 @@ func TestRateLimitIsWaitedOut(t *testing.T) {
{"no retry-after", limited, nil, 1, 200, 2},
{"relay's own words", `{"error":{"message":"当前分组上游负载已饱和,请稍后再试"}}`, nil, 2, 200, 3},
{"thrice", limited, nil, 3, 200, 4},
- {"too long", limited, nil, 9, 429, 1 + rateRetries},
+ // past the same-one retries, it is waited out within the plain
+ // provider's patience (zoecats on Discord), and given up on once
+ // that is spent (the rounds' backstop, with retryPause at 1ms)
+ {"past the same-one retries", limited, nil, 9, 200, 10},
+ {"never clears", limited, nil, 99, 429, 1 + rateRetries + replanRounds},
{"usage limit", `{"error":{"message":"You've hit your usage limit. Your limit resets in 5 hours."}}`, nil, 9, 429, 1},
{"no balance", `{"error":{"message":"余额不足"}}`, nil, 9, 429, 1},
{"an hour away", limited, http.Header{"Retry-After": {"3600"}}, 9, 429, 1},
diff --git a/internal/gateway/single_busy_test.go b/internal/gateway/single_busy_test.go
new file mode 100644
index 000000000..0252aa188
--- /dev/null
+++ b/internal/gateway/single_busy_test.go
@@ -0,0 +1,346 @@
+package gateway
+
+import (
+ "bufio"
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// busyUpstream answers each request with the next of its replies, the
+// last one again once they run out, and counts what it was asked.
+type busyUpstream struct {
+ mu sync.Mutex
+ replies []busyReply
+ n int
+}
+
+type busyReply struct {
+ code int
+ retryAfter string
+ body string
+}
+
+func (u *busyUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ io.ReadAll(r.Body)
+ u.mu.Lock()
+ x := u.replies[min(u.n, len(u.replies)-1)]
+ u.n++
+ u.mu.Unlock()
+ if x.retryAfter != "" {
+ w.Header().Set("Retry-After", x.retryAfter)
+ }
+ if !strings.HasPrefix(x.body, "{") {
+ w.Header().Set("Content-Type", "text/event-stream")
+ } else {
+ w.Header().Set("Content-Type", "application/json")
+ }
+ w.WriteHeader(x.code)
+ io.WriteString(w, x.body)
+}
+
+func (u *busyUpstream) asked() int {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ return u.n
+}
+
+// Anthropic's own rate limit reply.
+const rateLimited = `{"type":"error","error":{"type":"rate_limit_error","message":"Rate limited, please retry shortly"}}`
+
+// busyProvider saves provider a, served by u, alone: no group.
+func busyProvider(t *testing.T, u *busyUpstream) *Server {
+ t.Helper()
+ return busyProviderWaiting(t, u, 0)
+}
+
+// busyProviderWaiting is busyProvider with the Patience the user set.
+func busyProviderWaiting(t *testing.T, u *busyUpstream, patience int) *Server {
+ t.Helper()
+ fresh(t)
+ up := httptest.NewServer(u)
+ t.Cleanup(up.Close)
+ if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"}, Anthropic: up.URL, Patience: patience}); err != nil {
+ t.Fatal(err)
+ }
+ return New()
+}
+
+func singleAsk(stream bool) string {
+ s := "false"
+ if stream {
+ s = "true"
+ }
+ return `{"model":"a/m","max_tokens":10,"stream":` + s + `,"messages":[{"role":"user","content":"hi"}]}`
+}
+
+// scaled shrinks the waits the test goes through, keeping their order:
+// a Retry-After past the same-one retries' longestPause (8s), the pause
+// past keepHeldAfter (15s), all within singlePatience (60s).
+func scaled(t *testing.T, patience time.Duration) {
+ t.Helper()
+ lp, sp, kh, we, rp := longestPause, singlePatience, keepHeldAfter, watchEvery, retryPause
+ longestPause, singlePatience, keepHeldAfter, watchEvery, retryPause = 50*time.Millisecond, patience, 20*time.Millisecond, 2*time.Millisecond, 10*time.Millisecond
+ t.Cleanup(func() {
+ longestPause, singlePatience, keepHeldAfter, watchEvery, retryPause = lp, sp, kh, we, rp
+ })
+}
+
+// A request to one provider, not a group, whose vendor answers a short
+// rate limit — a Retry-After past what the same-one retries wait for —
+// is held and asked again once it has passed, as a group's members are
+// (zoecats on Discord: the 429 went straight to the agent). A streaming
+// agent is kept alive through the pause once it passes keepHeldAfter.
+func TestSingleProviderWaitsOutAShortRateLimit(t *testing.T) {
+ for _, stream := range []bool{true, false} {
+ name := "whole"
+ if stream {
+ name = "stream"
+ }
+ t.Run(name, func(t *testing.T) {
+ answer := anthropicAnswer
+ if !stream {
+ answer = `{"id":"m2","type":"message","role":"assistant","model":"m","content":[{"type":"text","text":"from b"}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":4}}`
+ }
+ u := &busyUpstream{replies: []busyReply{
+ {code: 429, retryAfter: "0.4", body: rateLimited},
+ {code: 200, body: answer},
+ }}
+ s := busyProvider(t, u)
+ scaled(t, 3*time.Second)
+ gw := httptest.NewServer(s.Handler())
+ t.Cleanup(gw.Close)
+ res, err := http.Post(gw.URL+"/v1/messages", "application/json", strings.NewReader(singleAsk(stream)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ var body strings.Builder
+ rd := bufio.NewReader(res.Body)
+ for {
+ line, err := rd.ReadString('\n')
+ body.WriteString(line)
+ if err != nil {
+ break
+ }
+ }
+ out := body.String()
+ if res.StatusCode != 200 || !strings.Contains(out, "from b") {
+ t.Fatalf("agent got %d %q, want the answer after the pause", res.StatusCode, out)
+ }
+ if n := u.asked(); n != 2 {
+ t.Errorf("upstream asked %d times, want 2", n)
+ }
+ alive := strings.Index(out, ": keepalive")
+ if stream && (alive < 0 || alive > strings.Index(out, "from b")) {
+ t.Errorf("no keepalive before the answer: %q", out)
+ }
+ r := lastRoute(s)
+ if len(r.Tries) != 2 || r.Tries[0].Again < 300 || r.Tries[0].Replan != 0 || r.Tries[0].Patience != 0 || r.Status != 200 {
+ t.Errorf("tries %+v: want the first asked again after its Retry-After, told as the last one left", r.Tries)
+ }
+ })
+ }
+}
+
+// A rate limit that lasts past the patience, or that is the plan's quota,
+// goes to the agent as the vendor said it, with nobody asked again: the
+// route is watched, not a duration, so a broken budget fails at once.
+func TestSingleProviderPassesALongLimitThrough(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ r busyReply
+ }{
+ {"an hour", busyReply{code: 429, retryAfter: "3600", body: rateLimited}},
+ {"quota", busyReply{code: 429, body: `{"type":"error","error":{"type":"rate_limit_error","message":"You exceeded your current quota, please check your plan and billing details"}}`}},
+ {"key refused", busyReply{code: 401, body: `{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}`}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ u := &busyUpstream{replies: []busyReply{c.r, {code: 200, body: anthropicAnswer}}}
+ s := busyProvider(t, u) // the real defaults
+ gw := httptest.NewServer(s.Handler())
+ t.Cleanup(gw.Close)
+ type got struct {
+ code int
+ after string
+ body string
+ }
+ // a failure below ends the request with the test, not when a
+ // pause it shouldn't have taken would
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ done := make(chan got, 1)
+ go func() {
+ req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+"/v1/messages", strings.NewReader(singleAsk(true)))
+ req.Header.Set("Content-Type", "application/json")
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ done <- got{}
+ return
+ }
+ b, _ := io.ReadAll(res.Body)
+ res.Body.Close()
+ done <- got{res.StatusCode, res.Header.Get("Retry-After"), string(b)}
+ }()
+ var g got
+ wait:
+ for {
+ select {
+ case g = <-done:
+ break wait
+ case <-time.After(5 * time.Millisecond):
+ }
+ s.trace.mu.Lock()
+ waiting := false
+ if k := len(s.trace.routes); k > 0 {
+ for _, tr := range s.trace.routes[k-1].Tries {
+ waiting = waiting || tr.Again > 0
+ }
+ }
+ s.trace.mu.Unlock()
+ if waiting {
+ t.Fatalf("magpie waits to ask again: %+v", lastRoute(s).Tries)
+ }
+ }
+ if g.code != c.r.code || u.asked() != 1 {
+ t.Fatalf("agent got %d %q, upstream asked %d times; want the vendor's %d, asked once", g.code, g.body, u.asked(), c.r.code)
+ }
+ if c.r.retryAfter != "" && g.after == "" {
+ t.Errorf("the vendor's Retry-After was dropped")
+ }
+ })
+ }
+}
+
+// An agent gone while magpie waits out its one provider's rate limit ends
+// the request there: the route is over as canceled, its try says the agent
+// left in the pause, and the vendor is asked nothing more.
+func TestSingleProviderAgentGoneInTheWait(t *testing.T) {
+ u := &busyUpstream{replies: []busyReply{
+ {code: 429, retryAfter: "120", body: rateLimited},
+ {code: 200, body: anthropicAnswer},
+ }}
+ s := busyProvider(t, u)
+ scaled(t, 5*time.Minute) // a pause of 120s, far longer than the test
+ gw := httptest.NewServer(s.Handler())
+ t.Cleanup(gw.Close)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+"/v1/messages", strings.NewReader(singleAsk(true)))
+ req.Header.Set("Content-Type", "application/json")
+ ended := make(chan struct{})
+ go func() {
+ defer close(ended)
+ if res, err := http.DefaultClient.Do(req); err == nil {
+ io.Copy(io.Discard, res.Body)
+ res.Body.Close()
+ }
+ }()
+ if !inPause(s, 1, 30*time.Second) {
+ t.Fatalf("magpie never paused to ask again: %+v", lastRoute(s).Tries)
+ }
+ cancel()
+ <-ended
+ var r Route
+ for deadline := time.Now().Add(60 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
+ s.trace.mu.Lock()
+ r = *s.trace.routes[len(s.trace.routes)-1]
+ r.Tries = append([]Try{}, r.Tries...)
+ s.trace.mu.Unlock()
+ if r.Done {
+ break
+ }
+ }
+ if !r.Done || r.Status != 499 {
+ t.Fatalf("route done %v status %d, want done 499 long before the pause ends", r.Done, r.Status)
+ }
+ if last := r.Tries[len(r.Tries)-1]; !last.Gone || last.Again == 0 {
+ t.Errorf("last try %+v: want its pause and that the agent left in it", last)
+ }
+ if n := u.asked(); n != 1 {
+ t.Errorf("upstream asked %d times after the agent left, want 1", n)
+ }
+}
+
+// The Patience the user set on the provider (magpie provider set a
+// patience=…) stands over singlePatience either way: off hands the agent a
+// rate limit the default would wait out, a shorter one hands it one the
+// default would wait for, and a longer one waits out one the default
+// wouldn't.
+func TestSingleProviderOwnPatienceWins(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ patience int // the user's, in seconds
+ byDefault time.Duration // singlePatience, scaled
+ retryAfter string
+ want int
+ }{
+ {"off", provider.PatienceOff, 3 * time.Second, "0.4", 429},
+ {"shorter", 1, 5 * time.Minute, "3", 429},
+ {"longer", 120, 100 * time.Millisecond, "0.4", 200},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ u := &busyUpstream{replies: []busyReply{
+ {code: 429, retryAfter: c.retryAfter, body: rateLimited},
+ {code: 200, body: anthropicAnswer},
+ }}
+ s := busyProviderWaiting(t, u, c.patience)
+ scaled(t, c.byDefault)
+ gw := httptest.NewServer(s.Handler())
+ t.Cleanup(gw.Close)
+ // a failure ends the request with the test, not when a pause
+ // it shouldn't have taken would
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+"/v1/messages", strings.NewReader(singleAsk(true)))
+ req.Header.Set("Content-Type", "application/json")
+ done := make(chan int, 1)
+ go func() {
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ done <- 0
+ return
+ }
+ io.Copy(io.Discard, res.Body)
+ res.Body.Close()
+ done <- res.StatusCode
+ }()
+ var code int
+ wait:
+ for {
+ select {
+ case code = <-done:
+ break wait
+ case <-time.After(5 * time.Millisecond):
+ }
+ if c.want != 200 {
+ s.trace.mu.Lock()
+ waiting := false
+ if k := len(s.trace.routes); k > 0 {
+ for _, tr := range s.trace.routes[k-1].Tries {
+ waiting = waiting || tr.Again > 0
+ }
+ }
+ s.trace.mu.Unlock()
+ if waiting {
+ t.Fatalf("magpie waits to ask again past the user's patience: %+v", lastRoute(s).Tries)
+ }
+ }
+ }
+ wantAsked := 1
+ if c.want == 200 {
+ wantAsked = 2
+ }
+ if code != c.want || u.asked() != wantAsked {
+ t.Fatalf("agent got %d, upstream asked %d times; want %d, asked %d", code, u.asked(), c.want, wantAsked)
+ }
+ })
+ }
+}
diff --git a/internal/gateway/toolong_unsaid_test.go b/internal/gateway/toolong_unsaid_test.go
index 6f4fefda2..c23286250 100644
--- a/internal/gateway/toolong_unsaid_test.go
+++ b/internal/gateway/toolong_unsaid_test.go
@@ -31,10 +31,12 @@ func TestOverflowTheVendorDidntSay(t *testing.T) {
// Text alone well past the window is enough to ask for compaction.
{"413 bytes", "/v1/messages", big, 413, `{"error":{"message":"Request Entity Too Large"}}`, 400, 1, "prompt is too long"},
{"413 request_too_large", "/v1/messages", big, 413, `{"error":{"type":"request_too_large","message":"Request exceeds the maximum size"}}`, 400, 1, "prompt is too long"},
- // not the conversation's length
- {"small 502", "/v1/messages", small, 502, `{"error":{"message":"We are experiencing capacity issues"}}`, 502, 1 + lastRetries, "capacity issues"},
- {"near the window", "/v1/messages", near, 502, `{"error":{"message":"We are experiencing capacity issues"}}`, 502, 1 + lastRetries, "capacity issues"},
- {"429", "/v1/messages", big, 429, `{"error":{"message":"Rate limit reached"}}`, 429, 1 + rateRetries, "Rate limit"},
+ // not the conversation's length: a plain provider's busy reply is
+ // asked again past the same-one retries, within its patience,
+ // until replan's rounds run out
+ {"small 502", "/v1/messages", small, 502, `{"error":{"message":"We are experiencing capacity issues"}}`, 502, 1 + lastRetries + replanRounds, "capacity issues"},
+ {"near the window", "/v1/messages", near, 502, `{"error":{"message":"We are experiencing capacity issues"}}`, 502, 1 + lastRetries + replanRounds, "capacity issues"},
+ {"429", "/v1/messages", big, 429, `{"error":{"message":"Rate limit reached"}}`, 429, 1 + rateRetries + replanRounds, "Rate limit"},
{"401", "/v1/messages", big, 401, `{"error":{"message":"invalid token"}}`, 401, 1, "invalid token"},
{"quota", "/v1/messages", big, 400, `{"error":{"message":"insufficient balance"}}`, 400, 1, "insufficient balance"},
} {
diff --git a/internal/gui/provider_patience_test.go b/internal/gui/provider_patience_test.go
new file mode 100644
index 000000000..506c2d875
--- /dev/null
+++ b/internal/gui/provider_patience_test.go
@@ -0,0 +1,39 @@
+package gui
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// A provider's Patience, set with `magpie provider set <id> patience=`
+// (zoecats on Discord), is not in the editor: the editor's save keeps it.
+func TestProviderSaveKeepsPatience(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_CACHE_HOME", t.TempDir())
+ for _, set := range []int{provider.PatienceOff, 150} {
+ if err := provider.Save(provider.Provider{ID: "or", Name: "OpenRouter", Chat: "https://example.invalid/v1", Key: "k", Patience: set}); err != nil {
+ t.Fatal(err)
+ }
+ mux := http.NewServeMux()
+ providerRoutes(mux, nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(`{"id":"or","name":"OpenRouter","chat":"https://example.invalid/v1"}`)))
+ if w.Code != 200 {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+ got, err := provider.Find("or")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Patience != set {
+ t.Fatalf("patience %d after the editor's save, want %d kept", got.Patience, set)
+ }
+ }
+}
diff --git a/internal/gui/providers.go b/internal/gui/providers.go
index 1e28c11c1..0ebc85c60 100644
--- a/internal/gui/providers.go
+++ b/internal/gui/providers.go
@@ -1567,6 +1567,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if !in.AdditionalTools && old != nil {
in.AdditionalTools = old.AdditionalTools
}
+ // and how long a request to it alone is kept while it is
+ // busy, set with `magpie provider set <id> patience=`
+ if in.Patience == 0 && old != nil {
+ in.Patience = old.Patience
+ }
// each account's own proxy likewise: {} clears them
if in.AccountProxies == nil && old != nil {
in.AccountProxies = old.AccountProxies
diff --git a/internal/provider/provider.go b/internal/provider/provider.go
index 2e1810883..f345dbc20 100644
--- a/internal/provider/provider.go
+++ b/internal/provider/provider.go
@@ -250,6 +250,16 @@ type Provider struct {
// turns the item away (#350).
AdditionalTools bool `json:"additionalTools,omitempty"`
+ // Patience is how many seconds more a request to this provider alone,
+ // not through a group, may be kept once it has failed in a way that
+ // passes (overloaded, unavailable, rate limited for a moment) and the
+ // same-one retries are spent, as a group's Patience is (zoecats on
+ // Discord): 0 keeps it PatienceDefault, PatienceOff hands the agent
+ // the error at once, and it is at most PatienceLongest. Set with
+ // `magpie provider set <id> patience=`; a group it is in keeps the
+ // group's own.
+ Patience int `json:"patience,omitempty"`
+
// NativeCompaction has Codex's compaction_trigger go to the provider
// as Codex sent it, and the compaction the provider writes back go to
// Codex as it came (#1099), where magpie otherwise asks the model for
@@ -1254,6 +1264,10 @@ func keyOptional(p Provider) bool {
func normalize(p Provider) Provider {
p.ID = strings.ToLower(strings.TrimSpace(p.ID))
p.Name = strings.TrimSpace(p.Name)
+ if p.Patience < 0 {
+ p.Patience = PatienceOff
+ }
+ p.Patience = min(p.Patience, PatienceLongest)
p.Key = strings.TrimSpace(p.Key)
p.Proxy = strings.TrimSpace(p.Proxy)
p.AccountProxies = normalAccountProxies(p.AccountProxies)