diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 29929b04d..7faaacb76 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -324,6 +324,7 @@ recorded as a prediction failure (`noPrediction`). - A group member let go for no first content within the group's `FirstToken` (`hw.slow` in [`gateway.go`](../../internal/gateway/gateway.go), 504 "no first token in Ns", `failSlow`) doesn't rest the first time: a long prompt is slow to start anywhere. Slow again on the same account's model with no answer from it in between, and within `slowForget` (30 minutes) of its last slow start, that model rests on that account (`restSlow` in [`routing.go`](../../internal/gateway/routing.go), keyed by `restID`, `Rest.Model` set): a minute from the second time (`slowRests`), doubling each time after, up to the provider's rest cap (`RestCapOr(longestRetry)`), and never for a provider whose cap is off. Its answer clears the count (`servedCandidate`). A request its client cancelled counts nothing, as the cancel is read before `hw.slow`. The walk has a total budget, `groupBudget` (540s, under the 600s a client waits): a member asked when little of it is left gets only what is left (`hw.budgeted`), and when it runs out no further member is asked, nothing rests, and the error names the budget (504 "no member of the group answered within its 540s budget", #5113, mycf_711: nine members at 60s took 660s and the client's hang-up was told as the last member's failure; `TestGroupWalkStopsAtItsBudget`). Before it, each new request asked the stalled member first again and waited out the whole `FirstToken` (小八 on Discord: a WorkBuddy account's kimi-k3-1 and glm-5.3 stalled 58 times on the vendor's per-model token limit, 15 times in 17 minutes in one session). The same model on another account and another model on the same account are asked as before (`TestSlowStartsRestTheModelOnItsAccount`, `TestCanceledSlowStartRestsNothing`; the Routing page's story, `routing-went-on.test.cjs`). - A plugin's try that isn't the last candidate is sent with `x-magpie-fallback: 1` (`provider.FallbackHeader`, `withFallback`), so a plugin whose vendor queues the request (Qoder's 10605, CodeArts' `queue-status: queued`) answers a `busy` 503 with Retry-After and the queue's reason at once instead of waiting minutes in the queue, and the next is asked; the last candidate isn't told and waits as the vendor's client does ([provider-plugins](provider-plugins.md#whether-another-candidate-follows), `TestPluginToldAnotherFollows`). - A Claude account's refusal worded "You've reached your Fable limit" (also "hit"; `claudeFamilyLimit`) names the family whose own limit it is, found in the model's id: that model rests on the account, its others keep being served (YsiCing on X: Opus was refused with it). "usage", "session", "weekly" or no word there is the account's. `TestClaudeNamedModelLimitRestsThatModelOnly`. +- A Claude account's plain 429 `rate_limit_error` for a model, naming no window (no 5-hour, session, weekly, usage or organization words, and no `anthropic-ratelimit-unified-representative-claim` of `five_hour` or `seven_day`), is that model's rate limit, as Anthropic counts them per model: that model rests, rate-limit ladder and sink included, and the account's other models are still asked (`claudeModelRate`, kaitokiku on X: Fable rate limited showed "限流" on Opus too; `TestClaudeModelRateRestsThatModelOnly`). A refusal of a window that counts every model rests the account as before. - A 402 is out of credit, unless it speaks of a usage limit (`usedUpWords`) and nothing of money (`creditWords`, `insufficient_quota`): then it is out of quota, and rests only the model when the account's windows say its pool is the one used up (`pooled`). Factory answers Standard's pool used up with 402 "You've reached your weekly standard usage limit (resets in …). Switch to Droid Core …"; read as credit, it rested the account 30 minutes and its Droid Core models with it (#1979). Both the built-in's windows and the plugin's (Standard's `notModels`, Core's `models`) are held to it. As a quota rest it lasts until the time the refusal names (`resetsAfter`: "resets in 0h 19min", "resets in 2d 3h", held to `longestWritten`), else the window's end, else `quotaRest` or the provider's own `quota-rest`, and is lifted once a reading finds the window renewed (`renewed`), which a credit rest never was (`TestFactoryStandardOutLeavesCore`, `TestPaymentRequiredReadByItsWords`, `TestResetsInWords`). An account whose windows weren't read yet (a start, or a reading that failed), or whose reading holds a window of some models only (Claude's Opus, Sonnet or Fable week) with none known full, can't tell the model's pool from the account's, so it rests whole, and (`Allowance.Scoped`; `TestClaudeFableWeekRestsFableOnly`, kaitokiku on X: Claude Code's "You've hit your limit" names no window) `narrowWhenRead` waits off the request for a reading (`AwaitAllowance`, up to `allowanceWait`) and moves the rest to the model alone (`restID`, the same end) when the reading says its pool is the one used up; no reading in time, or one that says the whole account, leaves the account's rest, as does a rest lifted or made again meanwhile (#2036; `TestFactoryStandardOutLeavesCore`'s unread case, `TestResetsInWords`). The request itself isn't held for the reading: it has failed over already, and the rest's scope only matters to later requests. - Codex offers its image tool (the `image_gen` namespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400, `attempt` asks it once more without the tool (`image_tool.go`). This happens both passed through and translated. If that works, the provider is marked unfit for the tool (`tool:image_gen`) and isn't offered it again. If it doesn't, the tool is restored and the 400 stands (#949). - A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (`buildCodeAssistSent`, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (`pairToolMessages`, #1275), right after the calls (`pairFunctionTurns`, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing a `functionResponse` with text is turned away too (#1533), and so is one mixing it with an image: on Vertex AI a tool's images (Codex's view_image) go in a user turn of their own after the response (`buildCodeAssistSent`, Voo_Ler on X); a Claude model on Antigravity gets it in the one tool_result turn. A call with no id counts as answered by a response of its name. A second answer to one call is left out, with the images it carried, before the turns are built (`dropSecondAnswers`, #2262): Google refuses a call turn whose `functionResponse` count differs from its `functionCall` count, and the Chat and Messages builds already keep the first answer. The Responses build (`buildResponses`) leaves it out the same way. A call made again under the same id takes an answer of its own. A Gemini client that keeps no ids answers two calls of one function by name in their order, and each answer goes to its own call (`parseGemini`), not both to the latest. `TestGeminiDropsASecondAnswer`, `TestSecondAnswerDroppedWithItsImages`, `TestGeminiClientUnnamedCallsAnsweredInOrder`. diff --git a/internal/gateway/claude_model_rate_rest_test.go b/internal/gateway/claude_model_rate_rest_test.go new file mode 100644 index 000000000..da6d9226b --- /dev/null +++ b/internal/gateway/claude_model_rate_rest_test.go @@ -0,0 +1,66 @@ +package gateway + +import ( + "net/http" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A Claude account's plain 429 rate_limit_error for one model rests that +// model on the account, not the account (kaitokiku on X: Fable rate limited +// showed "限流" on the account's Opus row too). A refusal of an allowance +// window that counts every model still rests the account. +func TestClaudeModelRateRestsThatModelOnly(t *testing.T) { + fresh(t) + acct := func(model string) candidate { + return candidate{p: provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "rate@example.com"}}, model: model, rest: "claude"} + } + s := &Server{} + body := func(msg string) []byte { + return []byte(`{"type":"error","error":{"type":"rate_limit_error","message":"` + msg + `"}}`) + } + hdr := http.Header{"Retry-After": {"2520"}} + fable := acct("claude-fable-5-2") + r := s.restAfter(fable, http.StatusTooManyRequests, hdr, body("This request would exceed your account's rate limit. Please try again later.")) + if r.Why != failRate || r.Model != "claude-fable-5-2" || r.Key != fable.restID() { + t.Fatalf("rest: %+v", r) + } + if _, ok := restingOf(acct("claude-opus-5-5")); ok { + t.Fatal("Opus rests on an account whose Fable is rate limited") + } + // the wrong guess: if Anthropic limits the whole account, Opus gets its + // own 429 there, rests on that account for Opus, and another account is + // still ready for it (the request falls over, as any rested candidate) + opus := acct("claude-opus-5-5") + if r := s.restAfter(opus, http.StatusTooManyRequests, hdr, body("This request would exceed your account's rate limit.")); r.Model != opus.model || r.Key != opus.restID() { + t.Fatalf("Opus rest: %+v", r) + } + if _, ok := restingOf(opus); !ok { + t.Fatal("Opus does not rest on the account that refused it") + } + if _, ok := restingOf(fable); !ok { + t.Fatal("Fable's rest was lost") + } + other := candidate{p: provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "second@example.com"}}, model: "claude-opus-5-5", rest: "claude"} + if _, ok := restingOf(other); ok { + t.Fatal("the second account rests for another account's refusal") + } + fresh(t) + // the account's windows rest the account + for _, c := range []struct { + msg string + h http.Header + }{ + {"5-hour limit reached", hdr}, + // as the live ledger's logs hold it (a warm-up refused by the weekly window) + {"Claude Code: You've hit your weekly limit · resets 2pm (Asia/Shanghai)", http.Header{}}, + {"This request would exceed your account's rate limit.", http.Header{"Retry-After": {"60"}, "Anthropic-Ratelimit-Unified-Representative-Claim": {"five_hour"}}}, + } { + o := acct("claude-opus-5-5") + if r := s.restAfter(o, http.StatusTooManyRequests, c.h, body(c.msg)); r.Key != o.restKey() { + t.Fatalf("%q rested %+v, want the account", c.msg, r) + } + fresh(t) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 6a75da2a2..0cc48f1ba 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -412,6 +412,8 @@ var ( // the model's, and the model alone rests claudeFamilyWords = lazyre.New(`(?:hit|reached) your ([a-z][a-z0-9.]*) limit`) otherModels = lazyre.New(`(?i)switch(?:ing)? to (?:the )?other models?|切换(?:到)?其他模型`) + // words of a window that counts every model of a Claude account + claudeWindowWords = lazyre.New(`5.?hour|five.?hour|session|weekly|7.?day|seven.?day|usage limit|your limit|organization|overage|extra usage`) // modelCooling is a relay that pools credentials per model saying // those of the requested model cooled down: CLIProxyAPI's 429 // model_cooldown, "All credentials for model model-a are cooling down @@ -1622,7 +1624,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo // key's own limit apart): the sink keeps the same scope, or // one model's 429 would send the remote's other models, never // limited, behind the others too - if remoteModelRest(c, failRate, header) || modelLimited(c, failRate, body) { + if remoteModelRest(c, failRate, header) || modelLimitedBy(c, failRate, header, body) { sink(c.restID(), now) } else { sink(c.restKey(), now) @@ -1779,7 +1781,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo // that model's: its siblings on the same key still answer upstream, // and the model's own sentence rests with the model, not on every // sibling's refusal (#3039) - if modelLimited(c, why, body) { + if modelLimitedBy(c, why, header, body) { id = c.restID() } // out of credit, or of a quota, on a model that costs credits where @@ -1883,6 +1885,33 @@ func modelLimited(c candidate, why string, body []byte) bool { return modelCooledDown(why, body) || modelNamed(c, why, body) } +// modelLimitedBy is modelLimited, and a Claude account's plain rate limit +// (claudeModelRate) too, which the reply's headers help tell. +func modelLimitedBy(c candidate, why string, header http.Header, body []byte) bool { + return modelLimited(c, why, body) || claudeModelRate(c, why, header, body) +} + +// claudeModelRate says a Claude account's 429 rate_limit_error, which names +// no window, is the limit of the model it was sent for: Anthropic counts +// rate limits per model (kaitokiku on X: Fable rate limited rested the +// account, and Opus showed "限流 · 42 分钟后恢复" with it, though Opus +// answered). A refusal of the account's allowance rests the account: the +// 5-hour, session, weekly or usage words (failQuota, never failRate), or +// anthropic-ratelimit-unified headers whose representative claim is a +// window that counts every model. +func claudeModelRate(c candidate, why string, header http.Header, body []byte) bool { + if why != failRate || c.model == "" || c.p.Account == nil || c.p.Account.UsageAgent() != "claude" { + return false + } + if claim := strings.ToLower(header.Get("anthropic-ratelimit-unified-representative-claim")); claim != "" { + switch claim { + case "five_hour", "seven_day", "overage", "session", "weekly": + return false + } + } + return !claudeWindowWords.Match(bytes.ToLower(wordsOf(body))) +} + // modelNamed says a rate or quota refusal names c's model in the vendor's // words, as the vendors that count per model do: OpenAI's "Rate limit // reached for gpt-4o in organization … on tokens per min", Groq's "Rate @@ -2076,7 +2105,7 @@ func vendorSaidWhen(header http.Header, body []byte) bool { // count where it is, so one request's own retries don't stretch it. func (s *Server) rateRest(c candidate, header http.Header, body []byte, sharedPool bool, now time.Time) (time.Duration, string, int) { id := c.restKey() - if c.isOpenRouterFree() && sharedPool || remoteModelRest(c, failRate, header) || modelLimited(c, failRate, body) { + if c.isOpenRouterFree() && sharedPool || remoteModelRest(c, failRate, header) || modelLimitedBy(c, failRate, header, body) { id = c.restID() } n := 1