magpie icon indicating copy to clipboard operation
magpie copied to clipboard

gateway: skip exhausted accounts/providers before and during fallback instead of retrying out-of-balance/quota upstreams

Open ArmedHelicopter opened this issue 1 week ago • 2 comments

Environment

  • magpie version: 0.1.4777 (Windows 11 amd64)
  • Where: Gateway (group/agentcompass, order routing across multiple providers/groups)

Summary

When a request walks a routing group (group/agentcompass), Magpie still sends live upstream requests to providers/accounts that are already out of credits or quota — including retrying another model on the exact same out-of-balance API key within the same request, and walking all 10 exhausted subscription accounts whose magpie quota windows are already at 100% (remaining: 0).

Evidence from routing/2026-11-24.jsonl

In a single request at 2026-11-24T14:51:45.772436-08:00 (19 tries before Sage-A1.5 returned 200):

[0]  workbuddy/deepseek-v4-pro           status=429  'WorkBuddy: 额度已用尽,请访问以下链接,购买加量包以获取更多额度:https://www.codebuddy.cn/profile/usage ...'
[1]  workbuddy/deepseek-v4-pro           status=429  'WorkBuddy: 额度已用尽,请访问以下链接,购买加量包以获取更多额度:https://www.codebuddy.cn/profile/usage ...'
[2..11] kiro/kimi-k3 (10 tries!)         status=429  'Kiro: usage limit reached: You have reached the limit. (MONTHLY_REQUEST_COUNT)'
...
[15] modelscope/DeepSeek-V4-Pro-0813     status=429  'ModelScope: insufficient balance'
[16] meoo/qwen3.8-max                    status=403  'Meoo: 积分余额不足,请充值后继续使用'
[17] meoo/deepseek-v4-pro-0813           status=403  'Meoo: 积分余额不足,请充值后继续使用'
[18] intern-inkstone/Sage-A1.5           status=200

