routing: a week at 90% renewing soonest is spent before its reset, not kept for last (ysicing_01858)
ysicing_01858 on Discord (Use before expiry, three accounts): the
account at 90% of its week, renewing today, took few requests, while most
went to one renewing tomorrow. Smart and Use before expiry put every
account at 90% of any window into tier 1 ("kept for last"), behind every
one with room, so what that week had left was lost at its reset.
Now 90% means "kept for last" only for a rate cap: the five hours, or a
window that doesn't say how long it runs (Allowance.CapUsed). An account
at 90% of its week alone (Seat.WeekLow) keeps its place: by its reset
(Smart) or by share left per hour (Use before expiry). 98% of any window
still puts it last. A new conversation kept for its session may go to
such an account (readyForNew). The trace carries weekLow, so the Routing
row doesn't call it "kept for last" and doesn't dim it. Least used first,
In order and the others are unchanged. The Pace description in Settings
says so in every language.
Their later report ("90% 额度账号已经自然重置了 现在的调度机制又默认主要调度到刚重置的
账号了") is not this bug, and this change doesn't alter it. Use before
expiry orders by share left / hours to reset. A fresh week is about
0.6%/h (100/168h), so it goes ahead of any account with less than that
per hour, e.g. 30% left in six days. Conversation affinity and the
fewest-tokens tie-break, for paces within a tenth, keep it there. Smart
is the routing that goes by the soonest reset alone. Their numbers would
tell whether a pace is wrong there.
Run on mote:
- At 49d6ad779, the same tree on 0ee424e3e:
- go test internal/routes and internal/provider: ok.
- internal/gateway -run WeekLow|Reset|Smart|Pace|Spread|Session|
Affinity|Weigh|Trace|Routing: ok.
- GUI: 162 routing-*, i18n-* and gui-* files, chromium and webkit:
2535 tests, 2500 passed, 35 failed. The 35 are in 11 files:
routing-folder, -many-keys, -order-unknown, -row-swap, -rule-drag,
-rule-remove, -rules-line, -sky-under, -steady, -steps-cap and
-story-shrinks. Run again alone at 49d6ad779: 26 red. At origin/main
0ee424e3e: 24 red, the same tests (#5088, #4585, #4627, #4628,
#4629). mote was at load 70-200 after a reboot.
- routing-week-low (new) passed: pace and smart, en/zh/zh-TW/ja/de,
1100 and 420, both engines.
- Rebased on origin/main 129baeca0, which changed internal/gateway's
resting. At d187c0c0c (this tree):
- go vet ok; internal/routes ok; internal/gateway -run with Rest|Fail|5 added: ok (146s).
- TestCoreScriptBudget: still red as on main (#5139). This tree's core
is 1534033, 12 bytes under main's.
- routing-week-low and i18n-keys: 46 of 46 ok.
- gofmt clean. go vet for darwin, linux and windows ran at 0ee424e3e.
Broken by hand:
- seatTier back to tier(s.Used): TestWeekLowKeepsItsPlace and
TestWeekLowIsSpentBeforeItsReset red.
- readyForNew without the weekLow clause: "isn't ready for a new
conversation" red.
- client.js's row label back to !w.routing: routing-week-low red (pace
rows lacked "kept for last" for the 93% five-hour account).
Not tried:
- Real accounts near 90% of a week.
- Smart's own description in Settings still says 90% of any window; it
was left as is to keep the core budget from growing.
This commit is contained in:
@@ -852,10 +852,12 @@ func leastHeld(scope, key string, cs []candidate, pl planned, ready bool) ([]can
|
||||
// readyForNew says whether order[i], behind order[0], is one routing would
|
||||
// put a new conversation on: not resting, nor a key for another protocol,
|
||||
// nor a fallback while the provider's own model leads, nor used past
|
||||
// lowShare unless it spends its credits first (Weighed.CreditsFirst).
|
||||
// lowShare unless it spends its credits first (Weighed.CreditsFirst) or
|
||||
// is that low on its week alone, which Smart and Use before expiry keep
|
||||
// with those that have room (Weighed.WeekLow).
|
||||
func readyForNew(order []Weighed, i int) bool {
|
||||
w := order[i]
|
||||
return w.Rest == nil && !w.Aside && !standsIn(order, i) && !(w.Known && w.Used >= lowShare && !w.CreditsFirst) && !lastBehind(order, i) && !busyBehind(order, i)
|
||||
return w.Rest == nil && !w.Aside && !standsIn(order, i) && !(w.Known && w.Used >= lowShare && !w.CreditsFirst && !(w.WeekLow && w.Used < usedShare)) && !lastBehind(order, i) && !busyBehind(order, i)
|
||||
}
|
||||
|
||||
// standsIn says whether order[i] is a provider's fallback while one of the
|
||||
|
||||
@@ -2076,8 +2076,11 @@ func (c candidate) allowanceKey() allowanceKey {
|
||||
}
|
||||
|
||||
type left struct {
|
||||
used float64
|
||||
renews []time.Time
|
||||
used float64
|
||||
// weekLow: used is at lowShare or more for its budget windows alone,
|
||||
// no rate cap of it near full (Allowance.CapUsed, routes.Seat.WeekLow)
|
||||
weekLow bool
|
||||
renews []time.Time
|
||||
// fullest: when the window used is the share of renews
|
||||
// (Allowance.Fullest), zero when not known
|
||||
fullest time.Time
|
||||
@@ -2136,6 +2139,14 @@ func routingOf(routing string) string {
|
||||
return provider.Ordered
|
||||
}
|
||||
|
||||
// keepsWeek: routed so, a pool keeps an account running low on its week
|
||||
// alone with those that have room (routes.Seat.WeekLow): Smart and Use
|
||||
// before expiry, which spend what a reset would lose.
|
||||
func keepsWeek(routing string) bool {
|
||||
r := routingOf(routing)
|
||||
return r == "" || r == provider.Pace
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -2180,6 +2191,7 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide
|
||||
l := left{used: u, renews: r, fullest: a.Fullest(c.model, now), soon: a.Renewal(c.model, now), lapse: a.Lapse(c.model, now), pace: pc, due: due, amount: amt, of: of, unit: unit,
|
||||
restarts: rs, dueRestart: !rs.IsZero() && due.Equal(rs), credits: spendsCredits(c.p, a)} // one not known counts as unused
|
||||
l.dueExpiry = !l.dueRestart && !l.lapse.IsZero() && due.Equal(l.lapse)
|
||||
l.weekLow = u >= lowShare && u < usedShare && a.CapUsed(c.model, now) < lowShare
|
||||
l.first = l.credits && provider.CodexCreditsFirst(c.p.Account.User)
|
||||
if b, bu, has := a.Left(c.model); has {
|
||||
// a wallet's figure is weighed only against the same
|
||||
@@ -2207,7 +2219,7 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide
|
||||
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, Lapse: l.lapse, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now), Credits: l.credits, First: l.first,
|
||||
Used: l.used, WeekLow: l.weekLow, Soon: l.soon, Lapse: l.lapse, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now), Credits: l.credits, First: l.first,
|
||||
Left: l.bal, LeftIn: l.balIn, Spent: spentRest(c)}
|
||||
}
|
||||
routed.Unlock()
|
||||
|
||||
@@ -299,6 +299,10 @@ type Weighed struct {
|
||||
Known bool `json:"known,omitempty"` // the vendor said what the account has left
|
||||
Learns bool `json:"learns,omitempty"` // not known, but its answer will tell
|
||||
Used float64 `json:"used"` // share of the allowance counting the model, used
|
||||
// WeekLow: Used is at 90% or more for its week alone, so Smart and Use
|
||||
// before expiry keep it with those that have room rather than for
|
||||
// last (routes.Seat.WeekLow); false under another routing
|
||||
WeekLow bool `json:"weekLow,omitempty"`
|
||||
// Amount of Limit in Unit: the count that share is of, when the
|
||||
// vendor counts it so (WorkBuddy's credits, #659)
|
||||
Amount float64 `json:"amount,omitempty"`
|
||||
@@ -541,6 +545,7 @@ func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from
|
||||
}
|
||||
if l, ok := wg.lefts[c.allowanceKey()]; ok {
|
||||
w.Known, w.Used, w.Renews, w.Pace, w.Credits, w.CreditsFirst = true, l.used, l.renews, l.pace, l.credits, l.first
|
||||
w.WeekLow = l.weekLow && keepsWeek(p.Routing)
|
||||
if !l.fullest.IsZero() {
|
||||
ur := l.fullest
|
||||
w.UsedRenews = &ur
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// ysicing_01858 on Discord, three accounts under Use before expiry: one at
|
||||
// 90% of its week, renewing today, took few requests, most going to one
|
||||
// renewing tomorrow. 90% of any window put an account behind every one
|
||||
// with room, so the week it would lose at its reset went unused. A week at
|
||||
// 90% alone now keeps its place by when it renews (Smart) or its pace
|
||||
// (Use before expiry), and new conversations kept for the session may go
|
||||
// to it; 90% of its five hours, a rate cap, still holds it back, and 98%
|
||||
// of its week still puts it last. Least used first is unchanged.
|
||||
func TestWeekLowIsSpentBeforeItsReset(t *testing.T) {
|
||||
old := allowances
|
||||
defer func() { allowances = old }()
|
||||
now := time.Now()
|
||||
share := map[string]provider.Allowance{}
|
||||
allowances = func(string) map[string]provider.Allowance { return share }
|
||||
acct := func(user string) candidate {
|
||||
return candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: user}}, model: "gpt-5.6-sol", rest: "codex#" + user}
|
||||
}
|
||||
plan := func(fiveHours, week float64, renews time.Duration) provider.Allowance {
|
||||
return provider.Allowance{
|
||||
{Used: fiveHours, Resets: now.Add(3 * time.Hour), Span: 5 * time.Hour},
|
||||
{Used: week, Resets: now.Add(renews), Span: 7 * 24 * time.Hour},
|
||||
}
|
||||
}
|
||||
for _, routing := range []string{provider.Pace, ""} {
|
||||
name := map[string]string{provider.Pace: "pace", "": "smart"}[routing]
|
||||
p := provider.Provider{ID: "codex", Routing: routing, Account: &provider.Account{Agent: "codex", User: "b@x.com"}}
|
||||
order := func() (string, []Weighed) {
|
||||
got, wg := weigh(p, []candidate{acct("b@x.com"), acct("a@x.com")}, "gpt-5.6-sol", provider.Chat)
|
||||
var s []string
|
||||
var ws []Weighed
|
||||
for _, c := range got {
|
||||
s = append(s, c.p.Account.User[:1])
|
||||
ws = append(ws, weighed(c, p, wg, false, provider.Chat))
|
||||
}
|
||||
return strings.Join(s, ""), ws
|
||||
}
|
||||
// B has room and renews tomorrow; A is at 91% of its week, which
|
||||
// renews in three hours: 9% left in 3h is more per hour than 70%
|
||||
// in 48h, and sooner, so A goes first by either routing
|
||||
share["b@x.com"] = plan(10, 30, 48*time.Hour)
|
||||
share["a@x.com"] = plan(20, 91, 3*time.Hour)
|
||||
got, ws := order()
|
||||
if got != "ab" {
|
||||
t.Fatalf("%s: a week at 91%% renewing in 3h went %s, want ab", name, got)
|
||||
}
|
||||
if !ws[0].WeekLow || ws[1].WeekLow {
|
||||
t.Fatalf("%s: weekLow %v %v, want A only", name, ws[0].WeekLow, ws[1].WeekLow)
|
||||
}
|
||||
// a new conversation kept for the session may go to A: Smart and
|
||||
// Use before expiry would put one there
|
||||
if !readyForNew([]Weighed{ws[1], ws[0]}, 1) {
|
||||
t.Fatalf("%s: A at 91%% of its week alone isn't ready for a new conversation", name)
|
||||
}
|
||||
// at 92% of its five hours it is near a rate cap: kept for last
|
||||
share["a@x.com"] = plan(92, 91, 3*time.Hour)
|
||||
if got, ws = order(); got != "ba" || ws[1].WeekLow {
|
||||
t.Fatalf("%s: five hours at 92%%: %s weekLow %v, want ba, false", name, got, ws[1].WeekLow)
|
||||
}
|
||||
if readyForNew(ws, 1) {
|
||||
t.Fatalf("%s: A at 92%% of its five hours is ready for a new conversation", name)
|
||||
}
|
||||
// all but used up: last, whatever its reset
|
||||
share["a@x.com"] = plan(20, 98, 3*time.Hour)
|
||||
if got, ws = order(); got != "ba" || ws[1].WeekLow {
|
||||
t.Fatalf("%s: week at 98%%: %s weekLow %v, want ba, false", name, got, ws[1].WeekLow)
|
||||
}
|
||||
}
|
||||
// Least used first goes by the share used: A at 91% goes after B, and
|
||||
// the trace doesn't call it kept with those with room
|
||||
p := provider.Provider{ID: "codex", Routing: provider.LeastUsed, Account: &provider.Account{Agent: "codex", User: "b@x.com"}}
|
||||
share["a@x.com"] = plan(20, 91, 3*time.Hour)
|
||||
got, wg := weigh(p, []candidate{acct("a@x.com"), acct("b@x.com")}, "gpt-5.6-sol", provider.Chat)
|
||||
if got[0].p.Account.User != "b@x.com" {
|
||||
t.Fatalf("least used: %s first, want b", got[0].p.Account.User)
|
||||
}
|
||||
if w := weighed(got[1], p, wg, false, provider.Chat); w.WeekLow {
|
||||
t.Fatalf("least used: A told weekLow")
|
||||
}
|
||||
}
|
||||
@@ -11927,7 +11927,7 @@ const ROUTINGS = [
|
||||
["drain", "Until used up", "Requests stay on one until it is used up, then go to the next in the list and stay there: one before it that renews meanwhile doesn't take them back. One rate limited or failing is passed over while it rests, and requests come back to it after."],
|
||||
["rotate", "In turn", "Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests."],
|
||||
["usage", "Least used first", "Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours."],
|
||||
["pace", "Use before expiry", "Each request goes to the subscription with the most left per hour until it is lost — its week at its reset, or credits in it that expire sooner — so less is lost to resets and expiry; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours."],
|
||||
["pace", "Use before expiry", "Each request goes to the subscription with the most left per hour until it is lost, at its reset or as credits expire; one at 90% of its five hours waits until the others can't answer, a week at 90% is still spent before its reset. A key goes by the tokens it served in the last hours."],
|
||||
["weight", "By weight", "Requests spread over the keys or accounts by the weight set beside each: one weighing 3 takes three requests for every one 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 it as Stays says."],
|
||||
["free", "Free first", "Requests go to what costs nothing first: the models their vendor serves at no cost to this subscription's allowance or credits, in their listed order, and only when those can't answer to one that spends them. Nothing that cost nothing is left unused."],
|
||||
["fast", "Speed first", "Requests go to the one that has answered this model fastest lately, by its time to the first token and how fast it writes; those within a tenth of each other keep their listed order. One not measured lately gets one request in five, so it is measured again, and one that fails is passed over while it rests."],
|
||||
|
||||
@@ -1898,7 +1898,7 @@ const I18N = {
|
||||
"Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "会话每一轮轮流交给下一个,均摊负载;同一轮内的请求留在起始处,保持提示词缓存;出错的在暂停期间跳过。",
|
||||
"Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours.": "每个请求发给用量最少的:订阅看已用额度比例,密钥看最近几小时经它的 token 数。",
|
||||
"Use before expiry": "到期前用完",
|
||||
"Each request goes to the subscription with the most left per hour until it is lost — its week at its reset, or credits in it that expire sooner — so less is lost to resets and expiry; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "每个请求发给剩余额度 ÷ 距作废小时数最高的订阅——周额度在重置时作废,更早过期的积分按过期时间算;用到 90% 以上的,等其他都无法响应时才用。密钥按最近几小时处理的 token 数排序。",
|
||||
"Each request goes to the subscription with the most left per hour until it is lost, at its reset or as credits expire; one at 90% of its five hours waits until the others can't answer, a week at 90% is still spent before its reset. A key goes by the tokens it served in the last hours.": "每个请求发给剩余额度 ÷ 距作废小时数最高的订阅——周额度在重置时作废,更早过期的积分按过期时间算;5 小时额度用到 90% 以上的,等其他都无法响应时才用,周额度用到 90% 的仍会在重置前用掉。密钥按最近几小时处理的 token 数排序。",
|
||||
"The gateway now uses {user} first": "网关现在优先使用 {user}",
|
||||
"{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} 登录首选账号;勾选多个时,前一个额度用完 magpie 自动换下一个。已在运行的会话保持原账号,重启后切换。",
|
||||
"{agent} is signed in to this account": "{agent} 当前登录的就是这个账号",
|
||||
@@ -6460,7 +6460,7 @@ const I18N = {
|
||||
"Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "會話每一輪輪流交給下一個,均攤負載;同一輪內的請求留在起始處,保持提示詞快取;出錯的在暫停期間跳過。",
|
||||
"Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours.": "每個請求發給用量最少的:訂閱看已用額度比例,金鑰看最近幾小時經它的 token 數。",
|
||||
"Use before expiry": "到期前用完",
|
||||
"Each request goes to the subscription with the most left per hour until it is lost — its week at its reset, or credits in it that expire sooner — so less is lost to resets and expiry; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "每個請求發給剩餘額度 ÷ 距作廢小時數最高的訂閱——週額度在重置時作廢,更早過期的點數按過期時間算;用到 90% 以上的,等其他都無法回應時才用。金鑰按最近幾小時處理的 token 數排序。",
|
||||
"Each request goes to the subscription with the most left per hour until it is lost, at its reset or as credits expire; one at 90% of its five hours waits until the others can't answer, a week at 90% is still spent before its reset. A key goes by the tokens it served in the last hours.": "每個請求發給剩餘額度 ÷ 距作廢小時數最高的訂閱——週額度在重置時作廢,更早過期的點數按過期時間算;5 小時額度用到 90% 以上的,等其他都無法回應時才用,週額度用到 90% 的仍會在重置前用掉。金鑰按最近幾小時處理的 token 數排序。",
|
||||
"The gateway now uses {user} first": "閘道現在優先使用 {user}",
|
||||
"{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} 登入首選帳號;勾選多個時,前一個額度用完 magpie 自動換下一個。已在執行的會話保持原帳號,重啟後切換。",
|
||||
"{agent} is signed in to this account": "{agent} 目前登入的就是這個帳號",
|
||||
@@ -10998,7 +10998,7 @@ const I18N = {
|
||||
"Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "会話のターンごとに次のものへ送り、負荷を均等に分散します。ターン内のリクエストは開始した場所に留まるのでプロンプトキャッシュが効きます。エラーになったものは休止中スキップされます。",
|
||||
"Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours.": "各リクエストは使用量が最も少ないものに送られます。サブスクリプションは利用枠の使用割合、キーは直近数時間に処理したトークン数で判断します。",
|
||||
"Use before expiry": "期限前に使い切る",
|
||||
"Each request goes to the subscription with the most left per hour until it is lost — its week at its reset, or credits in it that expire sooner — so less is lost to resets and expiry; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "各リクエストは、失われるまでの1時間あたりの残りが最も多いサブスクリプションに送られます — 週の枠はリセットで、それより早く期限切れになるクレジットはその期限で失われるため、リセットや期限切れで無駄になる分を減らします。90% 以上使用したものは他が応答できないときまで待機します。キーは直近数時間に処理したトークン数で判断します。",
|
||||
"Each request goes to the subscription with the most left per hour until it is lost, at its reset or as credits expire; one at 90% of its five hours waits until the others can't answer, a week at 90% is still spent before its reset. A key goes by the tokens it served in the last hours.": "各リクエストは、失われるまでの1時間あたりの残りが最も多いサブスクリプションに送られます — 週の枠はリセットで、それより早く期限切れになるクレジットはその期限で失われるため、リセットや期限切れで無駄になる分を減らします。5 時間枠を 90% 以上使用したものは他が応答できないときまで待機しますが、週の枠が 90% のものはリセット前に使い切ります。キーは直近数時間に処理したトークン数で判断します。",
|
||||
"The gateway now uses {user} first": "ゲートウェイは {user} を最初に使うようになりました",
|
||||
"{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} は最初のアカウントにサインインします。複数チェックすると、前のアカウントのクォータが切れたときに magpie が次へ切り替えます。実行中のセッションは再起動するまで元のアカウントのままです。",
|
||||
"{agent} is signed in to this account": "{agent} はこのアカウントにサインインしています",
|
||||
@@ -15567,7 +15567,7 @@ const I18N = {
|
||||
"Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "Jede Runde eines Gesprächs geht an das nächste, damit sich die Last gleichmäßig verteilt; die Anfragen einer Runde bleiben dort, wo sie begann, damit der Prompt-Cache greift, und ein fehlgeschlagenes wird übersprungen, solange es pausiert.",
|
||||
"Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours.": "Jede Anfrage geht an das am wenigsten genutzte: ein Abo nach dem verbrauchten Anteil seines Kontingents, ein Schlüssel nach den Token, die er in den letzten Stunden geliefert hat.",
|
||||
"Use before expiry": "Vor Ablauf aufbrauchen",
|
||||
"Each request goes to the subscription with the most left per hour until it is lost — its week at its reset, or credits in it that expire sooner — so less is lost to resets and expiry; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "Jede Anfrage geht an das Abo mit dem meisten Rest pro Stunde, bis er verfällt — seine Woche beim Reset oder Guthaben darin, das früher abläuft —, damit weniger durch Resets und Ablauf verfällt; eines mit 90 % oder mehr wartet, bis die anderen nicht antworten können. Ein Schlüssel richtet sich nach den Token, die er in den letzten Stunden geliefert hat.",
|
||||
"Each request goes to the subscription with the most left per hour until it is lost, at its reset or as credits expire; one at 90% of its five hours waits until the others can't answer, a week at 90% is still spent before its reset. A key goes by the tokens it served in the last hours.": "Jede Anfrage geht an das Abo mit dem meisten Rest pro Stunde, bis er verfällt — seine Woche beim Reset oder Guthaben darin, das früher abläuft —, damit weniger durch Resets und Ablauf verfällt; eines mit 90 % oder mehr seiner fünf Stunden wartet, bis die anderen nicht antworten können, eine Woche bei 90 % wird dagegen vor ihrem Reset noch aufgebraucht. Ein Schlüssel richtet sich nach den Token, die er in den letzten Stunden geliefert hat.",
|
||||
"The gateway now uses {user} first": "Der Zugangspunkt verwendet jetzt zuerst {user}",
|
||||
"{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} meldet sich beim ersten an. Haken Sie weitere an, wechselt magpie zum nächsten, sobald das vorherige kein Kontingent mehr hat. Laufende Sitzungen behalten ihres bis zum Neustart.",
|
||||
"{agent} is signed in to this account": "{agent} ist bei diesem Konto angemeldet",
|
||||
|
||||
@@ -593,7 +593,12 @@ function routingPage(part) {
|
||||
// noURLWord: its keys are all set to a protocol its provider has no URL
|
||||
// for, so it went out on the URLs it has (#1702)
|
||||
const noURLWord = (w) => t("key set to {api} only, no {api} URL · sent on the others", { api: API[w.noURL] || w.noURL });
|
||||
const group = (w) => w.used >= 98 ? "spent" : w.used >= 90 ? "low" : "fine";
|
||||
// group is the tier Smart and Use before expiry put one in: 90% of a
|
||||
// week alone (weekLow) is kept with those that have room, as what it
|
||||
// has left is lost at its reset (ysicing_01858 on Discord)
|
||||
const group = (w) => w.used >= 98 ? "spent" : w.used >= 90 && !w.weekLow ? "low" : "fine";
|
||||
// tiered: its routing holds one running low back (routes.seatTier)
|
||||
const tiered = (w) => !w.routing || w.routing === "pace";
|
||||
const renews = (w) => (w.renews || []).map((s) => known0(s) ? at(s) : 0);
|
||||
// usedRenews is when the window w.used is the share of renews: a row
|
||||
// says the two together, so they are of one window, a Factory account's
|
||||
@@ -2697,9 +2702,9 @@ function routingPage(part) {
|
||||
else if (w.known) {
|
||||
const soon = usedRenews(w);
|
||||
s = w.creditsLast && !r.order[0]?.creditsLast ? quota(w, "{n} used · on credits · after the others", "{n} left · on credits · after the others")
|
||||
: !w.routing && w.used >= 98 && w.credits ? quota(w, "{n} used · on credits", "{n} left · on credits")
|
||||
: !w.routing && w.used >= 98 ? quota(w, "{n} used · all but used up", "{n} left · all but used up")
|
||||
: !w.routing && w.used >= 90 ? quota(w, "{n} used · kept for last", "{n} left · kept for last")
|
||||
: tiered(w) && group(w) === "spent" && w.credits ? quota(w, "{n} used · on credits", "{n} left · on credits")
|
||||
: tiered(w) && group(w) === "spent" ? quota(w, "{n} used · all but used up", "{n} left · all but used up")
|
||||
: tiered(w) && group(w) === "low" ? quota(w, "{n} used · kept for last", "{n} left · kept for last")
|
||||
: (b = behindWhy(r, w)) === "kept" ? quota(w, "{n} used · conversation kept on another", "{n} left · conversation kept on another")
|
||||
: b === "sooner" && soon ? quota(w, "{n} used · renews in {d} · one renewing sooner goes first", "{n} left · renews in {d} · one renewing sooner goes first", { d: dur(soon - n) })
|
||||
: soon ? quota(w, "{n} used · renews in {d}", "{n} left · renews in {d}", { d: dur(soon - n) }) : quota(w, "{n} used", "{n} left");
|
||||
@@ -2742,7 +2747,7 @@ function routingPage(part) {
|
||||
const flying = !resting && (trying.has(id) || onWire.has(id));
|
||||
const on = flying || (!resting && answered.has(id));
|
||||
lightRow(row.li, row.wire, on, flying);
|
||||
row.li.classList.toggle("low", !!(!w.routing && w.known && w.used >= 90));
|
||||
row.li.classList.toggle("low", !!(tiered(w) && w.known && group(w) !== "fine"));
|
||||
row.li.classList.toggle("rest", !!resting || gave.has(id));
|
||||
row.li.classList.toggle("left", !!w.unlisted || !!w.window);
|
||||
// in the colour of the agent whose request is on it: the one it
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// ysicing_01858 on Discord: under Use before expiry an account at 90% of
|
||||
// its week, renewing today, took few requests. 90% of any window held an
|
||||
// account back, the week it would lose at its reset too. A week at 90%
|
||||
// alone (weekLow from the trace) now keeps its place under Smart and Use
|
||||
// before expiry, and its row doesn't say "kept for last"; one at 90% of its
|
||||
// five hours still does, now under Use before expiry too, which said
|
||||
// nothing before. In every language, at a window's width and at 420px, in
|
||||
// both engines.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const now = Date.now();
|
||||
const iso = (ms) => new Date(ms).toISOString();
|
||||
const H = 3600e3;
|
||||
const M = "gpt-5.6-sol";
|
||||
|
||||
// the first has room and renews in 48h, the second is at 91% of a week
|
||||
// renewing in 3h (weekLow), the third at 93% of its five hours
|
||||
const acct = (i, used, h, routing, weekLow) => ({ id: `cx#a${i}`, provider: "codex", name: "Codex", who: `cx-${i}@example.com`, kind: "account", model: M,
|
||||
routing, known: true, used, weekLow, renews: [iso(now + h * H + 5 * 60e3)], usedRenews: iso(now + h * H + 5 * 60e3) });
|
||||
let route;
|
||||
const routeFor = (routing) => ({
|
||||
id: 3, seq: 3, time: iso(now - 2000), agent: "claude", model: M, provider: "codex", done: true, status: 200, ms: 900, tokens: 10,
|
||||
order: [acct(1, 91, 3, routing, true), acct(2, 30, 48, routing, false), acct(3, 93, 2, routing, false)],
|
||||
tries: [{ id: "cx#a1", model: M, start: iso(now - 1500), done: true, status: 200 }],
|
||||
});
|
||||
|
||||
function serve(lang) {
|
||||
const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light", quotaLeft: false } };
|
||||
return async (r) => {
|
||||
const url = new URL(r.request().url());
|
||||
const json = (data) => r.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
|
||||
return json({ mine: true, now: new Date().toISOString(), seq: 3, totals: { requests: 1, rerouted: 0, errors: 0 }, routes: [route] });
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/usage/quotas/history") return json([]);
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await r.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const kept = { en: "kept for last", zh: "留到最后", "zh-TW": "留到最後", ja: "最後に回す", de: "für zuletzt aufgespart" };
|
||||
const rowText = async (page, who) => (await page.locator(".rt-accts > li", { hasText: who }).first().textContent()).trim();
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(`${engine}: a week at 90% renewing soon isn't called kept for last`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const routing of ["pace", ""]) {
|
||||
for (const lang of Object.keys(kept)) {
|
||||
for (const width of [1100, 420]) {
|
||||
await t.test(`${routing || "smart"} ${lang} at ${width}px`, async () => {
|
||||
route = routeFor(routing);
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang));
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
await page.locator(".rt-accts > li", { hasText: "cx-3@example.com" }).first().waitFor();
|
||||
const want = kept[lang];
|
||||
await page.waitForFunction(([w]) => [...document.querySelectorAll(".rt-accts > li")].some((l) => l.textContent.includes("cx-3@example.com") && l.textContent.includes(w)), [want], { timeout: 4000 }).catch(() => {});
|
||||
const five = await rowText(page, "cx-3@example.com");
|
||||
assert.ok(five.includes(want), `${routing} ${lang} ${width}: five hours at 93% says "${five}", not "${want}"`);
|
||||
const week = await rowText(page, "cx-1@example.com");
|
||||
assert.ok(!week.includes(want), `${routing} ${lang} ${width}: a week at 91% renewing in 3h says "${week}"`);
|
||||
const lows = await page.evaluate(() => [...document.querySelectorAll(".rt-accts > li.low")].map((l) => l.textContent.includes("cx-1@") ? 1 : l.textContent.includes("cx-3@") ? 3 : 0));
|
||||
assert.deepEqual(lows, [3], `${routing} ${lang} ${width}: rows dimmed as low`);
|
||||
const over = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth);
|
||||
assert.ok(over <= 1, `${lang} at ${width}: ${over}px past`);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally {
|
||||
await ctx.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -407,6 +407,29 @@ func (a Allowance) For(model string, now time.Time) (used float64, renews []time
|
||||
return used, renews
|
||||
}
|
||||
|
||||
// CapUsed is For's share over the windows that count model other than a
|
||||
// budget known to run a day or longer: a rate cap (the five hours), or a
|
||||
// window that doesn't say how long it runs. Smart and Use before expiry
|
||||
// hold an account back at routes.LowShare of these only: a rate cap near
|
||||
// full refuses the requests sent into it before the allowance is read
|
||||
// again, while what a week has left is lost at its reset, so a week at
|
||||
// 90% renewing today is spent first, not kept for last
|
||||
// (ysicing_01858 on Discord). A window whose reset has passed is empty.
|
||||
func (a Allowance) CapUsed(model string, now time.Time) float64 {
|
||||
model = strings.ToLower(model)
|
||||
used := 0.0
|
||||
for _, l := range a {
|
||||
if !l.applies(model) || l.Span >= budgetSpan {
|
||||
continue
|
||||
}
|
||||
if !l.Resets.IsZero() && !l.Resets.After(now) {
|
||||
continue
|
||||
}
|
||||
used = max(used, l.Used)
|
||||
}
|
||||
return used
|
||||
}
|
||||
|
||||
// Fullest is when the window For's share is of renews: the fullest that
|
||||
// counts model, the later of those as full. A display pairs the two, so
|
||||
// it names one window: a Factory account 32% into its week and 16% into
|
||||
|
||||
@@ -32,6 +32,13 @@ type Seat struct {
|
||||
Learns bool
|
||||
// Used is the share of its allowance used that counts the model, 0–100
|
||||
Used float64
|
||||
// WeekLow: Used is at LowShare or more for its budget windows alone
|
||||
// (a day or longer: the week), no rate cap of it near full
|
||||
// (provider.Allowance.CapUsed). Smart and Use before expiry keep it
|
||||
// with those that have room: what the week has left is lost at its
|
||||
// reset, and kept for last a week at 90% renewing today went unused
|
||||
// (ysicing_01858 on Discord).
|
||||
WeekLow bool
|
||||
// Soon is when its windows renew, the biggest first (Allowance.Renewal)
|
||||
Soon []time.Time
|
||||
// Lapse is when the soonest of what it has left is lost, apart from
|
||||
|
||||
@@ -174,6 +174,32 @@ func TestPace(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A seat at 90% of its week alone (WeekLow) keeps its place in Smart and
|
||||
// Use before expiry: renewing sooner, or with more per hour to lose, it
|
||||
// goes ahead of one with room (ysicing_01858 on Discord). Least used first
|
||||
// still puts it by its share; at 98% it is all but used up in every one.
|
||||
func TestWeekLowKeepsItsPlace(t *testing.T) {
|
||||
now := time.Now()
|
||||
s := []Seat{
|
||||
{Key: "room", Known: true, Used: 30, Soon: []time.Time{now.Add(48 * time.Hour)}, Pace: 70.0 / 48},
|
||||
{Key: "week", Known: true, Used: 91, WeekLow: true, Soon: []time.Time{now.Add(3 * time.Hour)}, Pace: 3},
|
||||
}
|
||||
for name, st := range map[string]Strategy{"smart": Smart, "pace": Pace} {
|
||||
if got := keys(s, Apply(st, "p", s)); !slices.Equal(got, []string{"week", "room"}) {
|
||||
t.Errorf("%s: %v, want [week room]", name, got)
|
||||
}
|
||||
}
|
||||
if got := keys(s, Apply(LeastUsed, "p", s)); !slices.Equal(got, []string{"room", "week"}) {
|
||||
t.Errorf("least used: %v, want [room week]", got)
|
||||
}
|
||||
s[1].Used = 98
|
||||
for name, st := range map[string]Strategy{"smart": Smart, "pace": Pace} {
|
||||
if got := keys(s, Apply(st, "p", s)); !slices.Equal(got, []string{"room", "week"}) {
|
||||
t.Errorf("%s at 98%%: %v, want [room week]", name, 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) {
|
||||
|
||||
@@ -11,7 +11,8 @@ import (
|
||||
)
|
||||
|
||||
// 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
|
||||
// can't take a request: low (in Smart and Use before expiry, of a rate cap:
|
||||
// Seat.WeekLow), and all but used up — where the agent signed
|
||||
// in to it is signed in to another, too (provider.SpentShare).
|
||||
const (
|
||||
LowShare = 90
|
||||
@@ -31,12 +32,19 @@ func tier(share float64) int {
|
||||
|
||||
// seatTier is tier of the seat's share used, but 0 for one set to spend
|
||||
// its credits before another account (Seat.First): a window it uses up
|
||||
// doesn't send its requests elsewhere (jojonas_xyz on X).
|
||||
// doesn't send its requests elsewhere (jojonas_xyz on X). Running low on
|
||||
// its week alone (Seat.WeekLow) is 0 too: Smart and Use before expiry
|
||||
// spend what is lost at the reset, and a week at 90% renewing today was
|
||||
// kept for last behind one renewing tomorrow (ysicing_01858 on Discord).
|
||||
// All but used up is 2 whatever the window.
|
||||
func seatTier(s Seat) int {
|
||||
if s.First {
|
||||
return 0
|
||||
}
|
||||
return tier(s.Used)
|
||||
if t := tier(s.Used); t != 1 || !s.WeekLow {
|
||||
return t
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// byLeft is how a pool's wallets go by what they have left (Seat.Left),
|
||||
@@ -342,9 +350,11 @@ var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int
|
||||
// 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
|
||||
// are Smart's: one at 90% or more of a rate cap that counts the model —
|
||||
// the five hours, which it would be sent into before its allowance was
|
||||
// read again — waits until the others can't answer (a week at 90% alone
|
||||
// doesn't: what it has left is lost at its reset, Seat.WeekLow), one all
|
||||
// but used up
|
||||
// until nothing else can; each tier by the share used, one all but used up
|
||||
// that goes on on its credits first (spentBefore). Among the rest, one
|
||||
// not known that tells what it has left as it answers goes first while it
|
||||
|
||||
Reference in New Issue
Block a user