diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ce173f287..0063ccb45 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -33,7 +33,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | 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). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. 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 group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `wrrMove`). 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`). 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`), 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, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`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) | +| 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. A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. | [`draw.go`](../../internal/gateway/draw.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.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`, `strict`. 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. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. 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`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), 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`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), 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/fallback.go b/internal/gateway/fallback.go index cc2a95fdc..a92e7e9b5 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -375,7 +375,9 @@ func (s *Server) plan(p provider.Provider, model string, from provider.Protocol) // alone, whatever the group's (#576): in order, in its place; else as // one, weighed with the rest by the one it would try first, and tried // whole where that one goes — the group's routing picks between its -// groups, never within them. A member's fallbacks are not the group's. +// groups, never within them. A group in the group sinks by its own Sink +// too, within its own order (#2255), before g's Sink orders the whole. +// A member's fallbacks are not the group's. func (s *Server) planGroup(g provider.Group, ms []provider.Member, from provider.Protocol) ([]candidate, planned) { var pl planned var asides []candidate @@ -460,6 +462,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. } var sub planned cs := planLevel(m.Via[depth], ms[i:j], depth+1, from, &sub, asides, wAsides) + cs, sub.order = sinkOwn(m.Via[depth], cs, sub.order) pl.left = append(pl.left, sub.left...) pl.capped = append(pl.capped, sub.capped...) if len(cs) > 0 { @@ -541,12 +544,18 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. for i := 0; i < len(ms); { m := ms[i] if len(m.Path) > depth+1 { - // a group in g: its models, planned by its routing + // a group in g: its models, planned by its routing and + // sunk by its Sink j := i + 1 for j < len(ms) && len(ms[j].Path) > depth+1 && ms[j].Path[depth] == m.Path[depth] { j++ } - out = append(out, planLevel(m.Via[depth], ms[i:j], depth+1, from, pl, asides, wAsides)...) + at := len(pl.order) + cs := planLevel(m.Via[depth], ms[i:j], depth+1, from, pl, asides, wAsides) + var order []Weighed + cs, order = sinkOwn(m.Via[depth], cs, pl.order[at:]) + pl.order = append(pl.order[:at], order...) + out = append(out, cs...) i = j continue } @@ -563,6 +572,19 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. return out } +// sinkOwn is cs, the keys and accounts of sub, a group in a group, as +// planLevel planned them, with those that sank behind the others when +// sub's own Sink is on, and order, what the trace says of each, kept with +// them (#2255, ggbdpq): a nested group is planned by its own routing +// (#576) and rules, and its Sink was left unread, only the group the +// agent asked for sinking. +func sinkOwn(sub provider.Group, cs []candidate, order []Weighed) ([]candidate, []Weighed) { + if !sinks(sub.Sink, sub.Routing) { + return cs, order + } + return sinkPlanned(cs, order) +} + // firstAwake is the first of cs that isn't resting, else the first: what // a group in a group, or a provider routed its own way, is weighed by. func firstAwake(cs []candidate) candidate { diff --git a/internal/gateway/sink_test.go b/internal/gateway/sink_test.go index d0ff7bdc4..abee71494 100644 --- a/internal/gateway/sink_test.go +++ b/internal/gateway/sink_test.go @@ -1,6 +1,7 @@ package gateway import ( + "cmp" "net/http" "slices" "testing" @@ -169,3 +170,100 @@ func TestGroupRateLimitedSinks(t *testing.T) { } } } + +// A group in the group with Sink on (#2255, ggbdpq): its key rate limited +// with quota left goes to the back of that group's own order — behind its +// own other keys, not behind the outer group's members, which the outer +// group's Sink alone would do — as it plans by its own routing (#576) and +// rules. Whatever the outer group's routing, at any depth; with the inner +// group's Sink off, and the outer's off, the order is the routing's. +func TestNestedGroupSinksItsOwnOrder(t *testing.T) { + forgetSinks(t) + s := &Server{} + prov := func(id string) provider.Provider { + return provider.Provider{ID: id, Chat: "http://127.0.0.1:1/v1", Key: "k-" + id} + } + // one member of outer: a model it names itself, or one of the + // groups via, the outermost first, down to the model + mem := func(id string, via ...provider.Group) provider.Member { + path := []string{} + for _, g := range via { + path = append(path, provider.GroupPrefix+g.ID) + } + path = append(path, id+"/m") + return provider.Member{ID: path[0], Path: path, Via: via, Provider: prov(id), Model: "m"} + } + ids := func(cs []candidate) []string { + var out []string + for _, c := range cs { + out = append(out, c.p.ID) + } + return out + } + first := func(cs []candidate, _ planned) []candidate { return cs } + rate := []byte(`{"error":{"message":"Too many requests"}}`) + sinkA := func(t *testing.T) { + t.Helper() + forgetSinks(t) + inner := provider.Group{ID: "inner", Routing: provider.Ordered} + cs, _ := s.planGroup(provider.Group{ID: "outer", Routing: provider.Ordered}, []provider.Member{mem("a", inner), mem("b", inner)}, provider.Chat) + if cs[0].p.ID != "a" { + t.Fatalf("first: %v", ids(cs)) + } + s.restAfter(cs[0], 429, http.Header{}, rate) // rate limited with quota left: it sank + rested(cs[0].restKey()) // and its minute is up + } + for _, routing := range []string{provider.Ordered, "", provider.Weighted} { + t.Run("outer "+cmp.Or(routing, "smart"), func(t *testing.T) { + sinkA(t) + inner := provider.Group{ID: "inner", Routing: provider.Ordered, Sink: true} + outer := provider.Group{ID: "outer", Routing: routing} + // the inner group first, then a model outer names itself: + // a goes behind b, next to it (where outer's routing puts + // the inner group is outer's: by weight it goes round) + out, pl := s.planGroup(outer, []provider.Member{mem("a", inner), mem("b", inner), mem("x")}, provider.Chat) + got := ids(out) + if b := slices.Index(got, "b"); b < 0 || b+1 >= len(got) || got[b+1] != "a" || (routing == provider.Ordered && !slices.Equal(got, []string{"b", "a", "x"})) { + t.Fatalf("the inner group's own Sink: order %v, want b then a", got) + } + for i, w := range pl.order { + if w.Provider != got[i] || (w.Sunk != nil) != (got[i] == "a") { + t.Fatalf("trace %+v for order %v", pl.order, got) + } + } + // its Sink off: the routing's order + inner.Sink = false + got = ids(first(s.planGroup(outer, []provider.Member{mem("a", inner), mem("b", inner), mem("x")}, provider.Chat))) + if a := slices.Index(got, "a"); a < 0 || a+1 >= len(got) || got[a+1] != "b" { + t.Fatalf("Sink off: order %v, want a then b", got) + } + }) + } + t.Run("deeper", func(t *testing.T) { + sinkA(t) + // outer → mid (Sink on) → inner (Sink off): mid orders its whole, + // inner's keys and its own c, and outer's own y stays last + mid := provider.Group{ID: "mid", Routing: provider.Ordered, Sink: true} + inner := provider.Group{ID: "inner", Routing: provider.Ordered} + outer := provider.Group{ID: "outer", Routing: provider.Ordered} + ms := []provider.Member{mem("a", mid, inner), mem("b", mid, inner), mem("c", mid), mem("y")} + if out, _ := s.planGroup(outer, ms, provider.Chat); !slices.Equal(ids(out), []string{"b", "c", "a", "y"}) { + t.Fatalf("mid's Sink: order %v, want [b c a y]", ids(out)) + } + // inner's Sink on, mid's off: a goes behind b only + mid.Sink, inner.Sink = false, true + ms = []provider.Member{mem("a", mid, inner), mem("b", mid, inner), mem("c", mid), mem("y")} + if out, _ := s.planGroup(outer, ms, provider.Chat); !slices.Equal(ids(out), []string{"b", "a", "c", "y"}) { + t.Fatalf("inner's Sink: order %v, want [b a c y]", ids(out)) + } + }) + t.Run("outer only", func(t *testing.T) { + sinkA(t) + // the outer group's Sink still orders the whole, as before + inner := provider.Group{ID: "inner", Routing: provider.Ordered} + outer := provider.Group{ID: "outer", Routing: provider.Ordered, Sink: true} + if out, _ := s.planGroup(outer, []provider.Member{mem("a", inner), mem("b", inner), mem("x")}, provider.Chat); !slices.Equal(ids(out), []string{"b", "x", "a"}) { + t.Fatalf("the outer group's Sink: order %v, want [b x a]", ids(out)) + } + }) +} diff --git a/internal/provider/group.go b/internal/provider/group.go index 786e0cfe3..f9065e3f3 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -16,9 +16,9 @@ package provider // // A group's member may be another group ("group/"): to the group it is // one member, which a rule can put first like a model; its models are its -// own group's, ordered by its own routing and rules. A group can't be in -// itself, however deep: SaveGroup refuses the loop, and one written into -// providers.json by hand is cut where it closes. +// own group's, ordered by its own routing, rules and Sink. A group can't +// be in itself, however deep: SaveGroup refuses the loop, and one written +// into providers.json by hand is cut where it closes. import ( "errors"