Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: a key out of a guessed quota is asked again after one refusal, and held a minute (zoecats)
yetonebe7f17467740
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex afb48764e..a75fa1982 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -140,7 +140,7 @@ recorded as a prediction failure (`noPrediction`).- A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: `reasoning_content` (DeepSeek's, which OpenCode and most clients send), `reasoning` (OpenRouter's) or `reasoning_details` (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (`messageReasoning`, `reasoningText`, read by `parseChat` in [chat.go](../../internal/gateway/chat.go)); the passthrough has read all three since `mistralThinking` (#494), which was the one place that did. Before that the parse layer read `reasoning_content` alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning.- 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). 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 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. 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 back (`soonestBack`). 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 <id> 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest <id> 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. 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 <id> 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest <id> 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 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`.- A member whose model is known to take less than the request isn't asked it (`roomy` in [`fallback.go`](../../internal/gateway/fallback.go), in `serve` after the rules, affinity, the image filter and `pinTo`, before `probeOne`; dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash, 200K, first in a group and a 1M subscription of it second). It is a check before sending, not a retry: the request's tokens are estimated as the overflow fall-over does (`estimate`, bytes/4 over text, tool arguments and schemas), and a candidate whose window (`windowOf`: the provider's `Contexts`, the catalog, `ContextOf`) is known and no larger is left out of the candidates and of the trace's order. Asked, such a member only refuses, and a refusal that doesn't say why, for a request short of `tooLongUnsaid`'s 1.2 margin, reached the agent as the vendor's error while the next member had room; it also spent a request against the member's limits. A conversation kept on a member by affinity moves once it outgrows it. Nothing is left out when its window isn't known, when the body doesn't parse, when only one model is among the candidates, or when no candidate holds the request: then the first is asked, and its overflow reaches the agent as one, to compact (`withRoom`, `failOverflow` and `tooLongUnsaid` stay for the window the estimate misses, which counts low on code and high on CJK text). A body shorter than four bytes per token of the least window isn't parsed. `count_tokens` (a count on the group's first member, not a send) and System One's decision models (short decision text) don't go through it. Those left out are the last resort: when the last candidate with room fails out of its allowance or credit (`failQuota`/`failCredit`), nothing before it having failed otherwise (`other`), and no account is pinned, the ones left out that aren't resting are asked after all, their rows added to the trace's order, and the one that failed rests as one before the last does. Its overflow tells the agent to compact, where the 429 only told it to wait for an allowance hours away (Kai on Discord: both Claude accounts spent until the next day, the Claude provider's Fallback a Codex model of 272K under a longer conversation, never asked). Another failure (a busy vendor, a bad key) still reaches the agent as it was, the small one not asked. The Routing page shows a member left out and not asked only by its absence from the route's order. `TestMemberTooSmallIsNotAsked`, `TestMemberTooSmallIsTheLastResort`, `TestClaudeAccountsSpentFallBackToCodex`, `TestConversationOutgrowingItsMemberMoves`, `TestRoomyLeavesWhatItCantJudge`.- Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while the last reply read from the cache and wrote to it at least `cacheWorth` (1024) tokens between them (the usage's `CacheRead` plus `CacheWrite`, passed to `answered`) and the cache isn't cold (`cacheCold`, 5 minutes). Past 5 minutes it stays while the vendor said it keeps at least `cacheWorth` tokens of the conversation for an hour (`hourCache`, #2302): a reply with Anthropic's 1-hour writes (`cache_creation.ephemeral_1h_input_tokens`, the usage's `CacheWrite1h`, as Claude Code asks of a subscription) keeps what it read plus those for `cacheHour`, a later reply on the same account and model that reads all of it starts the hour again, and one that reads less (moved, compacted) drops it. The stick keeps it on disk too (`cacheHour`, `cacheHourAt`), and a group's rules keep the turn's effort the same hour (`keepsEffort`). Vendors that report no 1-hour write are unchanged. `TestAffinityKeepsAnHourCachePastFiveMinutes`, `TestHourCacheAfter`. What was written counts: a first turn reads nothing and writes the whole prompt (Anthropic's `cache_creation_input_tokens`), and the second turn stays to read it rather than moving as `no-cache` and building it again elsewhere (vilicvane on Discord). The stick keeps both, on disk too (`affinity.json`'s `cacheWrite`, absent in a file from before and read as 0, so such a stick is judged by its read alone), and the trace's `Affinity.CacheWrite` lets the Routing page say what was read and what was written. A vendor that keeps a prompt cached without reporting it (OpenAI's automatic prefix cache, Gemini) says neither of a turn that read none, so the prompt that turn was sent (the usage's `Input`) stands for the write and its second turn stays too; a reply that reports no usage at all counts as no cache, as before. `TestAffinityKeepsACacheJustWritten`, `TestAffinityKeepsACacheTheVendorKeptSilently`, `routing-affinity-cache-write.test.cjs`.diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.goindex efb7ecf82..7ade0fbc4 100644--- a/internal/gateway/fallback.go+++ b/internal/gateway/fallback.go@@ -914,22 +914,32 @@ func restingOf(c candidate) (Rest, bool) {// quotaHeld is, when every candidate of cs is a key resting out of its// allowance or its credit — refused with a 429 or a 402 for it, the// vendor's words kept — the rest of the first, and when the first of them-// is back: asked before then, each would be refused the same (#1772). A+// is asked again: asked before then, each would be refused the same+// (#1772). A key whose rest magpie guessed the length of, the vendor and+// the user naming no time, is asked again all the same after its first+// refusal, and a minute on after the next (Rest.asksAt): zoecats on Discord, a local aggregator said "quota+// exhausted" for the moment it switched upstreams, and every request,+// the agent's retry first, was answered from its 15-minute rest. A// subscription account isn't held so: its resets may be spent for it// (autoReset), and its windows are read again as it is planned.func quotaHeld(cs []candidate) (Rest, time.Time, bool) {var first Restvar back time.Time+ now := time.Now()for i, c := range cs {r, ok := restingOf(c)if !ok || c.p.Account != nil || r.Why != failQuota && r.Why != failCredit || !quotaStatus(r.Status) || r.said == "" {return Rest{}, time.Time{}, false}+ at := r.asksAt(now)+ if !now.Before(at) {+ return Rest{}, time.Time{}, false+ }if i == 0 {first = r}- if back.IsZero() || r.Until.Before(back) {- back = r.Until+ if back.IsZero() || at.Before(back) {+ back = at}}return first, back, len(cs) > 0@@ -940,17 +950,18 @@ func quotaStatus(status int) bool {return status == http.StatusTooManyRequests || status == http.StatusPaymentRequired}-// soonestBack is when the first of cs is back from its rest; false when-// one of them isn't resting.+// soonestBack is when the first of cs is back from its rest, or asked+// again before it is (Rest.asksAt); false when one of them isn't resting.func soonestBack(cs []candidate) (time.Time, bool) {var back time.Time+ now := time.Now()for _, c := range cs {r, ok := restingOf(c)if !ok {return time.Time{}, false}- if back.IsZero() || r.Until.Before(back) {- back = r.Until+ if at := r.asksAt(now); back.IsZero() || at.Before(back) {+ back = at}}return back, !back.IsZero()diff --git a/internal/gateway/remote_magpie_key_limit_test.go b/internal/gateway/remote_magpie_key_limit_test.goindex 441ee6062..653932c49 100644--- a/internal/gateway/remote_magpie_key_limit_test.go+++ b/internal/gateway/remote_magpie_key_limit_test.go@@ -72,8 +72,12 @@ func TestRemoteMagpieRestsTheModel(t *testing.T) {if asked.Load() != 1 {t.Errorf("Qoder was asked %d times; want once", asked.Load())}- // Claude Code itself still rests: asked again, it is refused here- // without the other magpie being asked+ // Claude Code itself still rests: refused again (a rest of a length+ // magpie guessed is asked once more after the first refusal, zoecats+ // on Discord), it is refused here without the other magpie being asked+ if rec := send(id + "/cc/claude-opus-5-5"); rec.Code != http.StatusTooManyRequests {+ t.Fatalf("Claude Code asked again: %d %s; want its 429", rec.Code, rec.Body.String())+ }if rec := send(id + "/cc/claude-opus-5-5"); rec.Code != http.StatusTooManyRequests || !strings.Contains(rec.Body.String(), "not asked again") {t.Errorf("Claude Code asked again while it rests: %d %s; want its 429 held here", rec.Code, rec.Body.String())}diff --git a/internal/gateway/rest_all_test.go b/internal/gateway/rest_all_test.goindex 0a6dcd5ee..fcb79a30a 100644--- a/internal/gateway/rest_all_test.go+++ b/internal/gateway/rest_all_test.go@@ -4,6 +4,7 @@ import ("io""net/http""net/http/httptest"+ "slices""strconv""strings""sync"@@ -82,7 +83,9 @@ func postDead(t *testing.T, srv *Server) *httptest.ResponseRecorder {// #1772 (a fleet on four Ollama Cloud keys): every key out of its weekly// allowance, each new request had asked each key again (the first twice)// and answered 429 with no Retry-After, so a client that waits as told-// asked again at once.+// asked again at once. A key is held once it was refused so twice in a+// row (a single refusal may be a moment's, zoecats on Discord), and, its+// vendor naming no time, asked again a minute on, which Retry-After says.func TestAllRestingAnswersFromRest(t *testing.T) {d, srv := deadChain(t, "dead-a", "dead-b")rec := postDead(t, srv)@@ -92,9 +95,20 @@ func TestAllRestingAnswersFromRest(t *testing.T) {if got := d.took(); strings.Join(got, ",") != "dead-a,dead-b" {t.Errorf("first request asked %v, want each key once", got)}- ra, err := strconv.Atoi(rec.Header().Get("Retry-After"))- if err != nil || ra < int(quotaRest/time.Second)-5 || ra > int(quotaRest/time.Second) {- t.Errorf("first: Retry-After %q, want about %v", rec.Header().Get("Retry-After"), quotaRest)+ if ra := rec.Header().Get("Retry-After"); ra != "" {+ t.Errorf("first: Retry-After %q, while each key is asked again at once", ra)+ }+ // each asked once more, the soonest back first, one a request as+ // every candidate resting has it (restLast)+ var again []string+ for i := 0; i < 2; i++ {+ if rec = postDead(t, srv); rec.Code != 429 {+ t.Fatalf("confirming: %d %s", rec.Code, rec.Body)+ }+ again = append(again, d.took()...)+ }+ if slices.Sort(again); strings.Join(again, ",") != "dead-a,dead-b" {+ t.Errorf("asked again %v, want each key once", again)}for i := 0; i < 2; i++ {rec = postDead(t, srv)@@ -104,9 +118,9 @@ func TestAllRestingAnswersFromRest(t *testing.T) {if got := d.took(); len(got) != 0 {t.Errorf("again: asked %v while every key rests", got)}- ra, err = strconv.Atoi(rec.Header().Get("Retry-After"))- if err != nil || ra < int(quotaRest/time.Second)-5 || ra > int(quotaRest/time.Second) {- t.Errorf("again: Retry-After %q, want about %v", rec.Header().Get("Retry-After"), quotaRest)+ ra, err := strconv.Atoi(rec.Header().Get("Retry-After"))+ if err != nil || ra < 50 || ra > int(fallbackCooldown/time.Second) {+ t.Errorf("again: Retry-After %q, want about %v", rec.Header().Get("Retry-After"), fallbackCooldown)}if !strings.Contains(rec.Body.String(), "weekly usage limit") {t.Errorf("again: the vendor's reason is gone: %s", rec.Body)@@ -125,6 +139,12 @@ func TestOwnQuotaRest(t *testing.T) {if got := d.took(); rec.Code != 429 || len(got) != 2 {t.Fatalf("%d after %v: %s", rec.Code, got, rec.Body)}+ // the user's rest is no guess: held from the first refusal, and not+ // asked again a minute on+ rec = postDead(t, srv)+ if got := d.took(); rec.Code != 429 || len(got) != 0 {+ t.Fatalf("held: %d after %v: %s", rec.Code, got, rec.Body)+ }week := int(7 * 24 * time.Hour / time.Second)if ra, _ := strconv.Atoi(rec.Header().Get("Retry-After")); ra < week-5 || ra > week {t.Errorf("Retry-After %q, want a week", rec.Header().Get("Retry-After"))@@ -152,8 +172,12 @@ func TestQuotaHeldOnlyForKeysOutOfAllowance(t *testing.T) {body := []byte(`{"error":{"message":"you have reached your weekly usage limit"}}`)key := candidate{p: provider.Provider{ID: "k1"}, rest: "k1"}srv.restAfter(key, 429, nil, body)+ if _, _, ok := quotaHeld([]candidate{key}); ok {+ t.Error("a key refused once is held: its retry isn't asked")+ }+ srv.restAfter(key, 429, nil, body)if _, _, ok := quotaHeld([]candidate{key}); !ok {- t.Error("a key out of its allowance isn't held")+ t.Error("a key out of its allowance twice in a row isn't held")}forbidden := candidate{p: provider.Provider{ID: "k2"}, rest: "k2"}srv.restAfter(forbidden, 403, nil, []byte(`{"error":{"message":"quota exceeded for this region"}}`))diff --git a/internal/gateway/rest_retry_test.go b/internal/gateway/rest_retry_test.gonew file mode 100644index 000000000..aa1e80fa6--- /dev/null+++ b/internal/gateway/rest_retry_test.go@@ -0,0 +1,175 @@+package gateway++import (+ "io"+ "net/http"+ "net/http/httptest"+ "strconv"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/provider"+)++// onceRefused is an upstream that refuses each key once, with status,+// header and body, and serves it after: a local aggregator switching+// upstreams (zoecats on Discord), or a relay's moment of "quota+// exhausted".+type onceRefused struct {+ status int+ header http.Header+ body string++ mu sync.Mutex+ asked []string+ seen map[string]bool+}++func (o *onceRefused) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ io.Copy(io.Discard, r.Body)+ key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")+ o.mu.Lock()+ o.asked = append(o.asked, key)+ first := !o.seen[key]+ o.seen[key] = true+ o.mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ if first {+ for k, v := range o.header {+ w.Header()[k] = v+ }+ w.WriteHeader(o.status)+ io.WriteString(w, o.body)+ return+ }+ io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)+}++func (o *onceRefused) took() []string {+ o.mu.Lock()+ defer o.mu.Unlock()+ out := o.asked+ o.asked = nil+ return out+}++func onceChain(t *testing.T, o *onceRefused, keys ...string) *Server {+ t.Helper()+ noRests()+ t.Cleanup(noRests)+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ o.seen = map[string]bool{}+ up := httptest.NewServer(o)+ t.Cleanup(up.Close)+ p := provider.Provider{ID: "agg", Name: "Agg", Key: keys[0], Models: []string{"m1"}, Chat: up.URL + "/v1", Routing: provider.Ordered}+ for _, k := range keys[1:] {+ p.Keys = append(p.Keys, provider.KeyAccount{Key: k})+ }+ if err := provider.Save(p); err != nil {+ t.Fatal(err)+ }+ return New()+}++func postAgg(t *testing.T, srv *Server) *httptest.ResponseRecorder {+ t.Helper()+ rec := httptest.NewRecorder()+ req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"agg/m1","messages":[{"role":"user","content":"hi"}]}`))+ req.Header.Set("Content-Type", "application/json")+ srv.Handler().ServeHTTP(rec, req)+ return rec+}++// zoecats on Discord (#feedback, 10-25), by default, with no switch+// turned: a provider's key refused once out of its quota or credit, and+// served the moment after. The agent's retry, and every request after+// it, reach the upstream and are answered; magpie doesn't answer them+// from the rest, "out of its allowance: not asked again before …", for+// the half hour it guessed. Each refusal a vendor gives for a limit: its+// "insufficient_quota" (read as out of credit), a usage limit that names+// no reset, the same with a Retry-After of 0, and every key of the+// provider refused at once.+func TestRetryAfterALimitIsAsked(t *testing.T) {+ cases := []struct {+ name string+ status int+ header http.Header+ body string+ keys []string+ }{+ {"insufficient_quota", 429, nil, `{"error":{"message":"quota exhausted","type":"insufficient_quota"}}`, []string{"k1"}},+ {"usage limit", 429, nil, `{"error":{"message":"you have reached your usage limit","type":"rate_limit_error"}}`, []string{"k1"}},+ {"retry-after 0", 429, http.Header{"Retry-After": {"0"}}, `{"error":{"message":"you have reached your usage limit","type":"rate_limit_error"}}`, []string{"k1"}},+ {"402", 402, nil, `{"error":{"message":"insufficient balance"}}`, []string{"k1"}},+ {"every key", 429, nil, `{"error":{"message":"quota exhausted","type":"insufficient_quota"}}`, []string{"k1", "k2"}},+ // a rate limit was asked again before too (restLast, the retries+ // within the request): held to that+ {"rate limited, retry-after 0", 429, http.Header{"Retry-After": {"0"}}, `{"error":{"message":"Too many requests","type":"rate_limit_error"}}`, []string{"k1"}},+ {"rate limited, every key", 429, http.Header{"Retry-After": {"1"}}, `{"error":{"message":"Too many requests","type":"rate_limit_error"}}`, []string{"k1", "k2"}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ o := &onceRefused{status: tc.status, header: tc.header, body: tc.body}+ srv := onceChain(t, o, tc.keys...)+ // a rate limit is asked again within the request, and answered+ if rec := postAgg(t, srv); rec.Code != tc.status && rec.Code != http.StatusOK {+ t.Fatalf("first: %d %s", rec.Code, rec.Body)+ }+ if got := o.took(); len(got) < len(tc.keys) {+ t.Fatalf("first request asked %v", got)+ }+ for i := 0; i < 2; i++ {+ rec := postAgg(t, srv)+ got := o.took()+ if rec.Code != http.StatusOK || len(got) == 0 {+ t.Fatalf("request %d after the refusal: %d %s, upstream asked %v", i+2, rec.Code, rec.Body, got)+ }+ }+ })+ }+}++// Refused twice in a row, every key is held as #1772 wants, not asked+// on every request; but a rest whose length magpie guessed (the half+// hour out of credit, the quarter out of quota with no word of when) is+// asked again once a minute, and its Retry-After says so, so an agent+// that waits as told is answered within the minute the upstream is back.+// A time the vendor named still holds it to then.+func TestHeldLimitAskedAgainInAMinute(t *testing.T) {+ d, srv := deadChain(t, "dead-a")+ for i := 0; i < 2; i++ {+ if rec := postDead(t, srv); rec.Code != 429 {+ t.Fatalf("refusal %d: %d %s", i+1, rec.Code, rec.Body)+ }+ }+ if got := d.took(); len(got) != 2 {+ t.Fatalf("two refusals asked %v", got)+ }+ rec := postDead(t, srv)+ if got := d.took(); rec.Code != 429 || len(got) != 0 {+ t.Fatalf("held: %d, asked %v", rec.Code, got)+ }+ ra, err := strconv.Atoi(rec.Header().Get("Retry-After"))+ if err != nil || ra < 50 || ra > 61 {+ t.Errorf("held: Retry-After %q, want about a minute", rec.Header().Get("Retry-After"))+ }+ // a minute on: one more ask+ restingUntil.Lock()+ for k, r := range restingUntil.note {+ r.askAt = time.Now().Add(-time.Second)+ restingUntil.note[k] = r+ }+ restingUntil.Unlock()+ if rec := postDead(t, srv); rec.Code != 429 {+ t.Fatalf("a minute on: %d %s", rec.Code, rec.Body)+ }+ if got := d.took(); len(got) != 1 {+ t.Fatalf("a minute on asked %v, want once", got)+ }+ if rec := postDead(t, srv); rec.Code != 429 || len(d.took()) != 0 {+ t.Fatalf("refused again a minute on: held no more")+ }+}diff --git a/internal/gateway/routing.go b/internal/gateway/routing.goindex 896b909a1..c90c89a01 100644--- a/internal/gateway/routing.go+++ b/internal/gateway/routing.go@@ -510,6 +510,28 @@ type Rest struct {agent, user stringsaid string // the error it gave, for a failVerify heldhold time.Time // until when a failVerify is answered without asking+ // a key out of its allowance or credit for as long as magpie guessed,+ // the vendor and the user naming no time, is held (quotaHeld) once it+ // was refused so twice in a row, not on the first refusal (first),+ // and asked again from askAt, a minute on: zoecats on Discord, a local+ // aggregator's "quota exhausted" for the moment it switched upstreams+ // held every request for 15 minutes or more+ first bool+ askAt time.Time+}++// asksAt is when r, a key's rest out of its allowance or credit, has it+// asked again: at once after its first refusal, a minute on when magpie+// guessed how long it is out, else when it is back. Any other rest asks+// when it ends.+func (r Rest) asksAt(now time.Time) time.Time {+ switch {+ case r.first:+ return now+ case !r.askAt.IsZero() && r.askAt.Before(r.Until):+ return r.askAt+ }+ return r.Until}// renewed lifts the rests of a subscription account whose windows were@@ -923,6 +945,9 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo// (#1235): the key's other models are still servedunserved := why == failOther && (modelRefused(status, body) || codeAssistModelMissing(c.p, status, body))r := Rest{Why: why, Status: status, By: "cooldown"}+ // out of allowance or credit for as long as magpie guessed: the vendor+ // named no time, nor did the user (asksAt)+ guessed := false// a failure counted past the account's, for its model alone (below)modelBackoff := falseif why == failProxy {@@ -945,7 +970,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo}switch why {case failCredit:- d, r.By = creditRest, "credit"+ d, r.By, guessed = creditRest, "credit", truecase failQuota:if c.onCredits() {// a Codex account that holds credits refused as out of its@@ -993,6 +1018,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo}// a month's allowance whose refusal named its reset is out till// then, past the week's cap (#3276); nothing else is held longer+ guessed = r.By == "quota" && own <= 0longest := longestQuotaif r.By == "resets" && monthlyWords.Match(wordsOf(body)) {longest = longestMonthly@@ -1118,6 +1144,17 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bor.Model = c.model}restingUntil.Lock()+ if why == failQuota || why == failCredit {+ // out for as long as magpie guessed: refused so the time before+ // too, it is held from now on, and asked again a minute on; a+ // refusal on its own is asked once more. A time the vendor named,+ // or the user set, holds it from the first+ if guessed {+ prev, had := restingUntil.note[id]+ r.first = !had || prev.Why != failQuota && prev.Why != failCredit+ r.askAt = now.Add(fallbackCooldown)+ }+ }restingUntil.m[id] = r.UntilrestingUntil.note[id] = rrestingUntil.Unlock()