gateway: an Azure key that answered before, refused 401, rests suspended till it answers (canlee886 on X)

An Azure subscription with a spending limit (a student's $100 a month,
a trial's) is disabled by Azure when its credit runs out and enabled
again on its own when the credit renews. Meanwhile every request 401s
"Access denied due to invalid subscription key or wrong API endpoint",
the words a wrong key gets. magpie read that as any 401: failOther on
the 1-minute backoff climbing to 10 minutes, never asked in the
background, so the key was asked again by requests for weeks, and the
reporter turned the provider off and on by hand around the reset day.

Now restAfterMarked reads a failOther 401 as failSuspended when
azureSuspended holds: no account, Provider.IsAzure, and the key has
answered a request before (provider.LastServed at provider.ServedID,
served.json, 30 days) or is resting suspended already. It rests
suspendedRest (a day) by "suspended", and probeable takes it whatever
its status: keepProbingRests asks the resource's deployments list with
the key at 1, 2, 5 and then every 10 minutes (refused the same while
the subscription is off) and lifts the rest as soon as the list answers,
or when a request does. Its group's requests go to the next member
meanwhile, Azure not asked.

Product calls (mine to make, delegated):
- One 401 is enough, not "repeated" ones: a 401 is about the credential,
  never the model or the request content. On a key that worked, a
  transient 401 is lifted by the first ask a minute in, the same as the
  old one-minute backoff let it back.
- A bad key stays a bad key: a key 401 from its first request (new,
  mistyped, or edited, its KeyID then another) has no answer on record
  and rests as before, failOther/backoff, shown "401 · failed", never
  asked in the background. served.json unreadable is no answer on
  record too (a failed read is unknown, not "it worked").
- Azure only: a 401 says nothing of why on other vendors, and a list
  that answers without the key (OpenRouter's is public) would lift a key
  its vendor still refuses.
- No "back on day N" setting: the probe finds the day Azure enables the
  subscription, so there is nothing for the user to type in, and no
  Advanced field.

GUI: the key list says "Resting · 401 suspended by the vendor · back
at … · checked in the background, back as soon as it answers"; Routing's
restHow says its key answered before, so the vendor has most likely
suspended it (an Azure subscription out of credit). KEY_FAIL and the
routing plugin's FAIL gain "suspended", in en, zh, zh-TW, ja and de.
keyDead is unchanged, so "Remove failing" doesn't offer a suspended key.
docs/subsystems/gateway-routing.md has the rule beside the rest probe.

Not covered: a 403; a key whose last answer is over 30 days old after a
restart (rests are in memory); the last candidate of a request, which
rests only for quota, credit or a timed rate limit, so a lone Azure
provider is asked again by each request, as before, and answers as soon
as Azure does.

Run on mica (mote had other sessions' full suites), at b4c88d44e
unless named, rebased on 9fc1114d8 before the push:
- go test -tags nogui -run 'TestAzureKey|TestSuspended' ./internal/gateway:
  ok. Broken by hand, each red: azureSuspended always false (3 red:
  ThatAnswered, IsAzureOnly, OutlivesItsLastAnswer); served history
  ignored, every Azure 401 suspended (NeverAnsweredIsABadKey and
  OutlivesItsLastAnswer red); probeable's suspended branch off
  (ThatAnswered, IsAzureOnly red).
- azure-suspended.test.cjs, chromium and webkit, en zh zh-TW ja de,
  1100 and 420px: 40/40; with the base's four GUI assets, 0/40.
- At this head rebased, on mote (mica had another session's GUI suite):
  rest-try-now, key-rest-date, rest-probed, azure-suspended,
  routing-rest-off and i18n-keys, both engines: 146 of 164. All 18 reds
  are rest-try-now's (#4127 "ebody holds", #2564), 18 of 40 at
  origin/main 9fc1114d8 too. At b4c88d44e under load 47 on mica the
  same files had 50 timeouts; at light load only rest-try-now's,
  red on main too, are left.
- go test -count=3 -run 'TestAzureKey|TestSuspended|Probe|Rest'
  ./internal/gateway at this head rebased, on mote: ok.
- go vet ./internal/gateway ./internal/gui, and GOOS=linux and
  GOOS=windows go vet ./internal/gateway: ok.
- go test -timeout 45m ./... in a sandbox HOME: the first run filled
  mica's disk (another session's) and ~300 tests failed "no space left
  on device". The six packages it touched, run again: agent and
  provider ok, sessions ran past -timeout 45m with no test failed
  (TestTitleOfALongPromptAllocatesItsTitle at the deadline, #5451; it
  imports neither gateway nor gui); three reds, each filed and
  none in code this changes:
  - internal/dirent watch tests (#7031), red at origin/main 9fc1114d8
    too.
  - TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117), red at
    9fc1114d8 too.
  - TestGatewayModeListsNoOwnSessions (#7064, the listing race): red
    2 of 3 at b4c88d44e, ok 2 of 2 at 9fc1114d8 and 4 of 4 at this head
    rebased.

Not tried: a real Azure subscription disabled for its credit (none to
hand); the list's 401 while disabled is from Azure's documented
behaviour that the data plane refuses a disabled subscription's key on
every route.
This commit is contained in:
yetone
2026-11-19 19:38:31 +08:00
parent 9fc1114d84
commit ed405d1d78
10 changed files with 499 additions and 7 deletions
File diff suppressed because one or more lines are too long
+66
View File
@@ -0,0 +1,66 @@
package gateway
// An Azure subscription with a spending limit — a student's, a free
// trial's, a Visual Studio subscriber's monthly credit — is disabled by
// Azure when its credit runs out, and enabled again on its own when the
// credit renews. Meanwhile every request to the resource, with the key that
// worked an hour ago, answers 401 "Access denied due to invalid subscription
// key or wrong API endpoint" (canlee886 on X): the same words a wrong key
// gets. A 401 on a key that answered requests before is read as that
// subscription suspended, not as a bad key: the key sits out until it
// answers again (failSuspended), and the gateway asks its deployments list
// in the background meanwhile (rest_probe.go), so it is back within minutes
// of Azure enabling it, with nobody turning the provider off and on.
//
// What tells the two apart is the key's own past: provider.LastServed has
// when it last answered a request through the gateway (served.json, kept
// 30 days). A key that never answered — new, mistyped, or edited since
// (its KeyID is another then) — fails as before: a 401 shown as the key
// refused, on the short backoff, never asked in the background. A file that
// can't be read is no answer on record, the same. A key already resting
// suspended stays read so when its rest ends and it is refused again, after
// its last answer has left the file.
//
// Azure's alone: a 401 says nothing of why on any vendor, and a vendor
// whose model list answers without the key (OpenRouter's is public) would
// have a probe lift a key it still refuses. Azure's data plane checks the
// key on its deployments list as on its chat completions.
import (
"net/http"
"time"
"github.com/yetone/magpie/internal/provider"
)
// failSuspended: an Azure key that answered before is refused 401, as a
// subscription Azure disabled is (its credit used up). It rests
// suspendedRest, asked again in the background, and is back as soon as its
// list answers.
const failSuspended = "suspended"
// suspendedRest is how long a suspended key sits out with no answer from
// its probe: a day, after which a request asks it once more. The probe
// lifts it as soon as the vendor answers, so this bounds only a key the
// probe can't speak for (a list that answered while requests didn't,
// probeMissed).
const suspendedRest = 24 * time.Hour
// lastServedFor is provider.LastServed; swapped in tests.
var lastServedFor = provider.LastServed
// azureSuspended says c's 401 is a suspended subscription's: c is an Azure
// key (no account), the reply is a 401, and the key answered a request
// before, or is resting suspended already.
func azureSuspended(c candidate, status int) bool {
if status != http.StatusUnauthorized || c.p.Account != nil || !c.p.IsAzure() {
return false
}
restingUntil.Lock()
was := restingUntil.note[c.restKey()].Why == failSuspended
restingUntil.Unlock()
if was {
return true
}
return !lastServedFor()[provider.ServedID(c.p)].IsZero()
}
+253
View File
@@ -0,0 +1,253 @@
package gateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// Azure's answer to every request while a subscription is disabled for its
// credit spent, and to a wrong key alike (canlee886 on X).
const azureDenied = `{"error":{"code":"401","message":"Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource."}}`
// restsUnder is every rest whose key starts with id.
func restsUnder(id string) []Rest {
restingUntil.Lock()
var keys []string
for k := range restingUntil.m {
if k == id || strings.HasPrefix(k, id+"#") || strings.HasPrefix(k, id+"/") {
keys = append(keys, k)
}
}
restingUntil.Unlock()
var out []Rest
for _, k := range keys {
if r, ok := restOf(k); ok {
out = append(out, r)
}
}
return out
}
// azureGroup saves group/sol: the Azure key az first, then a backup bk
// that always answers, and counts the requests each was sent.
func azureGroup(t *testing.T, az http.HandlerFunc) (azHits, bkHits *atomic.Int32) {
t.Helper()
azHits, bkHits = new(atomic.Int32), new(atomic.Int32)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/chat/completions") {
azHits.Add(1)
}
az(w, r)
}))
t.Cleanup(up.Close)
bk := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bkHits.Add(1)
servedBy(provider.Chat, "gpt-sol")(w, r)
}))
t.Cleanup(bk.Close)
for _, p := range []provider.Provider{
{ID: "az", Name: "Azure", Preset: provider.AzurePreset, Key: "az-key", Chat: up.URL + "/openai/v1", Models: []string{"gpt-sol"}},
{ID: "bk", Name: "Backup", Key: "bk-key", Chat: bk.URL + "/v1", Models: []string{"gpt-sol"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
if err := provider.SaveGroup(provider.Group{Name: "Sol", Members: []string{"az/gpt-sol", "bk/gpt-sol"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
return azHits, bkHits
}
func askSol(t *testing.T, s *Server) {
t.Helper()
if code, body := postAs(t, s, "", `{"model":"group/sol","messages":[{"role":"user","content":"hi"}]}`); code != 200 {
t.Fatalf("group/sol answered %d %s", code, body)
}
}
// canlee886 on X: an Azure student subscription is disabled when its
// monthly credit runs out, every request 401 until Azure enables it again
// on the reset day, and the provider had to be turned off and on by hand.
// A key that answered before and is refused 401 now rests suspended — its
// group's requests go to the next member meanwhile, Azure not asked — is
// asked in the background with its own key (the deployments list, as the
// real List asks it), and is back as soon as Azure answers again.
func TestAzureKeyThatAnsweredRestsSuspendedTillItAnswers(t *testing.T) {
fresh(t)
var down atomic.Bool
var lists atomic.Int32
azHits, bkHits := azureGroup(t, func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("api-key") != "az-key" {
t.Errorf("%s asked with api-key %q", r.URL.Path, r.Header.Get("api-key"))
}
isList := !strings.HasSuffix(r.URL.Path, "/chat/completions")
if isList {
lists.Add(1)
}
if down.Load() {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, azureDenied)
return
}
if isList {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"data":[{"id":"gpt-sol","object":"model"}]}`)
return
}
servedBy(provider.Chat, "gpt-sol")(w, r)
})
s := New()
steps, was := restProbeSteps, listForProbe
restProbeSteps = []time.Duration{20 * time.Millisecond, 40 * time.Millisecond}
listForProbe = func(ctx context.Context, p provider.Provider) error { _, err := p.List(ctx); return err }
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { s.keepProbingRests(ctx); close(done) }()
t.Cleanup(func() { cancel(); <-done; restProbeSteps, listForProbe = steps, was })
untilState(t, "the loop to start", func() bool {
restProbes.Lock()
defer restProbes.Unlock()
return restProbes.asking[s]
})
askSol(t, s)
if azHits.Load() != 1 || bkHits.Load() != 0 {
t.Fatalf("a working Azure key: az %d, bk %d", azHits.Load(), bkHits.Load())
}
down.Store(true) // the credit spent: Azure disables the subscription
askSol(t, s) // answered by the backup
rs := restsUnder("az")
if len(rs) != 1 {
t.Fatalf("rests %+v, want the key's one", rs)
}
r := rs[0]
if r.Why != failSuspended || r.By != "suspended" || !r.Probed || r.Status != http.StatusUnauthorized {
t.Fatalf("a key that answered before, refused 401, rests %+v: not suspended and asked in the background", r)
}
if left := time.Until(r.Until); left < suspendedRest-time.Minute {
t.Fatalf("rests only %v: asked again by requests, each refused", left)
}
// still disabled: the probe's lists are refused, it stays out, and
// requests aren't sent it
untilState(t, "the probe to ask while disabled", func() bool { return lists.Load() >= 2 })
askSol(t, s)
if azHits.Load() != 2 || len(restsUnder("az")) != 1 {
t.Fatalf("while Azure refused its list: az asked %d times, rests %+v", azHits.Load(), restsUnder("az"))
}
down.Store(false) // the credit renewed: Azure enables it again
untilState(t, "the rest to be lifted", func() bool { return len(restsUnder("az")) == 0 })
askSol(t, s)
if azHits.Load() != 3 {
t.Fatalf("back, Azure asked %d times, want 3", azHits.Load())
}
}
// A key refused 401 on its first request — mistyped, revoked, another
// resource's — is a bad key, as before: it rests the short backoff and is
// shown refused, never read as a subscription suspended or asked in the
// background for ever.
func TestAzureKeyNeverAnsweredIsABadKey(t *testing.T) {
fresh(t)
var lists atomic.Int32
azureGroup(t, func(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/chat/completions") {
lists.Add(1)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, azureDenied)
})
s := New()
askSol(t, s)
rs := restsUnder("az")
if len(rs) != 1 {
t.Fatalf("rests %+v, want the key's one", rs)
}
if r := rs[0]; r.Why != failOther || r.By != "backoff" || r.Probed || time.Until(r.Until) > longestRetry {
t.Fatalf("a key never answered, refused 401, rests %+v: not as a bad key", r)
}
if probeQueued(rs[0].Key) {
t.Fatal("a bad key is asked in the background")
}
if n := lists.Load(); n != 0 {
t.Fatalf("a bad key's list asked %d times", n)
}
}
// The rule is Azure's: a 401 on another vendor's key that answered before
// rests as a refused key did, its list never asked for it (OpenRouter's
// answers without a key).
func TestSuspendedIsAzureOnly(t *testing.T) {
fresh(t)
was := lastServedFor
t.Cleanup(func() { lastServedFor = was })
s := probing(t, func(context.Context, provider.Provider) error { return nil })
for _, tc := range []struct {
name string
p provider.Provider
want string
}{
{"azure", provider.Provider{ID: "sus-az", Preset: provider.AzurePreset, Key: "k", Chat: "https://r.openai.azure.com/openai/v1"}, failSuspended},
{"azure host", provider.Provider{ID: "sus-azh", Key: "k", Chat: "https://r.cognitiveservices.azure.com/openai/v1"}, failSuspended},
{"relay", provider.Provider{ID: "sus-relay", Key: "k", Chat: "https://openrouter.ai/api/v1"}, failOther},
{"azure account", provider.Provider{ID: "sus-acct", Preset: provider.AzurePreset, Key: "k", Chat: "https://r.openai.azure.com/openai/v1",
Account: &provider.Account{Agent: "codex", User: "a@b.c"}}, failOther},
} {
c := probeKey(t, tc.p.ID)
c.p = tc.p
lastServedFor = func() map[string]time.Time {
return map[string]time.Time{provider.ServedID(tc.p): time.Now().Add(-time.Hour)}
}
r := s.restAfter(c, http.StatusUnauthorized, http.Header{}, []byte(azureDenied))
if r.Why != tc.want || (r.Why == failSuspended) != r.Probed {
t.Errorf("%s: rests %+v, want %s", tc.name, r, tc.want)
}
clearRest(c.restKey())
// a 403 or a 5xx on an Azure key that answered is no suspension
if tc.want == failSuspended {
for _, st := range []int{http.StatusForbidden, http.StatusTooManyRequests} {
if r := s.restAfter(c, st, http.Header{}, []byte(azureDenied)); r.Why == failSuspended {
t.Errorf("%s: a %d rests suspended", tc.name, st)
}
clearRest(c.restKey())
}
}
}
}
// A key resting suspended stays so when its rest ends and Azure still
// refuses it, after its last answer has aged out of served.json; served.json
// unreadable is no answer on record.
func TestSuspendedOutlivesItsLastAnswer(t *testing.T) {
fresh(t)
was := lastServedFor
t.Cleanup(func() { lastServedFor = was })
s := probing(t, func(context.Context, provider.Provider) error { return context.DeadlineExceeded })
c := probeKey(t, "sus-long")
c.p = provider.Provider{ID: "sus-long", Preset: provider.AzurePreset, Key: "k", Chat: "https://r.openai.azure.com/openai/v1"}
lastServedFor = func() map[string]time.Time { return map[string]time.Time{provider.ServedID(c.p): time.Now()} }
if r := s.restAfter(c, http.StatusUnauthorized, http.Header{}, []byte(azureDenied)); r.Why != failSuspended {
t.Fatalf("rests %+v", r)
}
lastServedFor = func() map[string]time.Time { return map[string]time.Time{} }
restingUntil.Lock()
restingUntil.m[c.restKey()] = time.Now().Add(-time.Second) // its day is over
restingUntil.Unlock()
if r := s.restAfter(c, http.StatusUnauthorized, http.Header{}, []byte(azureDenied)); r.Why != failSuspended {
t.Fatalf("refused again after its rest, with its answer gone from the file: %+v", r)
}
clearRest(c.restKey()) // Try now, or an answer
if r := s.restAfter(c, http.StatusUnauthorized, http.Header{}, []byte(azureDenied)); r.Why != failOther {
t.Fatalf("no answer on record and no suspension resting, it rests %+v", r)
}
}
+13 -2
View File
@@ -11,7 +11,9 @@ package gateway
// A list costs no allowance, and none is asked of a subscription's
// account, a plugin's, or a rest whose end the vendor or the user named
// (out of quota or credit, a Retry-After, a window full), which ends on
// time; nor of a rate limit, which a list answers while the chat endpoint
// time — but an Azure key that answered before and is refused 401, its
// subscription disabled until its credit renews (azure_suspended.go), is
// asked; nor of a rate limit, which a list answers while the chat endpoint
// still refuses, or of one model alone. A list answers for the vendor,
// not for every model behind it, so a rest the list lifted that fails
// again is not asked again until the key answers a request.
@@ -72,7 +74,16 @@ var restProbes = struct {
// A Retry-After the vendor sent with it is its word on when to ask again,
// which a list asked sooner would go around.
func probeable(c candidate, r Rest, header http.Header, now time.Time) bool {
if retryAfter(header, now) > 0 || c.p.Account != nil || r.Model != "" || r.Key != c.restKey() || r.Why != failOther || !c.p.ListAsks() {
if c.p.Account != nil || r.Model != "" || r.Key != c.restKey() || !c.p.ListAsks() {
return false
}
if r.Why == failSuspended {
// an Azure subscription disabled, its key refused till Azure
// enables it again, which nothing says the time of: its list is
// refused the same till then (azure_suspended.go)
return r.By == "suspended" && probeBefore(now.Add(restProbeSteps[0]), r.Until)
}
if retryAfter(header, now) > 0 || r.Why != failOther {
return false
}
if r.By != "backoff" {
+12 -2
View File
@@ -860,7 +860,8 @@ type Rest struct {
// or is rate limited again as soon as it is back), "restricted" (the
// vendor restricted the account: two hours, or until lifted by hand),
// "off" (no rest: its provider is set not to rest after an unknown
// failure, provider.RestCapOff).
// failure, provider.RestCapOff), "suspended" (an Azure key that
// answered before refused 401: a day, or until its probe answers).
By string `json:"by"`
Failures int `json:"failures,omitempty"` // in a row, for a backoff
// Key is what it rests by, for the app to lift the rest (Unrest)
@@ -1501,6 +1502,12 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
now := time.Now()
d := fallbackCooldown
why := failureOf(c, status, body)
if why == failOther && azureSuspended(c, status) {
// an Azure key that answered before, refused 401: its
// subscription disabled for its credit spent, back when Azure
// enables it again (azure_suspended.go)
why = failSuspended
}
if why == failCut {
// a plugin ended the turn on purpose, its upstream's stream having
// died mid-call (plugins#38): the account is as good as it was, the
@@ -1737,6 +1744,9 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
// Its words, for restrictedHeld to give again while it rests
d, r.By = restrictedRest, "restricted"
r.said = provider.APIError(body, http.StatusText(status))
case failSuspended:
// until it answers again: asked in the background (probeable)
d, r.By = suspendedRest, "suspended"
case failVerify:
d, r.By = verifyRest, "verify"
// the error as the agent was given it, and the link in it
@@ -1840,7 +1850,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
// greys its Send till it knows magpie is its provider
codexMayBeUsedUp(a.User)
}
} else if a == nil && why != failOther && why != failVerify && why != failRestricted {
} else if a == nil && why != failOther && why != failVerify && why != failRestricted && why != failSuspended {
staleKeyAllowance(c.p) // a key that reads its windows, too
}
r.Until = onWall(now.Add(d))
+1 -1
View File
@@ -15476,7 +15476,7 @@ const accountRestLines = (p, user) => {
};
// a key's rest, worded as the Routing page words a failure
const KEY_FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", verify: "needs verification", refused: "refused (safety filter)", proxy: "proxy not reachable", slow: "slow to start" };
const KEY_FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", verify: "needs verification", refused: "refused (safety filter)", proxy: "proxy not reachable", slow: "slow to start", suspended: "suspended by the vendor" };
// Rest.Rate: the vendor called it a rate limit
const keyFail = (r) => r.why === "quota" && r.rate ? KEY_FAIL.rate : KEY_FAIL[r.why] || "failed";
+4
View File
@@ -4458,6 +4458,7 @@ const I18N = {
"Minutes": "分钟数",
"min": "分钟",
"slow to start": "迟迟未开始",
"suspended by the vendor": "被服务商停用",
"In magpie": "magpie 内耗时",
"One rate limited while it still has quota rests as long as the vendor asks, then takes its place in the order again.": "仍有额度却被限流的账号按厂商要求休息,之后回到原位继续使用。",
"One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts.": "仍有额度却被限流(429)的账号排到最后,位于此后所有未被限流的账号之后;前面的账号依次被限流后才再轮到它,负载因此轮转,而非每次回到第一个。额度用完的照常休息。此顺序保留到 magpie 重启。",
@@ -9938,6 +9939,7 @@ const I18N = {
"Minutes": "分鐘數",
"min": "分鐘",
"slow to start": "遲遲未開始",
"suspended by the vendor": "被服務商停用",
"In magpie": "magpie 內耗時",
"One rate limited while it still has quota rests as long as the vendor asks, then takes its place in the order again.": "仍有額度卻被限流的帳號按廠商要求休息,之後回到原位繼續使用。",
"One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts.": "仍有額度卻被限流(429)的帳號排到最後,位於此後所有未被限流的帳號之後;前面的帳號依次被限流後才再輪到它,負載因此輪轉,而非每次回到第一個。額度用完的照常休息。此順序保留到 magpie 重啟。",
@@ -15429,6 +15431,7 @@ const I18N = {
"Minutes": "分",
"min": "分",
"slow to start": "応答開始が遅い",
"suspended by the vendor": "ベンダーが停止中",
"In magpie": "magpie 内",
"One rate limited while it still has quota rests as long as the vendor asks, then takes its place in the order again.": "クォータが残っているのにレート制限されたものは、ベンダーの指示する時間だけ休止し、その後また順番内の位置に戻ります。",
"One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts.": "クォータが残っているのにレート制限(429)されたものは順番の最後尾に回り、それ以降レート制限されていないすべての後ろに並びます。前にあるものが順にレート制限されると再び回ってくるため、負荷は毎回先頭に戻るのではなく順に回ります。クォータ切れの場合は通常どおり休止します。magpie を再起動するまで保持されます。",
@@ -20941,6 +20944,7 @@ const I18N = {
"Minutes": "Minuten",
"min": "Min.",
"slow to start": "langsamer Start",
"suspended by the vendor": "vom Anbieter ausgesetzt",
"In magpie": "In magpie",
"One rate limited while it still has quota rests as long as the vendor asks, then takes its place in the order again.": "Ein Konto, das trotz verbleibendem Kontingent ein Rate-Limit erhält, pausiert so lange wie vom Anbieter verlangt und nimmt dann wieder seinen Platz in der Reihenfolge ein.",
"One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts.": "Ein Konto, das trotz verbleibendem Kontingent ein Rate-Limit (429) erhält, wandert ans Ende der Reihenfolge, hinter alle seither nicht begrenzten, und kommt wieder an die Reihe, sobald auch die vor ihm ein Rate-Limit erhalten – so rotiert die Last, statt jedes Mal zum ersten zurückzukehren. Ist das Kontingent aufgebraucht, pausiert es wie üblich. Gilt bis zum Neustart von magpie.",
@@ -766,7 +766,7 @@ function routingPage(part) {
const quota = (w, used, left, vars) => w.balance != null ? t(left, { n: balText(w), ...vars }) + lapses(w)
: (w.usedWindow ? shortWindow(w.usedWindow) + " " : "") + (w.limit > 0 ? quotaCount(w) + " · " : "") + t(quotaLeft ? left : used, { n: pct(share(w)), ...vars });
const fill = (w) => Math.max(0, Math.min(100, share(w))) + "%";
const FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", canceled: "canceled", foreign: "another account's reasoning", floor: "reply too short", verify: "needs verification", refused: "refused (safety filter)", shape: "request not understood", sight: "images not taken", proxy: "proxy not reachable", offline: "network down", overloaded: "servers overloaded", effort: "reasoning effort not in its plan", overflow: "too long for its model", room: "reply asked past the window left", slow: "slow to start", prompt: "agent's prompt turned away", restricted: "account restricted by the vendor" };
const FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", canceled: "canceled", foreign: "another account's reasoning", floor: "reply too short", verify: "needs verification", refused: "refused (safety filter)", shape: "request not understood", sight: "images not taken", proxy: "proxy not reachable", offline: "network down", overloaded: "servers overloaded", effort: "reasoning effort not in its plan", overflow: "too long for its model", room: "reply asked past the window left", slow: "slow to start", prompt: "agent's prompt turned away", restricted: "account restricted by the vendor", suspended: "suspended by the vendor" };
// a refusal the vendor called a rate limit, resting as out of quota
// until the time it named (Rest.Rate), says rate limited: WorkBuddy's
// per-model "频率限制" read as the account's quota used up, its credits
@@ -951,6 +951,9 @@ function routingPage(part) {
// the vendor restricted the account itself (#1849): only its lifting,
// which the vendor's appeal asks for, brings it back
case "restricted": return t("The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here", { d });
// an Azure key that answered before, refused 401: its subscription
// disabled till its credit renews, asked in the background
case "suspended": return t("Its key answered before, so the vendor has most likely suspended it (an Azure subscription out of credit): checked in the background, back as soon as it answers");
case "backoff": return rest.why === "rate"
? t("It was rate limited again as soon as it was back ({n} times in a row): it rests {d}, longer each time until it answers", { n: rest.failures, d })
: (rest.failures > 1
@@ -473,6 +473,7 @@ magpie.strings({
"Verify the account ↗": "去验证账号 ↗",
"It's verified — try it again": "已验证,重新使用",
"account restricted by the vendor": "账号被服务商限制",
"Its key answered before, so the vendor has most likely suspended it (an Azure subscription out of credit): checked in the background, back as soon as it answers": "这个密钥之前能用,多半是服务商停用了它(比如 Azure 订阅额度用完):后台自动检测,恢复即用",
"The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here": "服务商限制了这个账号:它休息 {d},因为只有服务商解除限制才能让它恢复。请向服务商申诉;解除后,在这里重新使用",
"The restriction is lifted — try it again": "限制已解除,重新使用",
"{who} turned away the reasoning effort changed mid-conversation as an update that keeps its cache, so it is asked again at the new effort the usual way, before any of the reply reaches {agent}.": "{who} 不接受对话中途以保留缓存的「更新」方式切换推理强度,已在回复到达 {agent} 前按常规方式以新强度重问。",
@@ -1240,6 +1241,7 @@ magpie.strings({
"Verify the account ↗": "去驗證帳號 ↗",
"It's verified — try it again": "已驗證,重新使用",
"account restricted by the vendor": "帳號被服務商限制",
"Its key answered before, so the vendor has most likely suspended it (an Azure subscription out of credit): checked in the background, back as soon as it answers": "這個金鑰之前能用,多半是服務商停用了它(例如 Azure 訂閱額度用完):背景自動偵測,恢復即用",
"The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here": "服務商限制了這個帳號:它休息 {d},因為只有服務商解除限制才能讓它恢復。請向服務商申訴;解除後,在這裡重新使用",
"The restriction is lifted — try it again": "限制已解除,重新使用",
"{who} turned away the reasoning effort changed mid-conversation as an update that keeps its cache, so it is asked again at the new effort the usual way, before any of the reply reaches {agent}.": "{who} 不接受對話中途以保留快取的「更新」方式切換推理強度,已在回覆到達 {agent} 前按常規方式以新強度重問。",
@@ -2005,6 +2007,7 @@ magpie.strings({
"Verify the account ↗": "アカウントを確認 ↗",
"It's verified — try it again": "確認済み — もう一度試す",
"account restricted by the vendor": "ベンダーがアカウントを制限",
"Its key answered before, so the vendor has most likely suspended it (an Azure subscription out of credit): checked in the background, back as soon as it answers": "このキーは以前は応答していたので、ベンダーが停止した可能性が高いです(Azure サブスクリプションのクレジット切れなど):バックグラウンドで自動確認し、応答すれば復帰",
"The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here": "ベンダーがこのアカウントを制限しました:制限を解除できるのはベンダーだけなので、{d} 休止します。ベンダーに異議を申し立て、解除されたらここでもう一度試してください",
"The restriction is lifted — try it again": "制限が解除された — もう一度試す",
"{who} turned away the reasoning effort changed mid-conversation as an update that keeps its cache, so it is asked again at the new effort the usual way, before any of the reply reaches {agent}.": "{who} は会話の途中で推理レベルをキャッシュを保つ「更新」として変更することを受け付けなかったため、通常の方法で新しい推理レベルで再度リクエストします。応答が {agent} に届く前に処理されます。",
@@ -2772,6 +2775,7 @@ magpie.strings({
"Verify the account ↗": "Konto verifizieren ↗",
"It's verified — try it again": "Verifiziert – erneut versuchen",
"account restricted by the vendor": "Konto vom Anbieter gesperrt",
"Its key answered before, so the vendor has most likely suspended it (an Azure subscription out of credit): checked in the background, back as soon as it answers": "Der Schlüssel hat vorher geantwortet, also hat der Anbieter ihn wohl ausgesetzt (ein Azure-Abo ohne Guthaben): wird im Hintergrund geprüft, zurück sobald erreichbar",
"The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here": "Der Anbieter hat das Konto gesperrt: Es pausiert {d}, denn nur die Aufhebung der Sperre durch den Anbieter bringt es zurück. Legen Sie beim Anbieter Einspruch ein; sobald sie aufgehoben ist, versuchen Sie es hier erneut",
"The restriction is lifted — try it again": "Die Sperre ist aufgehoben – erneut versuchen",
"{who} turned away the reasoning effort changed mid-conversation as an update that keeps its cache, so it is asked again at the new effort the usual way, before any of the reply reaches {agent}.": "{who} hat den mitten in der Unterhaltung als cache-erhaltendes Update geänderten Reasoning-Effort abgelehnt, daher wird es auf normalem Weg mit dem neuen Effort erneut gefragt, bevor etwas von der Antwort {agent} erreicht.",
+140
View File
@@ -0,0 +1,140 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// An Azure key that answered before and is refused 401 — its subscription
// disabled for its credit spent (canlee886 on X) — rests suspended, asked
// again in the background and back as soon as it answers
// (gateway/azure_suspended.go). Its rest says the vendor suspended it, not
// that it failed, in the provider's key list and in the Routing page's words
// for the try; a key 401 from its first request still reads "failed", with
// no word of the background. In every language, at a wide and a narrow
// window, in both engines.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(process.env.MAGPIE_AZURE_SUSPENDED_ASSETS || path.join(__dirname, "../assets"));
const now = new Date();
const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-");
const start = new Date(now.getTime() - 60e3).toISOString();
const until = new Date(now.getTime() + 24 * 3600e3).toISOString();
const soon = new Date(now.getTime() + 4 * 60e3).toISOString();
const a = { id: "az#bbbbbbbbbb", provider: "az", name: "Azure", kind: "key", who: "Team", model: "big" };
const b = { id: "ww2", provider: "ww2", name: "WW2", kind: "provider", model: "big" };
const rest = { why: "suspended", status: 401, until, by: "suspended", failures: 1, key: "az#bbbbbbbbbb", probed: true };
const routes = [{
id: 100, seq: 100, time: start, agent: "codex", model: "group/g", provider: "az",
order: [a, b],
tries: [
{ id: a.id, model: a.model, start, done: true, status: 401, ms: 300, fail: "suspended", rest, error: "Azure: Access denied due to invalid subscription key or wrong API endpoint." },
{ id: b.id, model: b.model, start, done: true, status: 200, ms: 900 },
],
done: true, status: 200, ms: 1300,
}];
const azure = () => ({
id: "az", name: "Azure", icon: "azure-color", preset: "azure", chat: "https://res.openai.azure.com/openai/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "big", name: "", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "",
keyList: [
{ id: "aaaaaaaaaa", name: "New", masked: "sk-…one", on: true, active: true, rest: { why: "other", status: 401, until: soon, by: "backoff", key: "az#aaaaaaaaaa" } },
{ id: "bbbbbbbbbb", name: "Student", masked: "sk-…two", on: true, rest: { why: "suspended", status: 401, until, by: "suspended", key: "az#bbbbbbbbbb", probed: true } },
],
});
function serve(lang) {
const state = { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
const providers = { providers: [azure()], presets: [], excluded: [], gateway: { running: true, window: true } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3));
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
}
if (url.pathname === "/api/gateway/history") {
const d = url.searchParams.get("day");
return json({ cut: false, days: [{ day, requests: routes.length }], routes: d ? routes : [] });
}
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const probed = {
en: "checked in the background, back as soon as it answers",
zh: "后台自动检测,恢复即用",
"zh-TW": "背景自動偵測,恢復即用",
ja: "バックグラウンドで自動確認し、応答すれば復帰",
de: "wird im Hintergrund geprüft, zurück sobald erreichbar",
};
const suspended = { en: "suspended by the vendor", zh: "被服务商停用", "zh-TW": "被服務商停用", ja: "ベンダーが停止中", de: "vom Anbieter ausgesetzt" };
const failed = { en: "failed", zh: "失败", "zh-TW": "失敗", ja: "失敗", de: "fehlgeschlagen" };
const likely = {
en: "the vendor has most likely suspended it",
zh: "多半是服务商停用了它",
"zh-TW": "多半是服務商停用了它",
ja: "ベンダーが停止した可能性が高いです",
de: "hat der Anbieter ihn wohl ausgesetzt",
};
const sideways = (page) => page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth + 1);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(probed)) {
for (const width of [1100, 420]) {
const open = async (t, name, view) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const context = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name}.png`), fullPage: true });
}
await browser.close();
});
await page.goto("http://magpie.test/?view=" + view);
return { page, errors };
};
test(`${engine} ${lang} ${width}px: a suspended key says the vendor suspended it, a bad key that it failed`, async (t) => {
const { page, errors } = await open(t, "keys-suspended", "providers");
await page.locator(".row.provider", { hasText: "Azure" }).first().click();
const student = page.locator('.acc[data-account-id="bbbbbbbbbb"] .key-rest');
const fresh = page.locator('.acc[data-account-id="aaaaaaaaaa"] .key-rest');
await student.waitFor();
await fresh.waitFor();
const said = await student.textContent(), bad = await fresh.textContent();
assert(said.includes("401 " + suspended[lang]) && said.endsWith(" · " + probed[lang]), `the suspended key says: ${said}`);
assert(bad.includes("401 " + failed[lang]) && !bad.includes(suspended[lang]) && !bad.includes(probed[lang]), `the bad key says: ${bad}`);
assert(!(await sideways(page)), "the page scrolls sideways");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}px: Routing's words for the try say the vendor suspended it`, async (t) => {
const { page, errors } = await open(t, "routing-suspended", "routing");
await page.locator(".rt-days .rt-day").nth(1).click();
await page.locator(".rt-req").first().waitFor();
await page.locator(".rt-req").first().click();
await page.locator(".rt-steps li").first().waitFor();
const steps = (await page.locator(".rt-steps li").evaluateAll((ls) => ls.map((l) => l.textContent.replace(/\s+/g, " ")))).join("\n");
assert(steps.includes(suspended[lang]) && steps.includes(likely[lang]) && steps.includes(probed[lang]), `the steps say:\n${steps}`);
assert(!(await sideways(page)), "the page scrolls sideways");
assert.deepEqual(errors, []);
});
}
}
}