gateway: another magpie's key limit rests that magpie whole when relayed, and its marker stays here (#2791)

restAfterMarked reads a failed try's held header, which keepRetry
fills from the upstream's reply. keepRetry kept Retry-After and the
rate-limit reset headers but not X-Magpie-Limit-Reset
(remoteKeyLimitHeader), so a remote magpie's gateway key over its own
limit read as that one model's rate limit (remoteModelRest): the model
rested alone and the remote's other models were asked into the same
refusal.

Patch by ggbdpq (#2791): their test and the cause are theirs. Changed
from it: the patch whitelisted the raw marker into the held header,
and holdWriter passes that header on to the client, so the marker
reached the agent and, in a chain, a magpie asking this one, which
would rest all of this magpie for one key there. keepRetry now sets
an internal note (keyLimitThereHeader) that remoteModelRest reads and
holdWriter drops, with answeredThereHeader. The two keepRetry sites
that write to the client directly (count_tokens, decide_group) go
through keepRetryOut, which drops both notes; answeredThereHeader
leaked there before too. Doc sentence in gateway-routing.md.

Run (rebased on origin/main):
- TestRemoteMagpieKeyLimitRestsTheRemote (theirs): red with the note
  taken out of keepRetry by hand (rested office/glm/glm-5 and kimi, not
  office), green now.
- TestRemoteMagpieKeyLimitMarkerStaysHere (new): red with the patch's
  raw marker copy ("the agent's reply carries X-Magpie-Limit-Reset"),
  and red with keyLimitThereHeader taken out of pass()'s strip list
  ("carries X-Magpie-Key-Limit-There"), green now.
- RemoteMagpie|AnotherMagpie|KeyLimit ok; the whole internal/gateway
  package (-tags nogui -count=1 -timeout 45m) ok in 476s at fc860f2e6.
- gofmt -l clean; go vet ./internal/gateway for darwin, GOOS=windows,
  GOOS=linux -tags nogui clean.
Not tried: two real magpies over a network with a key limit hit.
This commit is contained in:
yetone
2026-10-28 00:27:02 +08:00
parent 791e27ec34
commit b10f43e899
6 changed files with 135 additions and 6 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -235,7 +235,7 @@ func (s *Server) serveDecideTries(w http.ResponseWriter, r *http.Request, body [
ctype = "application/json"
}
if status >= 400 {
keepRetry(w.Header(), header, b)
keepRetryOut(w.Header(), header, b)
}
w.Header().Set("Content-Type", ctype)
w.WriteHeader(status)
+2 -2
View File
@@ -1886,7 +1886,7 @@ func (h *holdWriter) pass() {
}
dst := h.w.Header()
for k, v := range h.header {
if k != resetsHeader && k != refusedHeader && k != zdrHeader && k != answeredThereHeader { // magpie's own notes, for restAfter and settle
if k != resetsHeader && k != refusedHeader && k != zdrHeader && k != answeredThereHeader && k != keyLimitThereHeader { // magpie's own notes, for restAfter and settle
dst[k] = v
}
}
@@ -2296,7 +2296,7 @@ func (h *holdWriter) keepAlive() {
}
dst := h.w.Header()
for k, v := range src {
if k != resetsHeader && k != refusedHeader && k != zdrHeader && k != answeredThereHeader && k != "Content-Length" {
if k != resetsHeader && k != refusedHeader && k != zdrHeader && k != answeredThereHeader && k != keyLimitThereHeader && k != "Content-Length" {
dst[k] = slices.Clone(v)
}
}
+1 -1
View File
@@ -1458,7 +1458,7 @@ func (s *Server) countOn(w http.ResponseWriter, r *http.Request, p provider.Prov
continue
}
}
keepRetry(w.Header(), res.Header, b)
keepRetryOut(w.Header(), res.Header, b)
writeError(w, provider.Anthropic, res.StatusCode, c.p.Explain(c.p.Name+": "+provider.APIError(b, res.Status), res.StatusCode, b))
return
}
@@ -2,10 +2,12 @@ package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
@@ -193,3 +195,109 @@ func anotherMagpieAddedByHand(t *testing.T, held bool) {
t.Errorf("Qoder was asked %d times; want twice", asked.Load())
}
}
// The marker comes by wire: the other magpie's keyLimited answers a 429
// with remoteKeyLimitHeader, and what reaches restAfterMarked here is what
// the relay kept of the upstream reply. The key's own limit there rests
// the whole remote, not the model it was asked for — the opposite of that
// model's own rate limit, which rests it alone
// (TestRemoteMagpieQuotaRestsTheModel). So asked again, the remote's
// models are behind the next member, neither of them asked.
func TestRemoteMagpieKeyLimitRestsTheRemote(t *testing.T) {
fresh(t)
forgetSinks(t)
var mu sync.Mutex
var asked []string
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req struct {
Model string `json:"model"`
}
json.NewDecoder(r.Body).Decode(&req)
mu.Lock()
asked = append(asked, req.Model)
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
if req.Model == "glm/glm-5" {
// what keyLimited answers with: its 429 names when the key
// resets, and marks itself the key's own
w.Header().Set(remoteKeyLimitHeader, "2026-10-19T00:00:00Z")
w.Header().Set("Retry-After", "60")
w.WriteHeader(http.StatusTooManyRequests)
io.WriteString(w, `{"error":{"message":"gateway key over its request budget","type":"rate_limit_error"}}`)
return
}
if req.Model == "kimi/kimi-k3" {
// that model's own rate limit there, no marker: rests alone
w.WriteHeader(http.StatusTooManyRequests)
io.WriteString(w, `{"error":{"message":"rate limit exceeded, slow down"}}`)
return
}
io.WriteString(w, `{"id":"x","choices":[{"index":0,"message":{"role":"assistant","content":"from `+req.Model+`"},"finish_reason":"stop"}]}`)
}))
t.Cleanup(remote.Close)
if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: "k",
Chat: remote.URL + "/v1", Models: []string{"glm/glm-5", "kimi/kimi-k3"}}); err != nil {
t.Fatal(err)
}
other := &keyed{}
serveOn(t, "other", "ko", []string{"m"}, other)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"office/glm/glm-5", "office/kimi/kimi-k3", "other/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
s := New()
// neither of the remote's models answers: the turn goes to the next
// member
if code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`); code != 200 || !strings.Contains(body, "from ko") {
t.Fatalf("the remote's key limit and its model's rate limit: %d %s", code, body)
}
// the key's own limit there rests the remote whole; kimi's own rate
// limit rests kimi alone
if _, ok := restOf("office"); !ok {
t.Errorf("the key's own limit there didn't rest the remote whole: %v", rests())
}
if r, ok := restOf("office/glm/glm-5"); ok {
t.Errorf("the key's own limit rested glm alone: %+v %v", r, rests())
}
if _, ok := restOf("office/kimi/kimi-k3"); !ok {
t.Errorf("kimi's own rate limit there didn't rest kimi alone: %v", rests())
}
// asked again, the remote sits out whole: neither model is
mu.Lock()
asked = nil
mu.Unlock()
if code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`); code != 200 || !strings.Contains(body, "from ko") || len(asked) != 0 {
t.Fatalf("the remote's models were asked %v after its key limit: %d %s", asked, code, body)
}
}
// The other magpie's key-limit marker is read here, not passed on: a
// magpie that asks this one would read it as this magpie's own key limit
// and rest all of this one, every provider behind it, for one key there
// (#2791). The agent gets the 429 without the marker or magpie's own
// note of it.
func TestRemoteMagpieKeyLimitMarkerStaysHere(t *testing.T) {
fresh(t)
forgetSinks(t)
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set(remoteKeyLimitHeader, "2026-10-19T00:00:00Z")
w.WriteHeader(http.StatusTooManyRequests)
io.WriteString(w, `{"error":{"message":"gateway key over its request budget","type":"rate_limit_error"}}`)
}))
t.Cleanup(remote.Close)
if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: "k",
Chat: remote.URL + "/v1", Models: []string{"glm/glm-5"}}); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions",
strings.NewReader(`{"model":"office/glm/glm-5","messages":[{"role":"user","content":"hi"}]}`)))
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
for _, h := range []string{remoteKeyLimitHeader, keyLimitThereHeader} {
if v := rec.Header().Get(h); v != "" {
t.Errorf("the agent's reply carries %s: %q", h, v)
}
}
}
+22 -1
View File
@@ -1275,7 +1275,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
// on Discord: "Remote Magpie: Claude Code: You've hit your session
// limit" answered every model of it for the five hours it named).
func remoteModelRest(c candidate, why string, header http.Header) bool {
if !c.p.IsRemoteMagpie() && header.Get(answeredThereHeader) == "" || header.Get(remoteKeyLimitHeader) != "" {
if !c.p.IsRemoteMagpie() && header.Get(answeredThereHeader) == "" || header.Get(remoteKeyLimitHeader) != "" || header.Get(keyLimitThereHeader) != "" {
return false
}
return why == failQuota || why == failCredit || why == failRate || why == failRestricted || why == failVerify
@@ -1453,6 +1453,15 @@ func keepRetry(dst, src http.Header, body []byte) {
dst.Set("Retry-After", strconv.Itoa(int(d.Seconds())))
}
}
if src.Get(remoteKeyLimitHeader) != "" {
// another magpie's gateway key is over its own limit: noted for
// restAfter, which rests that magpie whole (remoteModelRest), as
// the held try's header is all it reads (#2791, ggbdpq: the
// marker was left out, and the key's limit rested one model). A
// note, not the marker, so a magpie this one answers doesn't read
// another's key limit as this one's
dst.Set(keyLimitThereHeader, "1")
}
if who := src.Get(providerHeader); who != "" {
// another magpie refused it, naming its provider that did: this
// magpie's own name for the provider goes in the same header
@@ -1472,6 +1481,18 @@ func keepRetry(dst, src http.Header, body []byte) {
}
}
// keepRetryOut is keepRetry onto a reply that goes to the client as it
// is, with no holdWriter to drop magpie's own notes.
func keepRetryOut(dst, src http.Header, body []byte) {
keepRetry(dst, src, body)
dst.Del(answeredThereHeader)
dst.Del(keyLimitThereHeader)
}
// keyLimitThereHeader carries, from keepRetry to restAfter, that another
// magpie refused with its gateway key's own limit (remoteKeyLimitHeader).
const keyLimitThereHeader = "X-Magpie-Key-Limit-There"
// answeredThereHeader carries, from keepRetry to restAfter, the provider
// another magpie named on its refusal (providerHeader): the refusal is
// that magpie's model's (remoteModelRest).