gateway: the Qwen Token Plan's concurrency 429 is asked again on the same account (pelikanade on X)

pelikanade on X: under many requests at once the Qwen Token Plan answers
"HTTP 429: Qwen Token Plan: Allocated quota exceeded, please increase
your quota limit" with plenty of quota left, and a retry by hand works.

Cause: d83f887a7 made DashScope's "Allocated quota exceeded" a rate
limit for the rest (dashScopeRate, in failureOf), but passing and busy,
which decide whether the same one is asked again and whether patience
waits, read the body through failure(), which knows no vendor and reads
"quota" as out of quota. So a lone Qwen Token Plan provider gave the
agent the 429 after one try. A group moved on at once and rested the
member a minute.

Fix (qwen_plan_busy.go, gateway.go):
- qwenPlanBusy: a 429 from the qwen-token-plan preset or a provider at
  token-plan.maas.qianwenaiapi.com, in dashScopeRate's words (not its
  free allowance, nor a Coding Plan's hour/week/month).
- passingFor/busyFor replace passing/busy at the try loop's last-one
  and patience sites: that 429 is asked again on the same account up to
  rateRetries (3) times, with jittered pauses of about 1, 2 and 4s (half
  to one and a half of each, so one burst's requests don't come back
  together), or after the vendor's Retry-After, then within the
  provider's patience, as any rate limit is. The error is held, so
  nothing reaches the agent before then.
- A group member that isn't last is asked again in place as often
  (planAgain) before the group moves on. Only then does it rest, as a
  rate limit (failRate, a minute), never as out of quota.
- Other vendors are unchanged. DashScope pay-as-you-go (same words, a
  real per-minute limit), the Bailian and Alibaba Cloud Token Plans and
  any other provider still get one try. Bailian and Alibaba Cloud are
  the same plan on other hosts, but nobody has reported the concurrency
  429 there: #6950.
- docs/subsystems/gateway-routing.md: a bullet after the minute-limit one.

