Files
magpie/internal/gateway/limit_rest_off_test.go
T
yetone c6768f06f6 providers: a provider of the user's can be set never to rest for a limit
zoecats (Discord #feedback, 10-25): a local aggregator answers "quota
exhausted" (429 insufficient_quota) for the moment it switches
upstreams, and magpie set its key aside for 30 minutes, answering every
request itself ("out of its allowance: not asked again before …").

A provider the user added now has, under the editor's Advanced fold,
"Set it aside when out of quota or rate limited" (Rests), ticked by
default, with a note. Unticked (provider.LimitRestOff, limitRestOff in
providers.json), restAfterMarked rests nothing, counts no failure and
sinks nothing for a refusal it reads as out of quota, credit or rate
limited, or any 429: by "off", and the next request is sent to it as
usual. restDrawer rests no image model of it either. A 401, a model not
served and a plain failure still rest it. The default is as before. The
editor offers it only to a provider the user added (custom); a Save that
leaves it out keeps it. A checkbox (tick), no native select; strings in
zh, zh-TW, ja and de. app.js's budget (and the core's) are raised by the
576 bytes the row adds, with no room, after the comment was cut.

Run on origin/main 75e78a5a0 plus these two commits:
- gofmt -l clean; node --check app.js, i18n.js; go vet ./... on darwin
  and GOOS=linux/windows -tags nogui: ok.
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/gui/
  ./internal/provider/ (suite lock): gateway ok 417.9s, provider ok
  114.4s, gui red only on TestCoreScriptBudget (741 over); after the
  trim and the raise, TestCoreScriptBudget, TestProviderSaveLimitRestOff
  and TestI18n* ok.