Root Causes Found in Source

  1. Same key/provider called again in the same request after an account-wide credit refusal (meoo tries [16] & [17]):

    • [16] (meoo/qwen3.8-max) failed with 403: 积分余额不足,请充值后继续使用 (failCredit, restKey = "meoo").
    • [17] (meoo/deepseek-v4-pro-0813) on the same provider/key was still tried immediately afterward in the same fallback walk and failed with the exact same 403.
    • Once a candidate records a key-level failCredit / failQuota / failRestricted rest (c.restKey()), remaining planned candidates in the same request sharing that restKey() should be skipped before sending upstream requests.
  2. Exhausted accounts (used: 100%, remaining: 0) are not skipped when no manual HoldCaps is set (kiro x10 & workbuddy x2):

    • magpie quota --json already reports all 10 kiro accounts at 1000 / 1000 (used: 100, remaining: 0, holdsWhy: "log") and both workbuddy accounts at remaining: 0 (holdsWhy: "credits").
    • However, capHeld (internal/gateway/fallback.go:1002-1029) returns nil immediately if !caps.Holds() (when the user hasn't manually configured a HoldCaps percentage). As a result, all 10 exhausted Kiro accounts and both exhausted WorkBuddy accounts remain eligible candidates and get hit again whenever their short rest expires or probeLeft (fallback.go:1406) probes them.
  3. WorkBuddy Chinese 429 ("额度已用尽") doesn't match brokeWords:

    • internal/gateway/routing.go:612 only classifies a 429 as failCredit (creditLadder up to 7d) if brokeWords.Match(body) is true.
    • brokeWords (routing.go:353) checks 余额不足|欠费|请充值, so WorkBuddy's Chinese credit-exhaustion message ("额度已用尽,请访问以下链接,购买加量包以获取更多额度") falls through instead of climbing creditLadder.

Expected Behavior

  1. Within a single request's fallback loop, if a try fails with a key/account-wide failCredit / failQuota / failAuth / failRestricted, immediately skip subsequent candidates in cs that share the same restKey().
  2. When allowances already show an account/window at 100% (remaining == 0) with a known reset time (e.g., 1000 / 1000 credits), skip it by default (or treat 100% exhaustion as an implicit cap unless disabled), rather than sending 10+ doomed requests on every cooldown cycle.
  3. Add 额度已用尽 (when paired with credit/pack purchase context or on WorkBuddy 429) to brokeWords so it climbs creditLadder cleanly.

Related

  • #7515, #7066, #2632, #6907

ArmedHelicopter avatar Nov 24 '26 23:11 ArmedHelicopter

take

ggbdpq avatar Nov 26 '26 13:11 ggbdpq

@yetone Fix for retrying sibling models on an already-exhausted key within the same fallback walk and for classifying WorkBuddy's Chinese 429 credit-pack exhaustion, reported by @ArmedHelicopter (reproduced on f85c2f748).

Root cause:

  1. In internal/gateway/gateway.go, after s.restAfterMarked records a key- or account-wide rest (failCredit, failQuota, failAuth, failRestricted, failSuspended with rest.Key == c.restKey() and empty rest.Model), the fallback loop continued to remaining planned candidates in cands[i+1:] sharing that same restKey(), sending doomed upstream requests to another model on the exact same out-of-balance/exhausted key (e.g. meoo/qwen3.8-max 403 -> meoo/deepseek-v4-pro-0813 403).
  2. In internal/gateway/routing.go, creditWords and brokeWords did not match WorkBuddy's Chinese 429 credit-pack message (额度已用尽,请访问以下链接,购买加量包以获取更多额度), so it fell through to failQuota instead of failCredit (unlike the English 14018 Credits exhausted wording).
  3. Note on Point 2 of the report (capHeld returning nil for 100%-used accounts when no HoldCaps / NoCredits / NoExtraUsage is set): TestClaudeNoExtraUsage (internal/gateway/claude_extra_usage_test.go) explicitly asserts that a 100%-used account is not held by capHeld unless the user opts in via caps or credit/extra-usage holds (accounts with overage credits or stale readings still serve). Leaving that product policy untouched for maintainer decision.

The fix:

  • Add restSkipsKey and otherRestKeys in internal/gateway/fallback.go and prune remaining cands[i+1:] matching rest.Key in internal/gateway/gateway.go when a try records a key/account-wide rest (rest.Model == "", !rest.Until.IsZero(), rest.By != "off"). Model-scoped rests (rest.Model != "", such as PaidBesideFree, modelLimitedBy, pooled, unserved, remoteModelRest) keep sibling models eligible. When pruning removes all remaining candidates, mark last = true and guard try.Rest == nil on the terminal rest branches so the response is written without double-resting or making a second upstream call.
  • Extend creditWords and brokeWords in internal/gateway/routing.go with 额度已用尽.*(?:购买|充值|加量包) so WorkBuddy's Chinese 429 credit exhaustion classifies as failCredit while time-resetting quota messages remain failQuota.
patch: fix(gateway): skip remaining same-key candidates after key-wide rest and classify WorkBuddy zh 429 credit (#7690) — git am applies it as is; SHA-256 first 16: 22fd783bbda31e52
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Thu, 26 Nov 2026 21:29:57 +0800
Subject: [PATCH] fix(gateway): skip remaining same-key candidates after
 key-wide rest and classify WorkBuddy zh 429 credit (#7690)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

What changed:
- Add restSkipsKey and otherRestKeys in internal/gateway/fallback.go and prune remaining candidates sharing rest.Key in gateway.go when a try records a key/account-wide rest (failCredit, failQuota, failAuth, failRestricted, failSuspended) with empty rest.Model, avoiding doomed same-key retries in the same request while leaving model-scoped rests untouched; guard duplicate restAfterMarked calls when pruning turns the current try into the last candidate.
- Extend creditWords and brokeWords in internal/gateway/routing.go to classify WorkBuddy's Chinese 429 credit-pack exhaustion (额度已用尽…购买加量包) as failCredit instead of failQuota, while leaving time-resetting quota messages as failQuota.
- Add TestFallbackSkipsExhaustedSameKeyAndClassifiesWorkBuddyZhCredit covering same-key skip to backup, terminal same-key-only error without 2nd upstream call, model-scoped sibling retry, and WorkBuddy Chinese 429 classification.

Run:
- go test ./internal/gateway -run TestFallbackSkipsExhaustedSameKeyAndClassifiesWorkBuddyZhCredit|TestCreditsExhaustedIsOutOfCredit|TestQuotaHeld|TestTimedHeld|TestWorkBuddyRestricted|TestFailure -tags nogui -timeout 10m -count=1 -v (red before fix, green after)
- gofmt -l internal/gateway/fallback.go internal/gateway/gateway.go internal/gateway/routing.go internal/gateway/skip_exhausted_key_test.go (clean)
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./... (clean)
- go build; GOOS=linux go build -tags nogui; GOOS=windows go build (clean)

Generated-by: Gemini 4 Neon (Antigravity)
---
 internal/gateway/fallback.go                |  26 +++
 internal/gateway/gateway.go                 |  18 +-
 internal/gateway/routing.go                 |   7 +-
 internal/gateway/skip_exhausted_key_test.go | 204 ++++++++++++++++++++
 4 files changed, 248 insertions(+), 7 deletions(-)
 create mode 100644 internal/gateway/skip_exhausted_key_test.go

diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go
index 9fc0da71c..8458fcecc 100644
--- a/internal/gateway/fallback.go
+++ b/internal/gateway/fallback.go
@@ -2750,6 +2750,32 @@ func otherThanClaudeAccounts(left []candidate) []candidate {
 	return kept
 }
 
+// restSkipsKey says a key- or account-wide rest recorded during a fallback
+// walk makes remaining candidates sharing c.restKey doomed for this request.
+// Model-scoped rests (r.Model != "") leave sibling models on the same key
+// eligible (e.g. PaidBesideFree, pooled quotas, model-limited relays).
+func restSkipsKey(r Rest, c candidate) bool {
+	if r.Key == "" || r.Key != c.restKey() || r.Model != "" || r.Until.IsZero() || r.By == "off" {
+		return false
+	}
+	switch r.Why {
+	case failCredit, failQuota, failAuth, failRestricted, failSuspended:
+		return true
+	}
+	return false
+}
+
+// otherRestKeys is left without candidates sharing restKey.
+func otherRestKeys(left []candidate, restKey string) []candidate {
+	var kept []candidate
+	for _, x := range left {
+		if x.restKey() != restKey {
+			kept = append(kept, x)
+		}
+	}
+	return kept
+}
+
 // matesLast puts last, of the candidates left, the other keys or accounts
 // of the member c is of: what turns one of them away is in the request, so
 // it turns them all away the same, and the group is better spent on a
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 0b2ab8fc0..20fae904e 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -5868,7 +5868,17 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
 			if waitsOf(c.patience, patienceFallback) > 0 && !hw.turnedAway && busyFor(c, hw.code(), hw.errBody()) && !routedThere(hw.header) {
 				busyNow = noteBusy(busyNow, c, hw.header)
 			}
-			continue
+			if restSkipsKey(rest, c) {
+				if left := otherRestKeys(cands[i+1:], rest.Key); len(left) != len(cands[i+1:]) {
+					cands = append(cands[:i+1:i+1], left...)
+					if len(left) == 0 {
+						last = true
+					}
+				}
+			}
+			if !last {
+				continue
+			}
 		}
 		// (a plain provider's: not ChatGPT's reset of a large request,
 		// which Codex is told at its 503 with what may help, as Codex's
@@ -5914,7 +5924,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
 			}
 			if next, wait, ok := replan(busyNow, rounds, waitFrom, patienceFallback); ok && !kept.tooQuiet(wait) && !kept.outlives(wait) {
 				try.Fail, try.Again = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds()
-				if lastSpent {
+				if lastSpent && try.Rest == nil {
 					rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool)
 					try.Fail, try.Rest = rest.Why, &rest
 				}
@@ -6011,7 +6021,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
 				continue
 			}
 		}
