gateway: keys all out of their allowance are answered from their rests with a Retry-After, not asked again on every request, and a key listed twice is asked once (#1772)
A fleet on four Ollama Cloud keys, every one out of its weekly allowance:
each new request asked every key again (the first twice) and answered
429 with no Retry-After, so an agent that waits as told asked again at
once, and the vendor saw four refused requests a turn.
What changed:
- The first key twice: the reporter's providers.json named the first key
in "keys" as well as "key". KeysOn now lists a key once.
- When every key left for a request rests out of its allowance (a 429 or
402 that failure() calls quota or credit, keys only), the request is
answered from the rest without asking: the vendor's own words, "not
asked again before HH:MM", and Retry-After until the first of them is
back (quotaHeld, soonestBack). Accounts are left out, so autoReset
can still spend a reset for them; a 403 or 400 worded as quota is
asked as before.
- The last key out of its allowance now rests as the ones before it do
(before, the last one left was never rested), and a 429 the vendor gave
no Retry-After for gets the soonest rest's end as one.
- A provider can set how long its keys rest when the vendor says nothing
of when the allowance is back: quotaRest (minutes) in providers.json,
or `magpie provider quota-rest <id> 7d`; default stays 15 minutes, at
most 8 days. A time the vendor names (resets_at, Retry-After, a
window) still wins. A GUI save keeps it.
What was run:
- TestAllRestingAnswersFromRest, TestFirstKeyListedTwiceAskedOnce and
TestOwnQuotaRest fail on the old code (no Retry-After, keys re-asked;
"dead-1 dead-1 dead-2 ok-3", the reporter's log); they pass now, with
TestQuotaHeldOnlyForKeysOutOfAllowance, TestDeadChainWalksEachOnce and
TestRestMinutes. The mock answers with the reporter's literal 429 body.
- go test -tags nogui ./internal/provider ./internal/gui pass. A gateway
package run at load ~60 hit its 20m timeout mid-suite with only
TestMaxRPM* red; those pass 8/8 alone here and on origin/main
17c12621b (timing under load, filed as #1791).
Not verified: no run against real Ollama Cloud keys; quotaRest has no
field in the provider editor (CLI and providers.json only).
This commit is contained in:
@@ -56,7 +56,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
- A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop`. A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off.
|
||||
- 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). Smart 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 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). Only Smart reads it; Weekly pace, 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 Smart 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 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.
|
||||
- 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). 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. The last key left rests too when it is refused so, as the keys before it do. 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 back (`soonestBack`). 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 <id> 7d`). A time the vendor names stands over it. A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.
|
||||
- Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while at least `cacheWorth` (1024) tokens were read from the cache and the cache isn't cold (`cacheCold`, 5 minutes).
|
||||
- In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models.
|
||||
- A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits <account> off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again.
|
||||
|
||||
@@ -56,6 +56,9 @@ const providerUsage = `usage:
|
||||
past either a request is turned away with a 429 (0: no bound)
|
||||
magpie provider rpm <id> [n|off] how many requests each account or key sends the vendor in any minute;
|
||||
one more waits for room, up to 2 minutes, then is turned away with a 429
|
||||
magpie provider quota-rest <id> [30m|6h|7d|default]
|
||||
how long a key sits out once the vendor says it is out of its allowance
|
||||
without saying when it is back (default: 15 minutes; at most 8 days)
|
||||
magpie provider listed <id> yes|no no: its models serve only through routing groups, not in the list
|
||||
magpie provider off|on <id> switch it off (kept, but no agent or request uses it), or on again
|
||||
magpie provider test <id> [--as codex|claude-code] [model…]
|
||||
@@ -540,6 +543,8 @@ func providerCmd(args []string) error {
|
||||
return queueCmd(rest)
|
||||
case "rpm":
|
||||
return rpmCmd(rest)
|
||||
case "quota-rest":
|
||||
return quotaRestCmd(rest)
|
||||
case "listed":
|
||||
// no: the provider's models leave the list agents see and serve
|
||||
// only through the routing groups they are in
|
||||
@@ -1515,6 +1520,71 @@ func rpmCmd(rest []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// quotaRestCmd shows, or sets, how long a provider's keys sit out once the
|
||||
// vendor says one is out of its allowance without saying when it is back
|
||||
// (#1772: Ollama Cloud's weekly limit, asked again every 15 minutes).
|
||||
func quotaRestCmd(rest []string) error {
|
||||
if len(rest) < 1 || len(rest) > 2 {
|
||||
return fmt.Errorf("magpie provider quota-rest <id> [30m|6h|7d|default]")
|
||||
}
|
||||
p, err := provider.Find(rest[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rest) > 1 {
|
||||
minutes, err := restMinutes(rest[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := provider.SetQuotaRest(p.ID, minutes); err != nil {
|
||||
return err
|
||||
}
|
||||
if p, err = provider.Find(p.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if d := p.QuotaRestFor(); d > 0 {
|
||||
fmt.Printf("%s · a key out of its allowance, with no word of when it is back, sits out %s\n", p.Name, restWords(d))
|
||||
} else {
|
||||
fmt.Printf("%s · a key out of its allowance, with no word of when it is back, sits out 15 minutes (magpie's own)\n", p.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// restMinutes reads a rest as quotaRestCmd takes it: default (0), a
|
||||
// number of minutes, a Go duration (90m, 6h) or a number of days (7d).
|
||||
func restMinutes(s string) (int, error) {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
switch s {
|
||||
case "default", "off", "none", "-", "0":
|
||||
return 0, nil
|
||||
}
|
||||
if n, err := strconv.Atoi(s); err == nil {
|
||||
return n, nil
|
||||
}
|
||||
if days, ok := strings.CutSuffix(s, "d"); ok {
|
||||
if n, err := strconv.Atoi(days); err == nil {
|
||||
return n * 24 * 60, nil
|
||||
}
|
||||
}
|
||||
d, err := time.ParseDuration(s)
|
||||
if err != nil || d < time.Minute {
|
||||
return 0, fmt.Errorf("a rest is minutes, or as 30m, 6h or 7d, or default, not %q", s)
|
||||
}
|
||||
return int(d / time.Minute), nil
|
||||
}
|
||||
|
||||
// restWords is a rest as a person says it: 7 days, 6 hours, 90 minutes.
|
||||
func restWords(d time.Duration) string {
|
||||
switch {
|
||||
case d%(24*time.Hour) == 0:
|
||||
return plural(int(d/(24*time.Hour)), "day")
|
||||
case d%time.Hour == 0:
|
||||
return plural(int(d/time.Hour), "hour")
|
||||
}
|
||||
return plural(int(d/time.Minute), "minute")
|
||||
}
|
||||
|
||||
// printMoved says which agents a change moved off models it stopped
|
||||
// serving (agent.Reseat).
|
||||
func printMoved(moved []agent.Move) {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// #1772: `magpie provider quota-rest <id> 7d` takes a rest as a person says
|
||||
// it, and says it back the same way.
|
||||
func TestRestMinutes(t *testing.T) {
|
||||
for in, want := range map[string]int{"default": 0, "off": 0, "0": 0, "90": 90, "30m": 30, "6h": 360, "7d": 7 * 24 * 60, "1h30m": 90} {
|
||||
if got, err := restMinutes(in); err != nil || got != want {
|
||||
t.Errorf("%q: %d %v, want %d", in, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, in := range []string{"soon", "30s", "d"} {
|
||||
if _, err := restMinutes(in); err == nil {
|
||||
t.Errorf("%q taken", in)
|
||||
}
|
||||
}
|
||||
for d, want := range map[time.Duration]string{7 * 24 * time.Hour: "7 days", 6 * time.Hour: "6 hours", 90 * time.Minute: "90 minutes"} {
|
||||
if got := restWords(d); got != want {
|
||||
t.Errorf("%v: %q, want %q", d, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -747,6 +747,51 @@ func restingOf(c candidate) (Rest, bool) {
|
||||
return r, ok
|
||||
}
|
||||
|
||||
// quotaHeld is, when every candidate of cs is a key resting out of its
|
||||
// allowance or its credit — refused with a 429 or a 402 for it, the
|
||||
// vendor's words kept — the rest of the first, and when the first of them
|
||||
// is back: asked before then, each would be refused the same (#1772). A
|
||||
// subscription account isn't held so: its resets may be spent for it
|
||||
// (autoReset), and its windows are read again as it is planned.
|
||||
func quotaHeld(cs []candidate) (Rest, time.Time, bool) {
|
||||
var first Rest
|
||||
var back time.Time
|
||||
for i, c := range cs {
|
||||
r, ok := restingOf(c)
|
||||
if !ok || c.p.Account != nil || r.Why != failQuota && r.Why != failCredit || !quotaStatus(r.Status) || r.said == "" {
|
||||
return Rest{}, time.Time{}, false
|
||||
}
|
||||
if i == 0 {
|
||||
first = r
|
||||
}
|
||||
if back.IsZero() || r.Until.Before(back) {
|
||||
back = r.Until
|
||||
}
|
||||
}
|
||||
return first, back, len(cs) > 0
|
||||
}
|
||||
|
||||
// quotaStatus is a status a vendor says a key is out of its allowance with.
|
||||
func quotaStatus(status int) bool {
|
||||
return status == http.StatusTooManyRequests || status == http.StatusPaymentRequired
|
||||
}
|
||||
|
||||
// soonestBack is when the first of cs is back from its rest; false when
|
||||
// one of them isn't resting.
|
||||
func soonestBack(cs []candidate) (time.Time, bool) {
|
||||
var back time.Time
|
||||
for _, c := range cs {
|
||||
r, ok := restingOf(c)
|
||||
if !ok {
|
||||
return time.Time{}, false
|
||||
}
|
||||
if back.IsZero() || r.Until.Before(back) {
|
||||
back = r.Until
|
||||
}
|
||||
}
|
||||
return back, !back.IsZero()
|
||||
}
|
||||
|
||||
// spentAfter says whether every candidate in cs rests with its allowance
|
||||
// run out: none of them is likely to answer.
|
||||
func spentAfter(cs []candidate) bool {
|
||||
|
||||
@@ -1920,6 +1920,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
i--
|
||||
continue
|
||||
}
|
||||
if i < len(cands)-1 {
|
||||
if _, _, ok := quotaHeld(cands[i:]); ok {
|
||||
// every key left is out of its allowance, resting until it
|
||||
// is back: none is asked, and the agent is told so at once
|
||||
// (#1772)
|
||||
cands = cands[:i+1]
|
||||
}
|
||||
}
|
||||
last := i == len(cands)-1
|
||||
// the last one's failure is held too when an earlier one failed,
|
||||
// for its allowance running out to be told as that one's error
|
||||
@@ -2100,10 +2108,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
t.imageProvider = c.p.ID
|
||||
t.Tries = append(t.Tries, Try{ID: c.rest, Model: c.model, Effort: sent, Picked: picked, Fixed: fixed, Fast: fast, Start: began})
|
||||
})
|
||||
held := false // answered as its vendor did a moment ago, without asking
|
||||
var queued int64 // ms it waited for a slot of its key's or account's
|
||||
var laneErr error // turned away by its key's or account's queue
|
||||
at := &wireAt{} // the level a translated request was built at
|
||||
held := false // answered as its vendor did a moment ago, without asking
|
||||
var heldBack time.Time // when the first of those held out of their allowance is back
|
||||
var queued int64 // ms it waited for a slot of its key's or account's
|
||||
var laneErr error // turned away by its key's or account's queue
|
||||
at := &wireAt{} // the level a translated request was built at
|
||||
// the models Copilot's Auto picked for it, where from, and which
|
||||
// were refused (#256)
|
||||
autoPicked := func() []provider.AutoPick { return nil }
|
||||
@@ -2113,6 +2122,16 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
// just refused it
|
||||
held, call.Status, call.Error = true, http.StatusForbidden, said
|
||||
writeError(hw, from, call.Status, said)
|
||||
} else if rested, back, ok := quotaHeld(cands[i:]); ok && last {
|
||||
// it rests out of its allowance, and so does every key that
|
||||
// was left (#1772: four Ollama Cloud keys out for the week,
|
||||
// each asked again, and refused, on every request): its
|
||||
// refusal is given again without asking, with when the first
|
||||
// of them is back as Retry-After, for an agent that waits as
|
||||
// told to ask then rather than at once
|
||||
msg := fmt.Sprintf("%s (out of its allowance: not asked again before %s)", rested.said, back.Local().Format("15:04"))
|
||||
held, heldBack, call.Status, call.Error = true, back, rested.Status, c.p.Name+": "+msg
|
||||
writeError(hw, from, call.Status, msg)
|
||||
} else {
|
||||
// a stream that fails before anything is said is let go at
|
||||
// once (hw.stop), not read on until the vendor hangs up
|
||||
@@ -2667,6 +2686,23 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
continue
|
||||
}
|
||||
}
|
||||
if last && !held && !hw.passing && hw.failed() && c.p.Account == nil && quotaStatus(hw.code()) && (try.Fail == failQuota || try.Fail == failCredit || failure(hw.code(), hw.errBody()) == failQuota || failure(hw.code(), hw.errBody()) == failCredit) {
|
||||
// the last key left is out of its allowance: it rests as the
|
||||
// ones before it did, for the next request to be answered
|
||||
// from the rests until the first of them is back (#1772)
|
||||
rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool)
|
||||
try.Fail, try.Rest = rest.Why, &rest
|
||||
}
|
||||
if !hw.passing && hw.code() == http.StatusTooManyRequests && hw.header.Get("Retry-After") == "" {
|
||||
// the vendor said nothing of when: the agent is told when
|
||||
// magpie asks again, the first of those it rested back
|
||||
if heldBack.IsZero() {
|
||||
heldBack, _ = soonestBack(cands[:i+1])
|
||||
}
|
||||
if wait := time.Until(heldBack); wait > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int((wait+time.Second-1)/time.Second)))
|
||||
}
|
||||
}
|
||||
if hw.refused && !hw.passing {
|
||||
// nobody is left: the agent is told it was refused, as a
|
||||
// request it shouldn't send again as it is, not handed an empty
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// deadKeys answers as #1772's mock did: a key starting with "dead" is
|
||||
// out of its weekly allowance, in a 429 that names no reset; any other
|
||||
// is served.
|
||||
type deadKeys struct {
|
||||
mu sync.Mutex
|
||||
keys []string
|
||||
}
|
||||
|
||||
func (d *deadKeys) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
d.mu.Lock()
|
||||
d.keys = append(d.keys, key)
|
||||
d.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if strings.HasPrefix(key, "dead") {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
io.WriteString(w, `{"error":{"message":"you have reached your weekly usage limit","type":"rate_limit_error"}}`)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
|
||||
}
|
||||
|
||||
func (d *deadKeys) took() []string {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
out := d.keys
|
||||
d.keys = nil
|
||||
return out
|
||||
}
|
||||
|
||||
func deadChain(t *testing.T, keys ...string) (*deadKeys, *Server) {
|
||||
t.Helper()
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
restingUntil.Lock()
|
||||
restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}
|
||||
restingUntil.Unlock()
|
||||
t.Cleanup(func() {
|
||||
restingUntil.Lock()
|
||||
restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}
|
||||
restingUntil.Unlock()
|
||||
})
|
||||
d := &deadKeys{}
|
||||
up := httptest.NewServer(d)
|
||||
t.Cleanup(up.Close)
|
||||
p := provider.Provider{ID: "mockdead", Name: "mockdead", Chat: up.URL + "/v1", Models: []string{"glm-5.3-flash"}, Routing: provider.Ordered}
|
||||
p.Key = keys[0]
|
||||
for _, k := range keys[1:] {
|
||||
p.Keys = append(p.Keys, provider.KeyAccount{Key: k})
|
||||
}
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return d, New()
|
||||
}
|
||||
|
||||
func postDead(t *testing.T, srv *Server) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"mockdead/glm-5.3-flash","messages":[{"role":"user","content":"hi"}]}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
srv.Handler().ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// #1772 (a fleet on four Ollama Cloud keys): every key out of its weekly
|
||||
// allowance, each new request had asked each key again (the first twice)
|
||||
// and answered 429 with no Retry-After, so a client that waits as told
|
||||
// asked again at once.
|
||||
func TestAllRestingAnswersFromRest(t *testing.T) {
|
||||
d, srv := deadChain(t, "dead-a", "dead-b")
|
||||
rec := postDead(t, srv)
|
||||
if rec.Code != 429 {
|
||||
t.Fatalf("first: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if got := d.took(); strings.Join(got, ",") != "dead-a,dead-b" {
|
||||
t.Errorf("first request asked %v, want each key once", got)
|
||||
}
|
||||
ra, err := strconv.Atoi(rec.Header().Get("Retry-After"))
|
||||
if err != nil || ra < int(quotaRest/time.Second)-5 || ra > int(quotaRest/time.Second) {
|
||||
t.Errorf("first: Retry-After %q, want about %v", rec.Header().Get("Retry-After"), quotaRest)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
rec = postDead(t, srv)
|
||||
if rec.Code != 429 {
|
||||
t.Fatalf("again: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if got := d.took(); len(got) != 0 {
|
||||
t.Errorf("again: asked %v while every key rests", got)
|
||||
}
|
||||
ra, err = strconv.Atoi(rec.Header().Get("Retry-After"))
|
||||
if err != nil || ra < int(quotaRest/time.Second)-5 || ra > int(quotaRest/time.Second) {
|
||||
t.Errorf("again: Retry-After %q, want about %v", rec.Header().Get("Retry-After"), quotaRest)
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), "weekly usage limit") {
|
||||
t.Errorf("again: the vendor's reason is gone: %s", rec.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A provider whose keys are out for the week, its vendor saying nothing of
|
||||
// when, rests them as long as the user set (quotaRest), not 15 minutes.
|
||||
func TestOwnQuotaRest(t *testing.T) {
|
||||
d, srv := deadChain(t, "dead-a", "dead-b")
|
||||
if err := provider.SetQuotaRest("mockdead", 7*24*60); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := postDead(t, srv)
|
||||
if got := d.took(); rec.Code != 429 || len(got) != 2 {
|
||||
t.Fatalf("%d after %v: %s", rec.Code, got, rec.Body)
|
||||
}
|
||||
week := int(7 * 24 * time.Hour / time.Second)
|
||||
if ra, _ := strconv.Atoi(rec.Header().Get("Retry-After")); ra < week-5 || ra > week {
|
||||
t.Errorf("Retry-After %q, want a week", rec.Header().Get("Retry-After"))
|
||||
}
|
||||
for _, c := range []candidate{{p: provider.Provider{ID: "mockdead"}, rest: "mockdead#" + provider.KeyID("dead-a")}} {
|
||||
if r, ok := restingOf(c); !ok || time.Until(r.Until) < 7*24*time.Hour-time.Minute {
|
||||
t.Errorf("rests %v until %v", ok, r.Until)
|
||||
}
|
||||
}
|
||||
// a time the vendor names stands over it
|
||||
p, _ := provider.Find("mockdead")
|
||||
c := candidate{p: *p, model: "glm-5.3-flash", rest: "mockdead#x"}
|
||||
h := http.Header{"Retry-After": {"120"}}
|
||||
if r := srv.restAfter(c, 429, h, []byte(`{"error":{"message":"you have reached your weekly usage limit"}}`)); r.By != "retry-after" || time.Until(r.Until) > 3*time.Minute {
|
||||
t.Errorf("a vendor's Retry-After lost to the provider's own rest: %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
// Only a 429 or a 402 out of quota is answered from the rest: a 403 whose
|
||||
// words read as quota (a key's plan, a region) is asked again as before,
|
||||
// and so is a subscription account, whose resets may be spent for it.
|
||||
func TestQuotaHeldOnlyForKeysOutOfAllowance(t *testing.T) {
|
||||
deadChain(t, "dead-a")
|
||||
srv := New()
|
||||
body := []byte(`{"error":{"message":"you have reached your weekly usage limit"}}`)
|
||||
key := candidate{p: provider.Provider{ID: "k1"}, rest: "k1"}
|
||||
srv.restAfter(key, 429, nil, body)
|
||||
if _, _, ok := quotaHeld([]candidate{key}); !ok {
|
||||
t.Error("a key out of its allowance isn't held")
|
||||
}
|
||||
forbidden := candidate{p: provider.Provider{ID: "k2"}, rest: "k2"}
|
||||
srv.restAfter(forbidden, 403, nil, []byte(`{"error":{"message":"quota exceeded for this region"}}`))
|
||||
if _, _, ok := quotaHeld([]candidate{key, forbidden}); ok {
|
||||
t.Error("a 403 held")
|
||||
}
|
||||
acct := candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "a@b"}}, rest: "codex"}
|
||||
srv.restAfter(acct, 429, nil, body)
|
||||
if _, _, ok := quotaHeld([]candidate{acct}); ok {
|
||||
t.Error("an account held")
|
||||
}
|
||||
fresh := candidate{p: provider.Provider{ID: "k3"}, rest: "k3"}
|
||||
if _, _, ok := quotaHeld([]candidate{key, fresh}); ok {
|
||||
t.Error("held with a key not resting")
|
||||
}
|
||||
}
|
||||
|
||||
// #1772's providers.json named its first key in "keys" as well as in
|
||||
// "key": each key is one candidate, asked once.
|
||||
func TestFirstKeyListedTwiceAskedOnce(t *testing.T) {
|
||||
d, srv := deadChain(t, "dead-1", "dead-1", "dead-2", "ok-3")
|
||||
if rec := postDead(t, srv); rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if got := d.took(); strings.Join(got, ",") != "dead-1,dead-2,ok-3" {
|
||||
t.Errorf("cold walk asked %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A chain whose last key is served walks past the dead ones once each.
|
||||
func TestDeadChainWalksEachOnce(t *testing.T) {
|
||||
d, srv := deadChain(t, "dead-1", "dead-2", "ok-3")
|
||||
if rec := postDead(t, srv); rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if got := d.took(); strings.Join(got, ",") != "dead-1,dead-2,ok-3" {
|
||||
t.Errorf("cold walk asked %v", got)
|
||||
}
|
||||
if rec := postDead(t, srv); rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if got := d.took(); strings.Join(got, ",") != "ok-3" {
|
||||
t.Errorf("warm walk asked %v", got)
|
||||
}
|
||||
}
|
||||
@@ -487,6 +487,10 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
|
||||
// the account is as good as it was; the proxy is the user's to start
|
||||
return r
|
||||
}
|
||||
if why == failCredit || why == failQuota {
|
||||
// the vendor's words, for quotaHeld to give again
|
||||
r.said = provider.APIError(body, http.StatusText(status))
|
||||
}
|
||||
switch why {
|
||||
case failCredit:
|
||||
d, r.By = creditRest, "credit"
|
||||
@@ -500,6 +504,11 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
|
||||
// "in 59 minutes", the resets_at turned Retry-After and cut to an
|
||||
// hour, then was tried, refused and benched again)
|
||||
d, r.By = quotaRest, "quota"
|
||||
if own := c.p.QuotaRestFor(); own > 0 {
|
||||
// as long as the user set for this provider (#1772: Ollama
|
||||
// Cloud's weekly limit says nothing of when it renews)
|
||||
d = own
|
||||
}
|
||||
if w := resetsAt(body, now); w > 0 {
|
||||
d, r.By = w, "resets"
|
||||
} else if w := resetsNoted(header, now); w > 0 {
|
||||
|
||||
@@ -1313,6 +1313,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if keepRate && old != nil {
|
||||
in.PriceRate = old.PriceRate
|
||||
}
|
||||
// how long its keys rest out of quota is set in
|
||||
// providers.json or with `magpie provider quota-rest`,
|
||||
// which the form doesn't show: kept as it was (#1772)
|
||||
if in.QuotaRest == 0 && old != nil {
|
||||
in.QuotaRest = old.QuotaRest
|
||||
}
|
||||
// each account's own proxy likewise: {} clears them
|
||||
if in.AccountProxies == nil && old != nil {
|
||||
in.AccountProxies = old.AccountProxies
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Concurrency is how many requests the gateway lets be out at the vendor
|
||||
@@ -206,6 +207,30 @@ func CheckRPM(n int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MaxQuotaRest bounds QuotaRest, in minutes: eight days, a week's window
|
||||
// and a day over, the longest the gateway rests anyone out of quota.
|
||||
const MaxQuotaRest = 8 * 24 * 60
|
||||
|
||||
// QuotaRestFor is how long one of p's keys sits out of quota when the
|
||||
// vendor doesn't say when it is back, 0 for the gateway's own.
|
||||
func (p Provider) QuotaRestFor() time.Duration {
|
||||
return time.Duration(min(max(p.QuotaRest, 0), MaxQuotaRest)) * time.Minute
|
||||
}
|
||||
|
||||
// SetQuotaRest sets how many minutes the provider's keys sit out of quota
|
||||
// when the vendor doesn't say when they are back, 0 for the gateway's own.
|
||||
func SetQuotaRest(id string, minutes int) error {
|
||||
if minutes < 0 || minutes > MaxQuotaRest {
|
||||
return fmt.Errorf("a rest out of quota is from 0 (magpie's own) to %d minutes (8 days), not %d", MaxQuotaRest, minutes)
|
||||
}
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.QuotaRest = minutes
|
||||
return Save(*p)
|
||||
}
|
||||
|
||||
// SetRPM sets how many requests a minute each of the provider's keys or
|
||||
// accounts may send, 0 for no limit.
|
||||
func SetRPM(id string, n int) error {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -85,14 +86,15 @@ func (p Provider) KeyList() []KeyInfo {
|
||||
}
|
||||
|
||||
// KeysOn is the keys in use, first to last: the first key, then every
|
||||
// saved one that's on.
|
||||
// saved one that's on. A key listed twice — providers.json's "keys"
|
||||
// naming the first key again, as #1772's did — is one key, asked once.
|
||||
func (p Provider) KeysOn() []KeyAccount {
|
||||
if p.Key == "" {
|
||||
return nil
|
||||
}
|
||||
out := []KeyAccount{p.first()}
|
||||
for _, k := range p.Keys {
|
||||
if !k.Off && k.Key != "" {
|
||||
if !k.Off && k.Key != "" && !slices.ContainsFunc(out, func(o KeyAccount) bool { return o.Key == k.Key }) {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,6 +163,11 @@ type Provider struct {
|
||||
// can't keep to); one more waits for room (see RPMLimit). 0 is no
|
||||
// limit.
|
||||
MaxRPM int `json:"maxRPM,omitempty"`
|
||||
// QuotaRest is how many minutes one of its keys sits out once the
|
||||
// vendor says it is out of its allowance without saying when it is
|
||||
// back (#1772: Ollama Cloud's weekly limit); 0 is the gateway's own
|
||||
// quarter of an hour. A time the vendor names stands over it.
|
||||
QuotaRest int `json:"quotaRest,omitempty"`
|
||||
|
||||
// PriceRate is what the provider charges against the official price
|
||||
// (ITea312, #819): a relay that bills 0.8× or 1.5× of it. It scales the
|
||||
@@ -654,7 +659,7 @@ func Save(p Provider) error {
|
||||
if p.ID == "kiro" {
|
||||
key = p.Key
|
||||
}
|
||||
p = Provider{ID: p.ID, Key: key, Models: p.Models, PickedFrom: p.PickedFrom, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PinUpstream: p.PinUpstream, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}
|
||||
p = Provider{ID: p.ID, Key: key, Models: p.Models, PickedFrom: p.PickedFrom, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, QuotaRest: p.QuotaRest, PinUpstream: p.PinUpstream, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}
|
||||
} else {
|
||||
p.AccountProxies = keyProxies(p) // a provider of keys proxies each key apart
|
||||
if subscriptionID(p.ID) && !stored(p.ID) {
|
||||
@@ -1080,6 +1085,7 @@ func normalize(p Provider) Provider {
|
||||
p.AccountConcurrency = normalAccountConcurrency(p.AccountConcurrency)
|
||||
p.QueueLimit, p.QueueWait = min(max(p.QueueLimit, 0), MaxQueueLimit), min(max(p.QueueWait, 0), MaxQueueWait)
|
||||
p.MaxRPM = min(max(p.MaxRPM, 0), MaxRPMLimit)
|
||||
p.QuotaRest = min(max(p.QuotaRest, 0), MaxQuotaRest)
|
||||
p.Catalog = strings.Join(p.Catalogs(), ", ")
|
||||
// a Bedrock provider saved before the preset had its Responses API
|
||||
// (#176) gets it where its chat completions are: the runtime serves both
|
||||
|
||||
Reference in New Issue
Block a user