Files
magpie/internal/gateway/key_limit.go
T
yetone e215d335a6 gateway: a gateway key can cap its requests at once; the rest wait their turn
young02036 on Discord: a provider can be given a concurrency, so why
can't a gateway key? A key now has an optional MaxConcurrency, from 1
to 1000. Left unset (every key today), nothing changes.

- access: Key and Change get MaxConcurrency, and Identity carries it, the
  issuer's cap included. The concurrency-key action refuses a value
  below 0 or above 1000.
- gateway (key_slots.go): every route that asks a model is held to the
  key's cap, however the request came (loopback, LAN, a Remote magpie, a
  Responses socket's turn). One request too many waits in the key's
  queue in arrival order. It shows as "slot" in Active, and its wait goes
  into the try's Queued. A request whose agent goes away while it waits
  leaves the queue and sends nothing. A stream holds its slot until it
  ends. serve's routes (chat, responses, messages, ollama, gemini, the
  Codex backend) wait inside the try, after keepQueued, so a streaming
  agent gets keepalives while it waits. The other model routes (images,
  embeddings, rerank, audio, videos, search, decisions, native) wait
  before their handler runs. forward and codexUpstreamOn take the slot
  too, so nothing reaches a vendor without one. A key issued under
  another waits for its own slot, then for its issuer's.
  /v1/magpie/concurrency lists each capped key under "keys", and counts
  its waiters in "waiting". A key's limit (key_limit) reports the cap.
  Not held, as a provider's MaxConcurrency doesn't hold them: GET,
  HEAD, OPTIONS, count_tokens, :countTokens and MCP.
  TestKeySlotEveryRoute fails when a route is judged neither held nor
  free.
- cli: magpie gateway-key concurrency <id> [<n>|off]. It refuses 0, a
  negative, over 1000, a fraction, a word, --help or an extra argument
  with its usage.
- gui: the key row gets a badge in the provider concurrency badge's
  style. It opens the app's menu with No limit, 1/2/3/5/10 and Other…,
  and Other… takes a number typed in place. A value that isn't a whole
  number up to 1000 is refused and nothing is sent. Browser and
  read-only keys have no badge. Strings are in en, zh, zh-TW, ja and
  de. An unset badge, which a hover shows, gives way before the masked
  key (flex-shrink 8). Without that, at 420px in en and de, the extra
  badge squeezed the key until its copy button slid under the pointer
  that came to drag the row, and gateway-key-arrange went red.
- docs/subsystems/gateway-routing.md describes it.

Run (on mote, at this tree on origin/main 0f8c3d867; rebased onto 627fd1a3b,
which touches none of these files, and the budgets were run again):
- go test -timeout 45m ./internal/access ./internal/gateway ./internal/cli
  ./internal/gui: access, gateway (839s) and cli ok. gui had one red,
  TestGatewayModeStatsNameTheGatewaySessions, run at 00:40 PST: its
  record an hour back falls on yesterday in a day's first hour. It
  passes from 01:09, so it is unrelated; filed as #5690. The Budget/Size
  tests were run again after the CSS change: ok.
- gofmt -l: clean. go vet for darwin, plus GOOS=linux and GOOS=windows
  (-tags nogui), on those packages: ok.
