gateway: a single provider's busy or briefly rate-limited reply is waited out, for its own Patience (zoecats)

zoecats on Discord: a request to one provider (not a group) got a local
relay's short 429 straight back in Claude Code once the few same-one
retries were spent. A group would have held the agent and asked again.

A plain provider now takes the group's replan path (patience.go: replan,
pauseAlive, the held writer) once passing's same-one retries are spent:
its accounts take turns as members do, each pause never shorter than the
Retry-After, and a streaming agent gets keepalives past keepHeldAfter.
- Zero-config: unset, it waits singlePatience, PatienceDefault (60s),
  counted from when the agent would have had the error.
- The user's value wins: Provider.Patience, the same values as a group's
  Patience, set with `magpie provider set <id> patience=2m|off|default`
  (at most 4m). The provider editor has no row for it (no new UI), and its
  save keeps it. A group the provider is in keeps the group's own.
- Not retried: a Retry-After past the budget, quota/credit/plan limits,
  401/403, refusals, response protection, didNotStream, and an agent
  that has gone (499, try marked Gone).
- The try is traced with Again alone, so the Routing page tells it as
  "tried again in …".
- codexReset (ChatGPT's 503 for a large request) is left out of the
  plain-provider replan, so Codex still gets its 503 with advice.
- Codex's own one-account relay (codexUpstreamOn) does not join. It is
  relayed outside the candidate loop, and its backend 429 is always the
  plan's usage limit (codexBusy never retries one), so the short rate
  limit this waits out doesn't arise there. Its overloads keep
  lastRetries and then fallbacks.

longestPause became a var so tests can scale it. Tests updated for the
new count (1 + retries + replanRounds when it never clears):
- TestLastOneLeftIsTriedAgain
- TestRateLimitIsWaitedOut
- TestQueuedStreamFailureIsTheStreamsError
- TestOverflowTheVendorDidntSay

New tests, through the server with a fake upstream and injected
durations, waiting on trace state, not a duration:
- TestSingleProviderWaitsOutAShortRateLimit (stream and whole: 200,
  keepalive before the answer, asked twice)
- TestSingleProviderPassesALongLimitThrough (an hour, quota, 401)
- TestSingleProviderAgentGoneInTheWait
- TestSingleProviderOwnPatienceWins (off, shorter and longer than the
  default)
- TestPatiencePair (cli)
- TestProviderSaveKeepsPatience (gui)

Broken by hand, each red, then restored:
- singlePatience fallback 0 for a plain provider: WaitsOut stream and
  whole got 429, and AgentGone never paused.
- replan's budget check off: PassesALongLimitThrough/an_hour, "magpie
  waits to ask again".
- pauseAlive's ctx.Done case removed: AgentGone, "route done false
  status 0".
- The gateway ignoring Provider.Patience: OwnPatienceWins off, shorter
  and longer all red.
- The GUI save not keeping Patience: TestProviderSaveKeepsPatience,
  "patience 0 … want -1 kept".

Run in this tree, before the rebase:
- go test ./internal/gateway ./internal/cli ./internal/gui: ok.
- ./internal/provider: ok with -skip TestUnreadLogins. That test crashes
  with "close of synctest channel from outside bubble", the known #3632,
  in filememo and not touched here.
- gofmt -l: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: all 0.
- go build for darwin, linux (nogui) and windows: ok.

Run again after rebasing on origin/main 39526c069 (17 commits, 22 files
in gateway/provider/cli): gofmt, go build, go vet on the four
packages, the replan, retry, overflow and Codex-reset tests, and every
new test: all ok. The whole gateway package was not run again there.

Not run:
- The full ./... suite: machine load ~150, other sessions' suites
  running.
- A real vendor's 429.
- The GUI suite: no GUI file changed.
This commit is contained in:
yetone
2026-10-27 02:26:27 +08:00
parent 39526c0690
commit d56c14e953
13 changed files with 525 additions and 15 deletions
File diff suppressed because one or more lines are too long
+30
View File
@@ -0,0 +1,30 @@
package cli
import (
"testing"
"github.com/yetone/magpie/internal/provider"
)
// patience= sets how long a request to the provider alone is kept while it
// is busy (zoecats on Discord): a time up to four minutes, off, or default;
// anything else is refused and leaves what was set.
func TestPatiencePair(t *testing.T) {
var p provider.Provider
for _, c := range []struct {
v string
want int
}{
{"2m", 120}, {"90", 90}, {"45s", 45}, {"4m", 240}, {"off", provider.PatienceOff}, {"0", provider.PatienceOff}, {"default", 0},
} {
if err := applyPairs(&p, []string{"patience=" + c.v}); err != nil || p.Patience != c.want {
t.Fatalf("patience=%s: %v, got %d, want %d", c.v, err, p.Patience, c.want)
}
}
p.Patience = 30
for _, bad := range []string{"5m", "-3", "soon", "1h"} {
if err := applyPairs(&p, []string{"patience=" + bad}); err == nil || p.Patience != 30 {
t.Fatalf("patience=%s taken: %v, %d", bad, err, p.Patience)
}
}
}
+39
View File
@@ -47,6 +47,10 @@ const providerUsage = `usage:
additional-tools=on sends a tool Claude Code's tool search loads to its
Responses API where it was loaded (an additional_tools item, which
keeps the cache); additional-tools=default puts it with the other tools
patience=2m keeps a request to it alone (not through a group) that long
while it is busy or briefly rate limited, asking again after a pause
(at most 4m); patience=off hands the agent the error at once;
patience=default, 1m
magpie provider key <id> <key> change the API key
magpie provider icon <id> <file|name> give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon
magpie provider fallback <id> <provider/model>… where requests go when it's out of quota or down (none clears)
@@ -1102,6 +1106,14 @@ func applyPairs(p *provider.Provider, pairs []string) error {
default:
return fmt.Errorf("additional-tools=on|default, not %q", v)
}
case "patience":
// how long a request to the provider alone is kept while it
// is busy, as a group's Patience (zoecats on Discord)
n, err := patienceArg(v)
if err != nil {
return err
}
p.Patience = n
case "user-agent", "ua":
// agent: a request goes with the User-Agent the agent that
// sent it gave, for a coding plan that serves only agents it
@@ -2028,3 +2040,30 @@ func autoIncludeCmd(rest []string) error {
fmt.Printf("%s · a newly listed model is exposed when one of these matches its id: %s\n", p.Name, strings.Join(p.AutoInclude, " "))
return nil
}
// patienceArg reads patience=: off, default, or a time up to
// provider.PatienceLongest seconds, as 90, 90s or 2m.
func patienceArg(v string) (int, error) {
v = strings.ToLower(strings.TrimSpace(v))
switch v {
case "off", "no", "none", "0":
return provider.PatienceOff, nil
case "default", "":
return 0, nil
}
d, err := time.ParseDuration(v)
if err != nil {
n, nerr := strconv.Atoi(v)
if nerr != nil {
return 0, fmt.Errorf("patience=off|default|<time, e.g. 2m>, not %q", v)
}
d = time.Duration(n) * time.Second
}
if d == 0 {
return provider.PatienceOff, nil
}
if d < 0 || d > provider.PatienceLongest*time.Second {
return 0, fmt.Errorf("patience is at most %s, not %q", provider.PatienceLongest*time.Second, v)
}
return int((d + time.Second - 1) / time.Second), nil
}
+5 -3
View File
@@ -1446,11 +1446,13 @@ const (
// clear than a busy moment: pauses of 1, 2 and 4s, or what Retry-After
// says, under half a minute in all
rateRetries = 3
// longestPause is the longest the vendor's Retry-After is waited for
// before that; longer, and the agent gets the error.
longestPause = 8 * time.Second
)
// longestPause is the longest the vendor's Retry-After is waited for by
// the same-one retries; longer, and a plain provider or a group waits it
// out within its patience (replan), else the agent gets the error.
var longestPause = 8 * time.Second
// retryPause is the first pause before the last one left is tried again;
// each pause after is twice the one before.
var retryPause = time.Second
+17 -2
View File
@@ -2455,8 +2455,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
var patience, patienceFallback time.Duration
if isGroup {
patienceFallback = g.Waits()
patience = maxWaits(cands, patienceFallback)
} else {
// one provider asked for, not a group: its accounts busy are kept
// for its own Patience, as long by default as a group that sets
// none (zoecats on Discord: a relay's short 429 went straight to
// the agent once the few same-one retries were spent)
patienceFallback = waitsOf(p.Patience, singlePatience)
}
patience = maxWaits(cands, patienceFallback)
var busyNow []busyTry // the members of this round that failed so
rounds := 0 // the rounds they were asked again in
var waitFrom time.Time // when every member had first failed so
@@ -3486,7 +3492,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
continue
}
// (a plain provider's: not ChatGPT's reset of a large request,
// which Codex is told at its 503 with what may help, as Codex's
// own one-account relay leaves it, codexBusy)
if _, same := passing(hw.code(), hw.header, hw.errBody(), again); last && patience > 0 && !protected && !hw.turnedAway && !hw.refused && hw.failed() && busy(hw.code(), hw.errBody()) &&
(isGroup || !codexReset(hw.code(), hw.errBody())) &&
(len(busyNow) > 0 || waitsOf(c.patience, patienceFallback) > 0 && !same) {
// every member has failed, each in a way that passes — busy,
// overloaded, rate limited for a moment — with nothing of a
@@ -3512,7 +3522,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
memberWait = patience
}
if next, wait, ok := replan(busyNow, rounds, waitFrom, patienceFallback); ok && !kept.tooQuiet(wait) {
try.Fail, try.Again, try.Replan, try.Patience = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds(), len(next), int(memberWait/time.Second)
try.Fail, try.Again = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds()
if isGroup {
// a plain provider's is told as the last one left
// asked again: it has no members taking turns
try.Replan, try.Patience = len(next), int(memberWait/time.Second)
}
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
skipped = append(skipped, c.label()+": "+call.Error)
rounds, busyNow = rounds+1, nil
+11 -2
View File
@@ -27,8 +27,17 @@ const didNotStream = "did not stream"
// alone, as the last one left of a plain provider is (passing), while
// another member is busy too. A streaming agent is kept alive with SSE
// comments through the pause, as through a held stream. A plain provider,
// which the agent picked as itself, keeps the retries passing gives the
// last one left.
// which the agent picked as itself, is kept the same way once the retries
// passing gives the last one left are spent, its accounts its members,
// for its own Patience, unset singlePatience.
// singlePatience is how long a request to one provider, not a group, is
// kept once it has failed in a way that passes and the same-one retries
// (passing) are spent: as long as a group that sets no Patience waits
// (zoecats on Discord), unless the provider sets its own Patience (magpie
// provider set <id> patience=), which wins. A group's, set or not, is the
// group's.
var singlePatience = provider.PatienceDefault * time.Second
// replanRounds is how many times the members are asked again, at most:
// a backstop that never comes before the patience does. The pauses alone
+3 -1
View File
@@ -454,7 +454,9 @@ func TestQueuedStreamFailureIsTheStreamsError(t *testing.T) {
for _, a := range queueAsks {
t.Run(a.name, func(t *testing.T) {
one := 1
v := &streamVendor{fail: 10, block: make(chan struct{})}
// failing every time it is asked: past the same-one retries
// and the plain provider's patience (singlePatience) too
v := &streamVendor{fail: 1000, block: make(chan struct{})}
gw := queueGateway(t, v, func(p *provider.Provider) { p.MaxConcurrency = &one })
first := holdSlot(t, gw, v, a.path, a.body)
code, body, _, err := askHeard(gw, a.path, a.body, first.free)
+9 -2
View File
@@ -197,7 +197,10 @@ func TestLastOneLeftIsTriedAgain(t *testing.T) {
fresh(t)
a = &scripted{replies: []reply{{503, "", `{"error":{"message":"down"}}`}}}
scriptedOn(t, "a", provider.Chat, a)
if code, _ := postAs(t, New(), "", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`); code != 503 || a.n != 1+lastRetries {
// down for good: the same-one retries, then the rounds of its
// patience (singlePatience; with retryPause at 1ms the rounds'
// backstop comes first), then the agent has the 503
if code, _ := postAs(t, New(), "", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`); code != 503 || a.n != 1+lastRetries+replanRounds {
t.Fatalf("gave up with %d after %d tries", code, a.n)
}
@@ -226,7 +229,11 @@ func TestRateLimitIsWaitedOut(t *testing.T) {
{"no retry-after", limited, nil, 1, 200, 2},
{"relay's own words", `{"error":{"message":"当前分组上游负载已饱和,请稍后再试"}}`, nil, 2, 200, 3},
{"thrice", limited, nil, 3, 200, 4},
{"too long", limited, nil, 9, 429, 1 + rateRetries},
// past the same-one retries, it is waited out within the plain
// provider's patience (zoecats on Discord), and given up on once
// that is spent (the rounds' backstop, with retryPause at 1ms)
{"past the same-one retries", limited, nil, 9, 200, 10},
{"never clears", limited, nil, 99, 429, 1 + rateRetries + replanRounds},
{"usage limit", `{"error":{"message":"You've hit your usage limit. Your limit resets in 5 hours."}}`, nil, 9, 429, 1},
{"no balance", `{"error":{"message":"余额不足"}}`, nil, 9, 429, 1},
{"an hour away", limited, http.Header{"Retry-After": {"3600"}}, 9, 429, 1},
+346
View File
@@ -0,0 +1,346 @@
package gateway
import (
"bufio"
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// busyUpstream answers each request with the next of its replies, the
// last one again once they run out, and counts what it was asked.
type busyUpstream struct {
mu sync.Mutex
replies []busyReply
n int
}
type busyReply struct {
code int
retryAfter string
body string
}
func (u *busyUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
u.mu.Lock()
x := u.replies[min(u.n, len(u.replies)-1)]
u.n++
u.mu.Unlock()
if x.retryAfter != "" {
w.Header().Set("Retry-After", x.retryAfter)
}
if !strings.HasPrefix(x.body, "{") {
w.Header().Set("Content-Type", "text/event-stream")
} else {
w.Header().Set("Content-Type", "application/json")
}
w.WriteHeader(x.code)
io.WriteString(w, x.body)
}
func (u *busyUpstream) asked() int {
u.mu.Lock()
defer u.mu.Unlock()
return u.n
}
// Anthropic's own rate limit reply.
const rateLimited = `{"type":"error","error":{"type":"rate_limit_error","message":"Rate limited, please retry shortly"}}`
// busyProvider saves provider a, served by u, alone: no group.
func busyProvider(t *testing.T, u *busyUpstream) *Server {
t.Helper()
return busyProviderWaiting(t, u, 0)
}
// busyProviderWaiting is busyProvider with the Patience the user set.
func busyProviderWaiting(t *testing.T, u *busyUpstream, patience int) *Server {
t.Helper()
fresh(t)
up := httptest.NewServer(u)
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"}, Anthropic: up.URL, Patience: patience}); err != nil {
t.Fatal(err)
}
return New()
}
func singleAsk(stream bool) string {
s := "false"
if stream {
s = "true"
}
return `{"model":"a/m","max_tokens":10,"stream":` + s + `,"messages":[{"role":"user","content":"hi"}]}`
}
// scaled shrinks the waits the test goes through, keeping their order:
// a Retry-After past the same-one retries' longestPause (8s), the pause
// past keepHeldAfter (15s), all within singlePatience (60s).
func scaled(t *testing.T, patience time.Duration) {
t.Helper()
lp, sp, kh, we, rp := longestPause, singlePatience, keepHeldAfter, watchEvery, retryPause
longestPause, singlePatience, keepHeldAfter, watchEvery, retryPause = 50*time.Millisecond, patience, 20*time.Millisecond, 2*time.Millisecond, 10*time.Millisecond
t.Cleanup(func() {
longestPause, singlePatience, keepHeldAfter, watchEvery, retryPause = lp, sp, kh, we, rp
})
}
// A request to one provider, not a group, whose vendor answers a short
// rate limit — a Retry-After past what the same-one retries wait for —
// is held and asked again once it has passed, as a group's members are
// (zoecats on Discord: the 429 went straight to the agent). A streaming
// agent is kept alive through the pause once it passes keepHeldAfter.
func TestSingleProviderWaitsOutAShortRateLimit(t *testing.T) {
for _, stream := range []bool{true, false} {
name := "whole"
if stream {
name = "stream"
}
t.Run(name, func(t *testing.T) {
answer := anthropicAnswer
if !stream {
answer = `{"id":"m2","type":"message","role":"assistant","model":"m","content":[{"type":"text","text":"from b"}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":4}}`
}
u := &busyUpstream{replies: []busyReply{
{code: 429, retryAfter: "0.4", body: rateLimited},
{code: 200, body: answer},
}}
s := busyProvider(t, u)
scaled(t, 3*time.Second)
gw := httptest.NewServer(s.Handler())
t.Cleanup(gw.Close)
res, err := http.Post(gw.URL+"/v1/messages", "application/json", strings.NewReader(singleAsk(stream)))
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
var body strings.Builder
rd := bufio.NewReader(res.Body)
for {
line, err := rd.ReadString('\n')
body.WriteString(line)
if err != nil {
break
}
}
out := body.String()
if res.StatusCode != 200 || !strings.Contains(out, "from b") {
t.Fatalf("agent got %d %q, want the answer after the pause", res.StatusCode, out)
}
if n := u.asked(); n != 2 {
t.Errorf("upstream asked %d times, want 2", n)
}
alive := strings.Index(out, ": keepalive")
if stream && (alive < 0 || alive > strings.Index(out, "from b")) {
t.Errorf("no keepalive before the answer: %q", out)
}
r := lastRoute(s)
if len(r.Tries) != 2 || r.Tries[0].Again < 300 || r.Tries[0].Replan != 0 || r.Tries[0].Patience != 0 || r.Status != 200 {
t.Errorf("tries %+v: want the first asked again after its Retry-After, told as the last one left", r.Tries)
}
})
}
}
// A rate limit that lasts past the patience, or that is the plan's quota,
// goes to the agent as the vendor said it, with nobody asked again: the
// route is watched, not a duration, so a broken budget fails at once.
func TestSingleProviderPassesALongLimitThrough(t *testing.T) {
for _, c := range []struct {
name string
r busyReply
}{
{"an hour", busyReply{code: 429, retryAfter: "3600", body: rateLimited}},
{"quota", busyReply{code: 429, body: `{"type":"error","error":{"type":"rate_limit_error","message":"You exceeded your current quota, please check your plan and billing details"}}`}},
{"key refused", busyReply{code: 401, body: `{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}`}},
} {
t.Run(c.name, func(t *testing.T) {
u := &busyUpstream{replies: []busyReply{c.r, {code: 200, body: anthropicAnswer}}}
s := busyProvider(t, u) // the real defaults
gw := httptest.NewServer(s.Handler())
t.Cleanup(gw.Close)
type got struct {
code int
after string
body string
}
// a failure below ends the request with the test, not when a
// pause it shouldn't have taken would
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
done := make(chan got, 1)
go func() {
req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+"/v1/messages", strings.NewReader(singleAsk(true)))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
done <- got{}
return
}
b, _ := io.ReadAll(res.Body)
res.Body.Close()
done <- got{res.StatusCode, res.Header.Get("Retry-After"), string(b)}
}()
var g got
wait:
for {
select {
case g = <-done:
break wait
case <-time.After(5 * time.Millisecond):
}
s.trace.mu.Lock()
waiting := false
if k := len(s.trace.routes); k > 0 {
for _, tr := range s.trace.routes[k-1].Tries {
waiting = waiting || tr.Again > 0
}
}
s.trace.mu.Unlock()
if waiting {
t.Fatalf("magpie waits to ask again: %+v", lastRoute(s).Tries)
}
}
if g.code != c.r.code || u.asked() != 1 {
t.Fatalf("agent got %d %q, upstream asked %d times; want the vendor's %d, asked once", g.code, g.body, u.asked(), c.r.code)
}
if c.r.retryAfter != "" && g.after == "" {
t.Errorf("the vendor's Retry-After was dropped")
}
})
}
}
// An agent gone while magpie waits out its one provider's rate limit ends
// the request there: the route is over as canceled, its try says the agent
// left in the pause, and the vendor is asked nothing more.
func TestSingleProviderAgentGoneInTheWait(t *testing.T) {
u := &busyUpstream{replies: []busyReply{
{code: 429, retryAfter: "120", body: rateLimited},
{code: 200, body: anthropicAnswer},
}}
s := busyProvider(t, u)
scaled(t, 5*time.Minute) // a pause of 120s, far longer than the test
gw := httptest.NewServer(s.Handler())
t.Cleanup(gw.Close)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+"/v1/messages", strings.NewReader(singleAsk(true)))
req.Header.Set("Content-Type", "application/json")
ended := make(chan struct{})
go func() {
defer close(ended)
if res, err := http.DefaultClient.Do(req); err == nil {
io.Copy(io.Discard, res.Body)
res.Body.Close()
}
}()
if !inPause(s, 1, 30*time.Second) {
t.Fatalf("magpie never paused to ask again: %+v", lastRoute(s).Tries)
}
cancel()
<-ended
var r Route
for deadline := time.Now().Add(60 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
s.trace.mu.Lock()
r = *s.trace.routes[len(s.trace.routes)-1]
r.Tries = append([]Try{}, r.Tries...)
s.trace.mu.Unlock()
if r.Done {
break
}
}
if !r.Done || r.Status != 499 {
t.Fatalf("route done %v status %d, want done 499 long before the pause ends", r.Done, r.Status)
}
if last := r.Tries[len(r.Tries)-1]; !last.Gone || last.Again == 0 {
t.Errorf("last try %+v: want its pause and that the agent left in it", last)
}
if n := u.asked(); n != 1 {
t.Errorf("upstream asked %d times after the agent left, want 1", n)
}
}
// The Patience the user set on the provider (magpie provider set a
// patience=…) stands over singlePatience either way: off hands the agent a
// rate limit the default would wait out, a shorter one hands it one the
// default would wait for, and a longer one waits out one the default
// wouldn't.
func TestSingleProviderOwnPatienceWins(t *testing.T) {
for _, c := range []struct {
name string
patience int // the user's, in seconds
byDefault time.Duration // singlePatience, scaled
retryAfter string
want int
}{
{"off", provider.PatienceOff, 3 * time.Second, "0.4", 429},
{"shorter", 1, 5 * time.Minute, "3", 429},
{"longer", 120, 100 * time.Millisecond, "0.4", 200},
} {
t.Run(c.name, func(t *testing.T) {
u := &busyUpstream{replies: []busyReply{
{code: 429, retryAfter: c.retryAfter, body: rateLimited},
{code: 200, body: anthropicAnswer},
}}
s := busyProviderWaiting(t, u, c.patience)
scaled(t, c.byDefault)
gw := httptest.NewServer(s.Handler())
t.Cleanup(gw.Close)
// a failure ends the request with the test, not when a pause
// it shouldn't have taken would
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+"/v1/messages", strings.NewReader(singleAsk(true)))
req.Header.Set("Content-Type", "application/json")
done := make(chan int, 1)
go func() {
res, err := http.DefaultClient.Do(req)
if err != nil {
done <- 0
return
}
io.Copy(io.Discard, res.Body)
res.Body.Close()
done <- res.StatusCode
}()
var code int
wait:
for {
select {
case code = <-done:
break wait
case <-time.After(5 * time.Millisecond):
}
if c.want != 200 {
s.trace.mu.Lock()
waiting := false
if k := len(s.trace.routes); k > 0 {
for _, tr := range s.trace.routes[k-1].Tries {
waiting = waiting || tr.Again > 0
}
}
s.trace.mu.Unlock()
if waiting {
t.Fatalf("magpie waits to ask again past the user's patience: %+v", lastRoute(s).Tries)
}
}
}
wantAsked := 1
if c.want == 200 {
wantAsked = 2
}
if code != c.want || u.asked() != wantAsked {
t.Fatalf("agent got %d, upstream asked %d times; want %d, asked %d", code, u.asked(), c.want, wantAsked)
}
})
}
}
+6 -4
View File
@@ -31,10 +31,12 @@ func TestOverflowTheVendorDidntSay(t *testing.T) {
// Text alone well past the window is enough to ask for compaction.
{"413 bytes", "/v1/messages", big, 413, `{"error":{"message":"Request Entity Too Large"}}`, 400, 1, "prompt is too long"},
{"413 request_too_large", "/v1/messages", big, 413, `{"error":{"type":"request_too_large","message":"Request exceeds the maximum size"}}`, 400, 1, "prompt is too long"},
// not the conversation's length
{"small 502", "/v1/messages", small, 502, `{"error":{"message":"We are experiencing capacity issues"}}`, 502, 1 + lastRetries, "capacity issues"},
{"near the window", "/v1/messages", near, 502, `{"error":{"message":"We are experiencing capacity issues"}}`, 502, 1 + lastRetries, "capacity issues"},
{"429", "/v1/messages", big, 429, `{"error":{"message":"Rate limit reached"}}`, 429, 1 + rateRetries, "Rate limit"},
// not the conversation's length: a plain provider's busy reply is
// asked again past the same-one retries, within its patience,
// until replan's rounds run out
{"small 502", "/v1/messages", small, 502, `{"error":{"message":"We are experiencing capacity issues"}}`, 502, 1 + lastRetries + replanRounds, "capacity issues"},
{"near the window", "/v1/messages", near, 502, `{"error":{"message":"We are experiencing capacity issues"}}`, 502, 1 + lastRetries + replanRounds, "capacity issues"},
{"429", "/v1/messages", big, 429, `{"error":{"message":"Rate limit reached"}}`, 429, 1 + rateRetries + replanRounds, "Rate limit"},
{"401", "/v1/messages", big, 401, `{"error":{"message":"invalid token"}}`, 401, 1, "invalid token"},
{"quota", "/v1/messages", big, 400, `{"error":{"message":"insufficient balance"}}`, 400, 1, "insufficient balance"},
} {
+39
View File
@@ -0,0 +1,39 @@
package gui
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A provider's Patience, set with `magpie provider set <id> patience=`
// (zoecats on Discord), is not in the editor: the editor's save keeps it.
func TestProviderSaveKeepsPatience(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
for _, set := range []int{provider.PatienceOff, 150} {
if err := provider.Save(provider.Provider{ID: "or", Name: "OpenRouter", Chat: "https://example.invalid/v1", Key: "k", Patience: set}); err != nil {
t.Fatal(err)
}
mux := http.NewServeMux()
providerRoutes(mux, nil)
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(`{"id":"or","name":"OpenRouter","chat":"https://example.invalid/v1"}`)))
if w.Code != 200 {
t.Fatalf("%d %s", w.Code, w.Body)
}
got, err := provider.Find("or")
if err != nil {
t.Fatal(err)
}
if got.Patience != set {
t.Fatalf("patience %d after the editor's save, want %d kept", got.Patience, set)
}
}
}
+5
View File
@@ -1567,6 +1567,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if !in.AdditionalTools && old != nil {
in.AdditionalTools = old.AdditionalTools
}
// and how long a request to it alone is kept while it is
// busy, set with `magpie provider set <id> patience=`
if in.Patience == 0 && old != nil {
in.Patience = old.Patience
}
// each account's own proxy likewise: {} clears them
if in.AccountProxies == nil && old != nil {
in.AccountProxies = old.AccountProxies
+14
View File
@@ -250,6 +250,16 @@ type Provider struct {
// turns the item away (#350).
AdditionalTools bool `json:"additionalTools,omitempty"`
// Patience is how many seconds more a request to this provider alone,
// not through a group, may be kept once it has failed in a way that
// passes (overloaded, unavailable, rate limited for a moment) and the
// same-one retries are spent, as a group's Patience is (zoecats on
// Discord): 0 keeps it PatienceDefault, PatienceOff hands the agent
// the error at once, and it is at most PatienceLongest. Set with
// `magpie provider set <id> patience=`; a group it is in keeps the
// group's own.
Patience int `json:"patience,omitempty"`
// NativeCompaction has Codex's compaction_trigger go to the provider
// as Codex sent it, and the compaction the provider writes back go to
// Codex as it came (#1099), where magpie otherwise asks the model for
@@ -1254,6 +1264,10 @@ func keyOptional(p Provider) bool {
func normalize(p Provider) Provider {
p.ID = strings.ToLower(strings.TrimSpace(p.ID))
p.Name = strings.TrimSpace(p.Name)
if p.Patience < 0 {
p.Patience = PatienceOff
}
p.Patience = min(p.Patience, PatienceLongest)
p.Key = strings.TrimSpace(p.Key)
p.Proxy = strings.TrimSpace(p.Proxy)
p.AccountProxies = normalAccountProxies(p.AccountProxies)