From ed405d1d781d7832bababa8361fa6c299109128e Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 19 Nov 2026 19:38:31 +0800 Subject: [PATCH] gateway: an Azure key that answered before, refused 401, rests suspended till it answers (canlee886 on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- docs/subsystems/gateway-routing.md | 3 +- internal/gateway/azure_suspended.go | 66 +++++ internal/gateway/azure_suspended_test.go | 253 ++++++++++++++++++ internal/gateway/rest_probe.go | 15 +- internal/gateway/routing.go | 14 +- internal/gui/assets/app.js | 2 +- internal/gui/assets/i18n.js | 4 + internal/gui/assets/plugins/routing/client.js | 5 +- internal/gui/assets/plugins/routing/i18n.js | 4 + internal/gui/tests/azure-suspended.test.cjs | 140 ++++++++++ 10 files changed, 499 insertions(+), 7 deletions(-) create mode 100644 internal/gateway/azure_suspended.go create mode 100644 internal/gateway/azure_suspended_test.go create mode 100644 internal/gui/tests/azure-suspended.test.cjs diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 07424eab5..9f71eedb8 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -328,7 +328,8 @@ the key's leaves the call as asked, with a log line (`compactRefused`). - A request's masking record is told to the app for the "Masking alert" notification (Must2333 on X, `OnMasked` in [`masked.go`](../../internal/gateway/masked.go), set by the GUI; nil under `magpie serve`), after `maskrec.Hold` and with its text around placeholders (`Snips`, `Back`) taken out. [`mask_alert.go`](../../internal/gui/mask_alert.go) keeps the records while `settings.MaskAlert` is on (off until turned on, in Settings → Usage, hidden with masking) and says only the values a record masked for the first time (`maskrec.Fresh`, [`first.go`](../../internal/maskrec/first.go): each placeholder by the key of the first record that had it, read from memory and the days kept, so a conversation's history sent again each turn, or after a restart, is not news; a value sent as written is not one masked). A burst is gathered for `maskGather` (3s) and said as one, and one is said at most every `maskGap` (1 minute), what came in between said after it. It says each kind with its count and up to two agents, never a value nor its hint; a click opens the Masking page on the latest record (`clickView`, `masking&key=`). A held-back request (`noteBlocked`) is not said; a value whose records have all aged out (30 days) is new again. `TestFreshOnlyTheFirstTime`, `TestMaskAlertFirstTimeOnly`, `TestMaskAlertNeverSaysTheValue`, `TestMaskAlertCoalesces`, `mask-alert.test.cjs`. - A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (`heldClock`: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (`creditRest`, or `quotaRest` with no `Provider.OwnQuotaRest`), is held so only once it was refused so twice in a row (`Rest.first`): a single refusal may be a moment's, and the next request, the agent's retry first, asks it again (zoecats on Discord: a local aggregator said 429 `insufficient_quota` "quota exhausted" for the moment it switched upstreams, and every request was answered from its rest of 15 or 30 minutes, which only the provider's "Rests" switch, `LimitRestOff`, let through before). Held, it is asked again a minute on (`Rest.askAt`, `fallbackCooldown`), once, and held again if refused (`Rest.asksAt`); a time the vendor named, or the user set, holds it from the first refusal to then. The rest itself stays as long as before, so the order still passes it over for a candidate that is ready. The last key left rests too when it is refused so, as the keys before it do, and so does the last account left (a Codex or other subscription account; `quotaHeld` still holds keys alone, and `autoReset` lifts the rest of an account it spends a reset of): before, an account last in an in-order group, out of its quota, was never rested, so every request a relay ahead of it failed for a moment went on to it and ended on its 429 (dbydd on Discord; `TestGroupSpentLastAccountRests`). Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (`soonestBack`, by `asksAt`), none after a key's first refusal. `TestRetryAfterALimitIsAsked`, `TestHeldLimitAskedAgainInAMinute`. A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key or an account resting on a 429 for the time its vendor named (`Rest.By` "retry-after" or "resets": a `Retry-After`, an `anthropic-ratelimit-*-reset` or `x-ratelimit-reset-*` header, or a refusal's `resets_in_seconds` / `resets_at`), rate limited or out of its allowance, is held the same way when every candidate left rests so (`timedHeld`, `vendorTimed`): none is asked, not even the soonest back or a lone one, and the agent is answered with the first one's error and a `Retry-After` until the first of them is back, set on the held answer too, so neither the same-one retry (`passing`) nor the patience's rounds take it for a moment's limit. Not a Codex account that spends its resets by itself (`autoReset`), nor another computer's model (`Rest.there`), nor a provider with `LimitRestOff`, which never rests for a limit. The last one left rests on such a 429 too (`vendorSaidWhen`); one naming no time rests nobody, as before. Before, a key or account limited for 300 seconds was asked again every time the agent retried, about every half a second, until the vendor flagged the accounts (hsjzg58958 on X). Codex's own sign-in, and the account a compaction goes to, are relayed outside the candidate loop (`codexUpstreamOn`): a 429 there that names its time holds that account in `codexHolds` (`noteCodexHold`), and Codex's retries are answered with ChatGPT's own refusal and a `Retry-After` till then (`writeCodexHeld`), unless the turn has fallbacks or groups to go on to (`codexFallsBack`), which take it as they took the turn that held the account (`TestCodexHeldTurnFollowsTheGroup`); a reset spent or a window started again lifts a hold out of allowance (`restarted`). Codex's API key isn't held: OpenAI's platform answers it. `TestRateLimitedKeysHeldUntilTheirReset`, `TestRateLimitedCodexAccountsHeldUntilTheirReset`. A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`. - A model its plugin reports busier than the user's *Busy models last* (`settings.BusyLoad`, 1 to 9999 (`BusyLoadMost`-1), past 100 for a vendor that queues, its Custom… field taking any of them, off by default; axelburks on Discord) goes behind the ready candidates, ahead of the resting ones (`restLast`, `busyOf`), and its trace row has `busy` with the load. The load comes from the plugin through `plugin.ModelLoad` (see [provider plugins](provider-plugins.md#a-models-load)); one not reported in the last 5 minutes is unknown and keeps its place. A lone candidate is asked whatever its load. A conversation it answered moves, at its next turn, to the ready one that leads (`affine`'s Why `busy`, `busyBehind`); within a turn it stays. A turn going round (`after`), a new conversation spread (`readyForNew`) or In turn (`leastHeld`) never lands on it past a ready one. When every candidate is busy, nothing moves. -- A key resting after an outage that names no time is asked again in the background (`rest_probe.go`, heatonz on Discord). Behind ready keys, `probeOne` never asks it before its rest ends, though its vendor may be back in a minute. `restAfterMarked` marks the rest `Probed` when it is a key's own (not an account's or a plugin's, not one model's `restID`), `failOther` by `backoff` after a 5xx, a 408 or no connection, with no Retry-After or reset header, at a provider whose `List` asks over the network (`Provider.ListAsks`), and long enough for a first ask. `keepProbingRests`, started in `ListenAndServe`, then asks the vendor's model list with that key through its proxy (`Provider.List`, which saves nothing) 1, 2, 5 and then every 10 minutes into the rest, while it is the same rest. When the list answers, the rest is lifted as Try now lifts it (`liftedLocked`, `unsink`, the trace's lift). Not asked: rate limits (a list answers while the chat endpoint still refuses, and lifting one early would undo Sink), quota, credit, a Retry-After or reset, a refused key (401, 403, 400), restrictions and verification, each of which ends on its own time or the vendor's. A key a probe lifted that fails again within 30 minutes isn't asked again until it answers a request (`probeMissed`, `probeAnswered` in `served`): the list answered for the vendor, not for its chat. Only the loop's own `Server` asks (`restProbes.asking`), so a test's `Server` never reaches the network. The cost is one list per resting key per step, never one per request. The key list (`KeyRest.Probed`) and Routing's words for the try (`restHow`) add "checked in the background, back as soon as it answers". `TestRestProbeLiftsAKeyBackUp`, `TestRestProbeLeavesOtherRests`, `TestRestProbeOnlyByARunningLoop`, `rest-probed.test.cjs`. +- A key resting after an outage that names no time is asked again in the background (`rest_probe.go`, heatonz on Discord). Behind ready keys, `probeOne` never asks it before its rest ends, though its vendor may be back in a minute. `restAfterMarked` marks the rest `Probed` when it is a key's own (not an account's or a plugin's, not one model's `restID`), `failOther` by `backoff` after a 5xx, a 408 or no connection, with no Retry-After or reset header, at a provider whose `List` asks over the network (`Provider.ListAsks`), and long enough for a first ask. `keepProbingRests`, started in `ListenAndServe`, then asks the vendor's model list with that key through its proxy (`Provider.List`, which saves nothing) 1, 2, 5 and then every 10 minutes into the rest, while it is the same rest. When the list answers, the rest is lifted as Try now lifts it (`liftedLocked`, `unsink`, the trace's lift). Not asked: rate limits (a list answers while the chat endpoint still refuses, and lifting one early would undo Sink), quota, credit, a Retry-After or reset, a refused key (401, 403, 400; an Azure key that answered before is the exception below), restrictions and verification, each of which ends on its own time or the vendor's. A key a probe lifted that fails again within 30 minutes isn't asked again until it answers a request (`probeMissed`, `probeAnswered` in `served`): the list answered for the vendor, not for its chat. Only the loop's own `Server` asks (`restProbes.asking`), so a test's `Server` never reaches the network. The cost is one list per resting key per step, never one per request. The key list (`KeyRest.Probed`) and Routing's words for the try (`restHow`) add "checked in the background, back as soon as it answers". `TestRestProbeLiftsAKeyBackUp`, `TestRestProbeLeavesOtherRests`, `TestRestProbeOnlyByARunningLoop`, `rest-probed.test.cjs`. +- An Azure key that answered before and is refused 401 rests suspended (`azure_suspended.go`, canlee886 on X). An Azure subscription with a spending limit (a student's, a trial's) is disabled when its credit runs out and enabled again on its own when the credit renews; meanwhile every request 401s with "Access denied due to invalid subscription key or wrong API endpoint", the words a wrong key gets. `restAfterMarked` reads a `failOther` 401 as `failSuspended` when `azureSuspended` holds: no account, `Provider.IsAzure`, and the key has answered a request (`provider.LastServed` at `provider.ServedID`, served.json, kept 30 days) or is resting suspended already (so a rest that ends while Azure still refuses stays one after the answer leaves the file). It rests `suspendedRest`, a day, by `suspended`, and `probeable` takes it whatever its status: the background ask above lists the resource's deployments with the key (`azureModels`), refused the same while the subscription is off, and lifts the rest as soon as the list answers, or a request does (`served`). One 401 is enough: a 401 is about the credential, never the model or the request, and on a key that worked a transient one is lifted by the first ask a minute in, as the old one-minute backoff would have let it back. A key 401 from its first request (new, mistyped, or edited, its `KeyID` another) has no answer on record and fails as before: `failOther` on the short backoff, shown "401 · failed", never asked in the background; a served.json that can't be read is no answer on record too. Azure's alone: a 401 says nothing of why elsewhere, and a list that answers without the key (OpenRouter's is public) would lift a key the vendor still refuses. Not covered: a 403, a key whose last answer is over 30 days old after a restart (rests are in memory), and the last candidate of a request, which rests only for quota, credit or a timed rate limit and so is asked again by the next request as before. No setting: the probe finds the day Azure enables it, so there is no "back on day N" to type in. The key list says "suspended by the vendor" with the background words, and Routing's `restHow` says the vendor has likely suspended it. `TestAzureKeyThatAnsweredRestsSuspendedTillItAnswers`, `TestAzureKeyNeverAnsweredIsABadKey`, `TestSuspendedIsAzureOnly`, `TestSuspendedOutlivesItsLastAnswer`, `azure-suspended.test.cjs`. - A provider whose keys are on different plans (`KeyAccount.Plan`, `PlansMixed`; yckonnnn on X) sends each key to its plan's endpoints: every key path takes its copy through `WithKey`, which moves it there (`atKeyPlan`), on the first try and on a failover alike. `perKeyBarred` leaves out a key whose plan's list lacks the model (`PlanServing`: a pay-as-you-go model id at the Agent Plan's endpoint only answers 404), not shown in the trace; only when no key's plan has it are those keys asked. Embeddings and drawing go through the same `perKeyBarred` and `WithKey`; a video started on a mixed provider names its key in the task id (`videoStart.onKey`, `keyMark`) so its poll goes to that key's plan. `TestKeyPlansEachToItsOwnEndpoint`. - A subscription's account whose own model list lacks the model (`Account.Lists`: an Antigravity account's `fetchAvailableModels`, a ChatGPT or Copilot account's own `/models`, a plugin account's `models`) isn't planned while another of its accounts lists it (`perKeyBarred`'s `left`, `planned.unlisted`, the Routing page's "unlisted, skipped"). It is the next asked when every account of the subscription that lists the model has been asked and one refused it as a model it doesn't serve (`unservedTry`: `modelRefused`, or Code Assist's 404 NOT_FOUND, `codeAssistModelMissing`), before any later member or fallback (`unlistedNext`, `askUnlisted` moves its row from the route's left to its order after the one that refused). A list is fetched once and can be stale: 01huadalang's Gemini 4 was served by one Antigravity account of several, and the one whose list named it refused it with a 404 the agent got while the other could answer. The one that refused rests for that model alone. Not for another refusal (a 403, a quota), a request pinned to an account, a native compaction sealed to one, or a conversation kept strictly on one; a gateway key held to some accounts narrows the unlisted ones too (`allowedCandidates`). `TestUnlistedAccountAskedAfterModelRefused`, `TestUnlistedAccountNotAskedForOtherRefusals`. - A member whose model is known to take less than the request isn't asked it (`roomy` in [`fallback.go`](../../internal/gateway/fallback.go), in `serve` after the rules, affinity, the image filter and `pinTo`, before `probeOne`; dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash, 200K, first in a group and a 1M subscription of it second). It is a check before sending, not a retry: the request's tokens are estimated as the overflow fall-over does (`estimate`, bytes/4 over text, tool arguments and schemas), and a candidate whose window (`windowOf`: the provider's `Contexts`, the catalog, `ContextOf`) is known and no larger is left out of the candidates and of the trace's order, and listed in the trace's `left` with `window` set to that window. Asked, such a member only refuses, and a refusal that doesn't say why, for a request short of `tooLongUnsaid`'s 1.2 margin, reached the agent as the vendor's error while the next member had room; it also spent a request against the member's limits. A conversation kept on a member by affinity moves once it outgrows it. Nothing is left out when its window isn't known, when the body doesn't parse, when only one model is among the candidates, or when no candidate holds the request: then the first is asked, and its overflow reaches the agent as one, to compact (`withRoom`, `failOverflow` and `tooLongUnsaid` stay for the window the estimate misses, which counts low on code and high on CJK text). A body shorter than four bytes per token of the least window isn't parsed. `count_tokens` (a count on the group's first member, not a send) and System One's decision models (short decision text) don't go through it. Those left out are the last resort: when the last candidate with room fails out of its allowance or credit (`failQuota`/`failCredit`), nothing before it having failed otherwise (`other`), and no account is pinned, the ones left out that aren't resting are asked after all, their rows moved from the trace's `left` to its order, and the one that failed rests as one before the last does. Its overflow tells the agent to compact, where the 429 only told it to wait for an allowance hours away (Kai on Discord: both Claude accounts spent until the next day, the Claude provider's Fallback a Codex model of 272K under a longer conversation, never asked). Another failure (a busy vendor, a bad key) still reaches the agent as it was, the small one not asked. The Routing page keeps a row for a member left out and not asked, saying the request is longer than its window and that it was passed over, and its why list says so (#3749; it used to show it only by its absence from the order). `TestMemberTooSmallIsNotAsked`, `TestMemberTooSmallIsTheLastResort`, `TestClaudeAccountsSpentFallBackToCodex`, `TestConversationOutgrowingItsMemberMoves`, `TestRoomyLeavesWhatItCantJudge`. diff --git a/internal/gateway/azure_suspended.go b/internal/gateway/azure_suspended.go new file mode 100644 index 000000000..3ca62f9c5 --- /dev/null +++ b/internal/gateway/azure_suspended.go @@ -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() +} diff --git a/internal/gateway/azure_suspended_test.go b/internal/gateway/azure_suspended_test.go new file mode 100644 index 000000000..eb4f6c1af --- /dev/null +++ b/internal/gateway/azure_suspended_test.go @@ -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) + } +} diff --git a/internal/gateway/rest_probe.go b/internal/gateway/rest_probe.go index 62f879038..0d7f08404 100644 --- a/internal/gateway/rest_probe.go +++ b/internal/gateway/rest_probe.go @@ -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" { diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 0b47a54ca..c4e0cddf8 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -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)) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 24f3235ab..0c4bbda2d 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -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"; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index abfdbad30..dbeaccc49 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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.", diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 6eb602a52..786818c20 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -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 diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 6f64882b8..80a7b34e8 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -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.", diff --git a/internal/gui/tests/azure-suspended.test.cjs b/internal/gui/tests/azure-suspended.test.cjs new file mode 100644 index 000000000..6b489b4eb --- /dev/null +++ b/internal/gui/tests/azure-suspended.test.cjs @@ -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, []); + }); + } + } +}