diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 00474d855..9d192cfbc 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -342,7 +342,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`). - A plugin's window that says no models (`model`, `models`, `notModels`) but is named by a model id its provider serves counts that model only (`provider.namedModelWindows`): Google AI Studio's plugin (`@dorokuma/magpie-gemini-web`'s `ai-studio`) tells each model's cooldown as a window named after it, used 100 until it ends. Read as the whole account's, gemini-4-hydrogen's daily 429 held the account from every model till the reset, while argon still answered (WangYeruo on X). Its window for every model ("所有模型") stays the account's. A window kept this way has a `matches`, so `keepLast` doesn't write the reading down (`TestPluginWindowNamedByModelCountsThatModel`, `TestAIStudioModelDayRestsTheModel`). - An account is held at a usage cap (`capHeld`) or rested out of one model's pool (`pooled`). A key whose windows magpie reads (`provider.TakesUsageCap`: `readsKeyWindows`, OpenCode Go's 5 hours, week and month among them) takes the same cap by its key id (`AccountCaps`, `AccountWindowCaps`; @wanggenjidev on X) and is barred in `perKeyEvery` (`keyCapHeld`, `Provider.KeyCapHeld`) once a window is at it, as an account is, and back when that window renews. Windows not read yet, or a read that failed, hold nothing (`KeyAllowance` keeps the last good reading, `TestKeyUsageCapPassesTheKeyOver`). `CapCareful` and the one-turn-at-a-time rule near a cap are an account's only. A key is also held at its own spend cap (below). - A key at its spend cap ([providers](providers-accounts.md), `provider.SpendCap`) is barred in `perKeyEvery` (`spendHeld`) with a `capHold` whose `spend` is set: it is passed over and the provider's other keys and its fallbacks take the request. Routing's row says what it spent of its cap (`Weighed.SpendCap`, `Spent`, `SpendPeriod`, `SpendSince`). With every candidate held, `cappedError` answers 429 naming each key, what it spent of its cap and when it is back (the next day or month, or not until a cap in all is raised), and the command that changes it, with `Retry-After` at the soonest; a cap in all gives none. A spend hold is not a usage cap: `capHeldOnly` leaves it out, so neither Stop at the caps (`CapStop`) nor Strict's `strictKeep` sends a request to a key past what it may spend. `TestKeySpendCapPassesTheKeyOver`. -- A 429 for want of rate or quota whose words name the model asked (`modelNamed`: OpenAI's "Rate limit reached for gpt-4o in organization …", Groq's "for model `…`", Gemini's QuotaFailure with the model in `quotaDimensions`, WJaunita45604 on X) rests that model on that key or account alone (`modelLimited`, `restID`), with its backoff and its sink, and the other models are asked straight. The name is matched as a whole id (`gpt-4o` is not `gpt-4o-mini`). A refusal that names no model, one for want of credit, and a plain failure still rest the key or account whole. +- A 429 for want of rate or quota whose words name the model asked (`modelNamed`: OpenAI's "Rate limit reached for gpt-4o in organization …", Groq's "for model `…`", Gemini's QuotaFailure with the model in `quotaDimensions`, WJaunita45604 on X) rests that model on that key or account alone (`modelLimited`, `restID`), with its backoff and its sink, and the other models are asked straight. The name is matched as a whole id (`gpt-4o` is not `gpt-4o-mini`). A refusal that names no model, one for want of credit, and a plain failure still rest the key or account whole. Antigravity's quota refusal (`antigravityPoolSpent`: agy's "Individual quota reached … Resets in …", relayed by the agy-cli plugin, and Code Assist's "You have exhausted your capacity on this model") names no model but is the model's pool's, as Google counts Antigravity per pool (Claude and GPT, Gemini apart): it rests the model too, so the account's other pools are still asked and `timedHeld` doesn't answer them from the rest (BruceLu73129013 on X). Only on a Google sign-in (`googleSignIn`: Antigravity, Gemini CLI, and the antigravity and agy-cli plugins); another vendor's "individual quota reached" rests what it did (`TestCodexCompactCutSummaryFailsOver`). agy-cli's usage windows are display only (`aside`), so no reading narrows the rest for it. - 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 `plugins/routing/client.js`, #1960, `routing-model-rest.test.cjs`). - The Providers page shows a subscription account's rests in force on its row there too: `RestsUnder("@")` lists them, `providerJSON.accountRests` gives them by user in lower case (the account's own, and each model's, with `Rest.Model`, `Until`, `By` and the vendor's words, `Rest.Error`), and the row's line says which model, why and when it is back, the vendor's words beside it, with Try now lifting it by its key (`accountRestLines` in app.js). Before, only a key's rest showed there, and a WorkBuddy AI account whose model rested on a 429 "将在 … 重置" read as fine, its credits 82% left (maxleebeta on Discord; `TestRateLimitedModelListedUnderAccount`, `TestAccountRestsInProviderState`, `account-rest.test.cjs`). - 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`). diff --git a/internal/gateway/agy_quota_test.go b/internal/gateway/agy_quota_test.go index 9a12fd679..4d594790e 100644 --- a/internal/gateway/agy_quota_test.go +++ b/internal/gateway/agy_quota_test.go @@ -1,7 +1,10 @@ package gateway import ( + "io" + "net/http" "strings" + "sync" "testing" "time" @@ -61,7 +64,7 @@ func TestAgyCLIQuotaNoticeRestsUntilItsResetAndFallsOver(t *testing.T) { } // A reply that had begun before the quota ran out can't be taken back: the -// client keeps its words and is told why it stopped, and the account rests +// client keeps its words and is told why it stopped, and the model rests // until its reset all the same. func TestAgyCLIQuotaNoticeMidReplyStillRests(t *testing.T) { fresh(t) @@ -100,3 +103,91 @@ func TestAgyQuotaNoticeResetIsRead(t *testing.T) { } } } + +// BruceLu73129013 on X (magpie 0.1.4342, agy-cli 0.1.87): Opus's quota used +// up, Gemini 4 Carbon on the same account, its quota left, was answered the +// same 429 from magpie's rest (timedHeld on agy-cli@). Antigravity +// counts quota per pool of models (Claude and GPT, Gemini apart), so its +// refusal rests the model it was for, and the account's other models are +// still asked. agy-cli's usage windows are display only (aside), so no +// reading narrows the rest for it. +func TestAgyCLIQuotaRestsTheModelNotTheAccount(t *testing.T) { + for _, said := range []string{ + "agy bridge: Antigravity quota reached: " + agyQuotaNotice, + // Code Assist's words for the same, through any route + "You have exhausted your capacity on this model. Your quota will reset after 1h18m40s.", + } { + t.Run(said[:20], func(t *testing.T) { + fresh(t) + acct := func(model string) candidate { + return candidate{p: provider.PluginForTest("agy-cli", "agy-cli"), model: model, rest: "agy-cli"} + } + opus, carbon := acct("claude-opus-5-5"), acct("gemini-4-carbon") + s := &Server{} + r := s.restAfter(opus, http.StatusTooManyRequests, http.Header{}, []byte(`{"type":"error","error":{"type":"rate_limit_error","message":"`+said+`"}}`)) + if r.Why != failQuota || r.By != "resets" || r.Key != opus.restID() || r.Model != opus.model { + t.Fatalf("rest: %+v", r) + } + if _, _, held := timedHeld([]candidate{opus}); !held { + t.Fatal("Opus, refused until its reset, is asked again") + } + if r, ok := restingOf(carbon); ok { + t.Fatalf("Gemini 4 Carbon rests with Opus: %+v", r) + } + if _, _, held := timedHeld([]candidate{carbon}); held { + t.Fatal("Gemini 4 Carbon is answered Opus's 429 from the rest") + } + }) + } + // a quota refusal in other words, which tells no pool, still rests the + // account it came from; and so do Antigravity's words from another + // vendor, which has no pools + for _, c := range []struct { + p provider.Provider + said string + }{ + {provider.PluginForTest("agy-cli", "agy-cli"), "Quota exceeded. Resets in 1h."}, + {provider.PluginForTest("other", "other"), agyQuotaNotice}, + } { + fresh(t) + other := candidate{p: c.p, model: "m", rest: c.p.ID} + if r := (&Server{}).restAfter(other, http.StatusTooManyRequests, http.Header{}, []byte(`{"type":"error","error":{"type":"rate_limit_error","message":"`+c.said+`"}}`)); r.Key != other.restKey() { + t.Fatalf("%s %q rested %+v, want the account", c.p.ID, c.said, r) + } + } +} + +// Through the gateway and the plugin host: the agy-cli plugin's Claude +// model refused with agy's notice, the next request for its other model on +// the same account goes to it and is answered. +func TestAgyCLIQuotaLeavesTheOtherPoolAsked(t *testing.T) { + var mu sync.Mutex + var paths []string + // no model of it free, as agy-cli lists none: a paid model beside a + // free one rests alone anyway (PaidBesideFree) + t.Setenv("FAKE_NO_FREE", "1") + pid := besideFake(t, "agy-cli", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + paths = append(paths, r.URL.Path) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/messages") { + w.WriteHeader(http.StatusTooManyRequests) + io.WriteString(w, `{"type":"error","error":{"type":"rate_limit_error","message":"agy bridge: Antigravity quota reached: `+agyQuotaNotice+`"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"choices":[{"delta":{"content":"hello"}}]}`, + `data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`, `data: [DONE]`)) + })) + s := New() + if code, body := postAs(t, s, "", `{"model":"`+pid+`/fake-claude","messages":[{"role":"user","content":"hi"}]}`); code != http.StatusTooManyRequests { + t.Fatalf("the Claude model answered %d %s", code, body) + } + code, body := postAs(t, s, "", `{"model":"`+pid+`/fake-1","messages":[{"role":"user","content":"hi"}]}`) + mu.Lock() + defer mu.Unlock() + if code != 200 || !strings.Contains(body, "hello") { + t.Fatalf("the other pool's model: %d %s (vendor asked %v)", code, body, paths) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index ee4d53379..850ba27ed 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -1838,8 +1838,9 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo if zcodeTrialRestricted(c, why) { id = c.restID() } - // a relay's 429 that names the model whose credentials cooled down, or a - // vendor's that names the model it limits (modelNamed), is + // a relay's 429 that names the model whose credentials cooled down, a + // vendor's that names the model it limits (modelNamed), or + // Antigravity's for the model's pool (antigravityPoolSpent), is // 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) @@ -1941,10 +1942,34 @@ func modelCooledDown(why string, body []byte) bool { // modelLimited says a refusal for want of quota, credit or rate is the // model's own, not the key's or account's: a relay's pooled credentials of -// the model cooled down (modelCooledDown), or the vendor's words name the -// model it limited (modelNamed). +// the model cooled down (modelCooledDown), the vendor's words name the +// model it limited (modelNamed), or Antigravity's quota of the model's +// pool is used up (antigravityPoolSpent). func modelLimited(c candidate, why string, body []byte) bool { - return modelCooledDown(why, body) || modelNamed(c, why, body) + return modelCooledDown(why, body) || modelNamed(c, why, body) || antigravityPoolSpent(c, why, body) +} + +// antigravityPoolQuota is Antigravity's refusal of a model whose quota pool +// is used up, in agy's words ("Individual quota reached. Please upgrade +// your subscription to increase your limits. Resets in 1h18m40s.", which +// the agy-cli plugin relays) or Code Assist's ("You have exhausted your +// capacity on this model. Your quota will reset after 3h19m30s."). +var antigravityPoolQuota = lazyre.New(`(?i)\bindividual quota reached\b|\bexhausted your capacity on this model\b`) + +// antigravityPoolSpent says a quota refusal is Antigravity's for the +// model's pool, not the account's: Google counts an Antigravity account's +// quota per pool of models (Claude and GPT in one, Gemini's apart), and +// has no allowance of the whole account to run out. It rests the model, +// so the account's other pools are still asked. BruceLu73129013 on X +// (agy-cli 0.1.87): Opus used up rested the account, and Gemini 4 Carbon, +// its quota left, was answered the same 429 from the rest (timedHeld). +// The retired built-in's readings told the pools apart (Pooled); agy-cli's +// windows are display only (aside), so routing has no reading to narrow +// the rest by, and the refusal's own words are what tell it. Only a +// Google sign-in's (googleSignIn): another vendor's "individual quota +// reached" says nothing of pools, and rests what it always did. +func antigravityPoolSpent(c candidate, why string, body []byte) bool { + return c.model != "" && (why == failQuota || why == failRate) && googleSignIn(c.p) && antigravityPoolQuota.Match(wordsOf(body)) } // modelLimitedBy is modelLimited, and a Claude account's plain rate limit