routing: Smart ranks an account by its week once its month can't be used up before it renews (#5639)

Smart ranked a Volcengine Agent Plan (5 hours 2,000, week 7,000, month
20,000) by its month, the biggest window, so it always stood behind
accounts renewing weekly, and its month could reach a point where it
could no longer be used up before it renewed.

The rule keeps #1778's reasoning: a month holding less than its weeks add
up to is the real cap while the weeks can still carry it. Once what the
biggest window has left is more than the next window (a day or longer,
same unit, counts known) can let through between its own reset and the
biggest one's (Of x time between / Span), what the week leaves at its
reset is lost, and the week ranks the account.

- provider: Allowance.Unreached counts the biggest windows to pass over.
  Renewal and Seat.Soon are unchanged for other strategies and plugins.
- routes: Seat.Unreached; Smart compares Soon past it.
- gateway: weighRouted fills it; the trace's Weighed carries `unreached`.
- GUI Routing: renewsBy skips those windows, and a new story line says the
  shorter window decides. The Smart header and the group hint say so in
  en, zh, zh-TW, ja and de.
- docs: reference.md (How magpie picks an account) and
  subsystems/gateway-routing.md.

With the issue's numbers as reported (month 696 h away, 18,372 left),
four weeks carry 28,017, so the order is unchanged. Two weeks before the
month renews, 14,017 < 18,372, and the plan goes first, ahead of the
point where a week's leftover is lost.

Run on mote at this tree (base 2dac9b84e; origin/main bb33142ea touches
none of these files):
- go test -tags nogui ./internal/provider ./internal/routes: ok
- go test of TestMonthOutOfReachRanksByWeek,
  TestSmartSpendsAWeekTheMonthCantWait, TestSmartPassesAnUnreachedWindow
  and the Smart/Renewal/Weighed tests in provider, routes, gateway: ok
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok
- gofmt -l internal/: clean
- node --test routing-key-windows.test.cjs: 52/52 in Chromium and WebKit,
  en/zh/ja/de, the new #5639 scene included

