diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 38e599405..2d737c9a9 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -20,7 +20,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). | Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight` (`weightedFirst`). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/provider/routing.go`](../../internal/provider/routing.go) | -| Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`): one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks. | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | +| Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks. | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. | [`sink.go`](../../internal/gateway/sink.go) | | Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) | | One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`) and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) | diff --git a/internal/gateway/rpm.go b/internal/gateway/rpm.go index 7bb8efda3..b67089081 100644 --- a/internal/gateway/rpm.go +++ b/internal/gateway/rpm.go @@ -43,6 +43,17 @@ import ( // rpmWindow is the rolling window MaxRPM counts over; tests shorten it. var rpmWindow = time.Minute +// rpmSlack is added to the window. A request is counted when it starts to +// go, but the vendor counts it when it arrives: the first on a connection +// arrives later than the next ones by its dial and TLS handshake, so with +// the bare window the vendor could see one more than the limit in its own +// minute (TestMaxRPMWaitsForRoomInTheMinute went red under CI load, and +// does every time when the first is held 150ms on its way). +var rpmSlack = time.Second + +// rpmSpan is how long a request counted stays counted. +func rpmSpan() time.Duration { return rpmWindow + rpmSlack } + // rpmLongest is the longest a request waits for room in the minute when // the provider's QueueWait isn't shorter; tests shorten it. var rpmLongest = 2 * time.Minute @@ -78,11 +89,11 @@ func rpmWait(p provider.Provider) time.Duration { return rpmLongest } -// prune drops who's times a minute old or older, at now. +// prune drops who's times a minute (and rpmSlack) old or older, at now. func (l *rpms) prune(who string, now time.Time) []time.Time { ts := l.m[who] i := 0 - for i < len(ts) && !ts[i].After(now.Add(-rpmWindow)) { + for i < len(ts) && !ts[i].After(now.Add(-rpmSpan())) { i++ } ts = ts[i:] @@ -95,8 +106,8 @@ func (l *rpms) prune(who string, now time.Time) []time.Time { } // reserve takes who's next time to go, at most longest from now (0: no -// bound): now when the minute has room, else a minute after the limit-th -// from the end. +// bound): now when the minute has room, else a minute (and rpmSlack) after +// the limit-th from the end. func (l *rpms) reserve(who string, limit int, longest time.Duration, now time.Time) (time.Time, error) { l.mu.Lock() defer l.mu.Unlock() @@ -106,7 +117,7 @@ func (l *rpms) reserve(who string, limit int, longest time.Duration, now time.Ti ts := l.prune(who, now) at := now if len(ts) >= limit { - at = ts[len(ts)-limit].Add(rpmWindow) + at = ts[len(ts)-limit].Add(rpmSpan()) } if d := at.Sub(now); longest > 0 && d > longest { return time.Time{}, &errRPM{limit: limit, after: d, wait: longest} diff --git a/internal/gateway/rpm_test.go b/internal/gateway/rpm_test.go index cc8f55eb1..1c66eb686 100644 --- a/internal/gateway/rpm_test.go +++ b/internal/gateway/rpm_test.go @@ -22,11 +22,22 @@ type minuteVendor struct { at []time.Time path []string fail int + // late is how much later than the rest the first request arrives, as + // when its connection has to be dialed (and, to a real vendor, its TLS + // handshake made) while the later ones reuse it + late time.Duration + n int } func (v *minuteVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { io.Copy(io.Discard, r.Body) v.mu.Lock() + v.n++ + if v.n == 1 && v.late > 0 { + v.mu.Unlock() + time.Sleep(v.late) + v.mu.Lock() + } v.at = append(v.at, time.Now()) v.path = append(v.path, r.URL.Path) failing := v.fail > 0 && strings.HasSuffix(r.URL.Path, "/chat/completions") @@ -55,12 +66,20 @@ func (v *minuteVendor) times() []time.Time { } // shortMinute makes MaxRPM's window and longest wait w and longest for the -// test. +// test, with no slack unless the test gives it one (slackMinute). func shortMinute(t *testing.T, w, longest time.Duration) { t.Helper() - ow, ol := rpmWindow, rpmLongest - rpmWindow, rpmLongest = w, longest - t.Cleanup(func() { rpmWindow, rpmLongest = ow, ol }) + ow, ol, os := rpmWindow, rpmLongest, rpmSlack + rpmWindow, rpmLongest, rpmSlack = w, longest, 0 + t.Cleanup(func() { rpmWindow, rpmLongest, rpmSlack = ow, ol, os }) +} + +// slackMinute is shortMinute with a slack of a sixth of the window, as the +// real one is to its minute, for a test that times what the vendor sees. +func slackMinute(t *testing.T, w, longest time.Duration) { + t.Helper() + shortMinute(t, w, longest) + rpmSlack = w / 6 } // rpmGateway is a gateway as the real server serves it (lanGuard in @@ -97,8 +116,9 @@ func chatOnce(ctx context.Context, gw string) (*http.Response, string, error) { // first is a minute old, then is answered. func TestMaxRPMWaitsForRoomInTheMinute(t *testing.T) { window := 1500 * time.Millisecond - shortMinute(t, window, time.Minute) - v := &minuteVendor{} + slackMinute(t, window, time.Minute) + // the first dials the connection the others reuse + v := &minuteVendor{late: 150 * time.Millisecond} _, gw := rpmGateway(t, v, 2) start := time.Now() for i := range 3 { @@ -114,8 +134,8 @@ func TestMaxRPMWaitsForRoomInTheMinute(t *testing.T) { if d := at[1].Sub(start); d > window/2 { t.Fatalf("the second waited %s with room in the minute", d) } - if d := at[2].Sub(at[0]); d < window-50*time.Millisecond { - t.Fatalf("the third went %s after the first, inside the %s window", d, window) + if d := at[2].Sub(at[0]); d < window { + t.Fatalf("the vendor saw the third %s after the first, inside the %s window", d, window) } } @@ -188,8 +208,8 @@ func TestMaxRPMAgentGoneWhileWaiting(t *testing.T) { // room, so the next chat waits for the minute. func TestMaxRPMCountsRetriesAndCounts(t *testing.T) { window := 1500 * time.Millisecond - shortMinute(t, window, time.Minute) - v := &minuteVendor{fail: 1} + slackMinute(t, window, time.Minute) + v := &minuteVendor{fail: 1, late: 150 * time.Millisecond} _, gw := rpmGateway(t, v, 3) if res, body, err := chatOnce(context.Background(), gw); err != nil || res.StatusCode != 200 { t.Fatalf("first: %v %v %s", err, res, body) @@ -235,7 +255,7 @@ func TestMaxRPMCountsRetriesAndCounts(t *testing.T) { if len(at) != 4 { t.Fatalf("the vendor saw %d (%v), want 4", len(at), v.path) } - if d := at[3].Sub(at[0]); d < window-50*time.Millisecond { + if d := at[3].Sub(at[0]); d < window { t.Fatalf("the last went %s after the first, inside the %s window: the retry or the count wasn't counted", d, window) } } @@ -354,6 +374,30 @@ func TestRPMReserve(t *testing.T) { } } +// The slack is part of the minute both ways: a request waits for a minute +// and the slack after the limit-th from the end, and one that old no longer +// counts only once the slack has passed too. +func TestRPMReserveKeepsTheSlack(t *testing.T) { + shortMinute(t, time.Minute, 2*time.Minute) + rpmSlack = time.Second + var l rpms + t0 := time.Now() + for _, c := range []struct{ now, want time.Duration }{ + {0, 0}, {10 * time.Second, 61 * time.Second}, + {70 * time.Second, 122 * time.Second}, // a minute and the slack after 61 + } { + got, err := l.reserve("x", 1, 0, t0.Add(c.now)) + if err != nil || got.Sub(t0) != c.want { + t.Fatalf("at %s: %s %v, want %s", c.now, got.Sub(t0), err, c.want) + } + } + l = rpms{} + l.reserve("x", 1, 0, t0) + if got, _ := l.reserve("x", 1, 0, t0.Add(60500*time.Millisecond)); got.Sub(t0) != 61*time.Second { + t.Fatalf("half a second into the slack: %s, want 61s", got.Sub(t0)) + } +} + // A try's own requests are counted once, against the key or account the // try is of, however the provider names its account; a request to another // provider made on the way is counted against that one's.