Files
magpie/internal/gateway/plain403_rest_test.go
T
yetone d5bc9f0009 gateway: a plain 403 never rests an account until its window, and two accounts' alike 403 on one request rest neither (plugins#243)
zygs1083-dotcom on plugins#243: Factory answered 403 to a Claude Code
2.1.292 request (a changed instructions wrapper factory 0.1.33 didn't
adapt), and the accounts went into cooldown.

On ab7ec8c65 two things made that worse than one failed request:

- restAfterMarked's default branch rested any failure of an account
  whose cached reading was full (c.full: 98% under Smart) until the
  window reset, held to 8 days, by "window". A plain 403 says nothing
  of the window, so an account read at 98% sat out its week over it.
  A 401 or 403 no longer infers a window rest: one that names a quota
  is failQuota already (usedUpWords), and one that doesn't goes on the
  backoff ladder. Every other failure at 98% still rests by window.
- The candidate loop rested each account in turn for the same request's
  403, so one request walked the whole provider into backoff. Now a
  plain 403 (plainForbidden: failOther, not a model not served) from a
  second key or account of the same provider, model and reasoning in
  one request is the request refused: that one doesn't rest, the
  earlier mate's rest and counted failures are taken back (unforbid,
  only when the rest is still the one it took), its trace try loses
  its Rest, and the remaining mates are asked last (matesLast). The
  Routing page already words a failed try with no rest as "doesn't
  rest for it", so no new strings. One account's plain 403 alone still
  rests it as before.

docs/subsystems/gateway-routing.md says both, with the tests.

Tests (internal/gateway/plain403_rest_test.go):
- TestPlain403DoesNotRestUntilTheWindow: an account at 98% gets a plain
  403 and a plain 401: rests by backoff; a 403 saying used up still
  rests 39h by window; a 502 at 98% still by window. On ab7ec8c65's
  routing.go (the file swapped back) it fails: "a plain 403 at 98%
  rests 39h0m0s by window (other)".
- TestPlain403OnTwoMatesRestsNeither: three Codex accounts through the
  gateway against a fake ChatGPT backend: one 403 alone rests that
  account; two alike with a third answering, and two alike with nobody
  left, rest nobody and leave no failure counted. Broken by hand twice:
  the mate branch disabled (both alike cases red, "codex@me@example.com
  resting true, want false"), and unforbid leaving the counts (both red,
  "still counts 1 failures").

Run at ab7ec8c65 (macOS, go1.26.8, sandbox HOME), both commits in the
tree: gofmt, three vets clean; set -o pipefail; go test -timeout 45m
./...: exit 0, 64 packages ok, no FAIL (load ~200).

