Files
magpie/internal/gateway/key_limit.go
T
yetone 694f4a6d65 gateway: a Codex turn of its own reads past 512 MB, to a sixteenth of the machine's memory (dallascao)
dallascao on Discord: generating images in Codex and revising them again
and again, magpie answered 413 "request body is over magpie's gateway
limit of 512 MB (decoded); the provider was not asked" on
127.0.0.1:3425/backend-api/codex/responses, while Codex signed in to
OpenAI directly went on. The count was right: Codex keeps each image it
generated in the conversation (a function_call_output input_image, a
~3 MB PNG as ~4 MB base64; codex-rs ext/image-generation to_response_item,
and history keeps image_generation_call results), and over HTTP sends the
conversation whole every turn, so ~130 images is 512 MB decoded. To
OpenAI directly Codex uses its WebSocket and sends a delta.

- Codex's own path (codexBackend, the Codex relay, the Responses
  WebSocket's read limit, keyLimited on CodexPath) reads to
  codexBodyLimit: a sixteenth of the machine's memory (memLimit, else
  proc.MemTotal), 512 MB at least, 2 GB at most. 16 GB: 1024 MB,
  24 GB: 1536 MB, 32 GB+: 2048 MB, 8 GB or unknown: 512 MB as before.
  It is still the bomb guard: nothing decodes past it, and the zstd
  decoder keeps its window bound.
- A turn for a magpie model ("provider/model") on that path is held to
  the 512 MB of every other route once its model is read: it is
  translated, at several times its size. Its 413 says one of Codex's own
  models takes up to codexBodyLimit; writeError's /compact hint stays.
- provider.codexNamesBad read tools/input/tool_choice with
  GetManyBytes, which copied the whole input (the body's size: 300 MB of
  a 300 MB turn in the alloc profile). It reads in place now.

Cost at the largest input (mote, a relayed gpt-5.5 turn of random
~3 MB images, heap objects sampled every 5ms, load ~350): 300 MB took
4.7s, 600 MB 7.7s, 1000 MB 11.9s, peak heap 1.5 to 2.1 GB past the
body's own bytes. The rest of the cost is io.ReadAll growing the decoded
body and fillJSONIn/exchangeOf; bodyRoom still runs a body bigger than
its room alone.