- GUI (node --test, Chromium and WebKit, 1100 and 420 wide, en, zh,
  zh-TW, ja and de): every file that loads the gateway keys (59) plus
  i18n-keys and i18n-en-no-cjk. The reds left are the same on
  origin/main and already filed: gateway-key-models en (#5233, #4081),
  i18n-keys "a plugin's words are its own" (#5332), phone-connect-menu
  at 420 (#4706, #4707). After the flex-shrink fix:
  gateway-connect-keys, gateway-key-arrange, -concurrency, -mcp,
  -own-rotate and -quotas passed 104/104 in both engines, against
  84/84 on base.
- The tests:
  - TestKeyConcurrency, over LAN with cap 2: 2 of 3 requests reach the
    vendor and the third is shown as "slot". Another key isn't held. A
    cancelled waiter leaves the queue and never reaches the vendor. The
    third goes once one ends, every lane is given back, and its Queued
    is at least 40ms.
  - TestKeyConcurrencyKeepsStreamAlive: a waiting stream gets 200 and
    keepalives.
  - TestKeyConcurrencyEager: on embeddings an issued key waits on its
    parent's lane, a cancelled waiter leaves, never more than 1 runs at
    once, and a GET takes no slot.
- A real `serve` in a sandbox HOME (built from this tree, MAGPIE_ADDR
  127.0.0.1:38612) against a fake slow SSE upstream. Steps: `provider
  add fake url=…`, `gateway-key add`, `gateway-key concurrency <id> 1`,
  then three concurrent keyed streams. /v1/magpie/concurrency showed the
  key at busy 1, waiting 2, limit 1 (two in "slot"). The upstream's
  most at once was 1, and it saw 3 requests one after another (200s at
  1.9s, 3.7s and 5.5s, each with [DONE]). Afterwards "keys" was empty.
  `concurrency <id> 2000` exited 1 with its usage.

Broken by hand (each went red, then restored):
- keySlot returns nil: TestKeyConcurrency ("timed out waiting for c
  queued") and KeepsStreamAlive.
- The issuer's lane skipped: TestKeyConcurrencyEager.
- The eager take skipped: TestKeyConcurrencyEager.
- The CLI's bounds check removed: "accepted [concurrency id 0]".
- The GUI's bounds check removed: gateway-key-concurrency.
- Without the flex-shrink line: gateway-key-arrange chromium/webkit en
  and de 420px.

Not tried / not done:
- Full suite not run at push (neither `go test ./...` nor the whole GUI
  suite).
- Not tried with a real vendor account or a second computer on the LAN.
  The LAN path is covered by TestKeyConcurrency's lanServer.
- The key's badge shows the cap, not live running or waiting counts.
  /v1/magpie/concurrency has those.

Reported-by: young02036 (Discord)
2026-11-08 17:52:09 +08:00

232 lines
8.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.
//
// A limit of some models (access.Limit.Models) holds a request that names
// one of them here, and its spent ones are put on the request's caller
// (access.Identity.Spent), for every route to leave their models out of
// its candidates: a routing group's request goes on to the others, and
// counting tokens on a spent one is refused as serving it would be.
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/") || r.URL.Path == KeysPath {
next.ServeHTTP(w, r)
return
}
scoped := slices.ContainsFunc(limits, (*access.Limit).Scoped)
if strings.HasSuffix(r.URL.Path, "/count_tokens") {
if scoped {
r = withSpent(r, who, limitClock())
}
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 || scoped || 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()
if scoped {
// before the request's own reservation, which would count it
// spent on the model it holds
r = withSpent(r, who, now)
}
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)))
// a limit of some models rests a remote's model, not its key
if b, ok := refused.(*budget.Refusal); !ok || len(b.Models) == 0 {
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)
})
}
// withSpent is r with its caller's spent limits of some models on it
// (access.Identity.Spent), as the limiter serving who tells them; r as it
// is when none serves (a request it holds is refused by reserveFor).
func withSpent(r *http.Request, who access.Identity, now time.Time) *http.Request {
l, err := gwbudget.Limiting(who)
if err != nil || l == nil {
return r
}
sp, ok := l.(gwbudget.Spender)
if !ok {
return r
}
if who.Spent = sp.Spent(who, now); len(who.Spent) == 0 {
return r
}
return r.WithContext(access.WithIdentity(r.Context(), who))
}
// 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.
//
// A key held to a budget, models or accounts is told so as well, so this
// agrees with the quotas and the status line (steven_4422: a key held to
// Claude's models read {"limited":false} here and 403 gateway_key_held
// there): "heldTo" what holds it ("budget", "models", "accounts"),
// "models" the models it may use, and "quotas" whether it is told any
// quota, with "quotaProviders" the providers it is told those of
// (scopeQuotas). An account is not named: a key its owner tells no quota
// is told no account either. A key held to nothing has none of these.
// "mcp" is the MCP servers and tools a key may use, when its owner chose
// some.
func (s *Server) keyLimit(w http.ResponseWriter, r *http.Request) {
who := access.Caller(r.Context())
out := map[string]any{"limited": false, "key": who.KeyName}
if heldKey(who) {
var heldTo []string
if who.Limited() {
heldTo = append(heldTo, "budget")
}
if len(who.Models) > 0 && !who.AccountModels {
heldTo = append(heldTo, "models")
}
if len(who.Accounts) > 0 {
heldTo = append(heldTo, "accounts")
}
out["heldTo"], out["quotas"] = heldTo, who.Quotas
if len(who.Models) > 0 {
out["models"] = who.Models
}
if who.Quotas {
ps := []string{}
for id, every := range newQuotaScope(who, provider.Catalog()).every {
if every {
ps = append(ps, id)
}
}
slices.Sort(ps)
out["quotaProviders"] = ps
}
}
// 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())
}
// "mcp", the MCP servers and tools a key is held to (access.Key.MCP)
if who.KeyID != "" && len(who.MCP) > 0 {
out["mcp"] = who.MCP
}
if !who.Expires.IsZero() {
out["expires"] = who.Expires
}
// "maxConcurrency", how many of its requests may be in flight at once
// (key_slots.go), and its issuer's
if who.KeyID != "" && who.MaxConcurrency > 0 {
out["maxConcurrency"] = who.MaxConcurrency
}
if who.KeyID != "" && who.Issuer != nil && who.Issuer.MaxConcurrency > 0 {
out["issuerMaxConcurrency"] = who.Issuer.MaxConcurrency
}
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)
}