diff --git a/docs/reference.md b/docs/reference.md index 9b5e7ed31..fb11ad71f 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1421,6 +1421,11 @@ each of these groups ordered by the share used. Claude account not known goes first once, as in Smart; another unknown account counts as a fresh week. +The routings besides Smart are the built-in plugin `rotation` (Routing +strategies in Plugins › Built-in). It stays on while a provider or group is +routed by one of them. Turned off, the pickers offer Smart alone, and a +provider or group still set to one of them is tried in its listed order. + **Make first** sets the accounts' order. How much that order counts depends on the routing: diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ff61450d1..d2f1495e4 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -31,7 +31,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | | 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. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). 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). 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) | +| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight`. `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). 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 (`routes.Round` over `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`, `routes.MoveRound`). 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/routes/`](../../internal/routes), [`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. 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) | diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index dd59d4c30..97a0283cd 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -25,7 +25,7 @@ the plugin host) are a different thing; see | Ctx | What `Apply` gets: `OnDispose(f)`, `Contribute(slot, key)`, `Provide(name, v)` (withdrawn when it goes), `Service(name)`, and its composed `Config`. Disposers run in reverse, each one's panic logged and the rest still run. | [`pluginrt.go`](../../internal/pluginrt/pluginrt.go) | | plugins.yml | `appdir.Config()/plugins.yml`: `preset` (`essentials` or `all`) and `plugins`, rows of `{id, enabled, config}` holding only what the user set. | [`config.go`](../../internal/pluginrt/config.go) | | Settings schema | `SchemaOf(Settings)` makes a JSON Schema object of the struct, in its fields' order (`x-order`): each exported field with a json name is a setting, of `bool`, an int, `float64` or `string`, with tags `title` (English; the window translates it), `description`, `enum` (comma separated) and `min`/`max`. Its values are the defaults. A field a form can't draw, or a tag that doesn't parse, panics at `Register`. `Schema.Validate` takes a value only as the schema allows it (a JSON float64 or a YAML int for an integer); `SetConfig(id, config)` writes the user's row through it, and `Compose` leaves out a value edited into plugins.yml by hand that it doesn't allow, so the default stands. | [`schema.go`](../../internal/pluginrt/schema.go), [`config.go`](../../internal/pluginrt/config.go) | -| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing page, Essential and in use while the user has a routing group, since the page is where groups are made and changed. `usage` (P2), the Usage page, is Essential too, with no `InUse`: what it shows the gateway counts anyway, and the tray panel's Usage tab still shows the allowances with it off. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) | +| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing page, Essential and in use while the user has a routing group, since the page is where groups are made and changed. `rotation` (P3), the routings besides Smart, is Essential and in use while a provider or group is routed by one of them. `usage` (P2), the Usage page, is Essential too, with no `InUse`: what it shows the gateway counts anyway, and the tray panel's Usage tab still shows the allowances with it off. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) | The boundary is checked by `TestPluginsImportOnlyCore`: no package outside `plugins/` imports one (but `main.go`, through `plugins/all`), a plugin never @@ -170,8 +170,27 @@ plugin off the gateway does no observing work. | `internal/otlp` | The OTLP/HTTP exporter, moved whole out of `internal/usage`: `otlp.New()` is an `Exporter`, a `usage.Observer`. Its Begin leaves a local agent's own turn to the agent's transcript when session tracing reads it, and takes a W3C `traceparent` as the parent. Settings are read on each call, as before. | [`otlp/`](../../internal/otlp) | | `plugins/otel` | Requires `window`, `settings` and `gateway`. Apply registers `otlp.New()` and disposes of it when turned off. `InUse` is 1 while `settings.OTelExport` says to send (settings.json or `MAGPIE_OTEL_*`), so a user who exports only through the environment keeps it on under Essentials. | [`otel.go`](../../plugins/otel/otel.go) | -The other points follow in this order: router strategy (groups, rotation), -middleware (the JS gateway middleware becomes one consumer of it, with its +## Gateway extension points (P3): router strategy + +The router strategy point says the order a pool of routes is tried in: a +provider's accounts or keys, or the heads of a group's members. The gateway +still lists the pool, and keeps rests, affinity, rules, pins and the walk +over the order itself; a strategy only orders. Smart, the default, stays in +the core. The five other routings are the built-in plugin `rotation`'s. + +| Part | What it does | Source | +| --- | --- | --- | +| `routes.Strategy` | `Order(pool, seats) []int`: a permutation of the seats' indexes. `pool` is a provider's id or `group/`, for a strategy that keeps a round per pool. `Exact` keeps the order as given; otherwise a provider's API keys that fit the request better go first, each in its order. `ByUse` puts each seat's recent tokens in the trace. | [`routes.go`](../../internal/routes/routes.go) | +| `routes.Seat` | What a strategy weighs, read by `weighRouted` under the routing state's lock: its rest key, whether it is an account, whether its allowance is known or it learns it as it answers, the share used, when its windows renew, its weekly pace, its key's weight, whether it rests now and its tokens of the last hours. | [`routes.go`](../../internal/routes/routes.go), [`routing.go`](../../internal/gateway/routing.go) | +| `Register`, `Find`, `Apply` | `Register(routing, s)` serves a routing until its remove; registering again stacks, and the last one serves. `Find("")` is `Smart` always. `Apply` fails open: a strategy that panics, or answers what isn't a permutation, leaves the pool in its listed order, logged. Every route is still tried. | [`routes.go`](../../internal/routes/routes.go) | +| Strategies | `Smart` (core), and `Ordered`, `Rotate`, `LeastUsed`, `Pace` and `Weighted` in `routes.Builtin`. `Rotate` keeps a turn per pool and `Weighted` a smooth weighted round (`Round`, `MoveRound`), both moved out of the gateway; `Forget` clears them. | [`strategies.go`](../../internal/routes/strategies.go), [`round.go`](../../internal/routes/round.go) | +| Off | A routing no strategy serves is its listed order. `routingOf` in the gateway reads it as `order` wherever the core asks about a routing (a turn's mark, `sinks`, a rotate group's sessions, a group's heads), so nothing of the routing is left half on. | [`routing.go`](../../internal/gateway/routing.go) | +| `plugins/rotation` | Requires `providers` and `gateway`, `Essential`. Apply registers every `routes.Builtin` and removes them when turned off. `InUse` counts the providers and groups providers.json routes by one of them (`provider.Routings`, the file alone, not the catalog); an unreadable providers.json is an error, so it stays on. The gateway's `KeepFresh` watches providers.json too, so a routing set from the CLI or the TUI turns it on within 2s. Off, the window's routing pickers (the provider editor, the Routing page's pools and groups) offer Smart alone: their options are marked `data-feature="rotation"` (`routingSegs`). | [`rotation.go`](../../plugins/rotation/rotation.go), [`provider.go`](../../internal/provider/provider.go), [`app.js`](../../internal/gui/assets/app.js) | + +Groups are next on this point: `planGroup` behind it, the `groups` plugin +serving it. + +The other points follow in this order: middleware (the JS gateway middleware becomes one consumer of it, with its place, API and fail-open policy unchanged; redaction fails closed), then tool (search) and budget. @@ -210,7 +229,8 @@ remembering its layer (`Source`): is in use. - **The window**: see [GUI app shell](gui-shell.md), "Built-in plugins". - **The gateway**: the process serving it runs `pluginrt.KeepFresh` (every - 2s), which refreshes when plugins.yml or settings.json changes, so a + 2s), which refreshes when plugins.yml, settings.json or providers.json + changes, so a plugin turned on or off in the window or by `magpie plugin builtin` comes and goes in the gateway without a restart, and a headless `magpie serve` follows the file too. @@ -234,7 +254,10 @@ remembering its layer (`Source`): leave the window. The gateway, the TUI and the CLI serve the same either way, and nothing the user made is deleted. A gateway plugin's off is the gateway's: with `otel` off nothing is exported and no reply is kept - whole for it. An observer can't fail a request; it only reads. Davsync doesn't carry + whole for it. An observer can't fail a request; it only reads. With + `rotation` off a pool set to one of its routings is tried in its listed + order; a strategy that fails falls back to the same order, never to an + error. Davsync doesn't carry plugins.yml. ## Verification @@ -258,5 +281,12 @@ remembering its layer (`Source`): `go test ./internal/otlp/ ./plugins/otel/` (`TestOnExportsOffSendsNothing`, `TestInUseByEnvironment`) and `go test ./internal/pluginrt/ -run TestKeepFreshFollowsPluginsYml`. +- P3 router strategy: `go test ./internal/routes/ ./plugins/rotation/` + (`TestRegisterStacks`, `TestApplyFailsOpen`, the strategies' orders, + `TestOnServesOffDoesNot`, `TestInUse`), `go test ./internal/gateway/` + whole (its `TestMain` registers the strategies, so every routing test is + the parity run with the plugin on; `TestRotationOnAndOff` turns it off), + and `routing-save.test.cjs` (Smart alone with it off, every width and + engine). - By hand, under a sandbox HOME: `magpie plugin builtin`, `magpie plugin builtin on groups`, `magpie plugin dump`, and a plugins.yml broken by hand. diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index a92e7e9b5..c00641da9 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -341,7 +341,7 @@ func (s *Server) plan(p provider.Provider, model string, from provider.Protocol) cs, wg := weigh(q, cs, m, from) for i, c := range cs { w := weighed(c, q, wg, fallback, from) - w.Turn = i == 0 && (q.Routing == provider.Rotate || q.Routing == provider.Weighted) && len(cs) > 1 + w.Turn = i == 0 && goesRound(q.Routing) && len(cs) > 1 pl.order = append(pl.order, w) } pl.order = append(pl.order, asideOf(aside, q, fallback, from)...) @@ -433,7 +433,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. } return cs } - if g.Routing != provider.Ordered { + if routingOf(g.Routing) != provider.Ordered { // what the group weighs: each of its models' keys or accounts, // and each group in it as one — planned by its own routing, put // where the one it would try first is, the rest of it after @@ -445,7 +445,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. } // a group routed by weight weighs its members, each whole: a // model's keys in its provider's order, a group in it in its own - byWeight := g.Routing == provider.Weighted + byWeight := routingOf(g.Routing) == provider.Weighted var units []unit var heads []candidate at := map[string][]int{} // a head's seat → its units, in turn @@ -480,7 +480,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. var order []Weighed for k, c := range cs { w := weighed(c, m.Provider, wg, false, from) - w.Turn = k == 0 && (m.Provider.Routing == provider.Rotate || m.Provider.Routing == provider.Weighted) && len(cs) > 1 + w.Turn = k == 0 && goesRound(m.Provider.Routing) && len(cs) > 1 w.Via = m.Groups() order = append(order, w) } @@ -534,7 +534,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. w := weighed(c, u.m.Provider, wg, false, from) w.Routing, w.Via = g.Routing, u.m.Groups() w.Sunk = nil // weighed as the group's, whose own Sink tells - w.Turn = i == 0 && g.Routing == provider.Rotate && len(weighedHeads) > 1 + w.Turn = i == 0 && routingOf(g.Routing) == provider.Rotate && len(weighedHeads) > 1 pl.order = append(pl.order, w) out = append(out, c) } @@ -562,7 +562,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. cs, wg := weigh(m.Provider, keys(m), m.Model, from) for k, c := range cs { w := weighed(c, m.Provider, wg, false, from) - w.Turn = k == 0 && (m.Provider.Routing == provider.Rotate || m.Provider.Routing == provider.Weighted) && len(cs) > 1 + w.Turn = k == 0 && goesRound(m.Provider.Routing) && len(cs) > 1 w.Via = m.Groups() pl.order = append(pl.order, w) } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 680843093..d44b55dbc 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -479,7 +479,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error { defer stopObservers() freshCtx, stopFresh := context.WithCancel(ctx) defer stopFresh() - go pluginrt.KeepFresh(freshCtx, 2*time.Second, settings.Path()) + go pluginrt.KeepFresh(freshCtx, 2*time.Second, settings.Path(), provider.Path()) srv := &http.Server{Handler: lanGuard(s.Handler()), ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 5 * time.Minute} // the magpie serving the gateway, and only it, keeps the saved accounts // signed in, so two never refresh one sign-in at once @@ -1842,14 +1842,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // a conversation's affinity is to one model: another's cache is its // own, and an agent's side requests (a title, a summary) to a smaller // model leave the conversation where it is - scope, mode, rotate := p.ID+"/"+model, p.Affinity, p.Routing == provider.Rotate + scope, mode, rotate := p.ID+"/"+model, p.Affinity, routingOf(p.Routing) == provider.Rotate leadScope := scope // where the lead of a subagent is kept if isGroup { // a routing group: every member's keys or accounts weighed together cands, pl = s.planGroup(g, ms, from) group = groupRef(g, ms) group.Paused = paused - scope, mode, rotate = provider.GroupPrefix+g.ID, g.Affinity, g.Routing == provider.Rotate + scope, mode, rotate = provider.GroupPrefix+g.ID, g.Affinity, routingOf(g.Routing) == provider.Rotate leadScope = scope if words != "" { // a subagent a rule sends elsewhere mustn't take its agent's diff --git a/internal/gateway/group_test.go b/internal/gateway/group_test.go index 6387531bc..27e790b00 100644 --- a/internal/gateway/group_test.go +++ b/internal/gateway/group_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" ) // keyed is a vendor that says which key each request came with, and @@ -73,11 +74,9 @@ func fresh(t *testing.T) { // rather than a turn on, or with a failure already counted. func forgetRouting() { routed.Lock() - routed.turn, routed.used, routed.failures = map[string]int{}, map[string]tokenUse{}, map[string]int{} + routed.used, routed.failures = map[string]tokenUse{}, map[string]int{} routed.Unlock() - wrr.Lock() - wrr.m = map[string]*wrrRound{} - wrr.Unlock() + routes.Forget() } // setHome makes dir the home, where Windows (USERPROFILE) finds it too. @@ -324,9 +323,7 @@ func TestAffinity(t *testing.T) { serveOn(t, "aff", "k1", []string{"m"}, v, "k2") provider.SetRouting("aff", c.routing) provider.SetAffinity("aff", c.affinity) - routed.Lock() - delete(routed.turn, "aff") - routed.Unlock() + routes.Forget("aff") s := New() postAs(t, s, "s1", first) postAs(t, s, "s1", c.body) @@ -470,9 +467,7 @@ func TestRotateSpreadsSessions(t *testing.T) { if err := provider.SaveGroup(provider.Group{Name: "Pair", Members: []string{"ga/m1", "gb/m2"}, Routing: provider.Rotate, Affinity: provider.AffinitySession}); err != nil { t.Fatal(err) } - routed.Lock() - delete(routed.turn, provider.GroupPrefix+"pair") - routed.Unlock() + routes.Forget(provider.GroupPrefix + "pair") return a, b, New() } // which of the two the request went to diff --git a/internal/gateway/main_test.go b/internal/gateway/main_test.go index 86c7d40f0..bac27a827 100644 --- a/internal/gateway/main_test.go +++ b/internal/gateway/main_test.go @@ -9,6 +9,7 @@ import ( "github.com/yetone/magpie/internal/agentenv" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" "github.com/yetone/magpie/internal/testenv" ) @@ -17,6 +18,7 @@ import ( const standInsEnv = "MAGPIE_GATEWAY_TEST_STAND_INS" func TestMain(m *testing.M) { + serveRotation() code, err := isolatedTests(m) if err != nil { fmt.Fprintln(os.Stderr, err) @@ -114,3 +116,22 @@ func TestRunsAsAnIsolatedTestBinary(t *testing.T) { t.Fatalf("TestMain left %s unset", testenv.Marker) } } + +// rotation is what serveRotation registered: the routings plugins/rotation +// serves, which the gateway's tests route by as a user with it on does. +var rotation []func() + +func serveRotation() { + for name, s := range routes.Builtin { + rotation = append(rotation, routes.Register(name, s)) + } +} + +// withoutRotation takes them away for t, as plugins/rotation off does. +func withoutRotation(t *testing.T) { + for _, remove := range rotation { + remove() + } + rotation = nil + t.Cleanup(serveRotation) +} diff --git a/internal/gateway/rotate_burst_test.go b/internal/gateway/rotate_burst_test.go index abae7db33..fe69c6e2d 100644 --- a/internal/gateway/rotate_burst_test.go +++ b/internal/gateway/rotate_burst_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" ) // held answers once `want` requests are in at once (or after a while), so @@ -53,9 +54,7 @@ func TestRotateSpreadsABurstOfNewConversations(t *testing.T) { if err := provider.SetRouting("ag", provider.Rotate); err != nil { t.Fatal(err) } - routed.Lock() - delete(routed.turn, "ag") - routed.Unlock() + routes.Forget("ag") s := New() // a conversation from before, answered and held on one key if code, out := postAs(t, s, "", `{"model":"ag/m1","messages":[{"role":"user","content":"earlier"}]}`); code != 200 { diff --git a/internal/gateway/rotation_off_test.go b/internal/gateway/rotation_off_test.go new file mode 100644 index 000000000..a5435b0d0 --- /dev/null +++ b/internal/gateway/rotation_off_test.go @@ -0,0 +1,49 @@ +package gateway + +import ( + "slices" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" +) + +// The router strategy point with plugins/rotation on and off: a provider +// in turn sends each new conversation one key further along; with the +// plugin off, no strategy serves "rotate", so its keys are tried in their +// listed order — every conversation goes to the first — and no request is +// marked as one's turn. Smart is the core's and serves either way. +func TestRotationOnAndOff(t *testing.T) { + firsts := func(routing string) ([]string, bool) { + t.Helper() + fresh(t) + v := &keyed{} + serveOn(t, "ra", "k1", []string{"m"}, v, "k2", "k3") + if err := provider.SetRouting("ra", routing); err != nil { + t.Fatal(err) + } + routes.Forget("ra") + s := New() + turn := false + for _, sess := range []string{"s1", "s2", "s3"} { + if code, body := postAs(t, s, sess, `{"model":"ra/m","messages":[{"role":"user","content":"hi `+sess+`"}]}`); code != 200 { + t.Fatalf("%s: %d %s", sess, code, body) + } + for _, w := range s.trace.routes[len(s.trace.routes)-1].Order { + turn = turn || w.Turn + } + } + return v.tried, turn + } + if got, turn := firsts(provider.Rotate); !slices.Equal(got, []string{"k1", "k2", "k3"}) || !turn { + t.Fatalf("on, in turn: %v, turn marked %v", got, turn) + } + + withoutRotation(t) + if got, turn := firsts(provider.Rotate); !slices.Equal(got, []string{"k1", "k1", "k1"}) || turn { + t.Fatalf("off, in turn: %v (want the listed order), turn marked %v", got, turn) + } + if got, _ := firsts(""); len(got) != 3 { + t.Fatalf("off, Smart: %v", got) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 49553a7b5..20b08ba89 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -25,6 +25,7 @@ import ( "time" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" "github.com/yetone/magpie/internal/usage" ) @@ -34,10 +35,9 @@ const usageHalfLife = time.Hour var routed = struct { sync.Mutex - turn map[string]int // provider → requests routed in turn used map[string]tokenUse // candidate restKey → tokens it served failures map[string]int // candidate restKey → failures since it last answered -}{turn: map[string]int{}, used: map[string]tokenUse{}, failures: map[string]int{}} +}{used: map[string]tokenUse{}, failures: map[string]int{}} type tokenUse struct { n float64 @@ -975,11 +975,10 @@ func retryAfter(h http.Header, now time.Time) time.Duration { var allowances = provider.Allowances // Shares of an allowance past which an account is kept for when the others -// can't take a request: low, and all but used up — where the agent signed -// in to it is signed in to another, too (provider.SpentShare). +// can't take a request (routes.LowShare, routes.UsedShare). const ( - lowShare = 90 - usedShare = provider.SpentShare + lowShare = routes.LowShare + usedShare = routes.UsedShare ) // route orders one provider's candidates as its routing says. @@ -1043,6 +1042,26 @@ func weigh(p provider.Provider, cs []candidate, model string, from provider.Prot return cs, wg } +// routingOf is how a pool routed so is routed now. A routing no strategy +// serves (routes.Find: plugins/rotation off) is its listed order, In +// order's, and so is what the core does for one besides ordering it: a +// turn's mark, spreading a group's sessions, sending the rate limited back +// and a group's heads. +func routingOf(routing string) string { + if routing == "" || routing == provider.Manual || routes.Served(routing) { + return routing + } + return provider.Ordered +} + +// goesRound: routed so, a pool goes round by itself (in turn, by weight), +// so its first is marked as the turn's and the rate limited aren't sent +// back. +func goesRound(routing string) bool { + r := routingOf(routing) + return r == provider.Rotate || r == provider.Weighted +} + // weighRouted is weigh by the routing alone. func weighRouted(p provider.Provider, cs []candidate, model string, from provider.Protocol) ([]candidate, weighing) { var wg weighing @@ -1081,205 +1100,37 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide if len(cs) < 2 { return cs, wg } - lefts := wg.lefts - shareOf := func(c candidate) float64 { return lefts[c.allowanceKey()].used } - switch p.Routing { - case "": - // of those with quota to spare, the one whose allowance renews - // soonest, since what it has left is lost then, while one renewing - // later keeps: the biggest window decides — the week, not the five - // hours in it — and the next one only when that renews in the - // same hour. An account with no week (Claude Enterprise's five - // hours alone) goes by its five hours, so ahead of every week - // but one renewing sooner; a window not started renews its whole - // span from now (#576). A Codex account that spends a reset about - // to run out by itself (auto-use on, its windows used) renews when - // that is spent, if sooner: what it has left is lost there just the - // same (#718). Only holding one, or one that runs out after the - // week renews, changes nothing. Those alike stay in their order, keeping the vendor's - // prompt cache warm. Past that, whichever has the most left, and - // one all but used up only when nothing else can take it. Only the - // windows that count the model do: Opus's own weekly allowance - // being used up leaves Sonnet alone. - var fine, low, spent []candidate - for _, c := range cs { - switch v := shareOf(c); { - case v >= usedShare: - spent = append(spent, c) - case v >= lowShare: - low = append(low, c) - default: - fine = append(fine, c) - } - } - // one not known that tells what it has left as it answers goes - // first, once: else, kept after those known, it would never answer - // and never be known (Anthropic's usage endpoint can turn - // magpie away for hours) - sort.SliceStable(fine, func(i, j int) bool { - if li, lj := learns(fine[i], lefts), learns(fine[j], lefts); li != lj { - return li - } - ri, rj := lefts[fine[i].allowanceKey()].soon, lefts[fine[j].allowanceKey()].soon - for k := 0; k < len(ri) || k < len(rj); k++ { - var a, b time.Time // to the hour, so a few minutes don't reorder - if k < len(ri) { - a = ri[k].Truncate(time.Hour) - } - if k < len(rj) { - b = rj[k].Truncate(time.Hour) - } - switch { - case a.Equal(b): - continue - case a.IsZero() || b.IsZero(): // not known: after those known - return b.IsZero() - } - return a.Before(b) - } - return false - }) - for _, l := range [][]candidate{low, spent} { - sort.SliceStable(l, func(i, j int) bool { - return shareOf(l[i]) < shareOf(l[j]) - }) - } - cs = append(append(fine, low...), spent...) - case provider.Ordered: + // the routing's strategy orders them (internal/routes): Smart, or one + // a plugin registered; one not registered leaves them in their order + st, ok := routes.Find(p.Routing) + if !ok { return cs, wg - case provider.Rotate: - routed.Lock() - n := routed.turn[p.ID] % len(cs) - routed.turn[p.ID]++ - routed.Unlock() - cs = append(append([]candidate{}, cs[n:]...), cs[:n]...) - case provider.Weighted: - cs = weightedFirst(p.ID, cs) - case provider.LeastUsed: - // a subscription, or a key that reads its own windows, by the - // share of its allowance used, as the vendor says; then, and for - // other keys, by what magpie sent it lately - routed.Lock() - tokens := make([]float64, len(cs)) + } + seats := make([]routes.Seat, len(cs)) + routed.Lock() + for i, c := range cs { + l, known := wg.lefts[c.allowanceKey()] + pace := l.pace + if !known && c.p.Account != nil { + pace = provider.FreshPace + } + seats[i] = routes.Seat{Key: c.rest, Account: c.p.Account != nil, Known: known, Learns: learns(c, wg.lefts), + Used: l.used, Soon: l.soon, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now)} + } + routed.Unlock() + if st.ByUse { wg.tokens = map[string]float64{} for i, c := range cs { - tokens[i] = routed.used[c.restKey()].now(now) - wg.tokens[c.rest] = tokens[i] + wg.tokens[c.rest] = seats[i].Tokens } - routed.Unlock() - idx := make([]int, len(cs)) - for i := range idx { - idx[i] = i - } - sort.SliceStable(idx, func(a, b int) bool { - ca, cb := cs[idx[a]], cs[idx[b]] - if sa, sb := shareOf(ca), shareOf(cb); sa != sb { - return sa < sb - } - return tokens[idx[a]] < tokens[idx[b]] - }) - out := make([]candidate, len(cs)) - for i, j := range idx { - out[i] = cs[j] - } - cs = out - case provider.Pace: - // a subscription by what it has left of its week per hour until - // that renews, the most first: it has the most to lose at the - // reset, where the most left alone (least used) sends a fresh - // account ahead of one with 80% left and an hour to go, and the - // soonest reset alone (smart) sends one with 3% left and an hour - // to go ahead of one with 90% and two. The tiers are Smart's: one - // at 90% or more of any window that counts the model — the five - // hours too, a rate cap it would be sent into before its - // allowance was read again — waits until the others can't answer, - // one all but used up until nothing else can; each tier by the - // share used. Among the rest, one not known that tells what it - // has left as it answers goes first while it isn't, as in Smart, - // else it would never be known; then the pace, those alike within - // a tenth by what magpie sent them lately, then in their order, - // keeping the vendor's prompt cache warm. An account not known - // counts as a whole week ahead of it; a key has no week, unless it - // reads its own windows (a sub2api key's limits). A Codex - // account that spends a reset about to run out by itself goes by - // the hours until then when that is sooner (Allowance.Pace, #717). - paceOf := func(c candidate) float64 { - if l, ok := lefts[c.allowanceKey()]; ok { - return l.pace - } - if c.p.Account != nil { - return provider.FreshPace - } - return 0 - } - tier := func(share float64) int { - switch { - case share >= usedShare: - return 2 - case share >= lowShare: - return 1 - } - return 0 - } - // the bands of pace alike within a tenth, the highest first: drawn - // before sorting, from each band's highest down, so that sorting - // by them is consistent — "within a tenth of each other" alone is - // not, three paces a twelfth apart each going round in a circle. - // Drawn among those the pace orders alone — one running low - // would otherwise set a band's top and part two alike behind it - var byPace []int - for i, c := range cs { - if tier(shareOf(c)) == 0 && !learns(c, lefts) { - byPace = append(byPace, i) - } - } - sort.SliceStable(byPace, func(a, b int) bool { return paceOf(cs[byPace[a]]) > paceOf(cs[byPace[b]]) }) - band, top := make([]int, len(cs)), 0.0 - for k, i := range byPace { - if p := paceOf(cs[i]); k == 0 || p < 0.9*top { - top = p - if k > 0 { - band[i] = band[byPace[k-1]] + 1 - continue - } - } else { - band[i] = band[byPace[k-1]] - } - } - routed.Lock() - tokens := make([]float64, len(cs)) - wg.tokens = map[string]float64{} - for i, c := range cs { - tokens[i] = routed.used[c.restKey()].now(now) - wg.tokens[c.rest] = tokens[i] - } - routed.Unlock() - idx := make([]int, len(cs)) - for i := range idx { - idx[i] = i - } - sort.SliceStable(idx, func(a, b int) bool { - ca, cb := cs[idx[a]], cs[idx[b]] - sa, sb := shareOf(ca), shareOf(cb) - if ta, tb := tier(sa), tier(sb); ta != tb { - return ta < tb - } else if ta > 0 { - if sa != sb { - return sa < sb - } - } else if la, lb := learns(ca, lefts), learns(cb, lefts); la != lb { - return la - } else if band[idx[a]] != band[idx[b]] { - return band[idx[a]] < band[idx[b]] - } - return tokens[idx[a]] < tokens[idx[b]] - }) - out := make([]candidate, len(cs)) - for i, j := range idx { - out[i] = cs[j] - } - cs = out - default: + } + order := routes.Apply(st, p.ID, seats) + out := make([]candidate, 0, len(cs)) + for _, i := range order { + out = append(out, cs[i]) + } + cs = out + if st.Exact { return cs, wg } if p.Account == nil { diff --git a/internal/gateway/sink.go b/internal/gateway/sink.go index 7bbc5c2aa..ff9e5d262 100644 --- a/internal/gateway/sink.go +++ b/internal/gateway/sink.go @@ -57,7 +57,7 @@ func sunkAt(c candidate) (sinking, bool) { // in turn and by weight go round already, and a manual group has one // member. func sinks(on bool, routing string) bool { - return on && routing != provider.Rotate && routing != provider.Weighted && routing != provider.Manual + return on && !goesRound(routing) && routing != provider.Manual } // sinkOrder is the order of n candidates with those that sank moved diff --git a/internal/gateway/weighted.go b/internal/gateway/weighted.go index 7b259b79d..8c6770e72 100644 --- a/internal/gateway/weighted.go +++ b/internal/gateway/weighted.go @@ -17,24 +17,10 @@ package gateway // it is one member, planned by its own. import ( - "sync" - "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" ) -// wrr is each weighted provider's round: every key's current weight, and -// the total the last pick was charged. -var wrr = struct { - sync.Mutex - m map[string]*wrrRound // provider id → its round -}{m: map[string]*wrrRound{}} - -type wrrRound struct { - cur map[string]int // candidate rest, or a group's member → current weight - total int - last string // the one the last pick was charged to -} - // keyWeight is a candidate's weight: its key's, 1 when none. func keyWeight(c candidate) int { return max(c.p.KeyWeight, 1) } @@ -50,94 +36,24 @@ func resting(c candidate) bool { return false } -// weightedFirst puts first the key the provider id's round picks now, the -// others after it in their order, for failover. -func weightedFirst(id string, cs []candidate) []candidate { - keys, weights, rests := make([]string, len(cs)), make([]int, len(cs)), make([]bool, len(cs)) - for i, c := range cs { - keys[i], weights[i], rests[i] = c.rest, keyWeight(c), resting(c) - } - best := wrrPick(id, keys, weights, rests) - if best <= 0 { - return cs // first already, or all resting: restLast orders them - } - return append(append([]candidate{cs[best]}, cs[:best]...), cs[best+1:]...) -} - -// wrrPick is which of keys round id picks now, each weighing its weight, -// those resting left out of the round; -1 when every one rests. The -// pick is charged the round's total. -func wrrPick(id string, keys []string, weights []int, rests []bool) int { - wrr.Lock() - defer wrr.Unlock() - r := wrr.m[id] - if r == nil { - r = &wrrRound{cur: map[string]int{}} - wrr.m[id] = r - } - // keys no longer on are dropped from the round - on := make(map[string]bool, len(keys)) - for _, k := range keys { - on[k] = true - } - for k := range r.cur { - if !on[k] { - delete(r.cur, k) - } - } - best, total := -1, 0 - for i, k := range keys { - if rests[i] { - continue - } - r.cur[k] += weights[i] - total += weights[i] - if best < 0 || r.cur[k] > r.cur[keys[best]] { - best = i - } - } - if best < 0 { - return -1 - } - r.cur[keys[best]] -= total - r.total, r.last = total, keys[best] - return best -} - // weightedKept moves the pick of picked's round to kept, when affinity // keeps a conversation with kept, another key of the same weighted // provider, or another member of a group routed by weight that both are // in: the round counts the requests each key, and each member, really // took. func weightedKept(picked, kept candidate) { - if picked.p.Routing == provider.Weighted && picked.p.ID == kept.p.ID && picked.rest != kept.rest { - wrrMove(picked.p.ID, picked.rest, kept.rest) + if routingOf(picked.p.Routing) == provider.Weighted && picked.p.ID == kept.p.ID && picked.rest != kept.rest { + routes.MoveRound(picked.p.ID, picked.rest, kept.rest) } for _, s := range picked.seats { for _, t := range kept.seats { if s.round == t.round && s.member != t.member { - wrrMove(s.round, s.member, t.member) + routes.MoveRound(s.round, s.member, t.member) } } } } -// wrrMove charges round id's pick to kept rather than picked. -func wrrMove(id, picked, kept string) { - wrr.Lock() - defer wrr.Unlock() - r := wrr.m[id] - if r == nil || r.last != picked { - return - } - if _, ok := r.cur[kept]; !ok { - return - } - r.cur[picked] += r.total - r.cur[kept] -= r.total - r.last = kept -} - // wrrSeat is a candidate's place in the round of a group routed by // weight it is in: the round (the group's ref) and the member it is of. type wrrSeat struct{ round, member string } @@ -152,15 +68,5 @@ func weightedUnits(g provider.Group, members []string, heads []candidate) []int for i, m := range members { weights[i], rests[i] = g.MemberWeight(m), resting(heads[i]) } - order := make([]int, 0, len(members)) - best := wrrPick(provider.GroupPrefix+g.ID, members, weights, rests) - if best > 0 { - order = append(order, best) - } - for i := range members { - if i != best || best <= 0 { - order = append(order, i) - } - } - return order + return routes.First(routes.Round(provider.GroupPrefix+g.ID, members, weights, rests), len(members)) } diff --git a/internal/gateway/weighted_group_test.go b/internal/gateway/weighted_group_test.go index 6959d5a17..753957b59 100644 --- a/internal/gateway/weighted_group_test.go +++ b/internal/gateway/weighted_group_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" ) // A group routed by weight (#1910, DD on Discord): members weighing 3, 1 @@ -33,9 +34,7 @@ func TestWeightedGroup(t *testing.T) { {ID: "group/wsub", Path: []string{"group/wsub", "wd/m"}, Via: []provider.Group{sub}, Provider: d, Model: "m"}, } t.Cleanup(func() { - wrr.Lock() - delete(wrr.m, provider.GroupPrefix+g.ID) - wrr.Unlock() + routes.Forget(provider.GroupPrefix + g.ID) }) unitOf := map[string]string{"wa": "a", "wb": "b", "wc": "sub", "wd": "sub"} plan := func() []candidate { @@ -98,9 +97,7 @@ func TestWeightedGroup(t *testing.T) { if cs := plan(); cs[len(cs)-1].p.ID != "wa" { t.Fatalf("the resting member isn't last: %s", restsOf(cs)) } - wrr.Lock() - delete(wrr.m, provider.GroupPrefix+g.ID) - wrr.Unlock() + routes.Forget(provider.GroupPrefix + g.ID) if got := counts(5*20, nil); got["a"] != 0 || got["b"] != 20 || got["sub"] != 80 { t.Fatalf("with wa resting, 1:4 over 100: %v", got) } @@ -108,9 +105,7 @@ func TestWeightedGroup(t *testing.T) { // a conversation kept on wb each round of eight: the round counts it // against wb - wrr.Lock() - delete(wrr.m, provider.GroupPrefix+g.ID) - wrr.Unlock() + routes.Forget(provider.GroupPrefix + g.ID) got := counts(8*10, func(i int, cs []candidate) candidate { if i%8 != 0 || cs[0].p.ID == "wb" { return cs[0] diff --git a/internal/gateway/weighted_keys_test.go b/internal/gateway/weighted_keys_test.go index a66370572..07d5c352a 100644 --- a/internal/gateway/weighted_keys_test.go +++ b/internal/gateway/weighted_keys_test.go @@ -6,6 +6,7 @@ import ( "time" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" ) // Weighted routing (#841): a provider's keys weighing 3 and 1 take three @@ -18,9 +19,7 @@ func TestWeightedKeys(t *testing.T) { Routing: provider.Weighted} a, b, c := "wk#"+provider.KeyID("ka"), "wk#"+provider.KeyID("kb"), "wk#"+provider.KeyID("kc") t.Cleanup(func() { - wrr.Lock() - delete(wrr.m, p.ID) - wrr.Unlock() + routes.Forget(p.ID) restingUntil.Lock() delete(restingUntil.m, c) restingUntil.Unlock() @@ -78,9 +77,7 @@ func TestWeightedKeys(t *testing.T) { restingUntil.Lock() delete(restingUntil.m, c) restingUntil.Unlock() - wrr.Lock() - delete(wrr.m, p.ID) - wrr.Unlock() + routes.Forget(p.ID) got = map[string]int{} for i := range 8 * 10 { cs := route(p, perKey(p, "m", provider.Chat), "m", provider.Chat) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 5fea605cf..ed0f1fa71 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11020,6 +11020,16 @@ const ROUTINGS = [ ["pace", "Weekly pace", "Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours."], ["weight", "By weight", "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says."], ]; +// the routings besides Smart are the built-in plugin rotation's +// (plugins/rotation): off, their options leave the page, as anything marked +// data-feature does, and Smart is left — one in use keeps it on +const ROTATION = new Set(["order", "rotate", "usage", "pace", "weight"]); +// routingSegs: segs of routings, theirs marked as the plugin's +function routingSegs(items, current, onPick) { + const box = segs(items, current, onPick); + [...box.querySelectorAll(".opt")].forEach((b, i) => { if (ROTATION.has(items[i][0])) b.dataset.feature = "rotation"; }); + return box; +} // weight is a key's share: offered for a provider with keys only const routingsOf = (p) => p.account ? ROUTINGS.filter(([id]) => id !== "weight") : ROUTINGS; // as on the Routing page's list of these (routing/client.js AFF_OPTS) @@ -11081,7 +11091,7 @@ function renderRouting(p) { // each key's weight shows beside it while the routing is by weight for (const l of document.querySelectorAll(".accts.keys")) if (l.dataset.provider === p.id) l.classList.toggle("weighted", routingNow() === "weight"); }; - const rPick = segs(routingsOf(p).map(([id, name]) => [id, t(name)]), routingNow(), (routing) => { draft.routing = routing; drawRouting(); }); + const rPick = routingSegs(routingsOf(p).map(([id, name]) => [id, t(name)]), routingNow(), (routing) => { draft.routing = routing; drawRouting(); }); const rRow = el("div", "route-pick"); rRow.append(rPick, rUnsaved); const rWrap = el("div"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5a32f06e6..0eaaeaa06 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -760,6 +760,10 @@ const I18N = { "{n} warm-ups and check-ins on": "{n} 项预热和签到已开启", "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "把每个请求的追踪和指标发送到 OpenTelemetry 收集器,比如 Langfuse", "Sending to a collector": "正在发送到收集器", + "Routing strategies": "路由策略", + "The routings besides Smart: In order, In turn, Least used first, Weekly pace and By weight": "智能以外的路由方式:按顺序、轮流、用量少的优先、重置前用完和按权重", + "1 provider or group routed so": "1 个提供商或路由组在用", + "{n} providers and groups routed so": "{n} 个提供商和路由组在用", "In use, so it stays on": "正在使用,因此保持开启", "Gateway page": "网关页面", "The gateway's state and keys, how to connect a client, its models and recent calls": "网关的状态与密钥、客户端如何连接、它的模型和最近的调用", @@ -4325,6 +4329,10 @@ const I18N = { "{n} warm-ups and check-ins on": "{n} 項預熱和簽到已開啟", "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "把每個請求的追蹤和指標傳送到 OpenTelemetry 收集器,例如 Langfuse", "Sending to a collector": "正在傳送到收集器", + "Routing strategies": "路由策略", + "The routings besides Smart: In order, In turn, Least used first, Weekly pace and By weight": "智慧以外的路由方式:按順序、輪流、用量少的優先、重置前用完和按權重", + "1 provider or group routed so": "1 個提供商或路由組在用", + "{n} providers and groups routed so": "{n} 個提供商和路由組在用", "In use, so it stays on": "正在使用,因此保持開啟", "Gateway page": "閘道頁面", "The gateway's state and keys, how to connect a client, its models and recent calls": "閘道的狀態與金鑰、用戶端如何連線、它的模型和最近的呼叫", @@ -7862,6 +7870,10 @@ const I18N = { "{n} warm-ups and check-ins on": "{n} 件のウォームアップとチェックインがオン", "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "各リクエストのトレースとメトリクスを Langfuse などの OpenTelemetry コレクターに送ります", "Sending to a collector": "コレクターに送信中", + "Routing strategies": "ルーティング戦略", + "The routings besides Smart: In order, In turn, Least used first, Weekly pace and By weight": "スマート以外のルーティング:順番、交互、使用量が最少のものを優先、週ペース、重み付け", + "1 provider or group routed so": "1 個のプロバイダーまたはグループが使用中", + "{n} providers and groups routed so": "{n} 個のプロバイダーとグループが使用中", "In use, so it stays on": "使用中のためオンのままです", "Gateway page": "ゲートウェイページ", "The gateway's state and keys, how to connect a client, its models and recent calls": "ゲートウェイの状態とキー、クライアントの接続方法、モデルと最近の呼び出し", @@ -11413,6 +11425,10 @@ const I18N = { "{n} warm-ups and check-ins on": "{n} Vorwärmen und Check-ins an", "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "Traces und Metriken jeder Anfrage an einen OpenTelemetry-Collector senden, etwa Langfuse", "Sending to a collector": "Sendet an einen Collector", + "Routing strategies": "Routing-Strategien", + "The routings besides Smart: In order, In turn, Least used first, Weekly pace and By weight": "Die Routings neben Intelligent: Der Reihe nach, Abwechselnd, Am wenigsten genutzte zuerst, Wochentempo und Nach Gewicht", + "1 provider or group routed so": "1 Anbieter oder Gruppe so geroutet", + "{n} providers and groups routed so": "{n} Anbieter und Gruppen so geroutet", "In use, so it stays on": "In Gebrauch, daher bleibt es an", "Gateway page": "Gateway-Seite", "The gateway's state and keys, how to connect a client, its models and recent calls": "Zustand und Schlüssel des Gateways, wie sich ein Client verbindet, seine Modelle und letzten Aufrufe", diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index ecf28cbf5..29f76a152 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -4472,7 +4472,7 @@ function routingPage(part) { const rHint = el("div", "hint", t(GROUP_HINT[d.routing] || GROUP_HINT[""])); const rw = el("div"); - rw.append(segs(GROUP_ROUTE_OPTS.map(([id, n]) => [id, t(n)]), d.routing, (v) => { d.routing = v; rHint.textContent = t(GROUP_HINT[v] || GROUP_HINT[""]); draw(); drawRules(); drawSink(); }), rHint); + rw.append(routingSegs(GROUP_ROUTE_OPTS.map(([id, n]) => [id, t(n)]), d.routing, (v) => { d.routing = v; rHint.textContent = t(GROUP_HINT[v] || GROUP_HINT[""]); draw(); drawRules(); drawSink(); }), rHint); rw.append(el("div", "hint", t(GROUP_NEST))); ed.append(el("label", "", t("Routing")), rw); // one rate limited with quota left: its place, or the back @@ -5162,7 +5162,7 @@ function routingPage(part) { // by weight is a key's share (#841), set beside each key in the provider's editor const opts = p.kind === "account" ? ROUTE_OPTS : [...ROUTE_OPTS, ["weight", "By weight"]]; ctl.append( - lab(t("Routing"), segs(opts.map(([id, n]) => [id, t(n)]), p.routing || "", (v) => set("route", { id: p.provider, routing: v }, t("{name}: {routing}", { name: p.name, routing: t(opts.find(([id]) => id === v)[1]) })))), + lab(t("Routing"), routingSegs(opts.map(([id, n]) => [id, t(n)]), p.routing || "", (v) => set("route", { id: p.provider, routing: v }, t("{name}: {routing}", { name: p.name, routing: t(opts.find(([id]) => id === v)[1]) })))), lab(t("Stays"), segs(AFF_OPTS.map(([id, n]) => [id, t(n)]), p.affinity || "", (v) => set("affinity", { id: p.provider, affinity: v }, t("{name}: {routing}", { name: p.name, routing: t(AFF_OPTS.find(([id]) => id === v)[1]) }))))); if (sinkable(p.routing || "")) { const k = lab(t("Rate limited"), segs(SINK_OPTS.map(([id, n]) => [id, t(n)]), p.sink ? "sink" : "", (v) => set("sink", { id: p.provider, sink: v === "sink" }, t("{name}: {routing}", { name: p.name, routing: t(SINK_OPTS.find(([id]) => id === v)[1]) })))); diff --git a/internal/gui/builtins_test.go b/internal/gui/builtins_test.go index 776c6f7fb..78a892b9a 100644 --- a/internal/gui/builtins_test.go +++ b/internal/gui/builtins_test.go @@ -44,12 +44,13 @@ func TestBuiltinSwitch(t *testing.T) { if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { t.Fatal(err) } - if len(out) != 8 { + if len(out) != 9 { t.Fatalf("the built-ins: %+v", out) } for _, b := range out { - // the Gateway, Routing and Usage pages are essential: on in every preset - if b.On != (b.ID == "library" || b.ID == "gateway" || b.ID == "routing" || b.ID == "usage") || b.On != (b.State == pluginrt.Active) { + // the Gateway, Routing and Usage pages and the routing strategies + // are essential: on in every preset + if b.On != (b.ID == "library" || b.ID == "gateway" || b.ID == "rotation" || b.ID == "routing" || b.ID == "usage") || b.On != (b.State == pluginrt.Active) { t.Fatalf("after library on: %+v", out) } } diff --git a/internal/gui/tests/builtins.test.cjs b/internal/gui/tests/builtins.test.cjs index 82f21f641..4a5aaa122 100644 --- a/internal/gui/tests/builtins.test.cjs +++ b/internal/gui/tests/builtins.test.cjs @@ -23,14 +23,15 @@ const PLUGINS = [ { id: "groups", name: "Routing groups", sub: "Several models agents pick as one: each request goes to the right one, and to the next when one fails", one: "1 group in use", many: "{n} groups in use" }, { id: "library", name: "Library", sub: "Instructions, MCP servers, skills and hooks, kept once and given to every agent", one: "1 item given to agents", many: "{n} items given to agents" }, { id: "otel", name: "Observability", sub: "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse", one: "Sending to a collector", many: "Sending to a collector" }, + { id: "rotation", name: "Routing strategies", sub: "The routings besides Smart: In order, In turn, Least used first, Weekly pace and By weight", one: "1 provider or group routed so", many: "{n} providers and groups routed so" }, { id: "routing", name: "Routing", sub: "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups", one: "1 group in use", many: "{n} groups in use" }, { id: "sessions", name: "Sessions", sub: "Your agents' past conversations: read, search, resume and export them", one: "Recording gateway conversations", many: "Recording gateway conversations" }, { id: "usage", name: "Usage", sub: "Your allowances, what was spent and on what, each request, and what filled the context window" }, { id: "warmups", name: "Warm-up and check-in", sub: "Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits", one: "1 warm-up or check-in on", many: "{n} warm-ups and check-ins on" }, ]; // a new install's (the Essentials preset): all off but the Gateway, Routing -// and Usage pages, which are essential, and two routing groups the user made -const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], otel: [false, 0], routing: [true, 0], sessions: [false, 0], usage: [true, 0], warmups: [false, 0] }; +// and Usage pages and the routing strategies, which are essential, and two routing groups the user made +const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], otel: [false, 0], rotation: [true, 0], routing: [true, 0], sessions: [false, 0], usage: [true, 0], warmups: [false, 0] }; // the Gateway page's settings, as pluginrt.SchemaOf makes them const GATEWAY_SCHEMA = { @@ -162,9 +163,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual([gw.on, gw.disabled], ["true", false], `${where}: the Gateway page, on`); const rt = rows.find((r) => r.id === "routing"); assert.deepEqual([rt.on, rt.disabled], ["true", false], `${where}: the Routing page, on`); + const ro = rows.find((r) => r.id === "rotation"); + assert.deepEqual([ro.on, ro.disabled], ["true", false], `${where}: the routing strategies, on`); const us = rows.find((r) => r.id === "usage"); assert.deepEqual([us.on, us.disabled], ["true", false], `${where}: the Usage page, on`); - for (const r of rows.filter((r) => !["groups", "gateway", "routing", "usage"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`); + for (const r of rows.filter((r) => !["groups", "gateway", "rotation", "routing", "usage"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`); await page.locator('#builtinList [data-id="groups"] [role="switch"]').click({ force: true }); await page.waitForTimeout(100); assert.deepEqual(posts, [], `${where}: a locked switch posts nothing`); diff --git a/internal/gui/tests/routing-save.test.cjs b/internal/gui/tests/routing-save.test.cjs index 2b1a64d61..90ab2e4fc 100644 --- a/internal/gui/tests/routing-save.test.cjs +++ b/internal/gui/tests/routing-save.test.cjs @@ -8,6 +8,10 @@ // provider's Routing page row had alone, is beside Routing in the editor // too. Accounts and keys alike; nothing is sent, redrawn or scrolled before // the Save. In English and Chinese, Chromium and WebKit. +// +// The routings besides Smart are the built-in plugin rotation's +// (plugins/rotation): switched off, the editor offers Smart alone, at a +// phone's width too. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -28,13 +32,13 @@ const relay = { keyList: [1, 2].map((i) => ({ id: `key-${i}`, name: `Key ${i}`, masked: `sk-…000${i}`, active: i === 1, on: true })), }; -function serve(lang, posts) { +function serve(lang, posts, off = []) { const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; const providers = { providers: [sub, relay], presets: [], excluded: [], gateway: { running: true, window: true } }; return async (route) => { const url = new URL(route.request().url()); const json = (data) => route.fulfill({ json: data }); - if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true,featuresOff:${JSON.stringify(off)}};` }); if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); if (url.pathname === "/api/state") return json(state); if (url.pathname === "/api/providers") return json(providers); @@ -131,5 +135,33 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(errors, []); }); } + test(`${engine} ${lang}: with the routing strategies off, the editor offers Smart alone`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + for (const width of [900, 420]) { + for (const p of [sub, relay]) { + const where = `${width}px ${p.name}`; + const page = await (await browser.newContext({ viewport: { width, height: 720 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, [], ["rotation"])); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: p.name }).first().click(); + await page.locator(".editor .accts").first().waitFor(); + const field = page.locator(".editor label", { hasText: new RegExp(`^${L.routing}$`) }).locator("xpath=following-sibling::div[1]"); + const shown = await field.locator(".segs").first().evaluate((box) => [...box.querySelectorAll(".opt")].filter((b) => getComputedStyle(b).display !== "none").map((b) => b.textContent)); + assert.deepEqual(shown, [zh ? "智能" : "Smart"], `${where}: Smart alone`); + assert.match(await field.locator(".segs .opt").first().getAttribute("class"), /\bon\b/, `${where}: Smart picked`); + assert.ok(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth + 1), `${where}: fits`); + // on again, every routing is back + await page.evaluate(() => applyFeatures([{ id: "rotation", on: true }])); + const back = await field.locator(".segs").first().evaluate((box) => [...box.querySelectorAll(".opt")].filter((b) => getComputedStyle(b).display !== "none").length); + assert.equal(back, p.account ? 5 : 6, `${where}: every routing back`); + assert.deepEqual(errors, [], where); + await page.context().close(); + } + } + }); } } diff --git a/internal/provider/provider.go b/internal/provider/provider.go index eef286f69..4b0f5c35b 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -491,6 +491,28 @@ func FileError() error { return err } +// Routings is the routing of each provider and group providers.json sets +// one for, read from the file alone: for what asks often (the rotation +// plugin's InUse), without building the catalog and reading every sign-in. +func Routings() ([]string, error) { + f, err := read() + if err != nil { + return nil, err + } + var out []string + for _, p := range f.Providers { + if p.Routing != "" { + out = append(out, p.Routing) + } + } + for _, g := range f.Groups { + if g.Routing != "" { + out = append(out, g.Routing) + } + } + return out, nil +} + // store replaces providers.json whole, through a file renamed over it, so // that a read at that moment sees the old catalog or the new one, never a // file cut short. diff --git a/internal/routes/round.go b/internal/routes/round.go new file mode 100644 index 000000000..b92eb41eb --- /dev/null +++ b/internal/routes/round.go @@ -0,0 +1,96 @@ +package routes + +import "sync" + +// Weighted rounds (#841), as NGINX's smooth weighted round robin: keys +// weighing 3 and 1 go a, a, b, a, a, a, b, a…, the ratio held over a +// handful of requests rather than only on average. One resting is left out +// of the round while it rests, so the others share its requests by their +// own weights and it takes up its share when it is back. A provider routed +// by weight keeps one over its keys, a group routed by weight one over its +// members (#1910). + +var rounds = struct { + sync.Mutex + m map[string]*round // pool → its round +}{m: map[string]*round{}} + +type round struct { + cur map[string]int // a key, or a group's member → current weight + total int + last string // the one the last pick was charged to +} + +// Round is which of keys pool's round picks now, each weighing its +// weight, those resting left out of the round; -1 when every one rests. +// The pick is charged the round's total. +func Round(pool string, keys []string, weights []int, rests []bool) int { + rounds.Lock() + defer rounds.Unlock() + r := rounds.m[pool] + if r == nil { + r = &round{cur: map[string]int{}} + rounds.m[pool] = r + } + // keys no longer on are dropped from the round + on := make(map[string]bool, len(keys)) + for _, k := range keys { + on[k] = true + } + for k := range r.cur { + if !on[k] { + delete(r.cur, k) + } + } + best, total := -1, 0 + for i, k := range keys { + if rests[i] { + continue + } + r.cur[k] += weights[i] + total += weights[i] + if best < 0 || r.cur[k] > r.cur[keys[best]] { + best = i + } + } + if best < 0 { + return -1 + } + r.cur[keys[best]] -= total + r.total, r.last = total, keys[best] + return best +} + +// MoveRound charges pool's last pick to kept rather than picked, when +// affinity kept a conversation with kept: the round counts the requests +// each really took, so new conversations make up the share. +func MoveRound(pool, picked, kept string) { + rounds.Lock() + defer rounds.Unlock() + r := rounds.m[pool] + if r == nil || r.last != picked { + return + } + if _, ok := r.cur[kept]; !ok { + return + } + r.cur[picked] += r.total + r.cur[kept] -= r.total + r.last = kept +} + +// Forget drops what pool's round and turn hold, every pool's with none +// named: a test starts each anew. +func Forget(pools ...string) { + rounds.Lock() + turns.Lock() + defer rounds.Unlock() + defer turns.Unlock() + if len(pools) == 0 { + rounds.m, turns.m = map[string]*round{}, map[string]int{} + } + for _, p := range pools { + delete(rounds.m, p) + delete(turns.m, p) + } +} diff --git a/internal/routes/routes.go b/internal/routes/routes.go new file mode 100644 index 000000000..e14fd6aee --- /dev/null +++ b/internal/routes/routes.go @@ -0,0 +1,131 @@ +// Package routes is the gateway's router strategy point (P3 of +// docs/subsystems/plugin-runtime.md): how one pool of routes — a +// provider's accounts or keys, or the heads of a group's members — is +// ordered for a request. The gateway lists the pool, rests, affinity and +// failover itself; a Strategy only says the order. +// +// Smart, the default, is the core's. The others a provider or group can be +// routed by (order, rotate, usage, pace, weight) are here for a plugin to +// register: plugins/rotation does, and off, a pool routed by one of them is +// tried in its listed order, as an unknown routing always was. +package routes + +import ( + "log" + "slices" + "sync" + "time" +) + +// Seat is one route of a pool, as a strategy weighs it. +type Seat struct { + // Key is who it is: the account or key's rest key, the same for the + // same route from request to request + Key string + // Account is a subscription's account, not an API key + Account bool + // Known: its allowance is known. Used, Soon and Pace are read from it + Known bool + // Learns: an account not known yet, of an agent that tells what it has + // left as it answers (Claude Code's rate_limit_event) + Learns bool + // Used is the share of its allowance used that counts the model, 0–100 + Used float64 + // Soon is when its windows renew, the biggest first (Allowance.Renewal) + Soon []time.Time + // Pace is its week left per hour until that renews; an account not + // known has a whole week (provider.FreshPace), a key none + Pace float64 + // Weight is its key's weight, at least 1 + Weight int + // Resting: it rests after a failure now + Resting bool + // Tokens is what magpie sent it lately, decayed by an hour's half-life + Tokens float64 +} + +// Strategy orders a pool. +type Strategy struct { + // Order is the order to try seats in: a permutation of their indexes. + // pool names the pool (a provider's id, or "group/"), for a + // strategy that keeps a round per pool. It is asked with two seats or + // more. + Order func(pool string, seats []Seat) []int + // Exact: its order stands as it says. Otherwise, of a provider's API + // keys, those that fit the request better go first, each kept in its + // order among those alike. + Exact bool + // ByUse: it weighs by Tokens, which the routing trace then shows + ByUse bool +} + +var reg = struct { + sync.RWMutex + m map[string][]*Strategy // routing → registered, the last one serving +}{m: map[string][]*Strategy{}} + +// Register serves routing by s until remove is called. Registering one +// already served stacks: the last serves until it is removed. +func Register(routing string, s Strategy) (remove func()) { + e := &s + reg.Lock() + reg.m[routing] = append(reg.m[routing], e) + reg.Unlock() + var once sync.Once + return func() { + once.Do(func() { + reg.Lock() + defer reg.Unlock() + reg.m[routing] = slices.DeleteFunc(slices.Clone(reg.m[routing]), func(x *Strategy) bool { return x == e }) + }) + } +} + +// Find is the strategy serving routing: Smart for "", else the last one +// registered; ok is false when none is. +func Find(routing string) (Strategy, bool) { + if routing == "" { + return Smart, true + } + reg.RLock() + defer reg.RUnlock() + l := reg.m[routing] + if len(l) == 0 { + return Strategy{}, false + } + return *l[len(l)-1], true +} + +// Served says whether routing is served now. +func Served(routing string) bool { + _, ok := Find(routing) + return ok +} + +// Apply is the order s gives seats, checked: an order that isn't a +// permutation of them, or a strategy that panics, leaves them in their +// listed order, logged. A strategy only orders, so failing it fails open: +// every route is still tried. +func Apply(s Strategy, pool string, seats []Seat) (order []int) { + defer func() { + if r := recover(); r != nil { + log.Printf("routes: %s's strategy panicked: %v", pool, r) + order = identity(len(seats)) + } + }() + order = s.Order(pool, seats) + seen := make([]bool, len(seats)) + ok := len(order) == len(seats) + for _, i := range order { + if !ok || i < 0 || i >= len(seats) || seen[i] { + ok = false + break + } + seen[i] = true + } + if !ok { + log.Printf("routes: %s's strategy gave %v for %d routes; trying them in order", pool, order, len(seats)) + return identity(len(seats)) + } + return order +} diff --git a/internal/routes/routes_test.go b/internal/routes/routes_test.go new file mode 100644 index 000000000..2af07313c --- /dev/null +++ b/internal/routes/routes_test.go @@ -0,0 +1,151 @@ +package routes + +import ( + "slices" + "testing" + "time" +) + +func seats(n int) []Seat { + out := make([]Seat, n) + for i := range out { + out[i] = Seat{Key: string(rune('a' + i))} + } + return out +} + +// Registering stacks: the last one serves until it is removed, and the one +// under it serves again; removing twice removes once. Smart is served with +// nothing registered, and a routing with none registered is not. +func TestRegisterStacks(t *testing.T) { + if s, ok := Find(""); !ok || s.Order == nil { + t.Fatal("Smart isn't served") + } + if Served("t-stack") { + t.Fatal("served with none registered") + } + first := Register("t-stack", Strategy{Order: func(string, []Seat) []int { return []int{1, 0} }}) + second := Register("t-stack", Strategy{Order: func(string, []Seat) []int { return []int{0, 1} }, Exact: true}) + if s, _ := Find("t-stack"); !s.Exact { + t.Fatal("the last registered doesn't serve") + } + second() + second() + if s, ok := Find("t-stack"); !ok || s.Exact { + t.Fatalf("after removing the last, the first doesn't serve: %v", ok) + } + first() + if Served("t-stack") { + t.Fatal("still served after both were removed") + } +} + +// A strategy that panics, or answers what isn't a permutation of its +// seats, leaves them in their order: every route is still tried. +func TestApplyFailsOpen(t *testing.T) { + for name, order := range map[string]func(string, []Seat) []int{ + "panics": func(string, []Seat) []int { panic("boom") }, + "short": func(string, []Seat) []int { return []int{2, 1} }, + "repeats": func(string, []Seat) []int { return []int{2, 2, 0} }, + "out of it": func(string, []Seat) []int { return []int{3, 1, 0} }, + "negative": func(string, []Seat) []int { return []int{-1, 1, 0} }, + "nil": func(string, []Seat) []int { return nil }, + } { + if got := Apply(Strategy{Order: order}, "p", seats(3)); !slices.Equal(got, []int{0, 1, 2}) { + t.Errorf("%s: %v, want the listed order", name, got) + } + } + if got := Apply(Strategy{Order: func(string, []Seat) []int { return []int{2, 0, 1} }}, "p", seats(3)); !slices.Equal(got, []int{2, 0, 1}) { + t.Errorf("a good order was changed: %v", got) + } +} + +// Smart: those with room by when they renew, soonest first, unknown last; +// then those running low, then those all but used up, each by use. One +// learning goes first. +func TestSmart(t *testing.T) { + now := time.Now() + s := []Seat{ + {Key: "spent", Used: 99}, + {Key: "later", Used: 10, Soon: []time.Time{now.Add(48 * time.Hour)}}, + {Key: "low", Used: 92}, + {Key: "unknown"}, + {Key: "sooner", Used: 50, Soon: []time.Time{now.Add(2 * time.Hour)}}, + {Key: "learns", Learns: true}, + } + got := keys(s, Apply(Smart, "p", s)) + if want := []string{"learns", "sooner", "later", "unknown", "low", "spent"}; !slices.Equal(got, want) { + t.Fatalf("Smart: %v, want %v", got, want) + } +} + +func keys(s []Seat, order []int) []string { + out := make([]string, len(order)) + for i, j := range order { + out[i] = s[j].Key + } + return out +} + +// In turn starts one further along each time, per pool. +func TestRotate(t *testing.T) { + Forget("r1", "r2") + s := seats(3) + var got [][]string + for range 4 { + got = append(got, keys(s, Apply(Rotate, "r1", s))) + } + want := [][]string{{"a", "b", "c"}, {"b", "c", "a"}, {"c", "a", "b"}, {"a", "b", "c"}} + for i := range want { + if !slices.Equal(got[i], want[i]) { + t.Fatalf("turn %d: %v, want %v", i, got[i], want[i]) + } + } + if g := keys(s, Apply(Rotate, "r2", s)); g[0] != "a" { + t.Fatalf("another pool shares the turn: %v", g) + } + Forget("r1") + if g := keys(s, Apply(Rotate, "r1", s)); g[0] != "a" { + t.Fatalf("Forget kept the turn: %v", g) + } +} + +// Least used first by share used, then by tokens; in order is the listed +// order, and exact. +func TestLeastUsedAndOrdered(t *testing.T) { + s := []Seat{{Key: "a", Used: 50}, {Key: "b", Used: 10, Tokens: 9}, {Key: "c", Used: 10, Tokens: 1}} + if got := keys(s, Apply(LeastUsed, "p", s)); !slices.Equal(got, []string{"c", "b", "a"}) { + t.Fatalf("least used: %v", got) + } + if got := keys(s, Apply(Ordered, "p", s)); !slices.Equal(got, []string{"a", "b", "c"}) || !Ordered.Exact { + t.Fatalf("in order: %v", got) + } +} + +// Weekly pace: the most of a week left per hour first; one running low +// after, whatever its pace. +func TestPace(t *testing.T) { + s := []Seat{{Key: "slow", Pace: 1}, {Key: "low", Used: 95, Pace: 50}, {Key: "fast", Pace: 10}} + if got := keys(s, Apply(Pace, "p", s)); !slices.Equal(got, []string{"fast", "slow", "low"}) { + t.Fatalf("pace: %v", got) + } +} + +// By weight: over six requests a seat weighing 2 goes first twice as often +// as each weighing 1, and the others follow the one picked in their order. +func TestWeighted(t *testing.T) { + Forget("w") + s := []Seat{{Key: "a", Weight: 2}, {Key: "b", Weight: 1}, {Key: "c", Weight: 1}} + firsts := map[string]int{} + for range 8 { + order := keys(s, Apply(Weighted, "w", s)) + firsts[order[0]]++ + rest := slices.DeleteFunc(slices.Clone([]string{"a", "b", "c"}), func(k string) bool { return k == order[0] }) + if !slices.Equal(order[1:], rest) { + t.Fatalf("the others aren't in their order: %v", order) + } + } + if firsts["a"] != 4 || firsts["b"] != 2 || firsts["c"] != 2 { + t.Fatalf("by weight: %v, want a 4, b 2, c 2", firsts) + } +} diff --git a/internal/routes/strategies.go b/internal/routes/strategies.go new file mode 100644 index 000000000..bfca6ae18 --- /dev/null +++ b/internal/routes/strategies.go @@ -0,0 +1,222 @@ +package routes + +import ( + "sort" + "sync" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// Shares of an allowance past which an account is kept for when the others +// can't take a request: low, and all but used up — where the agent signed +// in to it is signed in to another, too (provider.SpentShare). +const ( + LowShare = 90 + UsedShare = provider.SpentShare +) + +// tier is 0 for a share with room, 1 for low, 2 for all but used up. +func tier(share float64) int { + switch { + case share >= UsedShare: + return 2 + case share >= LowShare: + return 1 + } + return 0 +} + +func identity(n int) []int { + idx := make([]int, n) + for i := range idx { + idx[i] = i + } + return idx +} + +// Smart is the default: of those with quota to spare, the one whose +// allowance renews soonest, since what it has left is lost then, while one +// renewing later keeps: the biggest window decides — the week, not the five +// hours in it — and the next one only when that renews in the same hour. An +// account with no week (Claude Enterprise's five hours alone) goes by its +// five hours, so ahead of every week but one renewing sooner; a window not +// started renews its whole span from now (#576). A Codex account that +// spends a reset about to run out by itself (auto-use on, its windows used) +// renews when that is spent, if sooner: what it has left is lost there just +// the same (#718). Only holding one, or one that runs out after the week +// renews, changes nothing. Those alike stay in their order, keeping the +// vendor's prompt cache warm. Past that, whichever has the most left, and +// one all but used up only when nothing else can take it. Only the windows +// that count the model do: Opus's own weekly allowance being used up leaves +// Sonnet alone. +// +// One not known that tells what it has left as it answers goes first, +// once: else, kept after those known, it would never answer and never be +// known (Anthropic's usage endpoint can turn magpie away for hours). +var Smart = Strategy{Order: func(_ string, seats []Seat) []int { + var fine, low, spent []int + for i, s := range seats { + switch tier(s.Used) { + case 2: + spent = append(spent, i) + case 1: + low = append(low, i) + default: + fine = append(fine, i) + } + } + sort.SliceStable(fine, func(i, j int) bool { + a, b := seats[fine[i]], seats[fine[j]] + if a.Learns != b.Learns { + return a.Learns + } + ri, rj := a.Soon, b.Soon + for k := 0; k < len(ri) || k < len(rj); k++ { + var x, y time.Time // to the hour, so a few minutes don't reorder + if k < len(ri) { + x = ri[k].Truncate(time.Hour) + } + if k < len(rj) { + y = rj[k].Truncate(time.Hour) + } + switch { + case x.Equal(y): + continue + case x.IsZero() || y.IsZero(): // not known: after those known + return y.IsZero() + } + return x.Before(y) + } + return false + }) + for _, l := range [][]int{low, spent} { + sort.SliceStable(l, func(i, j int) bool { return seats[l[i]].Used < seats[l[j]].Used }) + } + return append(append(fine, low...), spent...) +}} + +// Ordered tries a pool in its order: the first until it can't answer. +var Ordered = Strategy{Exact: true, Order: func(_ string, seats []Seat) []int { return identity(len(seats)) }} + +var turns = struct { + sync.Mutex + m map[string]int // pool → requests routed in turn +}{m: map[string]int{}} + +// Rotate starts each request one further along the pool. +var Rotate = Strategy{Order: func(pool string, seats []Seat) []int { + turns.Lock() + n := turns.m[pool] % len(seats) + turns.m[pool]++ + turns.Unlock() + return append(identity(len(seats))[n:], identity(n)...) +}} + +// LeastUsed puts a subscription, or a key that reads its own windows, by the +// share of its allowance used, as the vendor says; then, and for other +// keys, by what magpie sent it lately. +var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int { + idx := identity(len(seats)) + sort.SliceStable(idx, func(a, b int) bool { + sa, sb := seats[idx[a]], seats[idx[b]] + if sa.Used != sb.Used { + return sa.Used < sb.Used + } + return sa.Tokens < sb.Tokens + }) + return idx +}} + +// Pace puts a subscription by what it has left of its week per hour until +// that renews, the most first: it has the most to lose at the reset, where +// the most left alone (least used) sends a fresh account ahead of one with +// 80% left and an hour to go, and the soonest reset alone (smart) sends one +// with 3% left and an hour to go ahead of one with 90% and two. The tiers +// are Smart's: one at 90% or more of any window that counts the model — the +// five hours too, a rate cap it would be sent into before its allowance was +// read again — waits until the others can't answer, one all but used up +// until nothing else can; each tier by the share used. Among the rest, one +// not known that tells what it has left as it answers goes first while it +// isn't, as in Smart, else it would never be known; then the pace, those +// alike within a tenth by what magpie sent them lately, then in their +// order, keeping the vendor's prompt cache warm. An account not known +// counts as a whole week ahead of it; a key has no week, unless it reads +// its own windows (a sub2api key's limits). A Codex account that spends a +// reset about to run out by itself goes by the hours until then when that +// is sooner (Allowance.Pace, #717). +var Pace = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int { + // the bands of pace alike within a tenth, the highest first: drawn + // before sorting, from each band's highest down, so that sorting by + // them is consistent — "within a tenth of each other" alone is not, + // three paces a twelfth apart each going round in a circle. Drawn among + // those the pace orders alone — one running low would otherwise set a + // band's top and part two alike behind it + var byPace []int + for i, s := range seats { + if tier(s.Used) == 0 && !s.Learns { + byPace = append(byPace, i) + } + } + sort.SliceStable(byPace, func(a, b int) bool { return seats[byPace[a]].Pace > seats[byPace[b]].Pace }) + band, top := make([]int, len(seats)), 0.0 + for k, i := range byPace { + if p := seats[i].Pace; k == 0 || p < 0.9*top { + top = p + if k > 0 { + band[i] = band[byPace[k-1]] + 1 + continue + } + } else { + band[i] = band[byPace[k-1]] + } + } + idx := identity(len(seats)) + sort.SliceStable(idx, func(a, b int) bool { + sa, sb := seats[idx[a]], seats[idx[b]] + if ta, tb := tier(sa.Used), tier(sb.Used); ta != tb { + return ta < tb + } else if ta > 0 { + if sa.Used != sb.Used { + return sa.Used < sb.Used + } + } else if sa.Learns != sb.Learns { + return sa.Learns + } else if band[idx[a]] != band[idx[b]] { + return band[idx[a]] < band[idx[b]] + } + return sa.Tokens < sb.Tokens + }) + return idx +}} + +// Weighted spreads a pool's requests over its seats by each one's weight, +// smoothly (Round): the one the pool's round picks now first, the others +// after it in their order, for failover. +var Weighted = Strategy{Order: func(pool string, seats []Seat) []int { + keys, weights, rests := make([]string, len(seats)), make([]int, len(seats)), make([]bool, len(seats)) + for i, s := range seats { + keys[i], weights[i], rests[i] = s.Key, max(s.Weight, 1), s.Resting + } + return First(Round(pool, keys, weights, rests), len(seats)) +}} + +// First is the order of n with best first and the others after it in their +// order; best below 1 leaves it as it is. +func First(best, n int) []int { + idx := identity(n) + if best <= 0 { + return idx + } + return append(append([]int{best}, idx[:best]...), idx[best+1:]...) +} + +// Builtin are the routings besides Smart and their strategies, as +// plugins/rotation registers them. +var Builtin = map[string]Strategy{ + provider.Ordered: Ordered, + provider.Rotate: Rotate, + provider.LeastUsed: LeastUsed, + provider.Pace: Pace, + provider.Weighted: Weighted, +} diff --git a/plugins/all/all.go b/plugins/all/all.go index b2801a8b1..bf5a1e6f0 100644 --- a/plugins/all/all.go +++ b/plugins/all/all.go @@ -7,6 +7,7 @@ import ( _ "github.com/yetone/magpie/plugins/groups" _ "github.com/yetone/magpie/plugins/library" _ "github.com/yetone/magpie/plugins/otel" + _ "github.com/yetone/magpie/plugins/rotation" _ "github.com/yetone/magpie/plugins/routing" _ "github.com/yetone/magpie/plugins/sessions" _ "github.com/yetone/magpie/plugins/usage" diff --git a/plugins/rotation/rotation.go b/plugins/rotation/rotation.go new file mode 100644 index 000000000..160e29b67 --- /dev/null +++ b/plugins/rotation/rotation.go @@ -0,0 +1,47 @@ +// Package rotation is the routings a provider or group can be set to +// besides Smart: In order, In turn, Least used first, Weekly pace and By +// weight. While a provider or group is routed by one, it stays on. +// +// It is the first consumer of the gateway's router strategy point (P3 of +// docs/subsystems/plugin-runtime.md): Apply registers internal/routes' +// strategies, and off, a pool set to one of them is tried in its listed +// order and the window offers Smart alone. +package rotation + +import ( + "github.com/yetone/magpie/internal/pluginrt" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" +) + +func init() { + pluginrt.Register(pluginrt.Manifest{ + ID: "rotation", API: "^1", Requires: []string{"providers", "gateway"}, Essential: true, + Name: "Routing strategies", Sub: "The routings besides Smart: In order, In turn, Least used first, Weekly pace and By weight", + One: "1 provider or group routed so", Many: "{n} providers and groups routed so", + InUse: inUse, + Parts: []pluginrt.Part{{Slot: "part", Key: "rotation"}}, + Apply: func(c *pluginrt.Ctx) error { + for name, s := range routes.Builtin { + c.OnDispose(routes.Register(name, s)) + } + return nil + }, + }) +} + +// inUse counts the providers and groups routed by one of its strategies; +// a providers.json that can't be read is not known, so it stays on. +func inUse() (int, error) { + routings, err := provider.Routings() + if err != nil { + return 0, err + } + n := 0 + for _, r := range routings { + if _, ok := routes.Builtin[r]; ok { + n++ + } + } + return n, nil +} diff --git a/plugins/rotation/rotation_test.go b/plugins/rotation/rotation_test.go new file mode 100644 index 000000000..eb3604db7 --- /dev/null +++ b/plugins/rotation/rotation_test.go @@ -0,0 +1,100 @@ +package rotation + +import ( + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/pluginrt" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" + "github.com/yetone/magpie/internal/testenv" +) + +func TestMain(m *testing.M) { testenv.Main(m) } + +func manifest(t *testing.T) pluginrt.Manifest { + t.Helper() + for _, m := range pluginrt.Registered() { + if m.ID == "rotation" { + return m + } + } + t.Fatal("rotation not registered") + return pluginrt.Manifest{} +} + +func sandbox(t *testing.T) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, "cache")) +} + +// On, every routing besides Smart is served; off, none is, and Smart still +// is; on again, all are back. +func TestOnServesOffDoesNot(t *testing.T) { + sandbox(t) + rt := pluginrt.New([]pluginrt.Manifest{manifest(t)}) + defer rt.Stop() + served := func(want bool) { + t.Helper() + for name := range routes.Builtin { + if routes.Served(name) != want { + t.Fatalf("%s served: %v, want %v (%+v)", name, !want, want, rt.Statuses()) + } + } + if !routes.Served("") { + t.Fatal("Smart isn't served") + } + } + served(false) + rt.Reconcile(map[string]bool{"rotation": true}, nil) + served(true) + rt.Reconcile(map[string]bool{"rotation": false}, nil) + served(false) + rt.Reconcile(map[string]bool{"rotation": true}, nil) + served(true) +} + +// In use while a provider or a group is routed by one of its routings, by +// providers.json alone; Smart and Manual don't count, and a providers.json +// that can't be read keeps it on. +func TestInUse(t *testing.T) { + sandbox(t) + m := manifest(t) + if n, err := m.InUse(); err != nil || n != 0 { + t.Fatalf("no providers: %d %v", n, err) + } + for _, id := range []string{"a", "b"} { + if err := provider.Save(provider.Provider{ID: id, Name: id, Key: "k", Models: []string{"m"}, Chat: "http://127.0.0.1:1/v1"}); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{Name: "Hand", Members: []string{"a/m", "b/m"}, Routing: provider.Manual}); err != nil { + t.Fatal(err) + } + if n, err := m.InUse(); err != nil || n != 0 { + t.Fatalf("Smart and Manual: %d %v", n, err) + } + if err := provider.SetRouting("a", provider.Rotate); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{Name: "Pair", Members: []string{"a/m", "b/m"}, Routing: provider.Weighted}); err != nil { + t.Fatal(err) + } + if n, err := m.InUse(); err != nil || n != 2 { + t.Fatalf("a provider in turn and a group by weight: %d %v", n, err) + } + if err := os.WriteFile(provider.Path(), []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + for _, bak := range []string{".bak", ".lastgood"} { + os.Remove(provider.Path() + bak) + } + if _, err := m.InUse(); err == nil { + t.Fatal("an unreadable providers.json counted as known") + } +}