Run at the pushed head (mote): gofmt -l clean; GOOS=linux and
GOOS=windows go vet ./internal/gateway ./internal/provider ok;
go test -timeout 45m ./internal/provider ok, ./internal/gateway ok but
TestCompactionOverByteCapEveryTime, red in the full package run only
(#4862, filed before this; passes alone 3 of 3 here).
TestRequestBodyTooLarge/codex now sends codexBodyLimit+1.
- TestCodexGeneratedImagesPastOldLimit (16 GB machine fixture, a 516 MB
  turn of generated images in Codex's shape): reaches the fake ChatGPT
  backend whole in ~6s; the same turn for x/gpt-5 is 413 naming
  "one of Codex's own models takes up to 1024 MB".
- TestCodexBodyLimitFromMemory: 2/8/16/24/64 GiB and unknown memory.
Broken by hand: codexBackend reading with limit 0 (the old code) makes
TestCodexGeneratedImagesPastOldLimit red with the reporter's 413; the
magpie-model check turned off makes it red (404 from routing, not 413).

Not tried: the reporter's own session or a real Codex image-generation
run through magpie; a turn past 1 GB on a 16 GB machine; the WebSocket's
raised read limit has no test of its own.
2026-11-03 16:05:53 +08:00

143 lines
5.7 KiB
Go

package gateway
import (
"bytes"
"errors"
"io"
"net/http"
"slices"
"strconv"
"strings"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/gwbudget"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// limitClock is the time a gateway key's limit is checked at: the window
// a request counts in and when its 429 says the key resets. A variable for
// the tests.
var limitClock = time.Now
// remoteKeyLimitHeader marks a 429 as the gateway key's own limit, not a
// provider's: a magpie that uses this one as a remote rests its key on it,
// and only its model on any other refusal (#2077).
const remoteKeyLimitHeader = "X-Magpie-Limit-Reset"
// keyLimited holds a gateway key's requests to its limit (#585, see
// package budget for the rules): one that would go over is refused with a
// 429 before any provider is asked, saying the key, the limit and when it
// resets; one let in holds a reservation until it ends. A key with a limit
// while plugins/budget is off is refused with a 503, and nothing is sent. Reads, the
// bridge's tool callbacks and counting tokens cost nothing and pass.
func keyLimited(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
who := access.Caller(r.Context())
limits := who.Limits()
if who.Issuer != nil {
limits = append(slices.Clone(limits), who.Issuer.Limits()...)
}
if !who.Limited() || r.Method != http.MethodPost || strings.HasPrefix(r.URL.Path, "/_magpie/") || strings.HasPrefix(r.URL.Path, "/mcp/") || strings.HasSuffix(r.URL.Path, "/count_tokens") || r.URL.Path == KeysPath {
next.ServeHTTP(w, r)
return
}
size, model := r.ContentLength, ""
// a compressed body (#1223) is reserved at its decoded size and model
costCap := slices.ContainsFunc(limits, func(l *access.Limit) bool { return l.Cost > 0 })
if enc := r.Header.Get("Content-Encoding"); costCap || size < 0 || (enc != "" && !strings.EqualFold(enc, "identity")) {
// a turn on Codex's own path reads to its own limit (codexBackend)
var most int64
if strings.HasPrefix(r.URL.Path, CodexPath+"/") {
most = codexBodyLimit()
}
b, status, err := readBoundedRequestBody(w, r, requestLimits{body: most})
if err != nil {
writeError(w, protoOfPath(r.URL.Path), status, err.Error())
return
}
r.Body, r.ContentLength = io.NopCloser(bytes.NewReader(b)), int64(len(b))
size, model = int64(len(b)), budget.ModelOf(b)
}
now := limitClock()
release, err := reserveFor(who, size, model, now)
if err != nil {
status, errType := http.StatusServiceUnavailable, "gateway_key_limit_off"
var refused gwbudget.Refusal
if errors.As(err, &refused) {
status, errType = http.StatusTooManyRequests, "gateway_key_limit"
w.Header().Set("Retry-After", strconv.Itoa(refused.RetryAfter(now)))
w.Header().Set(remoteKeyLimitHeader, refused.ResetAt().Format(time.RFC3339))
}
// the Anthropic and OpenAI SDKs would otherwise retry a 429 or 503
w.Header().Set("X-Should-Retry", "false")
writeError(w, protoOfPath(r.URL.Path), status, err.Error())
c := callerOf(r)
appendUsage(r, usage.Record{Time: now, Agent: c.agent, Via: c.via, Requested: model, Status: status, Rejected: true,
Error: err.Error(), ErrType: errType, Endpoint: r.URL.Path, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header)})
return
}
defer release()
next.ServeHTTP(w, r)
})
}
// reserveFor holds a request of who's to its key's limits through the
// gateway's budget point (gwbudget): its release, or why it isn't let in,
// a gwbudget.Refusal or, for a key held to a limit while no limiter serves
// it, gwbudget.ErrUnlimited. A request without a limit is let in as it is.
func reserveFor(who access.Identity, size int64, model string, now time.Time) (release func(), err error) {
l, err := gwbudget.Limiting(who)
if err != nil {
return nil, err
}
if l == nil {
return func() {}, nil
}
release, refused := l.Reserve(who, size, model, now)
if refused != nil {
return nil, refused
}
return release, nil
}
// protoOfPath is the API a path is of, for an error said its way.
func protoOfPath(path string) provider.Protocol {
switch {
case strings.HasSuffix(path, "/messages"):
return provider.Anthropic
case strings.HasPrefix(path, "/v1beta/"):
return provider.Gemini
case strings.HasSuffix(path, "/responses"):
return provider.Responses
}
return provider.Chat
}
// keyLimit answers GET /v1/magpie/limit: the calling gateway key's limit,
// what it has used and when it resets; {"limited":false} for a key with
// none or a request without one. "limits" is each of a key's limits
// (#2227), and "limit" the one holding it most (budget.Binding), which is
// what a magpie from before them reads.
func (s *Server) keyLimit(w http.ResponseWriter, r *http.Request) {
who := access.Caller(r.Context())
out := map[string]any{"limited": false, "key": who.KeyName}
// an issued key is held to the limits of the key it was issued under
// too, which count every key issued under it: "issuerLimits"
if who.KeyID != "" && who.Issuer != nil && len(who.Issuer.Limits()) > 0 {
out["issuerLimits"] = budget.All(access.Key{ID: who.Issuer.KeyID, Name: who.Issuer.KeyName, Limit: who.Issuer.Limit, More: who.Issuer.More}, limitClock())
}
if !who.Expires.IsZero() {
out["expires"] = who.Expires
}
if who.KeyID == "" || len(who.Limits()) == 0 {
writeJSON(w, 200, out)
return
}
all := budget.All(access.Key{ID: who.KeyID, Name: who.KeyName, Limit: who.Limit, More: who.More}, limitClock())
out["limited"], out["limit"], out["limits"] = true, budget.Binding(all), all
writeJSON(w, 200, out)
}