gateway, routes, plugins: the routings besides Smart are the rotation plugin's, on the gateway's router strategy point (P3)

The second P3 extension point (docs/subsystems/plugin-runtime.md). A
router strategy orders one pool of routes: 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 failover; a strategy only orders.

- internal/routes: Seat, Strategy{Order, Exact, ByUse}, Register (stacks,
  the last serves), Find, Served, and Apply, which fails open: a strategy
  that panics or answers what isn't a permutation leaves the pool in its
  listed order, logged. Smart is the core's; Ordered, Rotate, LeastUsed,
  Pace and Weighted are routes.Builtin, moved out of the gateway with the
  rotate turns and the smooth weighted round (Round, MoveRound, Forget).
- plugins/rotation (Essential): registers routes.Builtin. InUse counts the
  providers and groups providers.json routes by one of them
  (provider.Routings), an unreadable file is an error, so it stays on. The
  gateway's KeepFresh watches providers.json too.
- Off, a routing no strategy serves is its listed order, and routingOf
  reads it as "order" wherever the core asks (a turn's mark, sinks, a
  rotate group's sessions, a group's heads, weightedKept).
- GUI: the routing pickers (provider editor, Routing page pools and group
  editor) mark the five as data-feature="rotation" (routingSegs), so off
  they offer Smart alone. i18n zh, zh-TW, ja, de.
- Docs: plugin-runtime.md router strategy section, gateway-routing.md
  (also drops a duplicated sentence about a lone key), reference.md.

Run in the worktree at this change (on origin/main fbfb76149):
- go test -count=1 ./... : 57 packages ok (gateway 587s)
- gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows
- GUI: full suite, chromium and webkit, every language: 9805 tests, 29
  red in 6 files. Each red alone the same way on origin/main bc470c6b6
  (just fetched): quota-count-wrap, quota-name-translated (#2228),
  refusal-retries-setting (#2258), routing-held-member (#2252), usage-fold
  (#2163), usage-agents-hide (#2276, from cf455ebd5). routing-save, builtins and
  rate-limited-sink pass in both engines.
- internal/gateway TestMain registers the strategies, so every routing test
  is the parity run with the plugin on; TestRotationOnAndOff turns it off
  (three Rotate sessions start k1,k2,k3 on, k1,k1,k1 off, no turn mark;
  Smart still served).

Rebased on origin/main 2b0037f41: go test ./... again, 56 packages ok at the
default timeout; internal/agent and internal/gateway passed with
-timeout 40m (1093s, 1039s: the machine at load ~17 with other sessions'
suites; the 10m panics stood in TestCodexAPIDisconnectStays and
TestCodexHeardWithinItsIdleTimeout, 1-2s in, no stack waiting on them).
Vets and gofmt clean again; routing-save, builtins, rate-limited-sink,
i18n-keys and the GUI files upstream changed pass.

Broken by hand, each test went red then restored:
- Apply's permutation check off: TestApplyFailsOpen
- Register's remove a no-op: TestRegisterStacks
- the plugin's Apply registers nothing: TestOnServesOffDoesNot
- InUse swallows providers.json's error: TestInUse
- routingOf passes an unserved routing through: TestRotationOnAndOff
- routingSegs not marking data-feature: routing-save.test.cjs "Smart alone"
This commit is contained in:
yetone
2026-10-15 09:09:15 +08:00
parent 2b0037f41d
commit af9bd6c3e2
28 changed files with 1035 additions and 355 deletions
+5
View File
@@ -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:
File diff suppressed because one or more lines are too long
+35 -5
View File
@@ -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/<id>`, 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.
+6 -6
View File
@@ -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)
}
+3 -3
View File
@@ -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
+5 -10
View File
@@ -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
+21
View File
@@ -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)
}
+2 -3
View File
@@ -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 {
+49
View File
@@ -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)
}
}
+52 -201
View File
@@ -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 {
+1 -1
View File
@@ -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
+5 -99
View File
@@ -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))
}
+4 -9
View File
@@ -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]
+3 -6
View File
@@ -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)
+11 -1
View File
@@ -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");
+16
View File
@@ -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",
@@ -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]) }))));
+4 -3
View File
@@ -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)
}
}
+6 -3
View File
@@ -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`);
+34 -2
View File
@@ -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();
}
}
});
}
}
+22
View File
@@ -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.
+96
View File
@@ -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)
}
}
+131
View File
@@ -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/<id>"), 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
}
+151
View File
@@ -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)
}
}
+222
View File
@@ -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,
}
+1
View File
@@ -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"
+47
View File
@@ -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
}
+100
View File
@@ -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")
}
}