Rebased onto b641868eb (origin/main, which moved gateway.go and
routing.go: b749cffbb's reply-room retry on a 400, b641868eb's
heldClockIn; neither touches the 403 path) and run again at a33699df6
(this pair's tree), macOS, go1.26.8, sandbox HOME: gofmt -l none; go
vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows
go vet ./...: all clean. go test -count=1 -timeout 45m
./internal/provider: ok (809s). go test -run
'TestPlain403|TestOrderedKeepsAnAccountAt98|TestPromptRefusalRestsNobody|ReplyFitsTheWindowLeft|TestHeldClock|Rest|Forbid|403'
./internal/gateway: ok (110s). go test -count=1 -timeout 45m
./internal/gateway: ok (1762s, load ~300). A full ./... at a33699df6 was started
and stopped after 46 minutes with one package done (load 320-420 from
other sessions, disk at 8.7G free); the earlier full run of the same
two commits on ab7ec8c65 was exit 0, 64 packages ok.

Not tried: no real Factory account or request; the 403 is a fake
backend's.
2026-10-19 22:17:39 +08:00

125 lines
4.8 KiB
Go

package gateway
import (
"io"
"net/http"
"slices"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// A plain 403 (or 401) that names no quota is about the key or the
// request, not the window: an account whose cached usage read 98% rests
// on the backoff ladder, not until its window resets. Before, it sat out
// the whole week on the reading alone (plugins#243, zygs1083-dotcom: one
// Factory 403 benched a working account into its reset). A 403 that does
// say the quota is spent still rests until the window, and so does any
// other failure at 98%, as before.
func TestPlain403DoesNotRestUntilTheWindow(t *testing.T) {
forgetRouting()
old := allowances
defer func() { allowances = old }()
now := time.Now()
week := now.Add(39 * time.Hour)
allowances = func(string) map[string]provider.Allowance {
return map[string]provider.Allowance{
"me@x.com": {{Used: 98, Resets: week, Span: 7 * 24 * time.Hour}},
}
}
acct := candidate{p: provider.Provider{ID: "factory", Account: &provider.Account{Agent: "factory", User: "me@x.com"}}, model: "claude-opus-4-7", rest: "factory#me@x.com"}
if !acct.full(now).Equal(week) {
t.Fatal("the account at 98% doesn't read as full; the test proves nothing")
}
s := &Server{}
near := func(d, want time.Duration) bool { return d > want-time.Minute && d <= want }
for _, status := range []int{http.StatusForbidden, http.StatusUnauthorized} {
forgetRouting()
r := s.restAfter(acct, status, http.Header{}, []byte(`{"error":{"message":"Forbidden"}}`))
if r.By == "window" || r.By != "backoff" || time.Until(r.Until) > longestRetry {
t.Fatalf("a plain %d at 98%% rests %v by %s (%s)", status, time.Until(r.Until).Round(time.Minute), r.By, r.Why)
}
}
// a 403 that says the quota is spent is out until the window
forgetRouting()
r := s.restAfter(acct, http.StatusForbidden, http.Header{}, []byte(`{"error":{"message":"You've hit your usage limit"}}`))
if r.Why != failQuota || r.By != "window" || !near(time.Until(r.Until), 39*time.Hour) {
t.Fatalf("a 403 saying used up rests %v by %s (%s)", time.Until(r.Until).Round(time.Minute), r.By, r.Why)
}
// and another failure at 98% still trusts the reading, as before
forgetRouting()
r = s.restAfter(acct, http.StatusBadGateway, http.Header{}, []byte("bad gateway"))
if r.By != "window" || !near(time.Until(r.Until), 39*time.Hour) {
t.Fatalf("a 502 at 98%% rests %v by %s", time.Until(r.Until).Round(time.Minute), r.By)
}
}
// One request refused with a plain 403 by two accounts of a provider is
// the request refused, not each account (plugins#243, zygs1083-dotcom:
// Factory's 403 for a Claude Code wrapper it refused walked every account
// into backoff, so the next requests found them all resting). Neither
// rests, and an account after them answers. One account's plain 403
// alone still rests it, as a key refused does.
func TestPlain403OnTwoMatesRestsNeither(t *testing.T) {
forbid := func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
io.WriteString(w, `{"error":{"message":"Forbidden"}}`)
}
for _, x := range []struct {
name string
spares []string
also []string // accounts after acct-1 that refuse too
resting []string // who rests after
code int
}{
{"alone", []string{"b@example.com"}, nil, []string{"codex@me@example.com"}, 200},
{"two alike, a third answers", []string{"b@example.com", "c@example.com"}, []string{"acct-2"}, nil, 200},
{"two alike, nobody left", []string{"b@example.com"}, []string{"acct-2"}, nil, 403},
} {
t.Run(x.name, func(t *testing.T) {
codexSignedIn(t, x.spares...)
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
t.Fatal(err)
}
var tried []string
chatgptRefusing(t, &tried, forbid, x.also...)
s := New()
code, body := codexAskOn(s, `{"model":"gpt-5.5","stream":true,"input":"ping"}`)
if code != x.code {
t.Fatalf("status %d: %s; tried %v", code, body, tried)
}
r := lastRoute(s)
for _, who := range append([]string{"codex@me@example.com"}, func() (w []string) {
for _, s := range x.spares {
w = append(w, "codex@"+s)
}
return
}()...) {
_, ok := restOf(who)
if want := slices.Contains(x.resting, who); ok != want {
t.Fatalf("%s resting %v, want %v; tried %v; tries %+v", who, ok, want, tried, r.Tries)
}
if !slices.Contains(x.resting, who) {
routed.Lock()
n := routed.failures[who]
routed.Unlock()
if n != 0 {
t.Fatalf("%s still counts %d failures", who, n)
}
}
}
if want := map[int]string{200: "acct-1,acct-2", 403: "acct-1,acct-2"}[code]; x.also != nil && !strings.HasPrefix(strings.Join(tried, ","), want) {
t.Fatalf("tried %v", tried)
}
if x.also != nil && (r.Tries[0].Rest != nil || r.Tries[1].Rest != nil) {
t.Fatalf("tries still say they rest: %+v", r.Tries)
}
})
}
}