From af39ee4b5f6519da89db8d295a245a0ccaf68d71 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 13 Oct 2026 17:48:08 +0800 Subject: [PATCH] gateway: a 402 for a usage limit rests the model out of quota, until the window renews (#1979) Factory answers a Standard pool used up with 402 "You've reached your weekly standard usage limit (resets in 0h 19min). Switch to Droid Core ...". failure() read every 402 as out of credit, so the whole account rested a fixed 30 minutes: its Droid Core models (GLM-5.3, the reporter's fallback) were skipped with it, the "resets in" was ignored, and renewed() never lifted the rest when the window came back, since it lifts only failQuota or By=="window" rests (Ziqi-Cui, 09:16Z). - failure(): a 402 that matches usedUpWords and says nothing of money (creditWords, insufficient_quota) is failQuota. A payment 402, an empty one, Kiro's monthly count, Command Code's credits stay credit. - With failQuota the pooled check applies: Factory's Standard windows are scoped away from Core (built-in factoryQuota matches; the plugin's notModels/models through quotaOfPlugin), so only the model rests, and only until its window's end. - resetsAt also reads "resets in Xd Yh Zmin" (resetsAfter) when no windows are known, capped at longestWritten. - FactoryAllowanceForTest / PluginAllowanceForTest let the gateway test build both paths' allowances from their real payloads. Run: TestFactoryStandardOutLeavesCore (built-in and plugin:factory), TestPaymentRequiredReadByItsWords, TestResetsInWords; full internal/gateway (327s) and internal/provider ok; gofmt -l; go vet darwin, windows, linux -tags nogui. Broken by hand: the new failure() case removed -> both subtests red (account rested for credit, GLM resting); resetsAfter returning 0 -> TestResetsInWords red; quotaOfPlugin's notModels ignored -> plugin subtest red. Not tried: a live Factory account; Factory's Droid Core used-up wording is assumed to read like Standard's. --- docs/subsystems/gateway-routing.md | 1 + internal/gateway/factory_pool_rest_test.go | 179 +++++++++++++++++++++ internal/gateway/routing.go | 37 ++++- internal/provider/factory_usage.go | 10 ++ internal/provider/plugin_usage.go | 11 ++ 5 files changed, 237 insertions(+), 1 deletion(-) create mode 100644 internal/gateway/factory_pool_rest_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index c9f84b183..af893dad4 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -107,6 +107,7 @@ recorded as a prediction failure (`noPrediction`). - An account resting out of its window (a Claude account by the time Claude Code's refusal named, `resets`, or any by `window`) is back once magpie's reading of its windows (`provider.Allowances`) finds it full till sooner: the window used below `SpentShareOf`, or its reset passed, with no other window over the same models still full. The reading tells `provider.OnRenewed` as the account's `UsageAgent` and user, and `renewed` lifts that account's rests out of quota or by `window`; its rests for a rate limit, its credit, a verification or a failure stay, as a key's do, and so does every rest of other accounts still out of their windows. Planning reads every account candidate's allowance, ordered groups included, so this needs no step of its own in `restingOf`. - Only an account is held at a usage cap (`capHeld`) or rested out of one model's pool (`pooled`); a key's windows order it and rest it, nothing more. - A rest of one model alone (keyed by `restID`: a pool, a model not served, a paid model beside free ones) names that model in the trace (`Rest.Model`). The Routing page shows it on that model's rows only: the account's other models' rows on the stage, and the account's row under Accounts and keys, don't read as resting. The account's row names the models resting on a line of their own under what it has left, and its Try now lifts their rests. A kept request from before `Rest.Model` has the model on the end of `Rest.Key`, which the page reads the same (`restModel` in `routing.js`, #1960, `routing-model-rest.test.cjs`). +- 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`). - 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); 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 request built for a Messages upstream (`buildAnthropic`: a Chat, Responses or Gemini client translated, and Zed's bridge) has its tool exchanges mended after its messages are built (`pairToolBlocks`, #1558, ggbdpq), since Anthropic answers 400 for a `tool_use` the next message doesn't answer and for a `tool_result` naming no call of the message before it. A call left unanswered gets the synthetic interrupted result, `is_error` set, first in the user message after it or in one of its own; a result that answers no call goes as a text block with what it said (its images as they came); a second answer to one call is dropped. A well-formed exchange goes as it was built. An Anthropic client relayed to a Messages upstream isn't mended. [`anthropic_tool_pairing_test.go`](../../internal/gateway/anthropic_tool_pairing_test.go). diff --git a/internal/gateway/factory_pool_rest_test.go b/internal/gateway/factory_pool_rest_test.go new file mode 100644 index 000000000..74c784426 --- /dev/null +++ b/internal/gateway/factory_pool_rest_test.go @@ -0,0 +1,179 @@ +package gateway + +import ( + "net/http" + "strconv" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// factoryStandardOut is Factory's refusal for Standard's week used up, as +// #1979 quotes it, with the 402 it comes with. +const factoryStandardOut = `{"error":{"message":"Factory: You've reached your weekly standard usage limit (resets in 0h 19min). Switch to Droid Core or enable Extra Usage to continue."}}` + +// Factory's Standard pool used up is Standard's: the account's Droid Core +// models still answer (#1979, Ziqi-Cui: a group of claude-opus-5-5 then +// glm-5.3 on two Factory accounts fell back to GLM a few times, then every +// request was Opus's 402, both accounts resting 30 minutes "for credit"). +// The allowance is as the built-in reads /api/billing/limits and as the +// plugin hands its windows on (Standard's notModels, Core's models), so a +// moved Factory is held to the same. +func TestFactoryStandardOutLeavesCore(t *testing.T) { + now := time.Now() + soon := now.Add(19 * time.Minute).UTC().Format(time.RFC3339) + later := now.Add(4 * 24 * time.Hour).UTC().Format(time.RFC3339) + limits := func(std, core int) []byte { + return []byte(`{"limits":{"standard":{"fiveHour":{"usedPercent":` + strconv.Itoa(std) + `,"windowEnd":"` + soon + `"},"weekly":{"usedPercent":` + strconv.Itoa(std) + `,"windowEnd":"` + soon + `"}},` + + `"core":{"fiveHour":{"usedPercent":` + strconv.Itoa(core) + `,"windowEnd":"` + later + `"},"weekly":{"usedPercent":` + strconv.Itoa(core) + `,"windowEnd":"` + later + `"}}},"extraUsageAllowed":false,"extraUsageBalanceCents":0}`) + } + // the factory plugin's limitWindows on limits(100, 1), as it answers + // usage (packages/factory/index.mjs, 0.1.x), its windows' ends moved + // to now + core := `["glm-5.3","glm-5.3-flash","glm-5.2","kimi-k3","deepseek-v4.1-flash","qwen3.8-max","minimax-m3","minimax-m2.7","mistral-medium-3.5","nemotron-3-ultra"]` + pluginUsage := func(std, coreUsed int) []byte { + return []byte(`{"windows":[` + + `{"name":"5 hours","used":` + strconv.Itoa(std) + `,"span":18000,"resetsAt":"` + soon + `","notModels":` + core + `},` + + `{"name":"7 days","used":` + strconv.Itoa(std) + `,"span":604800,"resetsAt":"` + soon + `","notModels":` + core + `},` + + `{"name":"Droid Core · 5 hours","used":` + strconv.Itoa(coreUsed) + `,"span":18000,"resetsAt":"` + later + `","models":` + core + `},` + + `{"name":"Droid Core · 7 days","used":` + strconv.Itoa(coreUsed) + `,"span":604800,"resetsAt":"` + later + `","models":` + core + `}]}`) + } + + for _, way := range []struct { + name string + agent string + of func(std, core int) provider.Allowance + }{ + {"built-in", "factory", func(std, core int) provider.Allowance { + return provider.FactoryAllowanceForTest(limits(std, core), now) + }}, + {"plugin", "plugin:factory", func(std, core int) provider.Allowance { + return provider.PluginAllowanceForTest(pluginUsage(std, core), now) + }}, + } { + t.Run(way.name, func(t *testing.T) { + old := allowances + defer func() { allowances = old }() + fresh(t) + al := map[string]provider.Allowance{"a@x.com": way.of(100, 1), "b@x.com": way.of(100, 1)} + allowances = func(string) map[string]provider.Allowance { return al } + acct := func(user, model string) candidate { + return candidate{p: provider.Provider{ID: "factory", Account: &provider.Account{Agent: way.agent, User: user}}, model: model, rest: "factory"} + } + s := &Server{} + + // both accounts' Opus refused for Standard, as in the report + for _, u := range []string{"a@x.com", "b@x.com"} { + opus := acct(u, "claude-opus-5-5") + r := s.restAfter(opus, 402, http.Header{}, []byte(factoryStandardOut)) + if r.Why != failQuota || r.Key != opus.restID() { + t.Fatalf("%s: Standard used up rests %+v, want Opus alone out of quota", u, r) + } + if d := time.Until(r.Until); d > 20*time.Minute { + t.Fatalf("%s: Opus rests %v, past Standard's window", u, d) + } + // Droid Core's models on the same account, and Standard's + // own siblings told apart from them + if _, ok := restingOf(acct(u, "glm-5.3")); ok { + t.Fatalf("%s: Standard used up rests GLM-5.3, which Droid Core counts", u) + } + if _, ok := restingOf(acct(u, "kimi-k3")); ok { + t.Fatalf("%s: Standard used up rests Kimi K3", u) + } + } + // read again once Standard's window has renewed, Opus is back: + // a rest out of quota is lifted by the reading, as one for + // credit wasn't (Ziqi-Cui on #1979) + renewed(way.agent, "a@x.com") + if _, ok := restingOf(acct("a@x.com", "claude-opus-5-5")); ok { + t.Fatal("Opus still rests after Standard's window renewed") + } + if _, ok := restingOf(acct("b@x.com", "claude-opus-5-5")); !ok { + t.Fatal("one account's window renewed lifted the other's rest") + } + // the next requests still go to GLM: nothing rests it, and the + // group's order doesn't spend it with Opus + for i := 0; i < 3; i++ { + if spentAfter([]candidate{acct("a@x.com", "glm-5.3"), acct("b@x.com", "glm-5.3")}) { + t.Fatal("GLM-5.3 counted spent after Opus's Standard refusal") + } + } + + // Droid Core used up leaves Standard to the vendors' models + fresh(t) + al = map[string]provider.Allowance{"a@x.com": way.of(10, 100)} + glm := acct("a@x.com", "glm-5.3") + r := s.restAfter(glm, 402, http.Header{}, []byte(`{"error":{"message":"Factory: You've reached your weekly Droid Core usage limit (resets in 3d 4h)."}}`)) + if r.Why != failQuota || r.Key != glm.restID() { + t.Fatalf("Core used up rests %+v, want GLM alone", r) + } + if _, ok := restingOf(acct("a@x.com", "claude-opus-5-5")); ok { + t.Fatal("Core used up rests Opus, which Standard counts") + } + + // an account out of money is still out whole + fresh(t) + al = map[string]provider.Allowance{"a@x.com": way.of(100, 1)} + opus := acct("a@x.com", "claude-opus-5-5") + r = s.restAfter(opus, 402, http.Header{}, []byte(`{"error":{"message":"Payment required: your subscription payment failed"}}`)) + if r.Why != failCredit || r.Key != opus.restKey() { + t.Fatalf("a payment 402 rests %+v, want the account out of credit", r) + } + if _, ok := restingOf(acct("a@x.com", "glm-5.3")); !ok { + t.Fatal("a payment 402 leaves the account's other models in") + } + }) + } +} + +// A 402 is out of quota when it speaks of a usage limit and nothing of +// money, and out of credit otherwise. +func TestPaymentRequiredReadByItsWords(t *testing.T) { + for _, c := range []struct { + body, want string + }{ + {factoryStandardOut, failQuota}, + {`{}`, failCredit}, + {`{"error":{"message":"Insufficient Balance"}}`, failCredit}, + {`{"error":{"message":"You have reached the limit.","reason":"MONTHLY_REQUEST_COUNT"}}`, failCredit}, + {`{"error":{"message":"usage limit reached, please top up your credit"}}`, failCredit}, + {`{"error":{"code":"insufficient_quota","message":"You exceeded your current quota"}}`, failCredit}, + {`Command Code: you have used this month's credits`, failCredit}, + } { + if got := failure(402, []byte(c.body)); got != c.want { + t.Errorf("402 %s: %s, want %s", c.body, got, c.want) + } + } +} + +// A refusal that says how long until it is back in hours and minutes rests +// that long when the account's windows aren't known: Factory's "resets in +// 0h 19min" was a 30-minute credit rest (#1979). +func TestResetsInWords(t *testing.T) { + for _, c := range []struct { + body string + want time.Duration + }{ + {factoryStandardOut, 19 * time.Minute}, + {`{"error":{"message":"weekly limit reached (resets in 2d 3h)"}}`, 51 * time.Hour}, + {`{"error":{"message":"limit reached, resets in 45 minutes"}}`, 45 * time.Minute}, + {`{"error":{"message":"limit reached, resets in 5 messages"}}`, 0}, + {`{"error":{"message":"resets in 30d"}}`, 0}, // past longestWritten + {`{"error":{"message":"usage limit reached"}}`, 0}, + } { + if got := resetsAfter([]byte(c.body)); got != c.want { + t.Errorf("%s: %v, want %v", c.body, got, c.want) + } + } + + old := allowances + defer func() { allowances = old }() + fresh(t) + allowances = func(string) map[string]provider.Allowance { return nil } + c := candidate{p: provider.Provider{ID: "factory", Account: &provider.Account{Agent: "factory", User: "a@x.com"}}, model: "claude-opus-5-5", rest: "factory"} + r := (&Server{}).restAfter(c, 402, http.Header{}, []byte(factoryStandardOut)) + if d := time.Until(r.Until); r.Why != failQuota || r.By != "resets" || d < 18*time.Minute || d > 19*time.Minute { + t.Fatalf("Standard used up, windows unknown, rests %v: %+v", d, r) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index e396514a5..ac8d0df34 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -279,6 +279,13 @@ func failure(status int, body []byte) string { // Kimi's "exceeded model token limit" is the conversation's // length, not the plan's return failOther + case status == 402 && usedUpWords.Match(body) && !creditWords.Match(body) && !strings.Contains(string(body), "insufficient_quota"): + // a 402 that says a usage limit and nothing of money is out of + // quota, not of credit: Factory's "You've reached your weekly + // standard usage limit (resets in …). Switch to Droid Core …" is + // Standard's pool, which counts some models only, and read as the + // account out of credit it rested Droid Core with it (#1979) + return failQuota case status == 402, creditWords.Match(body) && (status != 429 || brokeWords.Match(body)) || strings.Contains(string(body), "insufficient_quota"): return failCredit case status == 429 && resetsWhen.Match(body): @@ -499,7 +506,35 @@ func resetsAt(body []byte, now time.Time) time.Duration { if d := resetsIn(body, now); d > 0 { return d } - return resetsWritten(body, now) + if d := resetsWritten(body, now); d > 0 { + return d + } + return resetsAfter(body) +} + +// resetsInWords: a refusal that says how long until it is back in days, +// hours and minutes, as Factory's 402 does: "You've reached your weekly +// standard usage limit (resets in 0h 19min)" (#1979). At least one of +// them, each a number and its unit, and nothing else between. +var resetsInWords = regexp.MustCompile(`(?i)\bresets? in (?:(\d+)\s*d(?:ays?)?\b\s*)?(?:(\d+)\s*h(?:ours?|rs?)?\b\s*)?(?:(\d+)\s*m(?:in(?:utes?|s)?)?\b)?`) + +// resetsAfter is how long the refusal says until it is back (resetsInWords), +// held to longestWritten. Zero when it doesn't say. +func resetsAfter(body []byte) time.Duration { + m := resetsInWords.FindSubmatch(wordsOf(body)) + if m == nil || len(m[1])+len(m[2])+len(m[3]) == 0 { + return 0 + } + var d time.Duration + for i, unit := range []time.Duration{24 * time.Hour, time.Hour, time.Minute} { + if n, err := strconv.Atoi(string(m[i+1])); err == nil { + d += time.Duration(n) * unit + } + } + if d > longestWritten { + return 0 + } + return d } // longestWritten is the furthest off a reset time written in words is diff --git a/internal/provider/factory_usage.go b/internal/provider/factory_usage.go index 127967a94..f4a89750f 100644 --- a/internal/provider/factory_usage.go +++ b/internal/provider/factory_usage.go @@ -133,3 +133,13 @@ func factoryLoginQuota(ctx context.Context, l Login) SubscriptionQuota { q.Windows = factoryQuota(lim) return q } + +// FactoryAllowanceForTest is the allowance an account's /api/billing/limits +// answer gives routing, for the gateway's tests. +func FactoryAllowanceForTest(limits []byte, now time.Time) Allowance { + var l factoryLimits + if json.Unmarshal(limits, &l) != nil { + return nil + } + return allowanceOf(factoryQuota(l), now) +} diff --git a/internal/provider/plugin_usage.go b/internal/provider/plugin_usage.go index 3f2acd401..684458f5c 100644 --- a/internal/provider/plugin_usage.go +++ b/internal/provider/plugin_usage.go @@ -8,6 +8,7 @@ package provider import ( "context" + "encoding/json" "net/http" "regexp" "strings" @@ -251,3 +252,13 @@ func (a *Account) UsageAgent() string { } return a.Agent } + +// PluginAllowanceForTest is the allowance a plugin's usage answer gives +// routing, for the gateway's tests. +func PluginAllowanceForTest(usage []byte, now time.Time) Allowance { + var u plugin.Usage + if json.Unmarshal(usage, &u) != nil { + return nil + } + return allowanceOf(quotaOfPlugin(SubscriptionQuota{}, u).Windows, now) +}