diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index a980dcd0d..c00cbb0d9 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -327,7 +327,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`). - The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Quota first compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A biggest window its next one can't use up before it renews is passed over (`Allowance.Unreached`, `Seat.Unreached`, the trace's `unreached`): when what it has left is more than the next window, a day or longer and counted in the same unit, lets through between its own reset and the biggest one's (`Of` × the time between ÷ `Span`), what the next leaves at its reset is lost, so it ranks the account. A month holding less than its weeks add up to still ranks it while they can carry it (#1778); a Volcengine Agent Plan, 20,000 a month and 7,000 a week, goes by its week from about two weeks before its month renews (#5639, louisgreen0726; `TestMonthOutOfReachRanksByWeek`, `TestSmartSpendsAWeekTheMonthCantWait`, `TestSmartPassesAnUnreachedWindow`). Windows that tell only a share, and Ark replies with `Percent` alone, are never compared. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). When the renewals tie to the hour, Quota first goes by that moment once more (`Allowance.Lapse`, `Seat.Lapse`), so of accounts renewing together (WorkBuddy's free accounts all reset at the month's end, plugin 0.1.35) the one whose credits left lapse first, after that end, goes first, and one telling none goes after (zhaocai_83020 on Discord). The trace carries both keys as Quota first sorted by them, `soon` (`Allowance.Renewal`) and `lapse` (`Allowance.Lapse`) beside each window's own `renews` (`Weighed.Soon`, `Weighed.Lapse`), and the Routing page's story and rows compare those (`renewsBy`, `cmpRenews`, `firstWhy`, `behindWhy`): a credit pack ending before the month another account renews with is told as its credits expiring first, a tie broken by the lapse as that, and the order given only where every key ties (#5646, louisgreen0726; `TestTraceCarriesSmartSortKeys`, `routing-story-credits-expire.test.cjs`). A route from before `soon` is read from `renews` and `restarts`. Only Quota first reads the lapse; Use before expiry, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Quota first still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered. - A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`. - 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 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). A rest out of quota or credit till a time the vendor named is lifted only when a reading finds its window started again in fact (`restarted`, #2718); a reading that finds the window full no more while that time still stands (`renewed`) lets the hold go once for that time, without lifting the rest (`askOnRenewalLocked`, `restingUntil.renewAsked`), so the next request asks the vendor: a reset bought on the vendor's side (Zhipu's 重置卡) was answered with the held refusal till the time it named (RookieRicardoR on X; `TestRenewalAsksAVendorTimedRestOnce`). Refused again with the same time, it is held till it, whatever readings say. 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; 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`. diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 9d528ebc9..91380f52c 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -1616,6 +1616,10 @@ var restingUntil = struct { // found, from whichever page lifted it (zoecats on Discord: Try now // in the provider's editor left Routing at 429 until a restart) lifted map[string]time.Time + // renewAsked is, by the key it rests by, the end of a rest the vendor + // timed that a reading's renewal had asked again once + // (askOnRenewalLocked): not asked so again till another time is named + renewAsked map[string]time.Time }{m: map[string]time.Time{}, note: map[string]Rest{}, lifted: map[string]time.Time{}} // liftedLocked notes that the rest by key was lifted now, with diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index 4ccb0619d..c742d8341 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -108,6 +108,7 @@ func noRests() { restingUntil.m = map[string]time.Time{} restingUntil.note = map[string]Rest{} restingUntil.lifted = map[string]time.Time{} + restingUntil.renewAsked = nil restingUntil.Unlock() codexHolds.Lock() codexHolds.m = nil diff --git a/internal/gateway/no_reply_reuse_test.go b/internal/gateway/no_reply_reuse_test.go new file mode 100644 index 000000000..a282d9e6a --- /dev/null +++ b/internal/gateway/no_reply_reuse_test.go @@ -0,0 +1,65 @@ +package gateway + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// RookieRicardoR on X: the same prompt sent to DeepSeek from Claude Code, +// then from Pi, came back with the same words, and the reply was taken for +// one magpie kept and gave again. magpie keeps no reply to give a later +// request: each request, the same bytes from the same agent too, or from +// another agent and protocol, is asked of the vendor, and answered with +// what the vendor said to it. +func TestSameRequestIsAskedEveryTime(t *testing.T) { + fresh(t) + var mu sync.Mutex + asked := 0 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + mu.Lock() + asked++ + n := asked + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + text := fmt.Sprintf("answer number %d", n) + if strings.HasSuffix(r.URL.Path, "/messages") { + fmt.Fprintf(w, `{"id":"msg_%d","type":"message","role":"assistant","model":"deepseek-v4","content":[{"type":"text","text":%q}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":3}}`, n, text) + return + } + fmt.Fprintf(w, `{"id":"c%d","object":"chat.completion","model":"deepseek-v4","choices":[{"index":0,"message":{"role":"assistant","content":%q},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":3}}`, n, text) + })) + defer up.Close() + if err := provider.Save(provider.Provider{ID: "ds", Name: "DS", Key: "k", Models: []string{"deepseek-v4"}, + Chat: up.URL + "/v1", Anthropic: up.URL + "/anthropic"}); err != nil { + t.Fatal(err) + } + const prompt = "write a haiku about magpies" + claude := `{"model":"ds/deepseek-v4","max_tokens":64,"messages":[{"role":"user","content":"` + prompt + `"}]}` + chat := `{"model":"ds/deepseek-v4","messages":[{"role":"user","content":"` + prompt + `"}]}` + var replies []string + for i, q := range []struct{ path, body string }{ + {"/v1/messages", claude}, {"/v1/messages", claude}, {"/v1/chat/completions", chat}, {"/v1/chat/completions", chat}, + } { + code, body := post(t, q.path, q.body) + if code != http.StatusOK { + t.Fatalf("request %d (%s): %d %s", i, q.path, code, body) + } + replies = append(replies, body) + } + if asked != len(replies) { + t.Fatalf("the vendor was asked %d times for %d requests", asked, len(replies)) + } + for i, body := range replies { + if want := fmt.Sprintf("answer number %d", i+1); !strings.Contains(body, want) { + t.Errorf("request %d answered %s, want the vendor's own answer to it (%q)", i, body, want) + } + } +} diff --git a/internal/gateway/rest_renewal_ask_test.go b/internal/gateway/rest_renewal_ask_test.go new file mode 100644 index 000000000..3b76475a5 --- /dev/null +++ b/internal/gateway/rest_renewal_ask_test.go @@ -0,0 +1,95 @@ +package gateway + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// RookieRicardoR on X: a GLM key refused out of its allowance till the +// time Zhipu named, then given a reset (Zhipu's 重置卡) on the vendor's +// side, was still answered "limit reached" by magpie on every request +// till that time, the vendor never asked. A reading of the key's windows +// that finds the one it was out of full no more has the vendor asked once +// again; the rest itself stands (#2718), and refused again with the same +// time the key is held till it, however often its windows read less than +// full. +func TestRenewalAsksAVendorTimedRestOnce(t *testing.T) { + fresh(t) + provider.ForgetBalances() + t.Cleanup(provider.ForgetBalances) + old := keyAllowance + keyAllowance = provider.KeyAllowance // the key's windows as read, here + t.Cleanup(func() { keyAllowance = old }) + reset := time.Now().Add(3 * time.Hour).Truncate(time.Second) + var mu sync.Mutex + used := 800 + relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + u := used + mu.Unlock() + fmt.Fprintf(w, `{"isValid":true,"mode":"quota_limited","status":"active","rate_limits":[{"window":"5h","limit":800,"used":%d,"remaining":%d,"reset_at":%q}]}`, u, 800-u, reset.Format(time.RFC3339)) + })) + defer relay.Close() + if err := provider.Save(provider.Provider{ID: "kr", Name: "KR", Key: "sk-r", Models: []string{"glm-5.2"}, + Chat: relay.URL + "/v1", BalanceURL: relay.URL + "/v1/usage"}); err != nil { + t.Fatal(err) + } + saved, err := provider.Find("kr") + if err != nil { + t.Fatal(err) + } + c := perKey(*saved, "glm-5.2", provider.Chat)[0] + t.Cleanup(func() { clearRest(c.restKey()) }) + provider.KeyBalances(context.Background()) // its five hours read: used up + s := &Server{} + refusal := []byte(fmt.Sprintf(`{"error":{"message":"Usage limit reached. Your usage will reset at %s UTC+8, upgrade for more","type":"rate_limit_exceeded"}}`, + reset.In(zhipuZone).Format("2006-01-02 15:04:05"))) + refuse := func() { + t.Helper() + if r := s.restAfter(c, 429, http.Header{}, refusal); r.Why != failQuota || r.By != "resets" { + t.Fatalf("refused till %s: rests by %s (%s)", reset.Format(time.TimeOnly), r.By, r.Why) + } + } + held := func() bool { + _, _, ok := timedHeld([]candidate{c}) + return ok + } + read := func(u int) { + mu.Lock() + used = u + mu.Unlock() + provider.ForgetBalances() + provider.KeyBalances(context.Background()) + } + refuse() + if !held() { + t.Fatal("refused till a named time: not held") + } + read(800) // read again, still used up: nothing changes + if !held() { + t.Fatal("a reading that still finds the window full let the hold go") + } + read(0) // the reset bought on the vendor's side + if held() { + t.Fatal("the window read renewed, and the key is still held till the vendor's time: the vendor is never asked") + } + if _, ok := restOf(c.restKey()); !ok { + t.Fatal("the renewal lifted the rest itself; only the hold is let go (#2718)") + } + refuse() // asked, and refused again with the same time + if !held() { + t.Fatal("refused again with the same time: not held") + } + read(800) + read(0) // its windows read less than full again, the same time standing + if !held() { + t.Fatal("asked again for the same named time: a renewal asks once for it") + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index c4e0cddf8..a784f45a9 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -971,7 +971,10 @@ func liftRests(agent, user string, vendorTill bool) { if r.agent != agent || !strings.EqualFold(r.user, user) || !(r.Why == failQuota || r.By == "window" || r.Why == failCredit && agent == "codex") { continue } - if vendorTill != (r.By == "resets" || r.By == "retry-after") { + if timed := r.By == "resets" || r.By == "retry-after"; vendorTill != timed { + if timed && r.Why != failRate { + askOnRenewalLocked(k, r, now) + } continue } delete(restingUntil.m, k) @@ -980,6 +983,35 @@ func liftRests(agent, user string, vendorTill bool) { } } +// askOnRenewalLocked has a rest the vendor gave the time of, out of quota +// or credit, asked again once, without lifting it, when a reading of its +// windows finds the one it was out of full no more while the time the +// vendor named still stands: a reset bought on the vendor's side (Zhipu's +// 重置卡, RookieRicardoR on X) renews the window there, and every request +// was answered with the refusal till the time it named, the vendor never +// asked. The rest stands (#2718: the vendor's usage can say less than full +// while its refusal does too), so a pick that keeps off a resting account +// still does; only the hold is let go (asksAt), for the next request to +// ask. Once for each time the vendor named: refused again with the same +// time, the new rest holds till it, whatever readings say, as before. +func askOnRenewalLocked(k string, r Rest, now time.Time) { + until, ok := restingUntil.m[k] + if !ok || !now.Before(until) || restingUntil.renewAsked[k].Equal(until) { + return + } + if restingUntil.renewAsked == nil { + restingUntil.renewAsked = map[string]time.Time{} + } + for x, t := range restingUntil.renewAsked { + if !now.Before(t) { + delete(restingUntil.renewAsked, x) + } + } + restingUntil.renewAsked[k] = until + r.first, r.askAt = false, now + restingUntil.note[k] = r +} + // creditsKnown lifts the rests out of its allowance of a ChatGPT account // found to go on past it on credits (provider.OnCredits), whatever time // the refusal named: a turn turned away before magpie knew of the credits