-		if last && !held && !hw.passing && hw.failed() && quotaStatus(hw.code()) && (c.p.Account == nil || !hw.turnedAway && try.Fail != failPrompt) && (try.Fail == failQuota || try.Fail == failCredit || failure(hw.code(), hw.errBody()) == failQuota || failure(hw.code(), hw.errBody()) == failCredit) {
+		if last && try.Rest == nil && !held && !hw.passing && hw.failed() && quotaStatus(hw.code()) && (c.p.Account == nil || !hw.turnedAway && try.Fail != failPrompt) && (try.Fail == failQuota || try.Fail == failCredit || failure(hw.code(), hw.errBody()) == failQuota || failure(hw.code(), hw.errBody()) == failCredit) {
 			// the last key left is out of its allowance: it rests as the
 			// ones before it did, for the next request to be answered
 			// from the rests until the first of them is back (#1772). An
@@ -6024,7 +6034,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
 			// rest of an account it spends a reset of
 			rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool)
 			try.Fail, try.Rest = rest.Why, &rest
-		} else if last && !held && !hw.passing && hw.failed() && hw.code() == http.StatusTooManyRequests && !hw.turnedAway && try.Fail != failPrompt && failure(hw.code(), hw.errBody()) == failRate && vendorSaidWhen(hw.header, hw.errBody()) {
+		} else if last && try.Rest == nil && !held && !hw.passing && hw.failed() && hw.code() == http.StatusTooManyRequests && !hw.turnedAway && try.Fail != failPrompt && failure(hw.code(), hw.errBody()) == failRate && vendorSaidWhen(hw.header, hw.errBody()) {
 			// the last one left is rate limited till a time its vendor
 			// named: it rests till then too, for the agent's retries to be
 			// answered from the rest (timedHeld) rather than sent on to
diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go
index 7ca1b205f..3a13e9df1 100644
--- a/internal/gateway/routing.go
+++ b/internal/gateway/routing.go
@@ -339,17 +339,18 @@ func creditBackoff(id string, header http.Header, body []byte, now time.Time) (d
 
 var (
 	// creditWords: the account or key has no money left.
-	creditWords = lazyre.New(`(?i)insufficient.?(balance|credit|fund)|balance|credit|billing|payment|arrear|overdue|suspended|余额|欠费|充值|账户.*(不足|停)`)
+	creditWords = lazyre.New(`(?i)insufficient.?(balance|credit|fund)|balance|credit|billing|payment|arrear|overdue|suspended|余额|欠费|充值|账户.*(不足|停)|额度已用尽.*(?:购买|充值|加量包)`)
 	// brokeWords: a 429 that says the balance itself is spent, as Zhipu
 	// answers a GLM Coding Plan's key at the pay-as-you-go endpoint (1113
 	// "余额不足或无可用资源包,请充值") — out of credit, not a rate limit;
 	// WorkBuddy's 429 14018 "Credits exhausted. Please visit the link
-	// below to purchase add-on packs…" too (Creat.wu on Discord), and
+	// below to purchase add-on packs…" (Creat.wu on Discord) and its
+	// Chinese wording ("额度已用尽…购买加量包", #7690) too, and
 	// OpenAI's 429 credit_balance_exhausted for an organization whose
 	// prepaid API credits are spent: its underscores kept "credits
 	// exhausted" from matching, so it read as a rate limit and the same
 	// key was asked again rather than the next account
-	brokeWords = lazyre.New(`(?i)insufficient.?(balance|credit|fund)|\bcredits? (are )?exhausted\b|credit.?balance.?exhausted|余额不足|欠费|请充值`)
+	brokeWords = lazyre.New(`(?i)insufficient.?(balance|credit|fund)|\bcredits? (are )?exhausted\b|credit.?balance.?exhausted|余额不足|欠费|请充值|额度已用尽.*(?:购买|充值|加量包)`)
 	// quotaWords: it has used up what its plan allows for now. The budget's
 	// words needn't sit beside each other: LiteLLM's spent key answers 429
 	// "Budget has been exceeded! Key=… (sk-…), Current cost: …, Max budget:
diff --git a/internal/gateway/skip_exhausted_key_test.go b/internal/gateway/skip_exhausted_key_test.go
new file mode 100644
index 000000000..64eb5b4a0
--- /dev/null
+++ b/internal/gateway/skip_exhausted_key_test.go
@@ -0,0 +1,204 @@
+package gateway
+
+import (
+	"encoding/json"
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"sync"
+	"testing"
+
+	"github.com/yetone/magpie/internal/provider"
+)
+
+// Within a single request's fallback walk, a key- or account-wide refusal
+// (credit/quota/auth/restricted/suspended) must skip remaining candidates on
+// the same restKey rather than sending doomed retries on another model of the
+// same exhausted key; model-scoped rests still try sibling models; and
+// WorkBuddy's Chinese 429 credit-pack refusal must classify as failCredit
+// (#7690).
+func TestFallbackSkipsExhaustedSameKeyAndClassifiesWorkBuddyZhCredit(t *testing.T) {
+	t.Run("skips sibling model on same exhausted key and reaches backup", func(t *testing.T) {
+		fresh(t)
+		var mu sync.Mutex
+		var meooModels []string
+		meoo := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+			var q struct {
+				Model string `json:"model"`
+			}
+			b, _ := io.ReadAll(r.Body)
+			_ = json.Unmarshal(b, &q)
+			mu.Lock()
+			meooModels = append(meooModels, q.Model)
+			mu.Unlock()
+			w.Header().Set("Content-Type", "application/json")
+			w.WriteHeader(http.StatusForbidden)
+			_, _ = io.WriteString(w, `{"error":{"message":"Meoo: 积分余额不足,请充值后继续使用"}}`)
+		}))
+		defer meoo.Close()
+
+		backupHits := 0
+		backup := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+			mu.Lock()
+			backupHits++
+			mu.Unlock()
+			w.Header().Set("Content-Type", "application/json")
+			_, _ = io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"sage","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`)
+		}))
+		defer backup.Close()
+
+		if err := provider.Save(provider.Provider{
+			ID: "meoo", Name: "Meoo", Key: "k-meoo", Chat: meoo.URL + "/v1",
+			Models: []string{"qwen3.8-max", "deepseek-v4-pro-0813"},
+		}); err != nil {
+			t.Fatal(err)
+		}
+		if err := provider.Save(provider.Provider{
+			ID: "backup", Name: "Backup", Key: "k-backup", Chat: backup.URL + "/v1",
+			Models: []string{"sage"},
+		}); err != nil {
+			t.Fatal(err)
+		}
+		if err := provider.SaveGroup(provider.Group{
+			ID: "mix", Name: "Mix", Routing: provider.Ordered,
+			Members: []string{"meoo/qwen3.8-max", "meoo/deepseek-v4-pro-0813", "backup/sage"},
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		s := New()
+		rec := httptest.NewRecorder()
+		req := httptest.NewRequest("POST", "/v1/chat/completions",
+			strings.NewReader(`{"model":"group/mix","messages":[{"role":"user","content":"hi"}]}`))
+		s.Handler().ServeHTTP(rec, req)
+
+		if rec.Code != http.StatusOK {
+			t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+		}
+		mu.Lock()
+		gotMeoo := append([]string(nil), meooModels...)
+		gotBackup := backupHits
+		mu.Unlock()
+		if len(gotMeoo) != 1 || gotMeoo[0] != "qwen3.8-max" {
+			t.Fatalf("expected meoo called once for qwen3.8-max (skipping sibling on same key), got %v", gotMeoo)
+		}
+		if gotBackup != 1 {
+			t.Fatalf("expected backup called once, got %d", gotBackup)
+		}
+	})
+
+	t.Run("returns error without retrying sibling when only same key remains", func(t *testing.T) {
+		fresh(t)
+		var mu sync.Mutex
+		var meooModels []string
+		meoo := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+			var q struct {
+				Model string `json:"model"`
+			}
+			b, _ := io.ReadAll(r.Body)
+			_ = json.Unmarshal(b, &q)
+			mu.Lock()
+			meooModels = append(meooModels, q.Model)
+			mu.Unlock()
+			w.Header().Set("Content-Type", "application/json")
+			w.WriteHeader(http.StatusForbidden)
+			_, _ = io.WriteString(w, `{"error":{"message":"Meoo: 积分余额不足,请充值后继续使用"}}`)
+		}))
+		defer meoo.Close()
+
+		if err := provider.Save(provider.Provider{
+			ID: "meoo", Name: "Meoo", Key: "k-meoo", Chat: meoo.URL + "/v1",
+			Models: []string{"qwen3.8-max", "deepseek-v4-pro-0813"},
+		}); err != nil {
+			t.Fatal(err)
+		}
+		if err := provider.SaveGroup(provider.Group{
+			ID: "onlymeoo", Name: "OnlyMeoo", Routing: provider.Ordered,
+			Members: []string{"meoo/qwen3.8-max", "meoo/deepseek-v4-pro-0813"},
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		s := New()
+		rec := httptest.NewRecorder()
+		req := httptest.NewRequest("POST", "/v1/chat/completions",
+			strings.NewReader(`{"model":"group/onlymeoo","messages":[{"role":"user","content":"hi"}]}`))
+		s.Handler().ServeHTTP(rec, req)
+
+		if rec.Code != http.StatusForbidden {
+			t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+		}
+		mu.Lock()
+		gotMeoo := append([]string(nil), meooModels...)
+		mu.Unlock()
+		if len(gotMeoo) != 1 || gotMeoo[0] != "qwen3.8-max" {
+			t.Fatalf("expected meoo called once when only same-key sibling remains, got %v", gotMeoo)
+		}
+	})
+
+	t.Run("model-scoped refusal still tries sibling model on same key", func(t *testing.T) {
+		fresh(t)
+		var mu sync.Mutex
+		var seen []string
+		relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+			var q struct {
+				Model string `json:"model"`
+			}
+			b, _ := io.ReadAll(r.Body)
+			_ = json.Unmarshal(b, &q)
+			mu.Lock()
+			seen = append(seen, q.Model)
+			mu.Unlock()
+			w.Header().Set("Content-Type", "application/json")
+			if q.Model == "m1" {
+				w.WriteHeader(http.StatusNotFound)
+				_, _ = io.WriteString(w, `{"error":{"message":"The model m1 does not exist"}}`)
+				return
+			}
+			_, _ = io.WriteString(w, `{"id":"c2","object":"chat.completion","model":"m2","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`)
+		}))
+		defer relay.Close()
+
+		if err := provider.Save(provider.Provider{
+			ID: "relay", Name: "Relay", Key: "k-relay", Chat: relay.URL + "/v1",
+			Models: []string{"m1", "m2"},
+		}); err != nil {
+			t.Fatal(err)
+		}
+		if err := provider.SaveGroup(provider.Group{
+			ID: "ms", Name: "ModelScope", Routing: provider.Ordered,
+			Members: []string{"relay/m1", "relay/m2"},
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		s := New()
+		rec := httptest.NewRecorder()
+		req := httptest.NewRequest("POST", "/v1/chat/completions",
+			strings.NewReader(`{"model":"group/ms","messages":[{"role":"user","content":"hi"}]}`))
+		s.Handler().ServeHTTP(rec, req)
+
+		if rec.Code != http.StatusOK {
+			t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+		}
+		mu.Lock()
+		got := append([]string(nil), seen...)
+		mu.Unlock()
+		if len(got) != 2 || got[0] != "m1" || got[1] != "m2" {
+			t.Fatalf("expected [m1 m2] on model-scoped refusal, got %v", got)
+		}
+	})
+
+	t.Run("WorkBuddy Chinese 429 credits exhausted is failCredit", func(t *testing.T) {
+		wbZh := []byte(`{"error":{"message":"WorkBuddy: 额度已用尽,请访问以下链接,购买加量包以获取更多额度:https://www.codebuddy.cn/profile/usage"}}`)
+		if got := failure(http.StatusTooManyRequests, wbZh); got != failCredit {
+			t.Fatalf("WorkBuddy Zh 429: got %q, want %q", got, failCredit)
+		}
+		// Plain time-resetting quota stays failQuota.
+		quotaZh := []byte(`{"error":{"message":"您的今日额度已用尽,将于 2026-12-01 00:00:00 UTC+8 重置"}}`)
+		if got := failure(http.StatusTooManyRequests, quotaZh); got != failQuota {
+			t.Fatalf("resetting quota Zh 429: got %q, want %q", got, failQuota)
+		}
+	})
+}
-- 
2.56.0.windows.4

