routes: each provider's wallets go by what they have left in a group too (#4095)

mycf_711 (#4095, comment): SuperMagic's accounts asked directly went by
their points (6,636, 282, 119), but in group/deepseek-v4.1-flash1017
they went 282, 119, 6,635, the provider's listed order. A Smart group
weighs its members' accounts as one pool (planLevel → weigh over the
heads), and the pool held WorkBuddy's credits beside SuperMagic's
points: byLeft returned nil as soon as it saw two kinds of LeftIn, so
no balance ordered anyone. Each 400 「积分已不足」 was then met on the
small balances first.

byLeft now orders each kind (provider + unit) in the places its own
seats take: the told seats' places in the pool's order (Smart) or by
what magpie sent each lately (Pace, Least used, as their tie-break
after the balance), each kind's seats put into its places by what they
have left, and seats of two kinds keep that order between them. A seat
that told none still goes after those that did. It is one rank per
seat, so the comparators stay a consistent order; comparing two kinds
as a tie would not be. One kind alone orders exactly as before
(TestWalletsGoByWhatTheyHaveLeft unchanged).

Tests: TestWalletsOfSeveralProvidersEachGoByWhatTheyHaveLeft (routes:
Smart, Pace, Least used, the reporter's three behind a WorkBuddy seat,
two kinds interleaved, and Least used's token order between kinds) and
TestGroupWalletsGoByWhatTheyHaveLeft (gateway: weigh over a group's
pool with the reporter's balances, smart/pace/usage).
docs/subsystems/provider-plugins.md and gateway-routing.md say it.

Broken by hand: with the old strategies.go both tests are red (the
group keeps 632, 710, 051 under every routing).
Run on mote, at 157d575c3 with both #4095 commits on it (the pushed tree):
go test -count=1 -timeout 45m ./internal/gateway/... ./internal/routes/...
ok (gateway 781s, routes 0.4s); gofmt -l internal/gateway internal/routes
empty; GOOS=windows and GOOS=linux go vet ./internal/gateway/...
./internal/routes/... ok. The same was green at the earlier bases
40f206dff and 7a7931833. Pushed on 99299c7b1, whose commits since
157d575c3 change only internal/edit's tests; not run again there.
Not tried: a real group with SuperMagic and WorkBuddy accounts; the
affinity that keeps a conversation on a low wallet ("turn") is unchanged.
This commit is contained in:
yetone
2026-10-29 01:14:42 +08:00
parent 3627742104
commit e5e2aa58e5
5 changed files with 123 additions and 37 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -46,7 +46,7 @@ A window that leaves out `used` but tells its count, `amount` of `limit` with bo
## A wallet's balance
A prepaid wallet (SuperMagic's points, [#3950](https://github.com/yetone/magpie/issues/3950)) has a balance and nothing it is a share of. A usage window may send `balance` (a number, in `unit`) and leave out `used`, `limit` and `aside`: `{name: "积分", balance: 6291, unit: "积分"}`. The host passes a finite number on, at least 0, and anything else as `null` (`usageOf` in [`host.js`](../../internal/plugin/host.js)); `plugin.UsageWindow.Balance` and `provider.QuotaWindow.Balance` are `*float64`. [`quotaOfPlugin`](../../internal/provider/plugin_usage.go) keeps the figure and does not make the window `Text` or `Aside`, so the account is known to routing with no `Used` invented. `allowanceOf` copies it into `Limit.Balance`, and an empty wallet (0) counts as used up. `Allowance.Left(model)` is the least balance of the windows that count the model, with its unit. `weighRouted` sets `routes.Seat.Left` to it and `Seat.LeftIn` to the account's provider and unit; Smart, `pace` and `usage` put the seat with more left first where they would otherwise tie (`byLeft` in [`strategies.go`](../../internal/routes/strategies.go)), and only when every seat that has a balance shares one `LeftIn`, so balances in two units or two providers are never weighed against each other. The card, the Routing page (`Weighed.Balance`) and the CLI show the figure ("6,291 积分 left", `provider.BalanceText`) and no meter. A wallet window's `runsOutAt`/`runsOut` (its soonest batch to lapse) and the rows set aside after it (`aside` text: SuperMagic's day's, timed and permanent points) are display only: the card says them, and the Routing page reads them from the same card (`cardOf` in the routing plugin's `client.js`, live requests only), its row saying the lapse after the figure ("6,291 积分 left · 185 积分 expire 23:59", `runsOutText`, #3964) and its tooltip and account list each window (`winsOf`). Routing goes by the balance alone. Tests: `TestPluginWalletBalanceIsAReading`, `TestPluginHostPassesABalanceOn`, `TestWalletsGoByWhatTheyHaveLeft`, `TestWalletWithMoreLeftGoesFirst`, `usage-wallet-balance.test.cjs`, `routing-wallet-balance.test.cjs`, `routing-wallet-lapse.test.cjs`.
A prepaid wallet (SuperMagic's points, [#3950](https://github.com/yetone/magpie/issues/3950)) has a balance and nothing it is a share of. A usage window may send `balance` (a number, in `unit`) and leave out `used`, `limit` and `aside`: `{name: "积分", balance: 6291, unit: "积分"}`. The host passes a finite number on, at least 0, and anything else as `null` (`usageOf` in [`host.js`](../../internal/plugin/host.js)); `plugin.UsageWindow.Balance` and `provider.QuotaWindow.Balance` are `*float64`. [`quotaOfPlugin`](../../internal/provider/plugin_usage.go) keeps the figure and does not make the window `Text` or `Aside`, so the account is known to routing with no `Used` invented. `allowanceOf` copies it into `Limit.Balance`, and an empty wallet (0) counts as used up. `Allowance.Left(model)` is the least balance of the windows that count the model, with its unit. `weighRouted` sets `routes.Seat.Left` to it and `Seat.LeftIn` to the account's provider and unit; Smart, `pace` and `usage` put the seat with more left first where they would otherwise tie (`byLeft` in [`strategies.go`](../../internal/routes/strategies.go)), and only among seats that share one `LeftIn`, so balances in two units or two providers are never weighed against each other: each kind is put in the places its own seats take (the pool's order, or what magpie sent each lately for `pace` and `usage`), and the other kinds keep theirs. Before, a pool with two kinds was weighed by no balance, so a group of SuperMagic's and WorkBuddy's accounts spent SuperMagic's smallest balances first (#4095). The card, the Routing page (`Weighed.Balance`) and the CLI show the figure ("6,291 积分 left", `provider.BalanceText`) and no meter. A wallet window's `runsOutAt`/`runsOut` (its soonest batch to lapse) and the rows set aside after it (`aside` text: SuperMagic's day's, timed and permanent points) are display only: the card says them, and the Routing page reads them from the same card (`cardOf` in the routing plugin's `client.js`, live requests only), its row saying the lapse after the figure ("6,291 积分 left · 185 积分 expire 23:59", `runsOutText`, #3964) and its tooltip and account list each window (`winsOf`). Routing goes by the balance alone. Tests: `TestPluginWalletBalanceIsAReading`, `TestPluginHostPassesABalanceOn`, `TestWalletsGoByWhatTheyHaveLeft`, `TestWalletsOfSeveralProvidersEachGoByWhatTheyHaveLeft`, `TestWalletWithMoreLeftGoesFirst`, `TestGroupWalletsGoByWhatTheyHaveLeft`, `usage-wallet-balance.test.cjs`, `routing-wallet-balance.test.cjs`, `routing-wallet-lapse.test.cjs`.
## Cache a vendor doesn't count
+31
View File
@@ -51,3 +51,34 @@ func TestWalletWithMoreLeftGoesFirst(t *testing.T) {
}
}
}
// mycf_711 (#4095): the same SuperMagic accounts that go by their points
// asked directly went in their listed order in a group, which weighs the
// members' accounts as one pool beside WorkBuddy's credits: 282 points,
// then 119, then 6,635. In the group too SuperMagic's go by what they
// have left, and WorkBuddy's account keeps its place.
func TestGroupWalletsGoByWhatTheyHaveLeft(t *testing.T) {
old := allowances
defer func() { allowances = old }()
share := map[string]provider.Allowance{}
allowances = func(string) map[string]provider.Allowance { return share }
wallet := func(left float64, unit string) provider.Allowance {
return provider.Allowance{{Name: unit, Balance: &left, Unit: unit}}
}
share["181****632"], share["181****710"], share["189****051"] = wallet(282, "积分"), wallet(119, "积分"), wallet(6635, "积分")
share["wb"] = wallet(50, "credits")
acct := func(agent, user string) candidate {
return candidate{p: provider.Provider{ID: agent, Account: &provider.Account{Agent: agent, User: user}}, model: "m", rest: agent + "#" + user}
}
for _, routing := range []string{"", provider.Pace, provider.LeastUsed} {
g := provider.Provider{ID: provider.GroupPrefix + "deepseek-v4.1-flash1017", Routing: routing}
got, _ := weigh(g, []candidate{acct("workbuddy", "wb"), acct("magicrew", "181****632"), acct("magicrew", "181****710"), acct("magicrew", "189****051")}, "", provider.Chat)
var s []string
for _, c := range got {
s = append(s, c.p.Account.User)
}
if got, want := strings.Join(s, ","), "wb,189****051,181****632,181****710"; got != want {
t.Errorf("%q: %s, want %s", routing, got, want)
}
}
}
+56 -35
View File
@@ -1,6 +1,7 @@
package routes
import (
"cmp"
"sort"
"sync"
"time"
@@ -27,42 +28,62 @@ func tier(share float64) int {
return 0
}
// byLeft is how a pool's wallets go by what they have left (Seat.Left):
// the one with more first, a seat that told none after those that did.
// It orders only a pool whose balances are all in one provider's one unit;
// with two kinds, nothing is weighed by them (nil), since points and
// another vendor's points don't compare.
func byLeft(seats []Seat) func(a, b Seat) int {
in := ""
for _, s := range seats {
switch {
case s.LeftIn == "":
case in == "":
in = s.LeftIn
case in != s.LeftIn:
return nil
// byLeft is how a pool's wallets go by what they have left (Seat.Left),
// as a comparison of two seats by their index: of seats whose balance is
// in one provider's one unit (Seat.LeftIn), the one with more left first;
// a seat that told none after those that did. Points and another
// vendor's points don't compare, so each kind is ordered only within the
// places its own seats take: those places are the told seats' order by
// before (nil: the pool's own order), each kind's seats are put in its
// places by what they have left, and seats of two kinds keep before's
// order between them. Before, a pool with two kinds was weighed by
// nothing (nil), and a group of several providers' accounts spent the
// small balances first (#4095, mycf_711). Nil when no seat told one.
func byLeft(seats []Seat, before func(a, b Seat) bool) func(i, j int) int {
var told []int
for i, s := range seats {
if s.LeftIn != "" {
told = append(told, i)
}
}
if in == "" {
if len(told) == 0 {
return nil
}
return func(a, b Seat) int {
ha, hb := a.LeftIn != "", b.LeftIn != ""
switch {
case ha != hb:
if ha {
return -1
}
return 1
case a.Left > b.Left:
return -1
case a.Left < b.Left:
return 1
}
return 0
if before != nil {
sort.SliceStable(told, func(a, b int) bool { return before(seats[told[a]], seats[told[b]]) })
}
place := make([]int, len(seats))
for i := range place {
place[i] = len(seats) // told none: after every one that did
}
var kinds []string
places := map[string][]int{}
for p, i := range told {
in := seats[i].LeftIn
if _, ok := places[in]; !ok {
kinds = append(kinds, in)
}
places[in] = append(places[in], p)
}
for _, in := range kinds {
ps := places[in]
ids := make([]int, len(ps))
for k, p := range ps {
ids[k] = told[p]
}
sort.SliceStable(ids, func(a, b int) bool { return seats[ids[a]].Left > seats[ids[b]].Left })
for k, p := range ps {
place[ids[k]] = p
}
}
return func(i, j int) int { return cmp.Compare(place[i], place[j]) }
}
// fewerTokens is what Pace and LeastUsed go by after a wallet's balance:
// what magpie sent a seat lately, the least first. It sets the places
// wallets of two kinds keep between them (byLeft).
func fewerTokens(a, b Seat) bool { return a.Tokens < b.Tokens }
func identity(n int) []int {
idx := make([]int, n)
for i := range idx {
@@ -96,7 +117,7 @@ func identity(n int) []int {
// 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 {
left := byLeft(seats)
left := byLeft(seats, nil)
var fine, low, spent []int
for i, s := range seats {
switch tier(s.Used) {
@@ -135,7 +156,7 @@ var Smart = Strategy{Order: func(_ string, seats []Seat) []int {
x, y := a.Lapse.Truncate(time.Hour), b.Lapse.Truncate(time.Hour)
if x.Equal(y) {
// then a wallet with more left (#3950)
return left != nil && left(a, b) < 0
return left != nil && left(fine[i], fine[j]) < 0
}
if x.IsZero() || y.IsZero() {
return y.IsZero()
@@ -180,7 +201,7 @@ var Rotate = Strategy{Order: func(pool string, seats []Seat) []int {
// share, by what they have left first (Seat.Left). Of those all but used up, one that
// goes on on its credits goes first (spentBefore).
var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {
left := byLeft(seats)
left := byLeft(seats, fewerTokens)
idx := identity(len(seats))
sort.SliceStable(idx, func(a, b int) bool {
sa, sb := seats[idx[a]], seats[idx[b]]
@@ -191,7 +212,7 @@ var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int
return sa.Used < sb.Used
}
if left != nil {
if c := left(sa, sb); c != 0 {
if c := left(idx[a], idx[b]); c != 0 {
return c < 0
}
}
@@ -245,7 +266,7 @@ var Pace = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {
band[i] = band[byPace[k-1]]
}
}
left := byLeft(seats)
left := byLeft(seats, fewerTokens)
idx := identity(len(seats))
sort.SliceStable(idx, func(a, b int) bool {
sa, sb := seats[idx[a]], seats[idx[b]]
@@ -264,7 +285,7 @@ var Pace = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {
} else if left != nil {
// a wallet's pace is a whole week's; the one with more left
// first (#3950)
if c := left(sa, sb); c != 0 {
if c := left(idx[a], idx[b]); c != 0 {
return c < 0
}
}
+34
View File
@@ -52,3 +52,37 @@ func TestWalletLeftWithinItsTier(t *testing.T) {
}
}
}
// mycf_711 (#4095): a group's pool holds several providers' wallets —
// WorkBuddy's credits beside SuperMagic's points — and with two kinds in
// it nothing was weighed by a balance, so the group spent SuperMagic's
// 282 and 119 points before its 6,635. Each kind goes by what it has left
// in the places its own seats take; the other kind's seat, and a seat
// that told none, keep theirs.
func TestWalletsOfSeveralProvidersEachGoByWhatTheyHaveLeft(t *testing.T) {
const pts, credits = "magicrew\x00积分", "workbuddy\x00credits"
wallet := func(key string, left float64, in string) Seat {
return Seat{Key: key, Account: true, Known: true, Pace: 100.0 / 168, Left: left, LeftIn: in}
}
for _, st := range []struct {
name string
s Strategy
}{{"smart", Smart}, {"pace", Pace}, {"usage", LeastUsed}} {
s := []Seat{wallet("wb-small", 40, credits), wallet("632", 282, pts), wallet("710", 119, pts), wallet("wb-big", 900, credits), wallet("051", 6635, pts)}
if got, want := keys(s, Apply(st.s, "p", s)), []string{"wb-big", "051", "632", "wb-small", "710"}; !slices.Equal(got, want) {
t.Errorf("%s: %v, want %v", st.name, got, want)
}
// the reporter's three behind another provider's wallet
s = []Seat{wallet("wb", 50, credits), wallet("632", 282, pts), wallet("710", 119, pts), wallet("051", 6635, pts)}
if got, want := keys(s, Apply(st.s, "p", s)), []string{"wb", "051", "632", "710"}; !slices.Equal(got, want) {
t.Errorf("%s, reporter's: %v, want %v", st.name, got, want)
}
}
// least used: the kinds keep the order of what magpie sent them lately
// between them, each kind in its places by what it has left
s := []Seat{wallet("632", 282, pts), wallet("wb", 50, credits), wallet("051", 6635, pts)}
s[0].Tokens, s[1].Tokens, s[2].Tokens = 10, 20, 30
if got, want := keys(s, Apply(LeastUsed, "p", s)), []string{"051", "wb", "632"}; !slices.Equal(got, want) {
t.Errorf("usage by tokens: %v, want %v", got, want)
}
}