routing: Least used first counts a small check-in reward about to lapse (kudi3699 on X)

kudi3699 again: v0.1.3877's Lapsing faded the lost share across the
week and needed 0.5 points. A WorkBuddy check-in reward is a few dozen
credits (20 of a 5100 pool is 0.39 points, less the fade), so it stayed
under the threshold until its last hours and the half-used account was
still never picked. The plugin side is fine: mover min is 0.2.29, past
0.2.27 that reports check-in rewards' runsOutAt/runsOut, so no plugin
change.

Allowance.Lapsing is now the whole loss in points when RunsOut is within
7 days, none past it (no fade); routes.lapsingMin is 0.1 points. A seat
at 90%+ is still not helped.

Run (mote): go test internal/routes, internal/provider -run
"Lapsing|LeastUsed|Allowance", internal/gateway -run
"WorkBuddy|LeastUsed|Smart|Pace|Routing"; go vet -tags nogui for linux,
windows, darwin on the three packages; gofmt clean. Broken by hand:
lapsingMin back to 0.5 turns TestLeastUsedSpendsSmallCheckInRewardSixDaysOut
red (20 credits, 6 days out, old 50% vs new 20%). Not run: the full suite
(after the tag), real WorkBuddy accounts.
This commit is contained in:
yetone
2026-11-12 22:14:40 +08:00
parent f57da2b5b9
commit 3bbd8ceaaa
6 changed files with 40 additions and 13 deletions
+1 -1
View File
@@ -296,7 +296,7 @@ recorded as a prediction failure (`noPrediction`).
- In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones, a provider's fallback while the provider's own leads (`standsIn`) and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models.
- Requests that come together spread (`burstSpread` in [`burst.go`](../../internal/gateway/burst.go), #5242: Moody-Sin and Tericerice sent four at once to three Antigravity accounts, In turn and By pace, and every one went to one account). Routing weighs what each seat served (`Tokens`) and its allowance, which move only once a reply ends, and a lane counts a request only once its try begins, so requests planned at the same moment were all planned on the same figures; In turn's next turn (`after`) reads a stick that moves only on an answer too. Once the plan is made (after affinity, rules, pinning, `roomy`, `behindOverflow`), `burstSpread` puts first, of the candidates alike to the first, the one with the fewest requests in flight (`inFlight`, by `candidate.who`), ties keeping routing's order, and counts the request there in the same hold of the lock; the count is given back when `serve` ends. Alike (`burstAlike`): ready as the first is (not resting, aside, reserved, barred, held, capped, a fallback standing in, credits-last or busy behind), the same fallback, fit, protocol, URL and `Via`, the rule's member when a group's rule picked one; In turn any of the round; By pace a pace within a tenth (`paceAlike`, routes.Pace's band), the same `Learns`, both with room (`burstTier` 0) and no wallet told apart (`sameBalance`); Least used within a point used, the same tier and known-ness. In a group, a provider routed its own way (`ownRouting`) is alike only to its own provider's keys, by its routing, and a group in the group to nothing. Smart, In order, By weight and the others keep their order. Not moved, only counted: a conversation kept (`Affinity.Kept`), Strict, an `X-Magpie-Account` pin, a sealed task's lead, a native compaction's reader, and a new conversation `leastHeld` spreads (In turn, `spreadsSessions`), which counts those in flight itself (`sticks.opening`). A plugin's provider and a remote magpie take the same path; the remote spreads over its own accounts, the sessions passed on to it (`passOnCaller`). Not done: putting a markedly slower account behind (speed is read only for Speed first, `speedOf`), as a first token's wait goes with the prompt's size and the vendor's queue more than with the account. `burst_spread_test.go`.
- Stays: Session or Strict under a routing that picks by what is left (Smart, Least used first, Use before expiry: `spreadsSessions`) spreads new conversations the same way (connor_yang on Discord: three sessions over three accounts landed on two). `leastHeld` with `ready` passes over one routing keeps new conversations off (`readyForNew`: resting, a key for another protocol, a provider's fallback while its own model leads, one used past `lowShare`), counts only leads (a key without `|agent:`), and leaves the turn marks alone. A subagent's first request goes to its lead's key or account while that one is `readyForNew` (`withLead`), so a session keeps one account, its subagents included. Held is the last `heldFor` (30 minutes): a session idle longer counts no more. In order, By weight, Free first, Speed first, Cheapest, Manual and a plugin's routing keep their order. An answered conversation is kept as before; the spread only decides where a new one starts. `session_spread_test.go`.
- Least used first spends credits about to lapse first (kudi3699 on X, 11-12: a WorkBuddy account half through a pack ending in March, with check-in credits ending tomorrow, ranked by the whole pool's share and was never picked). `Allowance.Lapsing` is what a window loses at `RunsOut` (`RunsOutLeft` of `Of`, at most what is left) as points of the used share, fading to nothing a week out; an amount not told is zero, never guessed. `routes.Seat.Lapsing` at 0.5 points or more (`urgent`) puts a seat with room ahead of the rest, the soonest `Lapse` first, then the share used as before; one at 90% or more is not helped. Any plugin whose usage window sends `runsOutAt` and `runsOut` gets it. `TestLeastUsedSpendsLapsingFirst`, `TestLeastUsedSpendsWorkBuddyCheckInCreditsAboutToLapse`, `TestAllowanceLapsing`.
- Least used first spends credits about to lapse first (kudi3699 on X, 11-12: a WorkBuddy account half through a pack ending in March, with check-in credits ending tomorrow, ranked by the whole pool's share and was never picked). `Allowance.Lapsing` is what a window loses at `RunsOut` (`RunsOutLeft` of `Of`, at most what is left) as points of the used share, in full when it is within a week and not at all past it (11-12, kudi3699 again: a fade across the week left a 20-credit check-in reward under the threshold); an amount not told is zero, never guessed. `routes.Seat.Lapsing` at 0.1 points or more (`urgent`) puts a seat with room ahead of the rest, the soonest `Lapse` first, then the share used as before; one at 90% or more is not helped. Any plugin whose usage window sends `runsOutAt` and `runsOut` gets it. `TestLeastUsedSpendsLapsingFirst`, `TestLeastUsedSpendsWorkBuddyCheckInCreditsAboutToLapse`, `TestAllowanceLapsing`.
- A session's call to another model than its main conversation's goes to the key or account that main conversation is on (`withSession`, `Affinity.Why` `lead` with `LeadModel`; #5655, jerrychoi, and iamnil on Discord). Each model's conversation is kept under its own scope (`p.ID/model`), so Claude Desktop's own Sonnet calls beside an Opus chat (`desktop-beside`), Claude Code's auto mode classifier and a title were routed as sessions of their own: put by `leastHeld`, or by Smart's order once their cache was cold, on another account, they ran one session on two accounts at once and drained the second one's 5 hours. The main conversation is the session's largest stick (cache read plus written) under another scope by the session's own id, one a header names (`sessionNamed`: a conversation known only by its opening's hash has no session, since unrelated ones that open alike share it; no `|agent:`), answered within `heldFor`, holding at least `cacheWorth` (a main with nothing cached goes where its own next turn is sent), and it leads only while larger than the call's own, so the two never follow each other. It is followed for Why `first`, `gone`, `cold`, `no-cache`, `cache` and `session`, by the model routing put first (in a group, another member on that account is another model and is never picked), and only to one `readyForNew`. It is not followed mid-turn (a kept `Within`), under Strict, In turn, nor for a subagent (`withLead` does that), nor past a rest, a reserve, credits or a fallback routing put first. A call moved off its own cache writes it once where the session goes on reading it. The Routing page says so ("Put on {first}, where this session's {model} is…", `routing-affinity-lead.test.cjs`). `session_lead_test.go`.
- A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits <account> off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again. One let spend its credits, and holding some by its last `/wham/usage` (`credits.has_credits` with a balance over 0, or `unlimited`; `QuotaWindow.Credits`, `Limit.Credits`, `Allowance.OnCredits`), is not out when a window fills (豆子 and Zhenzhen on Discord): ChatGPT may answer the turn that uses the window up 429 `usage_limit_reached` before it spends the credits, and the next turn on them. So that 429 is asked again at once, once a request, on the same account, before a reset is looked at, on the routed path (`creditsAgain`, `creditsAsked`, `Try.Credits`) and on Codex's own sign-in's relay (`relayOnCredits`), rather than ended for the agent, which ended a running session while a new one worked. Refused again, it rests `fallbackCooldown` (`Rest.By` `credits`) and is read again, not until its window renews, and its full windows rest it nowhere else (`full` is zero for it, `spendsCredits`). Smart, Pace and Least used put such an account first of the spent tier (`routes.Seat.Credits`, `spentBefore`): after those with allowance left, ahead of those used up with nothing to go on with (`Weighed.Credits`, told on the Routing page). Switching to credits early, at a few percent left, was weighed and not done: the vendor spends credits only once the allowance is used up, so it would only waste what is left. `TestCodexCreditsAskedAgainAtTheEdge`, `TestCodexCreditsNoLongRest`, `TestCodexCreditsFirstOfTheSpent`, `TestCreditsFirstOfTheSpent`, `routing-codex-credits-again.test.cjs`.
- A third way, set per account, spends the credits only after everything else (gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then the subscription's credits): *Only after every other account, key and fallback* under the Usage card's *Use credits*, `magpie quota credits <account> last`, `settings.CodexCreditsLast` (`provider.CodexCreditsLast`, `SetCodexCreditsMode`; on or off clears it, and an account never in it keeps its place, so a setting saved before keeps its order). Such an account is `creditsLast` while it goes on on its credits (`spendsCredits`) and a window for the model is used up where *off* would hold it (`Allowance.CapHeld` at `WindowCaps{Credits: true}`; a call ChatGPT counts in no window, `freeOnChatGPT`, stays). `restLast` then puts it behind every candidate of the plan, the provider's fallbacks and groups included: ready, then resting, then the credits-last ones in their own order (`Weighed.CreditsLast`). Affinity doesn't keep a conversation on one while one not on its credits leads (`Affinity.Why` `credits`, `lastBehind`), within a turn too, and In turn's next pick and Smart/Pace/Least used's spreading of new sessions never bring one forward (`after`, `leastHeld`, `readyForNew`). Strict affinity keeps it, as a rule, an `X-Magpie-Account` pin and a sealed task's lead (`leadFirst`) still put theirs first. A reset is still spent before its credits when the try reaches it (`resetBeforeCredits`). Codex's own sign-in's relay has the one account and nothing to put first, so there it is as *on*. The Routing page tells each: behind the rest, first when every one is, and the conversation moved. `TestCodexCreditsLastAfterTheOthers`, `TestCodexCreditsLastAfterTheFallback`, `TestCodexCreditsLastNotKept`, `TestCodexCreditsLastMode`, `codex-credits-last.test.cjs`.
@@ -169,3 +169,24 @@ func TestLeastUsedSpendsWorkBuddyCheckInCreditsAboutToLapse(t *testing.T) {
t.Fatalf("least used first as before: %s", got)
}
}
// kudi3699 on X, again: the check-in reward that lapses is a few dozen
// credits (20 of 5100, six days out), not 500 tomorrow. It was faded to
// under the threshold, so the half-used account was still never picked.
func TestLeastUsedSpendsSmallCheckInRewardSixDaysOut(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 }
p := provider.Provider{ID: "workbuddy", Routing: provider.LeastUsed, Account: &provider.Account{Agent: "workbuddy", User: "a"}}
acct := func(user string) candidate {
return candidate{p: provider.Provider{ID: "workbuddy", Account: &provider.Account{Agent: "workbuddy", User: user}}, model: "hy3", rest: "workbuddy#" + user}
}
share["old"] = provider.Allowance{{Used: 50, Amount: 2550, Of: 5100, Unit: "credits", RunsOut: now.Add(6 * 24 * time.Hour), RunsOutLeft: 20}}
share["new"] = provider.Allowance{{Used: 20, Amount: 1020, Of: 5100, Unit: "credits", RunsOut: now.Add(200 * 24 * time.Hour), RunsOutLeft: 4080}}
got, _ := weigh(p, []candidate{acct("new"), acct("old")}, "hy3", provider.Chat)
if got[0].p.Account.User != "old" {
t.Fatalf("a small reward ending in 6 days not spent first: %s", got[0].p.Account.User)
}
}
+8 -7
View File
@@ -677,14 +677,16 @@ func (a Allowance) Lapse(model string, now time.Time) time.Time {
}
// lapseHorizon is how far ahead credits about to be lost count as spent
// already: they weigh in full when they lapse now and fade to nothing a
// week out (Allowance.Lapsing).
// already: all of them within a week, none past it (Allowance.Lapsing).
// They were faded across the week before, so a daily check-in reward of a
// few dozen credits, a fraction of a point of a 5000-credit pool, fell
// under the threshold until its last hours (kudi3699 on X).
const lapseHorizon = 7 * 24 * time.Hour
// Lapsing is the share of an allowance, in points of the 0–100 used share,
// that is lost soon whatever is done: what a window that counts model
// loses at RunsOut (RunsOutLeft of Of, never more than it has left), less
// the further off that is, to nothing at lapseHorizon. Credits that are
// loses at RunsOut (RunsOutLeft of Of, never more than it has left), when
// that is within lapseHorizon. Credits that are
// lost unspent cost nothing to spend, so a ranking by the share used takes
// them off it, and an account whose month is half used but whose check-in
// credits lapse tomorrow is not kept behind a fresh one (kudi3699 on X).
@@ -697,12 +699,11 @@ func (a Allowance) Lapsing(model string, now time.Time) float64 {
if !l.applies(model) || !l.RunsOut.After(now) || l.RunsOutLeft <= 0 || l.Of <= 0 {
continue
}
fade := 1 - float64(l.RunsOut.Sub(now))/float64(lapseHorizon)
if fade <= 0 {
if l.RunsOut.Sub(now) >= lapseHorizon {
continue
}
u := min(100, max(0, l.Used))
best = max(best, fade*min(100*l.RunsOutLeft/l.Of, 100-u))
best = max(best, min(100*l.RunsOutLeft/l.Of, 100-u))
}
return best
}
+8 -3
View File
@@ -242,17 +242,22 @@ func TestAllowanceLapsing(t *testing.T) {
w := func(used float64, in time.Duration, amount, of float64) Allowance {
return Allowance{{Used: used, Of: of, RunsOut: now.Add(in), RunsOutLeft: amount}}
}
// 500 of 5000 lapse in a day: 10 points, less a seventh
if got := w(50, 24*time.Hour, 500, 5000).Lapsing("m", now); !near(got, 10*(1-1.0/7)) {
// 500 of 5000 lapse in a day: 10 points, whole
if got := w(50, 24*time.Hour, 500, 5000).Lapsing("m", now); !near(got, 10) {
t.Fatalf("a day out: %v", got)
}
// a check-in reward of 20 credits ending in 6 days, in a 5100 pool:
// 0.39 points, not faded away (kudi3699 on X)
if got := w(50, 6*24*time.Hour, 20, 5100).Lapsing("m", now); !near(got, 100*20.0/5100) {
t.Fatalf("a small reward 6 days out: %v", got)
}
if got := w(50, 8*24*time.Hour, 500, 5000).Lapsing("m", now); got != 0 {
t.Fatalf("past the horizon: %v", got)
}
if got := w(50, 24*time.Hour, 0, 5000).Lapsing("m", now); got != 0 {
t.Fatalf("an amount not told was guessed: %v", got)
}
if got := w(95, 24*time.Hour, 4000, 5000).Lapsing("m", now); !near(got, 5*(1-1.0/7)) {
if got := w(95, 24*time.Hour, 4000, 5000).Lapsing("m", now); !near(got, 5) {
t.Fatalf("more than is left: %v", got)
}
if got := w(50, -time.Hour, 500, 5000).Lapsing("m", now); got != 0 {
+1 -1
View File
@@ -298,7 +298,7 @@ func TestLeastUsedSpendsLapsingFirst(t *testing.T) {
if got := keys(s, Apply(LeastUsed, "p", s)); !slices.Equal(got, []string{"half", "fresh"}) {
t.Fatalf("lapsing credits not spent first: %v", got)
}
s = []Seat{{Key: "fresh", Known: true, Used: 20}, {Key: "half", Known: true, Used: 50, Lapsing: 0.1, Lapse: now.Add(24 * time.Hour)}}
s = []Seat{{Key: "fresh", Known: true, Used: 20}, {Key: "half", Known: true, Used: 50, Lapsing: 0.05, Lapse: now.Add(24 * time.Hour)}}
if got := keys(s, Apply(LeastUsed, "p", s)); !slices.Equal(got, []string{"fresh", "half"}) {
t.Fatalf("a trifle unbalanced the pool: %v", got)
}
+1 -1
View File
@@ -22,7 +22,7 @@ const (
// lapsingMin is the points of the used share that lapsing soon unspent
// (Seat.Lapsing) must reach to send an account ahead in Least used first:
// a few credits of a large pool are not worth unbalancing it for.
const lapsingMin = 0.5
const lapsingMin = 0.1
// urgent says a seat with room has credits to spend before they lapse.
func urgent(s Seat) bool { return tier(s.Used) == 0 && s.Lapsing >= lapsingMin }