Branch with the commit: fix/7690-skip-exhausted-same-key-and-wb-credit (head a7d56d02668e3f732b07b99951aee6de8c75d1dc), rebased onto current upstream/main (f85c2f748); on a fresh checkout git am applies clean.

Check Result
TestFallbackSkipsExhaustedSameKeyAndClassifiesWorkBuddyZhCredit (new) red before the fix, pass after
TestCreditsExhaustedIsOutOfCredit|TestQuotaHeld|TestTimedHeld|TestWorkBuddyRestricted|TestFailure pass
go test ./internal/gateway -tags nogui -timeout 25m -count=1 not run (full gateway suite omitted while parallel sandboxes share CPU; targeted fallback/rest/credit/failure tests passed)
go test -tags nogui ./... (temp HOME, pinned Go caches) not run
targeted -race not run (no C toolchain on Windows host)
gofmt -l internal/gateway/fallback.go internal/gateway/gateway.go internal/gateway/routing.go internal/gateway/skip_exhausted_key_test.go prints nothing
go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./... clean
go build; GOOS=linux go build -tags nogui; GOOS=windows go build clean
Ablation reverting fallback.go, gateway.go, routing.go turns 3 of 4 subtests of TestFallbackSkipsExhaustedSameKeyAndClassifiesWorkBuddyZhCredit red (same-key retry to backup, same-key-only 2nd call, WorkBuddy zh 429=quota); restored, green
Clean git am on f85c2f748 applies clean; HEAD^{tree} matches branch HEAD^{tree}