Tests (fixtures are the reporter's words, in OpenAI's and DashScope's
error shapes, and Anthropic's for /apps/anthropic):
TestQwenPlanConcurrencyIsAskedAgain (lone: 429, 429, 200 is served on
the 3rd try with no rest; one that never clears is tried 1+3+12 times,
like any rate limit), TestQwenPlanConcurrencyInAGroup (served in place,
or after 4 tries the next member is asked and the member rests as
rate), TestQwenPlanConcurrencyOnAnthropic,
TestOtherVendorsAllocatedQuotaUnchanged (qwen-cn, bailian-token-plan
and a plain relay: one try alone, next member at once in a group),
TestQwenPlanBusyScope.

Run:
- Red on the old code (gateway.go from origin/main, the new tests kept):
  IsAskedAgain gave "429 after 1 tries" with the reporter's exact text
  ("Qwen Token Plan: Allocated quota exceeded, please increase your
  quota limit"), and InAGroup gave qwen 1, b 1.
- Broken by hand, the scope widened to every DashScope provider:
  TestOtherVendorsAllocatedQuotaUnchanged went red for qwen-cn and
  bailian-token-plan (alone 200 after 3 tries; in a group a 3, b 0), and
  TestQwenPlanBusyScope went red for dashscope.aliyuncs.com and
  token-plan.cn-beijing.
- mica: go test ./... -count=1 -timeout 45m at 9fa2a63c0 (this change
  on 167101d57): 102 ok, internal/gateway FAIL on my own test only.
  IsAskedAgain checked Again > 0, but a jittered 1ms test pause can
  round to 0ms. It now checks Fail == rate. The "close of closed
  channel" in the log is a recovered http panic in continuation_test's
  doneHold fake, and the package's verdict didn't depend on it.
- mica: the new tests -count=20 ok after the fix.
- At the pushed tree (rebased on cd89ccdb4): go vet, GOOS=linux go vet
  -tags nogui and GOOS=windows go vet of ./internal/gateway, and go test
  ./internal/gateway -count=1 -timeout 45m: vet ok on all three, ok (957s). gofmt -l empty.
- Rebased again on 64ad53f6c (claude_subscription.go and sessions_mcp.go
  changed in the gateway, not gateway.go): go vet ./internal/gateway and
  go test ./internal/gateway -run 'QwenPlan|OtherVendorsAllocatedQuota|
  DashScope|ClaudeSubscription': ok.

Not tried: a real Qwen Token Plan key under concurrency (there is none
here), so the real host's wait before it serves again is not measured.
This commit is contained in:
yetone
2026-11-17 17:40:23 +08:00
parent 64ad53f6c7
commit 0746140772
4 changed files with 301 additions and 4 deletions
+1
View File
@@ -337,6 +337,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`).
- A 5xx is a server error, not quota, unless the vendor's own quota code says so (`quotaCodes`: `usage_limit_reached`, `RESOURCE_EXHAUSTED`, Claude Code's `usage limit reached|<unix>`). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota by `usedUpWords` (上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (`usedUpWords`) still apply to a 4xx.
- A 429 that names in words when the account is back (WorkBuddy's "将在 2026-10-11 20:16:02 UTC+8重置" and "your usage will reset at 2026-10-11 12:37:53 UTC+8, …", #1669; Volcengine Ark's "You have exceeded the monthly usage quota. It will reset at 2026-10-25 23:59:59 +0800 CST.", #3251, #3276) is out of quota in either language (`resetsWhen`), and rests until that time (`resetsWritten`, read in the offset written). Only the reset phrasing right beside a whole date and time with its UTC/GMT offset, or its offset as Go prints one (four digits, then the zone's name, which isn't read), followed by 重置 or punctuation, is read, so a refusal cut short isn't read as UTC and another vendor's date in passing is no reset; a time past, not a real date, or further off than `longestSaid` isn't read: `longestWritten` (7 days), or `longestMonthly` (35 days) when the refusal says its allowance is a month's (`monthlyWords`: Ark's, Zhipu's 1310 "Weekly/Monthly Limit Exhausted"). Such a reset is the one rest out of quota held past `longestQuota`, to `longestMonthly`; a window read full or the user's own rest is still held to 8 days (`TestMonthlyWrittenResetRestsTheMonth`). Ark's windows as its AccessKey reads them (`volcPlanQuotas`) still reach only its usage card, not routing (#3251). Zhipu's 1308 and 1310 (Z.ai and bigmodel.cn, GLM Coding Plan: "Your limit will reset at 2026-10-15 20:12:13", "您的限额将在 … 重置") write the time with no zone; it is Beijing's, and is read as UTC+8 in those words only (`zhipuResets`, `resetsZhipu`), never when a digit, colon or zone of its own follows (Player on Discord: read by nothing, the key rested `quotaRest` and the refusal said "not asked again before 17:12" while Z.ai said 20:12; `TestZhipuRestsUntilItsReset`). One that points to the account's other models (`otherModels`: "切换其他模型", "switch to the other models") rests that model alone (`restID`). Out of credit or quota on a model that costs credits, where the subscription serves other models free (`catalog.Model.Free`: WorkBuddy's x0.00, Qoder's is_free, Cline's free models; `Provider.PaidBesideFree`), rests that model alone too: the free ones draw on no credits (Creat.wu on Discord, `TestOutOfCreditLeavesFreeModels`). A Credits window leaves the free models out the same way, so an account at 100% isn't ranked spent for them: the WorkBuddy plugin's lists them as `notModels` (0.1.23), and the built-in's scopes itself by the provider's last fetched list (`wbSpareFree`; with no list read, every model counts) (plugins#138, hheei: an account at 560 / 560 was still served deepseek-v4.1-flash; `TestWorkBuddyCreditsSpareFreeModels`). A free model the vendor refuses all the same (WorkBuddy refuses even 0-rate models to an account with no package) rests the account on its own refusal. Cline's daily limit of one free model, 429 "Daily free limit reached on model deepseek/deepseek-v4-flash. Try again in 23h 59m" (the words Cline's own clients read it by, `isClineFreeModelLimitMessage`), rests that model alone (`clineFreeLimit`, `clineModelLimited`, keyed by `restID`) until the time it names (`clineBackIn`, `tryAgainIn`, held to `longestWritten`; `resets`), from a provider whose requests reach Cline's API (`ClinePinnable`: the ClinePass preset, one at cline.bot, the Cline plugin's). The key's other models, free or the plan's, are still served, and the model out of its day is answered with its refusal without asking Cline again (#1398, wuasakura: one free model's 429 sent the whole Cline account to the back; `TestClineFreeLimitRestsTheModel`, `TestClineFreeLimitLeavesOtherModels`). Another vendor's same words, and a Cline 429 that doesn't name the model's limit, rest the key as before. WorkBuddy's 429 14018 "Credits exhausted" is out of credit (`brokeWords`), not a rate limit, on the built-in's raw body and the plugin's `insufficient_quota` alike (`TestCreditsExhaustedIsOutOfCredit`). On the rate-limit branch, a reset time the refusal names (`resetsAt`, or `resetsHeader` as `keepRetry` noted it) is believed up to `longestQuota`, as out of quota believes it, and the Routing page says it rests until then (`resets`); a `Retry-After` or a rate-limit reset header is still held to `longestWait` (an hour) (`rateRest`). The same rest runs for a plugin's requests: the WorkBuddy plugin passes these 429s on as they come (`TestPluginWrittenResetRests`). A JSON error body that escapes what isn't ASCII as `\uXXXX` (Python's json.dumps does by default) has its strings decoded before any word list (`creditWords`, `rateWords`, `plannedWords`, `usedUpWords`, `resetsWhen`, …) is matched (`wordsOf`), so an escaped 余额不足 or 用量 reads as an unescaped one does.
- A 429 that names a limit per minute or second (`minuteWords`: per minute, per second, TPM, RPM, `PerMinute` in Gemini's quotaId, Azure's "token rate limit" and "call rate limit") is a rate limit even when it calls itself a quota, unless it also names a longer window or a plan's limit (`longWords`: hour, day, week, month, usage limit, 用量, 套餐) or money spent (`brokeWords`, `insufficient_quota`) (`minuteLimit`). Gemini's "You exceeded your current quota … PerMinute", Vertex's "Quota exceeded for …requests_per_minute…" and Azure's rate limit, whose link is aka.ms/oai/quotaincrease, each rested a key the quarter of an hour of a quota with balance left (monater.114514 on Discord); now they rest as `rateRest` does, a minute or the vendor's `Retry-After`. Words inside a link (`urlWords`) don't make a rate limit a plan used up. DashScope words its TPM/TPS limit as a quota too, `Allocated quota exceeded, please increase your quota limit.` or OpenAI's `insufficient_quota`; from a DashScope provider (`dashScope`) those are rate limits (`dashScopeRate`, in `failureOf`), while its "Free allocated quota exceeded." and a Coding Plan's hour/week/month stay out of quota, and OpenAI's `insufficient_quota` stays out of credit (`TestMinuteLimitIsNotQuota`, `TestMinuteLimitRestsAMinute`, `TestDashScopeAllocationQuotaIsRate`).
- The Qwen AI platform's Token Plan (`qwenPlanBusy`: the `qwen-token-plan` preset, or a provider at `token-plan.maas.qianwenaiapi.com`) answers many requests at once with that same 429, `Allocated quota exceeded, please increase your quota limit`, its quota far from used, and the request asked again a moment later is served (pelikanade on X). `passing` read it as out of quota (`failure` knows no vendor), so the agent had the 429 after one try. Now `passingFor` and `busyFor` (`qwen_plan_busy.go`) take it as a rate limit: the last one left is asked again up to `rateRetries` times after jittered pauses of about 1, 2 and 4s (`jittered`, half to one and a half of each, so one burst's requests don't come back together), then within its patience; a group's member that isn't last is asked again in place as often (`planAgain`) before the group moves on, and only then rests as `dashScopeRate` says, a rate limit's minute. Nothing reaches the agent before. DashScope's pay-as-you-go hosts and the Bailian and Alibaba Cloud Token Plans keep the one try, their 429 resting as a rate limit as before (#6950; `TestQwenPlanConcurrencyIsAskedAgain`, `TestQwenPlanConcurrencyInAGroup`, `TestOtherVendorsAllocatedQuotaUnchanged`, `TestQwenPlanBusyScope`).
- Antigravity's 429 for a model's quota used up writes how long until it is back as Go prints a duration: "You have exhausted your capacity on this model. Your quota will reset after 3h19m30s." (`quotaResetAfter`, read by `resetsAfter` beside Factory's "resets in …", held to `longestWritten`). The account (or, as `pooled` says, that model on it) rests that long (`resets`), and the agent's Retry-After says it when no account is left. Unread, it rested `quotaRest`, so the account first in order was asked again, and refused, every 15 minutes while the next ticked account had its quota (Dani Ariyanto on Discord, 10-24; `TestAntigravityQuotaRestsUntilItsReset`). agy's own notice for an account's quota used up, "Individual quota reached. Please upgrade your subscription to increase your limits. Resets in 1h18m40s.", is read the same way; the agy-cli plugin (0.1.87) ends such a turn with a `rate_limit_error` in those words, mid-reply or not, where before it went to the client as the reply and the next account was never asked (@Airan_FS on X; `TestAgyCLIQuotaNoticeRestsUntilItsResetAndFallsOver`, `TestAgyCLIQuotaNoticeMidReplyStillRests`, `TestAgyQuotaNoticeResetIsRead`). Its other 429, "Resource has been exhausted (e.g. check quota).", names no time and rests `quotaRest` as before.
- A ZCode plugin account's Start Plan trial entry (`<model>-Trial`) that the plugin refuses before sending anything rests that entry alone (`zcodeTrialRefused`, `restID`), not the account: a 400 "ZCode has no active limited quota for GLM-5.3-Trial" when no live plan holds it any more (the trial ended), and a 429 "ZCode's limited quota for glm-5.3 is exhausted or temporarily unavailable" when its bucket is spent (the plugin names the bucket, the entry less `-Trial`). Read as `failQuota` by their words, both rested `zcode@…`, and the account's GLM Coding Plan models were paused with the trial (#3661, orion-nebula-dev; after skygunner's e04a1b994, which covered the 400). Only the plugin's exact words naming the model asked for count: another model named, a model without `-Trial`, the words on another status, the account's own quota or key, and the same words from another vendor still rest the account (`TestZCodeTrialRefusalRestsTheTrialAlone`). An expired trial still kept in a group is asked first and refused locally, as the guessed quota rest is asked again a minute on; the Routing page strikes it as skipped, which the gateway doesn't do for a member no account lists (#3805). ZCode's risk control refusing a trial entry (3012, `failRestricted`) rests that entry alone too (`zcodeTrialRestricted`): the entry goes to zcode.z.ai, a dual account's plain models to its GLM Coding Plan on api.z.ai, which kept serving them (young02036 on Discord, 11-07). The plain model's own 3012 rests the account, as on a gift-only account, where it goes to zcode.z.ai too.
- 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`.
+25 -4
View File
@@ -3617,6 +3617,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
wentTier := "" // the service tier the last try went out at (noteWireTier, #1784)
where := "" // the last try's provider.Where, for the usage
again := 0 // times the last one left has been tried again
planAgain := 0 // times a group's member was asked again in place for the Qwen Token Plan's concurrency 429 (qwenPlanBusy)
resealed := 0 // what of the conversation another account sealed was taken out: its reasoning, then its compaction
repicked := 0 // times Copilot's Auto was asked again for a model the account is served
floored := false // the reply's length raised to what the provider takes
@@ -5154,6 +5155,26 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
small, smallW = elsewhereWeighed(small, smallW, c)
last = i == len(cands)-1
}
if wait, ok := passingFor(c, hw.code(), hw.header, hw.errBody(), planAgain); ok && !protected && !last && !hw.passing && !hw.turnedAway && hw.failed() && qwenPlanBusy(c.p, hw.code(), hw.errBody()) && !kept.tooQuiet(wait) && !kept.outlives(wait) {
// the Qwen Token Plan turned the request away for its
// concurrency, its quota far from used (pelikanade on X): the
// same account is asked again after a jittered moment, a few
// times, before the group moves on to its next member, the
// account resting then as for a rate limit (dashScopeRate)
try.Fail, try.Again = failRate, wait.Milliseconds()
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
skipped = append(skipped, c.label()+": "+call.Error)
planAgain++
if pauseUntilReaddressed(r.Context(), wait, readdressedOf([]candidate{c})) {
i--
continue
}
call.Status, call.Error = canceled(r.Context())
try.Gone = true
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
break
}
planAgain = 0
if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !last && hw.failed() && spentAfter(cands[i+1:]) {
// the others left are out of their allowance (Discord, waroy: a
// Codex account run out, Grok busy a moment): this one is the
@@ -5391,7 +5412,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
forbade = append(forbade, forbidden{c: c, rest: rest, try: at, words: words5xx})
}
skipped = append(skipped, c.label()+": "+call.Error)
if waitsOf(c.patience, patienceFallback) > 0 && !hw.turnedAway && busy(hw.code(), hw.errBody()) && !routedThere(hw.header) {
if waitsOf(c.patience, patienceFallback) > 0 && !hw.turnedAway && busyFor(c, hw.code(), hw.errBody()) && !routedThere(hw.header) {
busyNow = noteBusy(busyNow, c, hw.header)
}
continue
@@ -5408,9 +5429,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// its allowance, asked only as the one back soonest, isn't: the
// members before it were asked again as the last that may answer
// (spentAfter) and the agent is told theirs
lastSpent := last && isGroup && len(busyNow) > 0 && !hw.passing && hw.failed() && !busy(hw.code(), hw.errBody()) &&
lastSpent := last && isGroup && len(busyNow) > 0 && !hw.passing && hw.failed() && !busyFor(c, hw.code(), hw.errBody()) &&
slices.Contains([]string{failQuota, failCredit}, failure(hw.code(), hw.errBody())) && !spentAfter([]candidate{c})
if _, same := passing(hw.code(), hw.header, hw.errBody(), again); last && patience > 0 && !protected && !sameRefusal && !hw.turnedAway && !hw.refused && hw.failed() && (busy(hw.code(), hw.errBody()) && (!routedThere(hw.header) || len(busyNow) > 0) || lastSpent) &&
if _, same := passingFor(c, hw.code(), hw.header, hw.errBody(), again); last && patience > 0 && !protected && !sameRefusal && !hw.turnedAway && !hw.refused && hw.failed() && (busyFor(c, hw.code(), hw.errBody()) && (!routedThere(hw.header) || len(busyNow) > 0) || lastSpent) &&
(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,
@@ -5462,7 +5483,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
break
}
}
if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !sameRefusal && !hw.turnedAway && hw.failed() && waitFrom.IsZero() && !kept.tooQuiet(wait) && !kept.outlives(wait) {
if wait, ok := passingFor(c, hw.code(), hw.header, hw.errBody(), again); ok && !protected && !sameRefusal && !hw.turnedAway && hw.failed() && waitFrom.IsZero() && !kept.tooQuiet(wait) && !kept.outlives(wait) {
// nobody else is left: the same one again, after a moment (not
// what Antigravity turned away: it turns it away again; nor
// once the group's patience is spent)
+63
View File
@@ -0,0 +1,63 @@
package gateway
import (
"math/rand/v2"
"net/http"
"time"
"github.com/yetone/magpie/internal/provider"
)
// qwenPlanHost is the Qwen AI platform's Token Plan host, its preset's
// (qwen-token-plan) and a custom provider's at it.
const qwenPlanHost = "token-plan.maas.qianwenaiapi.com"
// qwenPlanBusy says p is the Qwen AI platform's Token Plan and its 429 is
// the plan's concurrency limit: under many requests at once the host
// answers "Allocated quota exceeded, please increase your quota limit"
// (dashScopeRate's words) with the plan's quota far from used, and the
// same request asked again a moment later is served (pelikanade on X).
// It rests as a rate limit already (dashScopeRate); here it is also
// asked again on the same account, as a rate limit is, before any byte
// reaches the agent (passingFor), and a group's member is asked again
// in place before the group moves on. Only this host: DashScope's
// pay-as-you-go TPM limit says the same words and lasts the minute, and
// another vendor's "Allocated quota exceeded" is its own.
func qwenPlanBusy(p provider.Provider, status int, body []byte) bool {
if status != http.StatusTooManyRequests || p.Preset != "qwen-token-plan" && p.Host() != qwenPlanHost {
return false
}
return dashScopeRate(p, status, body)
}
// jittered is a pause of about d, between half and one and a half of it,
// so the many requests one burst of concurrency turned away aren't all
// sent again in the same instant, to be turned away again together.
func jittered(d time.Duration) time.Duration {
if d <= 1 {
return d
}
return d/2 + rand.N(d)
}
// passingFor is passing for c's failure: the Qwen Token Plan's
// concurrency 429 (qwenPlanBusy) passes as a rate limit does, for up to
// rateRetries tries again after jittered pauses of about 1, 2 and 4s, or
// what Retry-After says; any other failure is passing's.
func passingFor(c candidate, status int, header http.Header, body []byte, again int) (time.Duration, bool) {
if !qwenPlanBusy(c.p, status, body) || routedThere(header) {
return passing(status, header, body, again)
}
wait := jittered(retryPause << again)
if d := retryAfter(header, time.Now()); d > 0 {
wait = d
}
return wait, wait <= longestPause && again < rateRetries
}
// busyFor is busy for c's failure: the Qwen Token Plan's concurrency
// 429 is a moment's, as a rate limit is, and a group's or a plain
// provider's patience asks it again.
func busyFor(c candidate, status int, body []byte) bool {
return qwenPlanBusy(c.p, status, body) || busy(status, body)
}
+212
View File
@@ -0,0 +1,212 @@
package gateway
import (
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// The Qwen Token Plan's words for the 429 it answers under many requests
// at once, its quota far from used, as the reporter quoted them
// (pelikanade on X: "HTTP 429: Qwen Token Plan: Allocated quota exceeded,
// please increase your quota limit"; "Qwen Token Plan: " is magpie's
// label), in OpenAI's error shape on /compatible-mode/v1 and DashScope's
// own.
var qwenPlanBusyBodies = []string{
`{"error":{"message":"Allocated quota exceeded, please increase your quota limit","type":"limit_requests","param":null,"code":"limit_requests"},"request_id":"x"}`,
`{"code":"Throttling.AllocationQuota","message":"Allocated quota exceeded, please increase your quota limit.","request_id":"x"}`,
}
// scriptedAs is scriptedOn for a provider of the preset given, named
// name.
func scriptedAs(t *testing.T, id, name, preset string, s *scripted) {
t.Helper()
up := httptest.NewServer(s)
t.Cleanup(up.Close)
p := provider.Provider{ID: id, Name: name, Preset: preset, Key: "k", Models: []string{"m"}, Chat: up.URL + "/compatible-mode/v1"}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
// qwenStreamOK is a whole reply streamed: magpie asks DashScope's Token
// Plan for one streamed (TestDashScopeWholeAskedStreamed).
const qwenStreamOK = "data: {\"id\":\"ok\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"hello\"},\"finish_reason\":null}]}\n\n" +
"data: {\"id\":\"ok\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"
func qwenBusyTimes(n int, body string) *scripted {
a := &scripted{}
for range n {
a.replies = append(a.replies, reply{429, "", body})
}
a.replies = append(a.replies, reply{200, "text/event-stream", qwenStreamOK})
return a
}
// The Qwen Token Plan's concurrency 429 is asked again on the same
// account after a jittered moment, before anything reaches the agent, and
// the account doesn't rest when it then answers.
func TestQwenPlanConcurrencyIsAskedAgain(t *testing.T) {
for _, said := range qwenPlanBusyBodies {
fresh(t)
a := qwenBusyTimes(2, said)
scriptedAs(t, "qwen", "Qwen Token Plan", "qwen-token-plan", a)
s := New()
code, body := postAs(t, s, "", `{"model":"qwen/m","messages":[{"role":"user","content":"hi"}]}`)
if code != 200 || !strings.Contains(body, "hello") || a.n != 3 {
t.Errorf("%s: %d after %d tries: %s", said, code, a.n, body)
continue
}
r := s.trace.routes[len(s.trace.routes)-1]
// (Again is the pause in whole milliseconds, 0 for a jittered
// pause under one at the tests' 1ms retryPause)
if len(r.Tries) != 3 || r.Tries[0].Fail != failRate || r.Tries[1].Fail != failRate || r.Tries[0].Rest != nil || r.Tries[1].Rest != nil {
t.Errorf("%s: tries %+v", said, r.Tries)
}
restingUntil.Lock()
rests := len(restingUntil.m)
restingUntil.Unlock()
if rests != 0 {
t.Errorf("%s: %d rests after it answered", said, rests)
}
// never clears: asked again as a rate limit is, its same-one
// retries then its patience's rounds, and the agent has the 429
fresh(t)
a = qwenBusyTimes(99, said)
scriptedAs(t, "qwen", "Qwen Token Plan", "qwen-token-plan", a)
code, body = postAs(t, New(), "", `{"model":"qwen/m","messages":[{"role":"user","content":"hi"}]}`)
if code != 429 || a.n != 1+rateRetries+replanRounds || !strings.Contains(body, "Allocated quota exceeded") {
t.Errorf("%s never clearing: %d after %d tries: %s", said, code, a.n, body)
}
}
}
// In a group, the Qwen Token Plan member is asked again in place a few
// times; still turned away, the group moves on to its next member, the
// member resting as for a rate limit, not as out of quota.
func TestQwenPlanConcurrencyInAGroup(t *testing.T) {
said := qwenPlanBusyBodies[0]
group := func(t *testing.T, a *scripted) (*scripted, *Server) {
b := &scripted{replies: []reply{{200, "", chatOK}}}
scriptedAs(t, "qwen", "Qwen Token Plan", "qwen-token-plan", a)
scriptedOn(t, "b", provider.Chat, b)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"qwen/m", "b/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
return b, New()
}
fresh(t)
a := qwenBusyTimes(2, said)
b, s := group(t, a)
if code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`); code != 200 || a.n != 3 || b.n != 0 {
t.Fatalf("cleared: %d (qwen %d, b %d): %s", code, a.n, b.n, body)
}
fresh(t)
a = qwenBusyTimes(99, said)
b, s = group(t, a)
if code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`); code != 200 || a.n != 1+rateRetries || b.n != 1 {
t.Fatalf("never clearing: %d (qwen %d, b %d): %s", code, a.n, b.n, body)
}
r := s.trace.routes[len(s.trace.routes)-1]
var rest *Rest
for _, try := range r.Tries {
if try.Rest != nil {
rest = try.Rest
}
}
if rest == nil || rest.Why != failRate {
t.Fatalf("the member rests %+v, want a rate limit's; tries %+v", rest, r.Tries)
}
}
// Another vendor's 429 in the same words is as it was: DashScope's
// pay-as-you-go limit per minute, Bailian's Token Plan, a relay that
// isn't Alibaba's. None is asked again in place; the plain provider's
// agent has the 429 at once, a group's next member is asked at once.
func TestOtherVendorsAllocatedQuotaUnchanged(t *testing.T) {
said := qwenPlanBusyBodies[0]
for _, x := range []struct{ name, preset string }{
{"Qwen (China)", "qwen-cn"},
{"Bailian Token Plan", "bailian-token-plan"},
{"Relay", ""},
} {
fresh(t)
a := qwenBusyTimes(2, said)
scriptedAs(t, "a", x.name, x.preset, a)
if code, body := postAs(t, New(), "", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`); code != 429 || a.n != 1 {
t.Errorf("%s alone: %d after %d tries: %s", x.name, code, a.n, body)
}
fresh(t)
a = qwenBusyTimes(2, said)
b := &scripted{replies: []reply{{200, "", chatOK}}}
scriptedAs(t, "a", x.name, x.preset, a)
scriptedOn(t, "b", provider.Chat, b)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
if code, body := postAs(t, New(), "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`); code != 200 || a.n != 1 || b.n != 1 {
t.Errorf("%s in a group: %d (a %d, b %d): %s", x.name, code, a.n, b.n, body)
}
}
}
// The rule is the Qwen Token Plan's host's, a custom provider's at it too,
// and its concurrency words only: its free allowance or a plan window
// used up, or a 429 of other words, isn't it.
func TestQwenPlanBusyScope(t *testing.T) {
plan := provider.Provider{ID: "c", Chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1", Key: "k"}
for _, x := range []struct {
p provider.Provider
status int
body string
want bool
}{
{plan, 429, qwenPlanBusyBodies[0], true},
{plan, 429, qwenPlanBusyBodies[1], true},
{provider.Provider{Preset: "qwen-token-plan"}, 429, qwenPlanBusyBodies[0], true},
{plan, 500, qwenPlanBusyBodies[0], false},
{plan, 429, `{"code":"Throttling.AllocationQuota","message":"Free allocated quota exceeded.","request_id":"x"}`, false},
{plan, 429, `{"code":"Throttling.AllocationQuota","message":"hour allocated quota exceeded.","request_id":"x"}`, false},
{plan, 429, `{"error":{"message":"You've used up this month's credits"}}`, false},
{provider.Provider{Chat: "https://dashscope.aliyuncs.com/compatible-mode/v1"}, 429, qwenPlanBusyBodies[0], false},
{provider.Provider{Chat: "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"}, 429, qwenPlanBusyBodies[0], false},
{provider.Provider{Chat: "https://api.openai.com/v1"}, 429, qwenPlanBusyBodies[0], false},
} {
if got := qwenPlanBusy(x.p, x.status, []byte(x.body)); got != x.want {
t.Errorf("%s %d %s: %v, want %v", x.p.Host(), x.status, x.body, got, x.want)
}
}
for d := retryPause; d <= 8*retryPause; d *= 2 {
for range 50 {
if j := jittered(d); j < d/2 || j >= d/2+d {
t.Fatalf("jittered(%v) = %v", d, j)
}
}
}
}
// On the plan's Anthropic endpoint (/apps/anthropic) Claude Code's
// request is asked again the same, the 429 in Anthropic's error shape.
func TestQwenPlanConcurrencyOnAnthropic(t *testing.T) {
fresh(t)
ok := `{"id":"msg_1","type":"message","role":"assistant","model":"m","content":[{"type":"text","text":"hello"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`
a := &scripted{replies: []reply{
{429, "", `{"type":"error","error":{"type":"rate_limit_error","message":"Allocated quota exceeded, please increase your quota limit"}}`},
{200, "", ok},
}}
up := httptest.NewServer(a)
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "qwen", Name: "Qwen Token Plan", Preset: "qwen-token-plan", Key: "k", Models: []string{"m"}, Anthropic: up.URL + "/apps/anthropic"}); err != nil {
t.Fatal(err)
}
code, body := postTo(t, New(), "/v1/messages", `{"model":"qwen/m","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`)
if code != 200 || !strings.Contains(body, "hello") || a.n != 2 {
t.Fatalf("%d after %d tries: %s", code, a.n, body)
}
}