Broken by hand:
- Unreached returning 0: TestMonthOutOfReachRanksByWeek ("two weeks to
  go", "the last week") and TestSmartSpendsAWeekTheMonthCantWait went red.
- Smart comparing a.Soon, b.Soon whole: TestSmartPassesAnUnreachedWindow
  and TestSmartSpendsAWeekTheMonthCantWait went red.
- client.js without the slice and the story line: the #5639 GUI case went
  red (Chromium en).

Still running when pushed (the owner's rule not to hold a verified commit
behind the suite): the full internal/gateway package; all routing-*,
panel-routing*, gui-zh-tw/ja/de and i18n GUI files in both engines; and
the full go test ./... -timeout 45m. Any red they show gets its own issue.

Not tried: a real Volcengine Agent Plan account. Ark replies that send
only Percent carry no counts, so the rule can't apply to them. Not
changed: Use before expiry (Pace) still ranks this plan by its month;
filed as #5641.

Reported-by: louisgreen0726
Refs #5639
This commit is contained in:
yetone
2026-11-08 02:08:08 +08:00
parent bb33142eae
commit 3b541a7f36
13 changed files with 297 additions and 28 deletions
+5 -1
View File
@@ -2033,7 +2033,11 @@ each of these groups ordered by the share used.
when the month holds less than its weeks add up to (Factory's, by
one user's readings, about two weeks' worth), what a week leaves isn't
lost at the week's reset, as the
month still has it to spend later. Its row
month still has it to spend later. Once the weeks still to come before
the month renews can't let through what the month has left (a
Volcengine Agent Plan: 20,000 a month, 7,000 a week), what a week
leaves is lost at its reset after all, and the account goes by its
week. Its row
on the Routing page says the fullest window's share with when that
window renews: "32% used · renews in 3 days" is the week's.
- **In order**: the accounts in their order. The first takes every request
+1 -1
View File
@@ -212,7 +212,7 @@ recorded as a prediction failure (`noPrediction`).
- A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then, after a blank line (two newlines when that write stopped inside a line, `holdWriter.atLine`, #2446), the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop` (`usage.LoopErrType`), and Usage counts them per model (`Totals.Loops`), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, `TestLoopsCountedPerModel`, `usage-loops.test.cjs`). A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A reply passed through in the agent's own protocol is asked again once too, at the fallback loop (`holdWriter.mayReloop`, `letGoLoop`; #2436, lqisgod: pi's Chat stream to WorkBuddy was cut at once): when nothing of the try has reached the agent yet, in any protocol, its held bytes are dropped; when its reasoning is already passing, only a Chat stream goes on, written up to the end of the tripping event, with the next try's chunks after it. An Anthropic or Responses stream already passing still ends with the error, since a second `message_start` or `response.created` can't follow. Each re-ask, in place or at the fallback loop, counts in the usage record's tries. A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`). A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off.
- A conversation going round one tool call is answered by magpie and sent nowhere (audie on Discord: Codex Desktop on WorkBuddy's deepseek-v4-pro read the same file 308 times in half an hour, and 340 times that evening, 537 credits). `stoppedToolLoop` ([`tool_loop.go`](../../internal/gateway/tool_loop.go)) runs in `serveAgent` before hooks, middleware and routing, and in the Codex backend's passthrough on Codex's own sign-in. It reads the request's own history, so it is per conversation and keeps no state: when the last `toolLoopRepeats` (8) turns are each the same calls (name and arguments, keys in any order, call ids ignored) answered with the same results (with Codex's `Wall time`, `Chunk ID` and `duration_seconds` taken out, `runNoise`) and nothing else from the user, the turn is answered in the agent's own protocol, streamed or whole (`writeLocalText` through `relayStatus`), with a notice naming the call. Any different result, or a word of the user's, starts the count again; the notice is a turn without calls, so the user's next word goes on. A body with fewer than 8 tool results isn't parsed (`mayLoop`), and only the newest 64 items of a long one are (`tailOf`, gjson), ~1ms for a 1.5MB turn (`BenchmarkToolLoopCheck`). The turn is recorded as Codex's title turns are (`answeredHere`): the Routing trace as "Tool loop stopped", and a usage row with provider `magpie`, rejected, its session and an error starting `tool loop:`. A poll that gets the same answer 8 times in a row is stopped too. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off with the reply guard. Verification: `go test -tags nogui ./internal/gateway -run 'TestToolLoop'`.
- A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: `reasoning_content` (DeepSeek's, which OpenCode and most clients send), `reasoning` (OpenRouter's) or `reasoning_details` (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (`messageReasoning`, `reasoningText`, read by `parseChat` in [chat.go](../../internal/gateway/chat.go)); the passthrough has read all three since `mistralThinking` (#494), which was the one place that did. The same conversion covers a request translated to Mistral's Chat API (`forwardTranslated`): the build replays a turn's thinking in `reasoning_content` for a model whose name says DeepSeek wherever it is served (`chatReplaysReasoning`), which Mistral refuses — 422 `extra_forbidden` on `messages[].reasoning_content`, every follow-up of a Codex tool loop after its first call (#4906) — so the built body goes through `mistralThinking` too, and its thinking parts reach Mistral as its own replies carry them; a whitespace-only thinking (the `" "` a tool turn with no reasoning item is given) is dropped, not sent as a blank part. `TestTranslatedReasoningAsThinkingForMistral`, `TestTranslatedToolTurnWithoutReasoningForMistral`. Before that the parse layer read `reasoning_content` alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning.
- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). When the renewals tie to the hour, Smart goes by that moment once more (`Allowance.Lapse`, `Seat.Lapse`), so of accounts renewing together (WorkBuddy's free accounts all reset at the month's end, plugin 0.1.35) the one whose credits left lapse first, after that end, goes first, and one telling none goes after (zhaocai_83020 on Discord). Only Smart reads it; Use before expiry, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.
- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A biggest window its next one can't use up before it renews is passed over (`Allowance.Unreached`, `Seat.Unreached`, the trace's `unreached`): when what it has left is more than the next window, a day or longer and counted in the same unit, lets through between its own reset and the biggest one's (`Of` × the time between ÷ `Span`), what the next leaves at its reset is lost, so it ranks the account. A month holding less than its weeks add up to still ranks it while they can carry it (#1778); a Volcengine Agent Plan, 20,000 a month and 7,000 a week, goes by its week from about two weeks before its month renews (#5639, louisgreen0726; `TestMonthOutOfReachRanksByWeek`, `TestSmartSpendsAWeekTheMonthCantWait`, `TestSmartPassesAnUnreachedWindow`). Windows that tell only a share, and Ark replies with `Percent` alone, are never compared. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). When the renewals tie to the hour, Smart goes by that moment once more (`Allowance.Lapse`, `Seat.Lapse`), so of accounts renewing together (WorkBuddy's free accounts all reset at the month's end, plugin 0.1.35) the one whose credits left lapse first, after that end, goes first, and one telling none goes after (zhaocai_83020 on Discord). Only Smart reads it; Use before expiry, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.
- A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`.
- A request's masking record is told to the app for the "Masking alert" notification (Must2333 on X, `OnMasked` in [`masked.go`](../../internal/gateway/masked.go), set by the GUI; nil under `magpie serve`), after `maskrec.Hold` and with its text around placeholders (`Snips`, `Back`) taken out. [`mask_alert.go`](../../internal/gui/mask_alert.go) keeps the records while `settings.MaskAlert` is on (off until turned on, in Settings → Usage, hidden with masking) and says only the values a record masked for the first time (`maskrec.Fresh`, [`first.go`](../../internal/maskrec/first.go): each placeholder by the key of the first record that had it, read from memory and the days kept, so a conversation's history sent again each turn, or after a restart, is not news; a value sent as written is not one masked). A burst is gathered for `maskGather` (3s) and said as one, and one is said at most every `maskGap` (1 minute), what came in between said after it. It says each kind with its count and up to two agents, never a value nor its hint; a click opens the Masking page on the latest record (`clickView`, `masking&key=`). A held-back request (`noteBlocked`) is not said; a value whose records have all aged out (30 days) is new again. `TestFreshOnlyTheFirstTime`, `TestMaskAlertFirstTimeOnly`, `TestMaskAlertNeverSaysTheValue`, `TestMaskAlertCoalesces`, `mask-alert.test.cjs`.
- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (`heldClock`: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (`creditRest`, or `quotaRest` with no `Provider.OwnQuotaRest`), is held so only once it was refused so twice in a row (`Rest.first`): a single refusal may be a moment's, and the next request, the agent's retry first, asks it again (zoecats on Discord: a local aggregator said 429 `insufficient_quota` "quota exhausted" for the moment it switched upstreams, and every request was answered from its rest of 15 or 30 minutes, which only the provider's "Rests" switch, `LimitRestOff`, let through before). Held, it is asked again a minute on (`Rest.askAt`, `fallbackCooldown`), once, and held again if refused (`Rest.asksAt`); a time the vendor named, or the user set, holds it from the first refusal to then. The rest itself stays as long as before, so the order still passes it over for a candidate that is ready. The last key left rests too when it is refused so, as the keys before it do, and so does the last account left (a Codex or other subscription account; `quotaHeld` still holds keys alone, and `autoReset` lifts the rest of an account it spends a reset of): before, an account last in an in-order group, out of its quota, was never rested, so every request a relay ahead of it failed for a moment went on to it and ended on its 429 (dbydd on Discord; `TestGroupSpentLastAccountRests`). Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (`soonestBack`, by `asksAt`), none after a key's first refusal. `TestRetryAfterALimitIsAsked`, `TestHeldLimitAskedAgainInAMinute`. A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest <id> 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest <id> until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.
+68
View File
@@ -0,0 +1,68 @@
package gateway
import (
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// In a group routed Smart, a Volcengine Agent Plan key (5 hours of 2,000,
// a week of 7,000, a month of 20,000) stands behind a Codex account whose
// week renews in three days while its month can still be used up — and
// goes first once the weeks left before the month renews can't carry
// what the month has left, as what its week leaves is lost at its reset
// then (#5639, louisgreen0726's numbers). The Routing page is told which
// window ranks it.
func TestSmartSpendsAWeekTheMonthCantWait(t *testing.T) {
now := time.Now()
old := allowances
t.Cleanup(func() { allowances = old })
allowances = func(string) map[string]provider.Allowance {
return map[string]provider.Allowance{"me@example.com": {{Used: 10, Resets: now.Add(3 * 24 * time.Hour), Span: 7 * 24 * time.Hour}}}
}
weekRenews := now.Add(23*time.Hour + 36*time.Minute)
agentPlan := func(weekUsed, monthUsed float64, month time.Time) provider.Allowance {
return provider.Allowance{
{Used: 0, Span: 5 * time.Hour, Of: 2000, Name: "5 hours"},
{Used: weekUsed / 70, Amount: weekUsed, Of: 7000, Resets: weekRenews, Span: 7 * 24 * time.Hour, Name: "Weekly"},
{Used: monthUsed / 200, Amount: monthUsed, Of: 20000, Resets: month, Span: 30 * 24 * time.Hour, Name: "Month"},
}
}
of := map[string]provider.Allowance{}
keyWindows(t, of)
codex := provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "me@example.com"}}
ark := provider.Provider{ID: "volcengine", Key: "ark-key", Anthropic: "https://ark.cn-beijing.volces.com/api/plan"}
heads := []candidate{
{p: codex, model: "gpt-6-astra", rest: "codex"},
{p: ark, model: "doubao-seed-2.0-pro", rest: "volcengine"},
}
g := provider.Provider{ID: provider.GroupPrefix + "g"}
// as reported: 18,372 of the month left, four weeks to carry it
of["ark-key"] = agentPlan(1628, 1628, now.Add(696*time.Hour))
got, wg := weigh(g, heads, "", provider.Responses)
if restsOf(got) != "codex volcengine " {
t.Fatalf("the month within reach: %s", restsOf(got))
}
if w := weighed(got[1], ark, wg, false, provider.Responses); w.Unreached != 0 {
t.Fatalf("the month within reach, traced: %+v", w)
}
// two weeks on, the plan not used: two weeks hold 14,000 of 18,372
of["ark-key"] = agentPlan(0, 1628, weekRenews.Add(2*7*24*time.Hour+24*time.Minute))
got, wg = weigh(g, heads, "", provider.Responses)
if restsOf(got) != "volcengine codex " {
t.Fatalf("the month out of reach: %s", restsOf(got))
}
if w := weighed(got[0], ark, wg, false, provider.Responses); w.Unreached != 1 || len(w.Renews) != 3 {
t.Fatalf("the month out of reach, traced: %+v", w)
}
// a month holding less than its weeks add up to, with 9,000 left
// that two weeks carry: the month ranks it, as before (#1778)
of["ark-key"] = agentPlan(0, 11000, weekRenews.Add(2*7*24*time.Hour))
if got, _ := weigh(g, heads, "", provider.Responses); restsOf(got) != "codex volcengine " {
t.Fatalf("the month the real cap: %s", restsOf(got))
}
}
+8 -5
View File
@@ -2238,9 +2238,12 @@ type left struct {
// (Allowance.Fullest), zero when not known
fullest time.Time
soon []time.Time // renews as Smart ranks them (Allowance.Renewal)
lapse time.Time // when the soonest of what is left is lost (Allowance.Lapse)
pace float64 // weekly pace: share of its week left per hour until it renews
due time.Time // when the window that pace went by renews; zero when not known
// unreached: how many of soon's windows Smart passes over, as they
// can't be used up before they renew any more (Allowance.Unreached)
unreached int
lapse time.Time // when the soonest of what is left is lost (Allowance.Lapse)
pace float64 // weekly pace: share of its week left per hour until it renews
due time.Time // when the window that pace went by renews; zero when not known
// restarts: when an auto-used reset starts its windows again
// (Allowance.Restarts), zero when none will; dueRestart: due is that,
// sooner than the window renews by itself; dueExpiry: due is when
@@ -2357,7 +2360,7 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide
pc, due := a.Pace(c.model, now)
amt, of, unit := a.Count(c.model, now)
rs := a.Restarts(now)
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,
l := left{used: u, renews: r, fullest: a.Fullest(c.model, now), soon: a.Renewal(c.model, now), unreached: a.Unreached(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
@@ -2388,7 +2391,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, 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,
Used: l.used, WeekLow: l.weekLow, Soon: l.soon, Unreached: l.unreached, 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), Lead: c.p.UseFirst}
}
routed.Unlock()
+6
View File
@@ -364,6 +364,11 @@ type Weighed struct {
// "expiry" when it is when credits in them expire, sooner than they
// renew (Allowance.Pace)
DueBy string `json:"dueBy,omitempty"`
// Unreached: how many of Renews' windows, the biggest first, Smart
// passes over, as what they have left can't be used up before they
// renew unless the next one's is used first: the next one ranks it
// (left.unreached, #5639)
Unreached int `json:"unreached,omitempty"`
// Restarts: when that reset starts them again, set when it is sooner
// than its biggest window renews — Smart goes by it then (#718)
Restarts *time.Time `json:"restarts,omitempty"`
@@ -587,6 +592,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.Unreached = l.unreached
w.WeekLow = l.weekLow && keepsWeek(p.Routing)
if !l.fullest.IsZero() {
ur := l.fullest
@@ -625,7 +625,7 @@ function routingPage(part) {
const tryOk = (tr) => tr.status < 400 && !tr.fail;
const API = { anthropic: "Anthropic", chat: "OpenAI", responses: "OpenAI Responses", gemini: "Gemini" };
const MODES = {
"": ["Smart", "Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours. One at 90% or more waits until the others can't answer; one resting after a failure goes last."],
"": ["Smart", "Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours, and one whose month its weeks can no longer use up before it renews by its week. One at 90% or more waits until the others can't answer; one resting after a failure goes last."],
order: ["In order", "In order: the first answers everything until it can't; then the next."],
drain: ["Until used up", "Until used up: one answers everything until its quota is used up; then the next, which keeps them even after the one before renews."],
rotate: ["In turn", "In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache."],
@@ -700,10 +700,12 @@ function routingPage(part) {
// of one window says when.
const usedRenews = (w) => known0(w.usedRenews) ? at(w.usedRenews) : (w.renews || []).length === 1 ? renews(w)[0] : 0;
// renewsBy is renews as Smart ranks them: an auto-used Codex reset that
// starts the windows again sooner (restarts) is when they renew (#718)
// starts the windows again sooner (restarts) is when they renew (#718),
// and the biggest windows that can't be used up before they renew any
// more (unreached: a month its weeks can't carry) rank it no more (#5639)
const renewsBy = (w) => {
const rs = known0(w.restarts) ? at(w.restarts) : 0;
return renews(w).map((x) => rs && (!x || rs < x) ? rs : x);
return renews(w).slice(w.unreached || 0).map((x) => rs && (!x || rs < x) ? rs : x);
};
// cmpRenews orders two accounts' windows as the gateway does: the
@@ -935,6 +937,7 @@ function routingPage(part) {
if (!next) return t("{who} goes first: it has quota to spare, and the others are kept for last.", { who: w });
const { c, k } = cmpRenews(f, next);
if (c < 0 && k === 0 && known0(f.restarts)) return t("{who} goes first: of those with quota to spare, its allowance starts again soonest — one of its Codex resets about to run out is used by itself in {d}, and what it has left then is lost. {other} renews later and keeps its own.", { who: w, d: dur(at(f.restarts) - at(r.time)), other: who(next) });
if (c < 0 && k === 0 && f.unreached) return t("{who} goes first: its longer window has more left than its shorter one can still let through before it renews, so the shorter one decides — it renews soonest, in {d}, and what it has left then is lost. {other} renews later and keeps its own.", { who: w, d: dur(renewsBy(f)[0] - at(r.time)), other: who(next) });
if (c < 0 && k === 0) return t("{who} goes first: of those with quota to spare, its allowance renews soonest — in {d} — and what it has left then is lost. {other} renews later and keeps its own.", { who: w, d: dur(renews(f)[0] - at(r.time)), other: who(next) });
if (c < 0) return t("{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.", { who: w, other: who(next), d: dur(renewsBy(f)[k] - at(r.time)) });
if (c === 0 && walletWhy(r, f)) return walletWhy(r, f);
@@ -5717,7 +5720,7 @@ function routingPage(part) {
strict: "A conversation stays with the account or key that answered it and never moves to another, even past its usage cap: when that one is rate limited or out of quota, the error goes to the agent. New conversations are routed as usual.",
};
const GROUP_HINT = {
"": "Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later; one resting after a failure goes last.",
"": "Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later, and one whose month its weeks can no longer use up before it renews by its week; one resting after a failure goes last.",
order: "In order: the first model until it can't answer, then the next — each over its own accounts or keys as its provider routes them.",
drain: "Until used up: one account or key, across the members, takes every request until it is used up; then the next in the list, which keeps them even after an earlier one renews. One rate limited or failing is passed over only while it rests.",
rotate: "In turn: each conversation's next turn goes to the next member's account or key, spreading the load.",
+12 -8
View File
@@ -375,7 +375,7 @@ magpie.strings({
"each provider routes over its own": "各供应商在自己的账号或 Key 间路由",
"Change how {name} routes": "改 {name} 的路由方式",
"Only one account or key is on for this, so routing has nothing to choose between. Turn on a second in the provider's editor, and how it routes is set under Several accounts or keys below.": "这里只开了一个账号或 Key,路由没有可选的。在供应商的编辑页再开一个,路由方式就在下面的「多账号 / 多 Key」里设置。",
"Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later; one resting after a failure goes last.": "智能:成员的账号和 Key 统一排序。有余量的订阅中额度最先重置的排第一,以周额度为准;只有 5 小时额度的账号(如 Claude Enterprise)按 5 小时重置,排在更晚重置的周额度之前;失败后休息中的排最后。",
"Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later, and one whose month its weeks can no longer use up before it renews by its week; one resting after a failure goes last.": "智能:成员的账号和 Key 统一排序。有余量的订阅中额度最先重置的排第一,以周额度为准;只有 5 小时额度的账号(如 Claude Enterprise)按 5 小时重置,排在更晚重置的周额度之前;月额度已来不及靠每周额度用完的按周重置;失败后休息中的排最后。",
"In order: the first model until it can't answer, then the next — each over its own accounts or keys as its provider routes them.": "按顺序:先用第一个模型,无法响应再换下一个;各成员按其供应商的路由在自己的账号或 Key 间分配。",
"In turn: each conversation's next turn goes to the next member's account or key, spreading the load.": "轮流:会话的每一轮交给下一个成员的账号或 Key,均摊负载。",
"Least used first: the account or key with the most of its allowance left goes first.": "最少使用优先:剩余额度最多的账号或 Key 排第一。",
@@ -442,7 +442,7 @@ magpie.strings({
"Another magpie serves the gateway; its routing plays live in that magpie's window.": "网关由另一个 magpie 提供,它的路由在那个 magpie 的窗口里实时播放。",
"The gateway isn't running, so nothing is routed.": "网关没有运行,因此没有任何路由。",
"The gateway is served by a magpie without a window (magpie serve), so its routing can't be watched. Stop it and let this magpie serve the gateway to see routing live.": "网关由无窗口的 magpie(magpie serve)提供,无法在此查看路由。停止它并由当前 magpie 提供网关,即可实时查看。",
"Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours. One at 90% or more waits until the others can't answer; one resting after a failure goes last.": "智能:有余量的账号中额度最先重置的排第一,以免剩余额度在重置时作废。以周额度为准;只有 5 小时额度的账号按 5 小时重置。用到 90% 以上的,等其他都无法响应时才用;失败后休息中的排最后。",
"Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours, and one whose month its weeks can no longer use up before it renews by its week. One at 90% or more waits until the others can't answer; one resting after a failure goes last.": "智能:有余量的账号中额度最先重置的排第一,以免剩余额度在重置时作废。以周额度为准;只有 5 小时额度的账号按 5 小时重置,月额度已来不及靠每周额度用完的按周重置。用到 90% 以上的,等其他都无法响应时才用;失败后休息中的排最后。",
"Smart: keys that suit the request go first — one made for the model's own API — then in their order. One resting after a failure goes last.": "智能:适合此请求的 Key(为该模型原生 API 准备的)排前,其余按顺序。失败后休息中的排最后。",
"In order: the first answers everything until it can't; then the next.": "按顺序:第一个处理所有请求,无法响应时再换下一个。",
"In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache.": "轮流:会话的下一轮交给上一轮回答者的下一个账号,新会话再往后一个;一轮之内不换账号,保持提示词缓存。",
@@ -479,6 +479,7 @@ magpie.strings({
"{who} goes first: it has quota to spare, and the others are kept for last.": "{who} 排第一:它还有余量,其他账号留到最后。",
"{who} goes first: of those with quota to spare, its allowance starts again soonest — one of its Codex resets about to run out is used by itself in {d}, and what it has left then is lost. {other} renews later and keeps its own.": "{who} 排第一:有余量的账号中它的额度最先重新开始,{d}后将自动使用其快到期的 Codex 重置卡,届时剩余额度作废。{other} 重置较晚,额度暂留。",
"{who} goes first: of those with quota to spare, its allowance renews soonest — in {d} — and what it has left then is lost. {other} renews later and keeps its own.": "{who} 排第一:有余量的账号中它的额度最先重置({d}后),届时剩余额度作废。{other} 重置较晚,额度暂留。",
"{who} goes first: its longer window has more left than its shorter one can still let through before it renews, so the shorter one decides — it renews soonest, in {d}, and what it has left then is lost. {other} renews later and keeps its own.": "{who} 排第一:它较长窗口的剩余额度,较短窗口在其重置前已来不及放行,所以按较短窗口排序——它最先重置({d}后),届时剩余额度作废。{other} 重置较晚,额度暂留。",
"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} 排第一:它与 {other} 的额度在同一小时重置,而它较短的窗口更早({d}后)。",
"{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} 和 {other} 在同一小时内重置,保持原顺序,厂商的提示词缓存也保持命中。",
"{who} goes first, in the order given: when its allowance renews isn't known.": "{who} 按原有顺序排第一:不知道它的额度何时重置。",
@@ -1048,7 +1049,7 @@ magpie.strings({
"each provider routes over its own": "各供應商在自己的帳號或 Key 間路由",
"Change how {name} routes": "改 {name} 的路由方式",
"Only one account or key is on for this, so routing has nothing to choose between. Turn on a second in the provider's editor, and how it routes is set under Several accounts or keys below.": "這裡只開了一個帳號或 Key,路由沒有可選的。在供應商的編輯頁再開一個,路由方式就在下面的「多帳號 / 多 Key」裡設定。",
"Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later; one resting after a failure goes last.": "智慧:成員的帳號和 Key 統一排序。有餘量的訂閱中額度最先重置的排第一,以週額度為準;只有 5 小時額度的帳號(如 Claude Enterprise)按 5 小時重置,排在更晚重置的週額度之前;失敗後休息中的排最後。",
"Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later, and one whose month its weeks can no longer use up before it renews by its week; one resting after a failure goes last.": "智慧:成員的帳號和 Key 統一排序。有餘量的訂閱中額度最先重置的排第一,以週額度為準;只有 5 小時額度的帳號(如 Claude Enterprise)按 5 小時重置,排在更晚重置的週額度之前;月額度已來不及靠每週額度用完的按週重置;失敗後休息中的排最後。",
"In order: the first model until it can't answer, then the next — each over its own accounts or keys as its provider routes them.": "按順序:先用第一個模型,無法回應再換下一個;各成員按其供應商的路由在自己的帳號或 Key 間分配。",
"In turn: each conversation's next turn goes to the next member's account or key, spreading the load.": "輪流:會話的每一輪交給下一個成員的帳號或 Key,均攤負載。",
"Least used first: the account or key with the most of its allowance left goes first.": "最少使用優先:剩餘額度最多的帳號或 Key 排第一。",
@@ -1115,7 +1116,7 @@ magpie.strings({
"Another magpie serves the gateway; its routing plays live in that magpie's window.": "閘道由另一個 magpie 提供,它的路由在那個 magpie 的窗口裡即時播放。",
"The gateway isn't running, so nothing is routed.": "閘道沒有執行,因此沒有任何路由。",
"The gateway is served by a magpie without a window (magpie serve), so its routing can't be watched. Stop it and let this magpie serve the gateway to see routing live.": "閘道由無視窗的 magpie(magpie serve)提供,無法在此檢視路由。停止它並由目前 magpie 提供閘道,即可即時檢視。",
"Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours. One at 90% or more waits until the others can't answer; one resting after a failure goes last.": "智慧:有餘量的帳號中額度最先重置的排第一,以免剩餘額度在重置時作廢。以週額度為準;只有 5 小時額度的帳號按 5 小時重置。用到 90% 以上的,等其他都無法回應時才用;失敗後休息中的排最後。",
"Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours, and one whose month its weeks can no longer use up before it renews by its week. One at 90% or more waits until the others can't answer; one resting after a failure goes last.": "智慧:有餘量的帳號中額度最先重置的排第一,以免剩餘額度在重置時作廢。以週額度為準;只有 5 小時額度的帳號按 5 小時重置,月額度已來不及靠每週額度用完的按週重置。用到 90% 以上的,等其他都無法回應時才用;失敗後休息中的排最後。",
"Smart: keys that suit the request go first — one made for the model's own API — then in their order. One resting after a failure goes last.": "智慧:適合此請求的 Key(為該模型原生 API 準備的)排前,其餘按順序。失敗後休息中的排最後。",
"In order: the first answers everything until it can't; then the next.": "按順序:第一個處理所有請求,無法回應時再換下一個。",
"In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache.": "輪流:會話的下一輪交給上一輪迴答者的下一個帳號,新會話再往後一個;一輪之內不換帳號,保持提示詞快取。",
@@ -1152,6 +1153,7 @@ magpie.strings({
"{who} goes first: it has quota to spare, and the others are kept for last.": "{who} 排第一:它還有餘量,其他帳號留到最後。",
"{who} goes first: of those with quota to spare, its allowance starts again soonest — one of its Codex resets about to run out is used by itself in {d}, and what it has left then is lost. {other} renews later and keeps its own.": "{who} 排第一:有餘量的帳號中它的額度最先重新開始,{d}後將自動使用其快到期的 Codex 重置卡,屆時剩餘額度作廢。{other} 重置較晚,額度暫留。",
"{who} goes first: of those with quota to spare, its allowance renews soonest — in {d} — and what it has left then is lost. {other} renews later and keeps its own.": "{who} 排第一:有餘量的帳號中它的額度最先重置({d}後),屆時剩餘額度作廢。{other} 重置較晚,額度暫留。",
"{who} goes first: its longer window has more left than its shorter one can still let through before it renews, so the shorter one decides — it renews soonest, in {d}, and what it has left then is lost. {other} renews later and keeps its own.": "{who} 排第一:它較長窗口的剩餘額度,較短窗口在其重置前已來不及放行,所以按較短窗口排序——它最先重置({d}後),屆時剩餘額度作廢。{other} 重置較晚,額度暫留。",
"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} 排第一:它與 {other} 的額度在同一小時重置,而它較短的時段更早({d}後)。",
"{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} 和 {other} 在同一小時內重置,保持原順序,廠商的提示詞快取也保持命中。",
"{who} goes first, in the order given: when its allowance renews isn't known.": "{who} 按原有順序排第一:不知道它的額度何時重置。",
@@ -1719,7 +1721,7 @@ magpie.strings({
"each provider routes over its own": "各プロバイダが自身のアカウントやキーでルーティング",
"Change how {name} routes": "{name} のルーティングを変更",
"Only one account or key is on for this, so routing has nothing to choose between. Turn on a second in the provider's editor, and how it routes is set under Several accounts or keys below.": "有効なアカウントやキーが 1 つだけなので、ルーティングに選択肢はありません。プロバイダの編集画面で 2 つ目を有効にすると、ルーティングは下の「複数のアカウントやキー」で設定できます。",
"Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later; one resting after a failure goes last.": "スマート(メンバーのアカウントとキーをまとめて扱う):クォータに余裕のあるサブスクリプションのうち、利用枠のリセットが最も早いものが先頭です。週の枠で判断し、5 時間枠のみで週の枠がないアカウント(Claude Enterprise)は 5 時間枠で判断するため、それより後にリセットされるどの週の枠よりも前になります。失敗後に休止中のものは最後です。",
"Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later, and one whose month its weeks can no longer use up before it renews by its week; one resting after a failure goes last.": "スマート(メンバーのアカウントとキーをまとめて扱う):クォータに余裕のあるサブスクリプションのうち、利用枠のリセットが最も早いものが先頭です。週の枠で判断し、5 時間枠のみで週の枠がないアカウント(Claude Enterprise)は 5 時間枠で判断するため、それより後にリセットされるどの週の枠よりも前になります。月の枠をリセットまでに週の枠では使い切れなくなったものは週の枠で判断します。失敗後に休止中のものは最後です。",
"In order: the first model until it can't answer, then the next — each over its own accounts or keys as its provider routes them.": "順番:先頭のモデルが応答できなくなるまで使い、その後次へ。各モデルはそのプロバイダのルーティングに従って自身のアカウントやキーを使います。",
"In turn: each conversation's next turn goes to the next member's account or key, spreading the load.": "交互:各会話の次のターンを次のメンバーのアカウントやキーに送り、負荷を分散します。",
"Least used first: the account or key with the most of its allowance left goes first.": "使用量が最少を優先:利用枠の残りが最も多いアカウントやキーが先頭です。",
@@ -1786,7 +1788,7 @@ magpie.strings({
"Another magpie serves the gateway; its routing plays live in that magpie's window.": "ゲートウェイは別の magpie が提供しています。そのルーティングはその magpie のウィンドウでライブ再生されます。",
"The gateway isn't running, so nothing is routed.": "ゲートウェイが実行されていないため、何もルーティングされません。",
"The gateway is served by a magpie without a window (magpie serve), so its routing can't be watched. Stop it and let this magpie serve the gateway to see routing live.": "ゲートウェイはウィンドウのない magpie(magpie serve)が提供しているため、ルーティングを見ることができません。それを停止し、この magpie にゲートウェイを提供させるとルーティングをライブで見られます。",
"Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours. One at 90% or more waits until the others can't answer; one resting after a failure goes last.": "スマート:クォータに余裕のあるアカウントのうち、利用枠が最も早く更新されるものが先です — 残りはリセット時に失われるためです。週の枠で決まり、5 時間枠だけで週の枠がないアカウントは 5 時間枠で決まります。90% 以上使ったアカウントは他が応答できなくなるまで待ち、失敗後に休止中のアカウントは最後になります。",
"Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours, and one whose month its weeks can no longer use up before it renews by its week. One at 90% or more waits until the others can't answer; one resting after a failure goes last.": "スマート:クォータに余裕のあるアカウントのうち、利用枠が最も早く更新されるものが先です — 残りはリセット時に失われるためです。週の枠で決まり、5 時間枠だけで週の枠がないアカウントは 5 時間枠で、月の枠を更新までに週の枠では使い切れなくなったアカウントは週の枠で決まります。90% 以上使ったアカウントは他が応答できなくなるまで待ち、失敗後に休止中のアカウントは最後になります。",
"Smart: keys that suit the request go first — one made for the model's own API — then in their order. One resting after a failure goes last.": "スマート:リクエストに合うキー — モデル本来の API 用のキー — が先で、その後は設定順です。失敗後に休止中のキーは最後になります。",
"In order: the first answers everything until it can't; then the next.": "順番:最初の 1 つが応答できなくなるまですべてに応答し、その後は次へ。",
"In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache.": "交互:各会話の次のターンは前回応答したアカウントの次のアカウントへ、新しい会話はさらにその次から始まります。ターン内のリクエストは同じアカウントのままで、プロンプトキャッシュを保ちます。",
@@ -1823,6 +1825,7 @@ magpie.strings({
"{who} goes first: it has quota to spare, and the others are kept for last.": "{who} が先です:クォータに余裕があり、他のアカウントは最後に回します。",
"{who} goes first: of those with quota to spare, its allowance starts again soonest — one of its Codex resets about to run out is used by itself in {d}, and what it has left then is lost. {other} renews later and keeps its own.": "{who} が先です:クォータに余裕のあるアカウントのうち、利用枠が最も早く再開します — 期限切れ間近の Codex リセットの 1 つが {d} 後に自動で使われ、その時点の残りは失われます。{other} は更新が遅いので、自分の残りを保ちます。",
"{who} goes first: of those with quota to spare, its allowance renews soonest — in {d} — and what it has left then is lost. {other} renews later and keeps its own.": "{who} が先です:クォータに余裕のあるアカウントのうち、利用枠が最も早く — {d} 後に — 更新され、その時点の残りは失われます。{other} は更新が遅いので、自分の残りを保ちます。",
"{who} goes first: its longer window has more left than its shorter one can still let through before it renews, so the shorter one decides — it renews soonest, in {d}, and what it has left then is lost. {other} renews later and keeps its own.": "{who} が先です:長い方の枠の残りは、その更新までに短い方の枠ではもう使い切れないため、短い方の枠で決まります — 最も早く、{d} 後に更新され、その時点の残りは失われます。{other} は更新が遅いので、自分の残りを保ちます。",
"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} が先です:利用枠が {other} と同じ時間帯に更新され、短いほうの枠がより早く — {d} 後に — 更新されます。",
"{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} と {other} は同じ時間帯に更新されるため、設定順のままです — ベンダーのプロンプトキャッシュも温かいままです。",
"{who} goes first, in the order given: when its allowance renews isn't known.": "{who} が設定順で先です:利用枠がいつ更新されるか不明です。",
@@ -2392,7 +2395,7 @@ magpie.strings({
"each provider routes over its own": "jeder Anbieter leitet über seine eigenen weiter",
"Change how {name} routes": "Ändern, wie {name} weiterleitet",
"Only one account or key is on for this, so routing has nothing to choose between. Turn on a second in the provider's editor, and how it routes is set under Several accounts or keys below.": "Hier ist nur ein Konto oder Schlüssel aktiv, also hat die Weiterleitung keine Wahl. Aktiviere im Editor des Anbieters ein zweites; wie weitergeleitet wird, legst du dann unten unter „Mehrere Konten oder Schlüssel“ fest.",
"Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later; one resting after a failure goes last.": "Intelligent, über Konten und Schlüssel aller Mitglieder zusammen: Von den Abos mit freiem Kontingent kommt das zuerst, dessen Kontingent sich am frühesten erneuert – die Woche entscheidet, und ein Konto mit fünf Stunden und ohne Woche (Claude Enterprise) richtet sich nach seinen fünf Stunden, also vor jeder später erneuerten Woche; eines, das nach einem Fehler pausiert, kommt zuletzt.",
"Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later, and one whose month its weeks can no longer use up before it renews by its week; one resting after a failure goes last.": "Intelligent, über Konten und Schlüssel aller Mitglieder zusammen: Von den Abos mit freiem Kontingent kommt das zuerst, dessen Kontingent sich am frühesten erneuert – die Woche entscheidet, und ein Konto mit fünf Stunden und ohne Woche (Claude Enterprise) richtet sich nach seinen fünf Stunden, also vor jeder später erneuerten Woche, und eines, dessen Monat seine Wochen vor der Erneuerung nicht mehr aufbrauchen können, nach seiner Woche; eines, das nach einem Fehler pausiert, kommt zuletzt.",
"In order: the first model until it can't answer, then the next — each over its own accounts or keys as its provider routes them.": "Der Reihe nach: das erste Modell, bis es nicht mehr antworten kann, dann das nächste – jedes über seine eigenen Konten oder Schlüssel, wie sein Anbieter sie weiterleitet.",
"In turn: each conversation's next turn goes to the next member's account or key, spreading the load.": "Abwechselnd: Die nächste Runde jeder Unterhaltung geht an Konto oder Schlüssel des nächsten Mitglieds und verteilt so die Last.",
"Least used first: the account or key with the most of its allowance left goes first.": "Am wenigsten genutzt zuerst: Das Konto oder der Schlüssel mit dem größten Restkontingent kommt zuerst.",
@@ -2459,7 +2462,7 @@ magpie.strings({
"Another magpie serves the gateway; its routing plays live in that magpie's window.": "Ein anderes magpie stellt den Zugangspunkt bereit; seine Weiterleitung wird live in dessen Fenster abgespielt.",
"The gateway isn't running, so nothing is routed.": "Der Zugangspunkt läuft nicht, daher wird nichts weitergeleitet.",
"The gateway is served by a magpie without a window (magpie serve), so its routing can't be watched. Stop it and let this magpie serve the gateway to see routing live.": "Der Zugangspunkt wird von einem magpie ohne Fenster (magpie serve) bereitgestellt, daher lässt sich seine Weiterleitung nicht beobachten. Beenden Sie es und lassen Sie dieses magpie den Zugangspunkt bereitstellen, um die Weiterleitung live zu sehen.",
"Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours. One at 90% or more waits until the others can't answer; one resting after a failure goes last.": "Intelligent: Von den Konten mit freiem Kontingent kommt das zuerst, dessen Kontingent sich am frühesten erneuert – sein Rest würde beim Zurücksetzen verfallen. Die Woche entscheidet; ein Konto mit fünf Stunden und ohne Woche richtet sich nach seinen fünf Stunden. Eines ab 90 % wartet, bis die anderen nicht antworten können; eines, das nach einem Fehler pausiert, kommt zuletzt.",
"Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours, and one whose month its weeks can no longer use up before it renews by its week. One at 90% or more waits until the others can't answer; one resting after a failure goes last.": "Intelligent: Von den Konten mit freiem Kontingent kommt das zuerst, dessen Kontingent sich am frühesten erneuert – sein Rest würde beim Zurücksetzen verfallen. Die Woche entscheidet; ein Konto mit fünf Stunden und ohne Woche richtet sich nach seinen fünf Stunden, eines, dessen Monat seine Wochen vor der Erneuerung nicht mehr aufbrauchen können, nach seiner Woche. Eines ab 90 % wartet, bis die anderen nicht antworten können; eines, das nach einem Fehler pausiert, kommt zuletzt.",
"Smart: keys that suit the request go first — one made for the model's own API — then in their order. One resting after a failure goes last.": "Intelligent: Schlüssel, die zur Anfrage passen, kommen zuerst – einer für die eigene API des Modells –, dann in ihrer Reihenfolge. Einer, der nach einem Fehler pausiert, kommt zuletzt.",
"In order: the first answers everything until it can't; then the next.": "Der Reihe nach: Der erste beantwortet alles, bis er nicht mehr kann; dann der nächste.",
"In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache.": "Abwechselnd: Die nächste Runde jeder Unterhaltung geht an das Konto nach dem, das die letzte beantwortet hat, und eine neue Unterhaltung beginnt eines weiter; die Anfragen innerhalb einer Runde bleiben, sodass der Prompt-Cache erhalten bleibt.",
@@ -2496,6 +2499,7 @@ magpie.strings({
"{who} goes first: it has quota to spare, and the others are kept for last.": "{who} kommt zuerst: Es hat freies Kontingent, die anderen werden für zuletzt aufgehoben.",
"{who} goes first: of those with quota to spare, its allowance starts again soonest — one of its Codex resets about to run out is used by itself in {d}, and what it has left then is lost. {other} renews later and keeps its own.": "{who} kommt zuerst: Von denen mit freiem Kontingent beginnt seines am frühesten neu – einer seiner bald verfallenden Codex-Resets wird in {d} von selbst eingelöst, und der Rest verfällt dann. {other} erneuert sich später und behält seines.",
"{who} goes first: of those with quota to spare, its allowance renews soonest — in {d} — and what it has left then is lost. {other} renews later and keeps its own.": "{who} kommt zuerst: Von denen mit freiem Kontingent erneuert sich seines am frühesten – in {d} –, und der Rest verfällt dann. {other} erneuert sich später und behält seines.",
"{who} goes first: its longer window has more left than its shorter one can still let through before it renews, so the shorter one decides — it renews soonest, in {d}, and what it has left then is lost. {other} renews later and keeps its own.": "{who} kommt zuerst: Sein längeres Fenster hat mehr übrig, als sein kürzeres bis zu dessen Erneuerung noch durchlassen kann, also entscheidet das kürzere – es erneuert sich am frühesten, in {d}, und sein Rest verfällt dann. {other} erneuert sich später und behält seines.",
"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} kommt zuerst: Sein Kontingent erneuert sich in derselben Stunde wie das von {other}, sein kürzeres aber früher – in {d}.",
"{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} und {other} erneuern sich in derselben Stunde, daher bleibt die vorgegebene Reihenfolge – und der Prompt-Cache des Anbieters bleibt warm.",
"{who} goes first, in the order given: when its allowance renews isn't known.": "{who} kommt gemäß vorgegebener Reihenfolge zuerst: Wann sich sein Kontingent erneuert, ist unbekannt.",
@@ -6,7 +6,8 @@
// account in a group, or among a provider's keys, all at 90% or more. A
// key not known is told as before. A lone key bought as a plan (#1016:
// Kimi Code's, 49% of its 5 hours used) says what it has left too, at
// 440px as well. In English, Chinese, Japanese and German.
// 440px as well. A key whose month its weeks can no longer use up goes by
// its week, and says so (#5639). In English, Chinese, Japanese and German.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -56,6 +57,16 @@ const scenes = {
{ id: "kimi-code-cn", provider: "kimi-code-cn", name: "Kimi Code (China)", kind: "provider", model: "kimi-for-coding", known: true, used: 49, renews: [ahead(26), ahead(2)], usedRenews: ahead(2) },
],
},
// #5639: a Volcengine Agent Plan key whose month (renewing in 15 days)
// its weeks can't use up any more goes by its week, renewing in a day,
// ahead of an account whose week renews in three
unreached: {
group: { id: "g", name: "Daily", routing: "" },
order: [
{ id: "volcengine", provider: "volcengine", name: "Volcengine", kind: "provider", model: "doubao-seed-2.0-pro", known: true, used: 8, renews: [ahead(360), ahead(24), ahead(2)], unreached: 1, usedRenews: ahead(360) },
{ id: "codex", provider: "codex", name: "Codex", who: "me@example.com", kind: "account", agent: "codex", model: "doubao-seed-2.0-pro", known: true, used: 10, renews: [ahead(72)] },
],
},
// keys whose windows aren't read: as before
plain: {
order: [
@@ -149,7 +160,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.match(await row("relay-b").locator("em").textContent(), /95%/);
// the header tells Smart as it weighs them, not as keys in their order
assert.equal((await page.locator(".rt-mode").textContent()).trim(),
await say("Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours. One at 90% or more waits until the others can't answer; one resting after a failure goes last."));
await say("Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours, and one whose month its weeks can no longer use up before it renews by its week. One at 90% or more waits until the others can't answer; one resting after a failure goes last."));
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: one whose month its weeks can't use up says its week decides (#5639)`, async (t) => {
const { errors, say, why } = await open(t, engine, lang, "unreached");
const want = await say("{who} goes first: its longer window has more left than its shorter one can still let through before it renews, so the shorter one decides — it renews soonest, in {d}, and what it has left then is lost. {other} renews later and keeps its own.", { who: "Volcengine", d: await say("{n} h", { n: "24" }), other: "{other}" });
const head = want.split("{other}")[0];
assert.ok(head.length > 40 && (await why()).startsWith(head), `${await why()}\nwant ${head}…`);
assert.deepEqual(errors, []);
});
for (const width of [1100, 440]) {
@@ -183,7 +201,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const steps = await page.locator(".rt-steps li").allTextContents();
assert.ok(steps.some((s) => s.includes(aside)), steps.join("\n"));
assert.equal((await page.locator(".rt-mode").textContent()).trim(),
await say("Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours. One at 90% or more waits until the others can't answer; one resting after a failure goes last."));
await say("Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours, and one whose month its weeks can no longer use up before it renews by its week. One at 90% or more waits until the others can't answer; one resting after a failure goes last."));
assert.deepEqual(errors, []);
});
+86
View File
@@ -0,0 +1,86 @@
package provider
import (
"encoding/json"
"fmt"
"testing"
"time"
)
// A Volcengine Agent Plan's month (20,000) is ranked by its week (7,000)
// once the weeks still to come before the month renews can't carry what
// the month has left: what the week leaves at its reset is lost then
// (#5639, louisgreen0726's reading on v0.1.3260: 1,628 used of the week
// and of the month, the week renewing in 23.6 hours, the month in 696).
// While they can, the month is the real cap (#1778) and ranks it.
func TestMonthOutOfReachRanksByWeek(t *testing.T) {
now := time.Now().Truncate(time.Second)
day, week := 24*time.Hour, 7*24*time.Hour
weekRenews := now.Add(23*time.Hour + 36*time.Minute)
// the Agent Plan's GetAFPUsage, its resets in milliseconds
plan := func(weekUsed, monthUsed float64, month time.Time) Allowance {
t.Helper()
ws, _ := volcReadAFP(json.RawMessage(fmt.Sprintf(`{"Tier":"Pro",
"AFPFiveHour":{"Quota":2000,"Used":0},
"AFPWeekly":{"Quota":7000,"Used":%v,"ResetTimestamp":%d},
"AFPMonthly":{"Quota":20000,"Used":%v,"ResetTimestamp":%d}}`,
weekUsed, weekRenews.UnixMilli(), monthUsed, month.UnixMilli())))
if len(ws) != 3 {
t.Fatalf("windows: %+v", ws)
}
return allowanceOf(ws, now)
}
for _, c := range []struct {
name string
a Allowance
want int
first time.Time // the renewal Smart ranks it by
}{
// the reading as reported: four weeks to go hold 28,017, more
// than the 18,372 left, so the month still decides
{"as reported", plan(1628, 1628, now.Add(696*time.Hour)), 0, now.Add(696 * time.Hour)},
// three weeks to go: 21,017 still carry 18,372
{"three weeks to go", plan(0, 1628, weekRenews.Add(3*week)), 0, weekRenews.Add(3 * week)},
// two weeks and a bit to go: 14,017 can't, so what this week
// leaves is lost at its reset, and the week ranks it
{"two weeks to go", plan(0, 1628, weekRenews.Add(2*week+24*time.Minute)), 1, weekRenews},
// the last week: whatever is left past 7,000 is lost anyway,
// and the week ranks it all the more
{"the last week", plan(1628, 1628, weekRenews.Add(day)), 1, weekRenews},
// a month holding less than its weeks add up to, with less left
// than the weeks to come carry (#1778): the month, as today
{"month within reach", plan(0, 11000, weekRenews.Add(2*week)), 0, weekRenews.Add(2 * week)},
} {
got := c.a.Unreached("doubao-seed-2.0-pro", now)
if got != c.want {
t.Errorf("%s: unreached %d, want %d", c.name, got, c.want)
}
if r := c.a.Renewal("doubao-seed-2.0-pro", now); len(r) != 3 || !r[got].Equal(c.first) {
t.Errorf("%s: ranked by %v, want %v", c.name, r, c.first)
}
}
// nothing else changes: a window alone, windows that tell only a
// share, and counts in different units are never compared
month := now.Add(2*week + day)
for name, a := range map[string]Allowance{
"one window": {{Used: 10, Resets: month, Span: 30 * day, Amount: 2000, Of: 20000}},
"shares only": {
{Used: 10, Resets: month, Span: 30 * day},
{Used: 0, Resets: weekRenews, Span: week},
},
"other units": {
{Used: 10, Resets: month, Span: 30 * day, Amount: 2000, Of: 20000, Unit: "credits"},
{Used: 0, Resets: weekRenews, Span: week, Of: 7000, Unit: "USD"},
},
// the next window a rate cap: what five hours leave isn't lost
"five hours under a week": {
{Used: 10, Resets: now.Add(6 * time.Hour), Span: week, Amount: 700, Of: 7000},
{Used: 0, Span: 5 * time.Hour, Of: 2000},
},
} {
if got := a.Unreached("m", now); got != 0 {
t.Errorf("%s: unreached %d", name, got)
}
}
}
+46 -4
View File
@@ -525,6 +525,17 @@ func (a Allowance) Count(model string, now time.Time) (amount, of float64, unit
// whose credits have no reset, go by the package that ends first
// (cdredfox on X).
func (a Allowance) Renewal(model string, now time.Time) []time.Time {
ls := a.renewing(model, now)
out := make([]time.Time, len(ls))
for i, l := range ls {
out[i] = l.Resets
}
return out
}
// renewing is the windows that count model as Renewal ranks them, the
// biggest first, each Resets its renewal.
func (a Allowance) renewing(model string, now time.Time) []Limit {
model = strings.ToLower(model)
restart := a.Restarts(now)
var ls []Limit
@@ -533,6 +544,7 @@ func (a Allowance) Renewal(model string, now time.Time) []time.Time {
continue
}
if !l.Resets.After(now) {
l.Used, l.Amount = 0, 0 // its reset has passed: empty again
l.Resets = time.Time{}
if l.Span > 0 {
l.Resets = now.Add(l.Span)
@@ -550,11 +562,41 @@ func (a Allowance) Renewal(model string, now time.Time) []time.Time {
}
return ls[i].Resets.After(ls[j].Resets)
})
out := make([]time.Time, len(ls))
for i, l := range ls {
out[i] = l.Resets
return ls
}
// Unreached is how many of Renewal's windows, the biggest first, Smart
// passes over, ranking the account by the next one: a window whose left
// the next shorter window can no longer let through before it renews,
// once that one renews, unless what that one has left is used first.
// Both are counted in one unit (Limit.Of): a Volcengine Agent Plan's
// month of 20,000 with 18,372 left, renewing two weeks after its week of
// 7,000 does, can take at most 14,000 after the week renews, so what the
// week has left is lost at its reset as a weekly plan's is, and it ranks
// by its week (#5639, louisgreen0726). While the weeks still to come can
// carry what the month has left, the month is the real cap, as when the
// month holds less than its weeks add up to (#1778), and it ranks by the
// month as before. A week partly before the month renews counts for the
// share of it that is. Only a budget window ranks so (budgetSpan): what
// five hours leave at their reset is never taken for lost, as
// everywhere in Smart. Windows that don't tell their counts, or tell
// them in different units, are never compared: 0.
func (a Allowance) Unreached(model string, now time.Time) int {
ls := a.renewing(model, now)
n := 0
for ; n+1 < len(ls); n++ {
big, next := ls[n], ls[n+1]
if big.Of <= 0 || next.Of <= 0 || big.Unit != next.Unit || next.Span < budgetSpan || big.Span <= next.Span ||
big.Resets.IsZero() || !next.Resets.Before(big.Resets) {
break
}
left := big.Of * (100 - min(100, max(0, big.Used))) / 100
after := next.Of * float64(big.Resets.Sub(next.Resets)) / float64(next.Span)
if left <= after {
break
}
}
return out
return n
}
// Left is how much a wallet that counts model has left, in unit
+6
View File
@@ -42,6 +42,12 @@ type Seat struct {
WeekLow bool
// Soon is when its windows renew, the biggest first (Allowance.Renewal)
Soon []time.Time
// Unreached is how many of Soon's windows, the biggest first, can no
// longer be used up before they renew unless the next one's left is
// used before that renews (provider.Allowance.Unreached): Smart ranks
// it by the next one, as what that leaves at its reset is lost
// (#5639). 0 for every account whose windows don't tell their counts.
Unreached int
// Lapse is when the soonest of what it has left is lost, apart from
// its windows' renewals (Allowance.Lapse): zero when not told. Smart
// goes by it when Soon ties.
+23
View File
@@ -79,6 +79,29 @@ func TestSmart(t *testing.T) {
}
}
// Smart passes over a biggest window that can't be used up before it
// renews any more (Seat.Unreached) and ranks the seat by the next: an
// Agent Plan whose month renews in 15 days, its week tomorrow, goes before
// a week renewing in three days once its month is out of reach (#5639),
// and after it while the month isn't. An Unreached past Soon is harmless.
func TestSmartPassesAnUnreachedWindow(t *testing.T) {
now := time.Now()
week := now.Add(3 * 24 * time.Hour)
plan := []time.Time{now.Add(15 * 24 * time.Hour), now.Add(24 * time.Hour), now.Add(5 * time.Hour)}
for _, c := range []struct {
unreached int
want []string
}{{0, []string{"weekly", "plan"}}, {1, []string{"plan", "weekly"}}, {5, []string{"weekly", "plan"}}} {
s := []Seat{
{Key: "weekly", Used: 10, Soon: []time.Time{week, now.Add(5 * time.Hour)}},
{Key: "plan", Used: 8, Soon: plan, Unreached: c.unreached},
}
if got := keys(s, Apply(Smart, "p", s)); !slices.Equal(got, c.want) {
t.Errorf("unreached %d: %v, want %v", c.unreached, got, c.want)
}
}
}
func keys(s []Seat, order []int) []string {
out := make([]string, len(order))
for i, j := range order {
+8 -2
View File
@@ -114,7 +114,11 @@ func identity(n int) []int {
// 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
// hours in it — and the next one only when that renews in the same hour. A
// biggest window whose left the next can no longer let through before it
// renews (Seat.Unreached: a Volcengine Agent Plan's month two weeks out,
// with more left than two weeks hold) is passed over: what the week
// leaves is lost at its reset then, so the week decides (#5639). 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
@@ -153,7 +157,9 @@ var Smart = Strategy{Order: func(_ string, seats []Seat) []int {
if a.Learns != b.Learns {
return a.Learns
}
ri, rj := a.Soon, b.Soon
// a window that can't be used up before it renews any more ranks
// it no more: the next one does (Seat.Unreached)
ri, rj := a.Soon[min(a.Unreached, len(a.Soon)):], b.Soon[min(b.Unreached, len(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) {