Source: Verified against upstream/main (f85c2f748): internal/gateway/gateway.go (main candidate fallback loop & restAfterMarked call sites), internal/gateway/fallback.go (restKey, capHeld), internal/gateway/routing.go (creditWords, brokeWords, failure, restAfterMarked), and internal/gateway/claude_extra_usage_test.go.

Red without the fix: TestFallbackSkipsExhaustedSameKeyAndClassifiesWorkBuddyZhCredit fails with got [qwen3.8-max deepseek-v4-pro-0813] on both same-key subtests and WorkBuddy Zh 429: got "quota", want "credit".

Siblings: Audited all non-test restAfter / restAfterMarked call sites in internal/gateway/: gateway.go's count_tokens loop only iterates candidates for a single model (counts), decide_group.go / gateway.go stream-break paths are single-candidate or post-stream rests, and gateway.go's main fallback loop is the sole multi-model candidate walk. Checked lastSpent and terminal quotaStatus/vendorSaidWhen branches in gateway.go and guarded all three with try.Rest == nil so pruning to last = true never double-rests.

Not verified: Live group/agentcompass traffic against real Meoo / WorkBuddy / Kiro accounts; full internal/gateway suite and full-repo go test -tags nogui ./...; -race (no C toolchain on Windows host). Implicit 100%-used capHeld skipping without user-configured HoldCaps was intentionally left unchanged as it contradicts TestClaudeNoExtraUsage.

Attribution: AI-written; I've read the whole diff and the tests pass. Please keep the author (ggbdpq) or add Co-authored-by: ggbdpq <[email protected]>.

ggbdpq avatar Nov 26 '26 13:11 ggbdpq