- GUI, chromium and webkit: provider-limit-rest (new; en, zh, zh-TW, ja,
  de at 1100 and 420), provider-insecure-tls, i18n-keys, fallback-more:
  128/128. Every provider*, every file opening Advanced, i18n-keys,
  routing-lifted-elsewhere, rest-try-now, rate-limited-sink (58 files):
  1053 of 1055 (on the pre-trim app.js, the trim only a comment and an
  unused class): providers-last-known webkit zh-TW (filed #3565) and
  tencent-access-key webkit en (#2733) red at load ~130; each passes
  alone in WebKit on this tree and on origin/main 5b2b3d3f5.
  After the trim: provider-limit-rest, i18n-keys, provider-insecure-tls
  124/124.
- Sandbox HOME, a dev build of this tree, fake upstream answering 429
  insufficient_quota "quota exhausted": by default the second request was
  magpie's own "not asked again before 13:17" (1 upstream hit). Saved
  limitRestOff:true through /api/provider/save and lifted the rest:
  three requests, three upstream hits, each the vendor's 429; then 429
  rate_limit_error: no rest on the key (each request still asked again
  after 1s, 2s, 4s within itself, as a lone candidate always is); the
  upstream back, 200 at once.

Broken by hand, each red, then restored:
- the check in restAfterMarked off: TestLimitRestOffKeepsAsking ("1
  rests set after the refusal, want none") and
  TestLimitRestOffRestsNothingForALimit ("rests 29m59s by credit").
- the save's keep-when-left-out branch removed: TestProviderSaveLimitRestOff
  ("a Save that left it out turned rests back on").
- app.js's save line removed: provider-limit-rest's first two tests red
  in webkit zh-TW 420.

Not tried: zoecats' own aggregator; the in-request retries on a rate
limit (1s, 2s, 4s) are left as they are, as they are not a rest.

Again after rebasing on origin/main 1b039a3c7 (which changed app.js,
client.js and gateway.go): gofmt, node --check, vet on three OSes ok;
go test ./internal/gui/ ok (the budgets set to this head's sizes);
go test -run 'TestTryNow|TestRenewed|TestLimitRestOff|TestRestCapOff|
TestOwnRestCap|Sink|Unrest|Rest' ./internal/gateway/ ok; GUI, both engines: provider-limit-rest,
i18n-keys, provider-insecure-tls, routing-lifted-elsewhere, rest-try-now,
rate-limited-sink, routing-model-rest, routing-rest-off, routing-rule-drag,
routing-rule-models, view-trackpad-coast, fallback-more: 272/272.
2026-10-25 14:00:59 +08:00

128 lines
4.6 KiB
Go

package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// zoecats on Discord: a local aggregator says "quota exhausted" for a
// moment while it switches upstreams, and the half hour magpie rested its
// one key for it held every request back, answered "out of its allowance"
// without asking. With rests on quota and 429 turned off for the provider
// (LimitRestOff), the refusal goes to the agent as it came, nothing is set
// aside, and the next request is sent to the aggregator, which answers.
func TestLimitRestOffKeepsAsking(t *testing.T) {
noRests()
t.Cleanup(noRests)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
var calls, failing atomic.Int32
failing.Store(1)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
calls.Add(1)
w.Header().Set("Content-Type", "application/json")
if failing.Load() == 1 {
w.WriteHeader(http.StatusTooManyRequests)
io.WriteString(w, `{"error":{"message":"quota exhausted","type":"insufficient_quota"}}`)
return
}
io.WriteString(w, `{"id":"x","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)
}))
t.Cleanup(up.Close)
p := provider.Provider{ID: "agg", Name: "Agg", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1", LimitRestOff: true}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
req := `{"model":"agg/m1","messages":[{"role":"user","content":"hi"}]}`
code, body := post(t, "/v1/chat/completions", req)
if code != http.StatusTooManyRequests || !strings.Contains(body, "quota exhausted") {
t.Fatalf("first: %d %s", code, body)
}
restingUntil.Lock()
n := len(restingUntil.m)
restingUntil.Unlock()
if n != 0 {
t.Fatalf("%d rests set after the refusal, want none", n)
}
before := calls.Load()
// refused again: asked again, never answered from a rest
code, body = post(t, "/v1/chat/completions", req)
if code != http.StatusTooManyRequests || strings.Contains(body, "not asked again") || calls.Load() == before {
t.Fatalf("second, still refusing: %d %s, upstream asked %d times", code, body, calls.Load()-before)
}
failing.Store(0)
code, body = post(t, "/v1/chat/completions", req)
if code != http.StatusOK || !strings.Contains(body, `"hi"`) {
t.Fatalf("third, upstream back: %d %s", code, body)
}
}
// The switch covers every refusal it names, and only those: out of quota
// or credit and rate limited, at any status, and any 429, rest nothing,
// count toward no backoff and sink nothing; a refused key still rests.
// Off by default: the same refusals rest a provider without it.
func TestLimitRestOffRestsNothingForALimit(t *testing.T) {
s := &Server{}
limits := []struct {
status int
body string
}{
{429, `{"error":{"message":"quota exhausted","type":"insufficient_quota"}}`},
{429, `{"error":{"message":"Too many requests","type":"rate_limit_error"}}`},
{429, `{"error":{"message":"busy"}}`},
{403, `{"error":{"message":"Your quota has been exhausted","type":"insufficient_quota"}}`},
{402, `{"error":{"message":"Insufficient balance","type":"insufficient_balance"}}`},
}
for _, off := range []bool{true, false} {
c := candidate{p: provider.Provider{ID: "lim", Key: "k", LimitRestOff: off}, model: "m", rest: "lim#k"}
id := c.restKey()
clean := func() {
clearRest(id)
clearRest(c.restID())
routed.Lock()
delete(routed.failures, id)
delete(routed.failures, c.restID())
routed.Unlock()
sunk.Lock()
delete(sunk.m, id)
sunk.Unlock()
}
clean()
t.Cleanup(clean)
for _, k := range limits {
clean()
r := s.restAfter(c, k.status, http.Header{}, []byte(k.body))
if off && (r.By != "off" || r.Until.After(time.Now()) || resting(c)) {
t.Fatalf("off, %d %s: rests %v by %s (%s), want none", k.status, k.body, time.Until(r.Until), r.By, r.Why)
}
if !off && (r.By == "off" || !resting(c)) {
t.Fatalf("on, %d %s: not rested (%s by %s)", k.status, k.body, r.Why, r.By)
}
routed.Lock()
f := routed.failures[id]
routed.Unlock()
sunk.Lock()
_, sank := sunk.m[id]
sunk.Unlock()
if off && (f != 0 || sank) {
t.Fatalf("off, %d: %d failures counted, sunk %v", k.status, f, sank)
}
}
if off {
clean()
r := s.restAfter(c, 401, http.Header{}, []byte(`{"error":{"message":"invalid api key"}}`))
if r.By == "off" || !resting(c) {
t.Fatalf("a refused key isn't rested: %s by %s", r.Why, r.By)
}
}
}
}