gateway: In turn passes over a provider's fallback while the provider is ready (01huadalang)
01huadalang on Discord (#feedback, 10-31): once the main provider has quota again, requests keep going to the fallback model, which is only meant for emergencies. Cause: a provider routed In turn treated its fallback rows as more of its own keys. A new turn went to the row after the last answerer (after), which past the provider's last key is the fallback, and a new conversation went to the row the fewest conversations held (leastHeld), which is the fallback nobody is on. Both happened while every key of the provider was ready. The session spread already skipped fallbacks (readyForNew); rotate's after and leastHeld(ready=false) did not. Fix: standsIn(order, i) marks a fallback row when the plan's first row is the provider's own. after, leastHeld and readyForNew all skip it, so a fallback takes a new turn or conversation only when nothing ahead of it can. Within one turn (tool results) a conversation still stays on whoever answered, because of sealed reasoning. Stays: Strict is the user's own choice and is not changed. A conversation it keeps on the fallback stays there. The trace now names the provider's ready first row (Affinity.Main), and the Routing page says why: the provider is ready again, Strict never moves a conversation, and new conversations go to the provider (en, zh, zh-TW, ja, de). Tests (internal/gateway/affinity_fallback_paths_test.go): - TestRotatingProviderKeepsItsFallbackForEmergencies (1 and 2 keys) - TestFallbackGivesBackAcrossRoutings: auto, in turn, in turn+session, least used+session, stays turn, and a group fallback with auto, in turn and session - TestStrictKeepsTheFallbackAndSaysTheMainIsReady On the old code, the rotate provider's new turn went to spare-key (Why new-turn), and in turn+session's new conversation went to the fallback (Why first). Broken by hand: with after's standsIn removed and Strict's Main dropped, the rotate test, the in-turn cases and the Strict test go red. session_spread_test's fallback case pinned the old In turn pick; it now expects k2. GUI: routing-affinity-order has a "strict" case. Run (via mote-run unless noted): - go test -tags nogui -count=1 -timeout 45m ./... at b08f35fcc (this change on7428f3229): every package ok except two reds, both filed and the same on main: internal/gui TestSettingsSaveKeepsWhatItDoesNotSend (SearchAll, #4514) and internal/usage TestRequestChunksFromDisk (TempDir cleanup, #4390). - Rebased onto0fe9f97c1, at this head: go test ./internal/gateway -run 'Affinity|Rotat|Fallback|Strict|Spread|Turn|Stick|Lead|Order': ok; go vet -tags nogui ./internal/gateway: ok - go vet ./internal/gateway; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway ./internal/gui: ok - gofmt -l: clean - GUI in WSL (wsl-run), routing-affinity-order, routing-affinity-cache- write and i18n-keys in chromium and webkit: 43 of 44. The red is i18n-keys' "Unmarked", the same on main (#4524). Not tried: a real account. This was reproduced with fake upstreams only.
This commit is contained in:
@@ -211,9 +211,9 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- A member whose model is known to take less than the request isn't asked it (`roomy` in [`fallback.go`](../../internal/gateway/fallback.go), in `serve` after the rules, affinity, the image filter and `pinTo`, before `probeOne`; dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash, 200K, first in a group and a 1M subscription of it second). It is a check before sending, not a retry: the request's tokens are estimated as the overflow fall-over does (`estimate`, bytes/4 over text, tool arguments and schemas), and a candidate whose window (`windowOf`: the provider's `Contexts`, the catalog, `ContextOf`) is known and no larger is left out of the candidates and of the trace's order, and listed in the trace's `left` with `window` set to that window. Asked, such a member only refuses, and a refusal that doesn't say why, for a request short of `tooLongUnsaid`'s 1.2 margin, reached the agent as the vendor's error while the next member had room; it also spent a request against the member's limits. A conversation kept on a member by affinity moves once it outgrows it. Nothing is left out when its window isn't known, when the body doesn't parse, when only one model is among the candidates, or when no candidate holds the request: then the first is asked, and its overflow reaches the agent as one, to compact (`withRoom`, `failOverflow` and `tooLongUnsaid` stay for the window the estimate misses, which counts low on code and high on CJK text). A body shorter than four bytes per token of the least window isn't parsed. `count_tokens` (a count on the group's first member, not a send) and System One's decision models (short decision text) don't go through it. Those left out are the last resort: when the last candidate with room fails out of its allowance or credit (`failQuota`/`failCredit`), nothing before it having failed otherwise (`other`), and no account is pinned, the ones left out that aren't resting are asked after all, their rows moved from the trace's `left` to its order, and the one that failed rests as one before the last does. Its overflow tells the agent to compact, where the 429 only told it to wait for an allowance hours away (Kai on Discord: both Claude accounts spent until the next day, the Claude provider's Fallback a Codex model of 272K under a longer conversation, never asked). Another failure (a busy vendor, a bad key) still reaches the agent as it was, the small one not asked. The Routing page keeps a row for a member left out and not asked, saying the request is longer than its window and that it was passed over, and its why list says so (#3749; it used to show it only by its absence from the order). `TestMemberTooSmallIsNotAsked`, `TestMemberTooSmallIsTheLastResort`, `TestClaudeAccountsSpentFallBackToCodex`, `TestConversationOutgrowingItsMemberMoves`, `TestRoomyLeavesWhatItCantJudge`.
|
||||
- Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while the last reply read from the cache and wrote to it at least `cacheWorth` (1024) tokens between them (the usage's `CacheRead` plus `CacheWrite`, passed to `answered`) and the cache isn't cold (`cacheCold`, 5 minutes; for a ChatGPT account `chatGPTCold`, an hour, as measured on a real account (a thread left 7 to 60 minutes read back from cache all it had sent before), since the ChatGPT backend keeps a Codex conversation cached far longer and a move sends the whole context to the other account uncached; on DeepSeek's own API (`api.deepseek.com`) `deepseekCold`, an hour, since DeepSeek clears an unused prefix cache after hours and a Claude Code conversation idle 7 and 26 minutes read 98–99% back, so a second DeepSeek key no longer takes it over after five minutes: `coldAfter`, which a group's rules read too for `keepsEffort`). Past that window it stays while the vendor said it keeps at least `cacheWorth` tokens of the conversation for an hour (`hourCache`, #2302): a reply with Anthropic's 1-hour writes (`cache_creation.ephemeral_1h_input_tokens`, the usage's `CacheWrite1h`, as Claude Code asks of a subscription) keeps what it read plus those for `cacheHour`, a later reply on the same account and model that reads all of it starts the hour again, and one that reads less (moved, compacted) drops it. The stick keeps it on disk too (`cacheHour`, `cacheHourAt`), and a group's rules keep the turn's effort the same hour (`keepsEffort`). Vendors that report no 1-hour write are unchanged. `TestAffinityKeepsAnHourCachePastFiveMinutes`, `TestHourCacheAfter`, `TestDeepSeekConversationStaysPastFiveMinutes`. What was written counts: a first turn reads nothing and writes the whole prompt (Anthropic's `cache_creation_input_tokens`), and the second turn stays to read it rather than moving as `no-cache` and building it again elsewhere (vilicvane on Discord). The stick keeps both, on disk too (`affinity.json`'s `cacheWrite`, absent in a file from before and read as 0, so such a stick is judged by its read alone), and the trace's `Affinity.CacheWrite` lets the Routing page say what was read and what was written. A vendor that keeps a prompt cached without reporting it (OpenAI's automatic prefix cache, Gemini) says neither of a turn that read none, so the prompt that turn was sent (the usage's `Input`) stands for the write and its second turn stays too; a reply that reports no usage at all counts as no cache, as before. `TestAffinityKeepsACacheJustWritten`, `TestAffinityKeepsACacheTheVendorKeptSilently`, `routing-affinity-cache-write.test.cjs`.
|
||||
- Strict (`strict`, #1797, miniers) never moves a conversation to another key or account (`who`). Its stick is kept as session's is, and while it is fresh `affine` keeps only the candidates of that `who` (`strictOnly`): its other models stay, so a group's rules still pick among them, but no other account, key or provider is asked, and a resting or spent one is asked anyway. A failure there reaches the agent and rests the account as a non-lone candidate's would (`strictAlone`), so new conversations go elsewhere. A reply that breaks off after its 200 (#733) forgets the stick under every other mode; under strict it doesn't, so the agent's retry goes back to the same account, member or key, failing there while it fails and going on there once it answers (imwhatiam123 on Discord: a group of Qoder CN and WorkBuddy AI moved a session to WorkBuddy AI, the retry routed as a new conversation; `TestStrictGroupKeepsItsMemberPastABrokenReply`). Before planning, `strictKeep` takes the stuck account back from what holds new conversations off it: a usage cap (`pl.capped`, `capHeldOnly`), so the conversation goes on past it. An account held for credits it may not spend is answered 429 naming the account and Strict, and nothing reaches the vendor, rather than moved. An account removed, switched off, barred, or not allowed for the calling key is gone, and the conversation moves as under session. The trace says `strict` even with one candidate. `strict_affinity_test.go`, `stays-strict.test.cjs`.
|
||||
- A provider's fallback is its emergency path, not a place a conversation stays (01huadalang on Discord). When the one that answered a conversation last is one of a provider's `Fallback` models (its trace row's `Fallback`) and the provider's own model stands first in the plan, ready, the next turn goes to the provider, whatever the fallback cached and in every mode but Strict (`backToMain` in `affine`, `Affinity.Why` `main`). "Ready" is what `restLast` says: the provider's rest over, which is when the rest `restAfter` set ends (a minute and backing off for a plain failure, the vendor's named reset or Retry-After for a quota or rate limit, `quotaRest` 15 minutes when nothing names a time), or earlier when its windows are read full no more (`renewed`) or a background probe finds it answering (`Rest.Probed`). While the provider rests, the fallback is ahead of it and keeps the conversation as any answerer does. Within a turn (the agent sending tool results back) the conversation stays on the fallback until the user speaks again: the turn's tool loop runs on reasoning the fallback sealed, which the provider can't read, and the provider is sent the whole prompt afresh at the next turn all the same. Strict is left as the user set it: it never moves a conversation, a fallback's included. A routing group's members are never `Fallback`, so a group's own affinity is unchanged, and a routing group named as a provider's fallback is a fallback here as a whole. Before this, Auto kept a conversation on the fallback by its cache for as long as each turn read it, and Session for the session. `TestFallbackGivesTheConversationBackOnceTheMainIsReady`, `TestGroupMemberKeepsTheConversationOnceAnotherIsBack`. The Routing page says so ("{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again…", `affWhy` in `plugins/routing/client.js`); before, `main` showed no reason at all.
|
||||
- A provider's fallback is its emergency path, not a place a conversation stays (01huadalang on Discord). When the one that answered a conversation last is one of a provider's `Fallback` models (its trace row's `Fallback`) and the provider's own model stands first in the plan, ready, the next turn goes to the provider, whatever the fallback cached and in every mode but Strict (`backToMain` in `affine`, `Affinity.Why` `main`). "Ready" is what `restLast` says: the provider's rest over, which is when the rest `restAfter` set ends (a minute and backing off for a plain failure, the vendor's named reset or Retry-After for a quota or rate limit, `quotaRest` 15 minutes when nothing names a time), or earlier when its windows are read full no more (`renewed`) or a background probe finds it answering (`Rest.Probed`). While the provider rests, the fallback is ahead of it and keeps the conversation as any answerer does. Within a turn (the agent sending tool results back) the conversation stays on the fallback until the user speaks again: the turn's tool loop runs on reasoning the fallback sealed, which the provider can't read, and the provider is sent the whole prompt afresh at the next turn all the same. Strict is left as the user set it: it never moves a conversation, a fallback's included; the trace then names the provider's ready key or account (`Affinity.Main`) and the Routing page says the conversation stays on the fallback for Strict while new conversations go to the provider (`TestStrictKeepsTheFallbackAndSaysTheMainIsReady`, `routing-affinity-order.test.cjs`). A provider routed In turn goes round its own keys and accounts only: its next turn (`after`) and a new conversation (`leastHeld`) pass over a fallback while one of the provider's own leads (`standsIn`). Before, a fallback was one more seat in the round, so with one key every other turn went to the fallback, and a new conversation went to it as the one nobody was on, the provider ready (01huadalang again, 10-31; `TestRotatingProviderKeepsItsFallbackForEmergencies`, `TestFallbackGivesBackAcrossRoutings`). A routing group's members are never `Fallback`, so a group's own affinity is unchanged, and a routing group named as a provider's fallback is a fallback here as a whole. Before this, Auto kept a conversation on the fallback by its cache for as long as each turn read it, and Session for the session. `TestFallbackGivesTheConversationBackOnceTheMainIsReady`, `TestGroupMemberKeepsTheConversationOnceAnotherIsBack`. The Routing page says so ("{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again…", `affWhy` in `plugins/routing/client.js`); before, `main` showed no reason at all.
|
||||
- A routing group set to In order is tried in the order the user put its members in, and a later member keeps a conversation only until a member ahead of it is ready again (yyhhyyyyyy on Discord: an API key first and a Claude subscription second for Opus, 8 of 10 Claude Code requests on the subscription). One failure of the first member (a 429, a 5xx, a rest) sent a conversation to the second, and Auto affinity's `cache` kept it there at every turn after, since each turn read what the last had written. Now, with Stays left on Auto, a new turn goes back to the first ready member when it is another member than the one that answered last (`backToFirst` in `affine`, `Affinity.Why` `order`; another key or account of the same member, or a group in the group, keeps its own affinity). Within a turn it stays, on the reasoning the later member sealed, as with `main`. Stays: Session and Strict are the user's own and keep the conversation where it is; a group routed any other way keeps it by its cache as before. The Routing page says why it moved. `TestOrderedGroupGivesTheConversationBackToItsFirstMember`, `routing-affinity-order.test.cjs`.
|
||||
- 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 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.
|
||||
- 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.
|
||||
- Stays: Session or Strict under a routing that picks by what is left (Smart, Least used first, Weekly pace: `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`.
|
||||
- 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`.
|
||||
- Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873).
|
||||
|
||||
@@ -114,8 +114,14 @@ type Affinity struct {
|
||||
// "main" (a provider's fallback answered it, and the provider's own
|
||||
// model is ready again: backToMain), "order" (a later member of a
|
||||
// group routed In order answered it, and a member ahead is ready
|
||||
// again at a new turn: backToFirst).
|
||||
// again at a new turn: backToFirst), "strict" (Stays: Strict, kept
|
||||
// whatever it is).
|
||||
Why string `json:"why"`
|
||||
// Main is, for a conversation kept strictly on a provider's fallback,
|
||||
// the provider's own key or account that is ready again: it would have
|
||||
// gone back to it ("main") but for Stays: Strict, which the Routing
|
||||
// page says.
|
||||
Main *Weighed `json:"main,omitempty"`
|
||||
}
|
||||
|
||||
type stick struct {
|
||||
@@ -556,6 +562,12 @@ func affine(scope, mode string, rotate, spread, inOrder bool, in http.Header, fr
|
||||
// whatever it is — resting, all but used up, past its cap
|
||||
// (strictKeep) — it is the one asked (#1797)
|
||||
a.Why = "strict"
|
||||
if !a.Within && backToMain(pl.order, at) {
|
||||
// a fallback the user's own Strict keeps the conversation on,
|
||||
// the provider ready again: said, not overridden
|
||||
m := pl.order[0]
|
||||
a.Main = &m
|
||||
}
|
||||
case pl.order[at].Rest != nil:
|
||||
a.Why = "resting"
|
||||
case !a.Within && backToMain(pl.order, at):
|
||||
@@ -682,7 +694,9 @@ const heldFor = 30 * time.Minute
|
||||
// stands. A conversation whose first request is still out counts where it
|
||||
// was sent (sticks.opening, under key until opened ends it): many started
|
||||
// at once all went to the one holding the fewest before any of them was
|
||||
// answered (#1342: 24 requests at once over 5 accounts).
|
||||
// answered (#1342: 24 requests at once over 5 accounts). A fallback is
|
||||
// none of those while the provider's own leads (standsIn): held by nobody,
|
||||
// it was the one held on fewest.
|
||||
//
|
||||
// ready is for a conversation kept for the whole session (spreadsSessions):
|
||||
// it goes only to one routing would put a new conversation on as well —
|
||||
@@ -725,7 +739,7 @@ func leastHeld(scope, key string, cs []candidate, pl planned, ready bool) ([]can
|
||||
seat := func(c candidate) string { return c.who() + "/" + provider.WithMemberEffort(c.model, c.effort) }
|
||||
best := -1
|
||||
for i, c := range cs {
|
||||
if pl.order[i].Rest != nil || pl.order[i].Aside || ready && i > 0 && !readyForNew(pl.order, i) {
|
||||
if pl.order[i].Rest != nil || pl.order[i].Aside || standsIn(pl.order, i) || ready && i > 0 && !readyForNew(pl.order, i) {
|
||||
continue
|
||||
}
|
||||
if best < 0 || held[seat(c)] < held[seat(cs[best])] {
|
||||
@@ -751,7 +765,19 @@ func leastHeld(scope, key string, cs []candidate, pl planned, ready bool) ([]can
|
||||
// lowShare.
|
||||
func readyForNew(order []Weighed, i int) bool {
|
||||
w := order[i]
|
||||
return w.Rest == nil && !w.Aside && !(w.Fallback && !order[0].Fallback) && !(w.Known && w.Used >= lowShare)
|
||||
return w.Rest == nil && !w.Aside && !standsIn(order, i) && !(w.Known && w.Used >= lowShare)
|
||||
}
|
||||
|
||||
// standsIn says whether order[i] is a provider's fallback while one of the
|
||||
// provider's own keys or accounts leads, ready: restLast puts a resting
|
||||
// one behind every ready one, so a fallback leads only when none of the
|
||||
// provider's own can take the request. A fallback is the provider's
|
||||
// emergency path, never a seat a round or a spread goes to: In turn's
|
||||
// next turn (after) and its new conversation (leastHeld) took it for one
|
||||
// more key, and sent every other turn to it, with the provider ready
|
||||
// (01huadalang on Discord, 10-31).
|
||||
func standsIn(order []Weighed, i int) bool {
|
||||
return i < len(order) && order[i].Fallback && !order[0].Fallback
|
||||
}
|
||||
|
||||
// withLead puts first, for a subagent's conversation nobody has answered
|
||||
@@ -799,11 +825,11 @@ func spreadsSessions(mode, routing string) bool {
|
||||
}
|
||||
|
||||
// after puts first the one after cs[at], round from the end, that isn't
|
||||
// resting.
|
||||
// resting, nor a fallback while the provider's own leads (standsIn).
|
||||
func after(cs []candidate, pl planned, at int) ([]candidate, planned) {
|
||||
for d := 1; d < len(cs); d++ {
|
||||
i := (at + d) % len(cs)
|
||||
if pl.order[i].Rest != nil || pl.order[i].Aside {
|
||||
if pl.order[i].Rest != nil || pl.order[i].Aside || standsIn(pl.order, i) {
|
||||
continue // a turn goes round the keys routed over only
|
||||
}
|
||||
if i > 0 {
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// chatTurns builds the Chat Completions body of a conversation's n-th user
|
||||
// turn (n from 1), each earlier turn answered.
|
||||
func chatTurns(model string, n int) string {
|
||||
var b strings.Builder
|
||||
b.WriteString(`{"model":"` + model + `","messages":[`)
|
||||
for i := 1; i <= n; i++ {
|
||||
if i > 1 {
|
||||
b.WriteString(`{"role":"assistant","content":"yo"},`)
|
||||
}
|
||||
b.WriteString(`{"role":"user","content":"turn ` + itoa(i) + `"}`)
|
||||
if i < n {
|
||||
b.WriteString(",")
|
||||
}
|
||||
}
|
||||
b.WriteString(`]}`)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// mainReady ends every rest, as when the minute or the reset passes, and
|
||||
// has the upstream answer again.
|
||||
func mainReady(d *downThenUp) {
|
||||
d.mu.Lock()
|
||||
d.down = false
|
||||
d.mu.Unlock()
|
||||
restingUntil.Lock()
|
||||
for k := range restingUntil.m {
|
||||
restingUntil.m[k] = time.Now().Add(-time.Second)
|
||||
}
|
||||
restingUntil.Unlock()
|
||||
}
|
||||
|
||||
// A provider's fallback is for when none of the provider's own keys or
|
||||
// accounts can take a request (01huadalang on Discord, again on 10-31:
|
||||
// "主供应商有额度后请求还是一直走备用模型,备用只是应急"). A provider routed
|
||||
// In turn went round its fallbacks as if they were more of its keys: a
|
||||
// new turn went to the one after the last answerer (after), which past
|
||||
// the provider's last key is its fallback, and a new conversation to the
|
||||
// one the fewest conversations were on (leastHeld), which is the fallback
|
||||
// nobody is on — while every key of the provider was ready.
|
||||
func TestRotatingProviderKeepsItsFallbackForEmergencies(t *testing.T) {
|
||||
for _, keys := range []int{1, 2} {
|
||||
t.Run(itoa(keys)+" keys", func(t *testing.T) {
|
||||
fresh(t)
|
||||
main := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}}
|
||||
spare := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}}
|
||||
mu, su := httptest.NewServer(main), httptest.NewServer(spare)
|
||||
t.Cleanup(mu.Close)
|
||||
t.Cleanup(su.Close)
|
||||
mp := provider.Provider{ID: "main", Name: "Main", Key: "main-key", Models: []string{"m"}, Anthropic: mu.URL + "/v1",
|
||||
Fallback: []string{"spare/s"}, Routing: provider.Rotate}
|
||||
if keys == 2 {
|
||||
mp.Keys = []provider.KeyAccount{{Key: "main2-key"}}
|
||||
}
|
||||
for _, p := range []provider.Provider{mp,
|
||||
{ID: "spare", Name: "Spare", Key: "spare-key", Models: []string{"s"}, Anthropic: su.URL + "/v1"},
|
||||
} {
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
s := New()
|
||||
for _, sess := range []string{"s1", "s2", "s3"} {
|
||||
for n := 1; n <= 4; n++ {
|
||||
code, body := postAs(t, s, sess, chatTurns("main/m", n))
|
||||
if code != 200 || strings.Contains(body, "from spare-key") || !strings.Contains(body, "from main") {
|
||||
a := s.trace.routes[len(s.trace.routes)-1].Affinity
|
||||
t.Fatalf("%s turn %d: %d %s (affinity %+v), want a key of main's while main is ready", sess, n, code, body, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The same with the provider down for one turn: the fallback answers it,
|
||||
// and once the provider is ready the next turn and a new conversation go
|
||||
// to the provider, in every routing and Stays but Strict.
|
||||
func TestFallbackGivesBackAcrossRoutings(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, routing, mode string
|
||||
group bool // the fallback is a routing group
|
||||
}{
|
||||
{"auto", "", "", false},
|
||||
{"in turn", provider.Rotate, "", false},
|
||||
{"in turn, session", provider.Rotate, provider.AffinitySession, false},
|
||||
{"least used, session", provider.LeastUsed, provider.AffinitySession, false},
|
||||
{"stays turn", "", provider.AffinityTurn, false},
|
||||
{"group fallback", "", "", true},
|
||||
{"group fallback, in turn", provider.Rotate, "", true},
|
||||
{"group fallback, session", "", provider.AffinitySession, true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
fresh(t)
|
||||
main := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}, down: true}
|
||||
spare := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}}
|
||||
mu, su := httptest.NewServer(main), httptest.NewServer(spare)
|
||||
t.Cleanup(mu.Close)
|
||||
t.Cleanup(su.Close)
|
||||
fb := "spare/s"
|
||||
if c.group {
|
||||
if err := provider.SaveGroup(provider.Group{ID: "fb", Name: "FB", Members: []string{"spare/s", "spare2/s"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fb = provider.GroupPrefix + "fb"
|
||||
}
|
||||
for _, p := range []provider.Provider{
|
||||
{ID: "main", Name: "Main", Key: "main-key", Keys: []provider.KeyAccount{{Key: "main2-key"}}, Models: []string{"m"}, Anthropic: mu.URL + "/v1",
|
||||
Fallback: []string{fb}, Routing: c.routing, Affinity: c.mode},
|
||||
{ID: "spare", Name: "Spare", Key: "spare-key", Models: []string{"s"}, Anthropic: su.URL + "/v1"},
|
||||
{ID: "spare2", Name: "Spare2", Key: "spare2-key", Models: []string{"s"}, Anthropic: su.URL + "/v1"},
|
||||
} {
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
s := New()
|
||||
if code, body := postAs(t, s, "s1", chatTurns("main/m", 1)); code != 200 || !strings.Contains(body, "from spare") {
|
||||
t.Fatalf("first turn %d %s, want the fallback's answer", code, body)
|
||||
}
|
||||
mainReady(main)
|
||||
for n := 2; n <= 4; n++ {
|
||||
code, body := postAs(t, s, "s1", chatTurns("main/m", n))
|
||||
if code != 200 || !strings.Contains(body, "from main") {
|
||||
a := s.trace.routes[len(s.trace.routes)-1].Affinity
|
||||
t.Fatalf("turn %d %d %s (affinity %+v), want main's answer", n, code, body, a)
|
||||
}
|
||||
}
|
||||
for _, sess := range []string{"s2", "s3", "s4"} {
|
||||
code, body := postAs(t, s, sess, chatTurns("main/m", 1))
|
||||
if code != 200 || !strings.Contains(body, "from main") {
|
||||
a := s.trace.routes[len(s.trace.routes)-1].Affinity
|
||||
t.Fatalf("new conversation %s: %d %s (affinity %+v), want main's answer", sess, code, body, a)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Stays: Strict is the user's own: a conversation it keeps on the fallback
|
||||
// stays there once the provider is ready again, and the trace names the
|
||||
// provider's ready key (Affinity.Main) for the Routing page to say why.
|
||||
// A new conversation goes to the provider.
|
||||
func TestStrictKeepsTheFallbackAndSaysTheMainIsReady(t *testing.T) {
|
||||
fresh(t)
|
||||
main := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}, down: true}
|
||||
spare := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}}
|
||||
mu, su := httptest.NewServer(main), httptest.NewServer(spare)
|
||||
t.Cleanup(mu.Close)
|
||||
t.Cleanup(su.Close)
|
||||
for _, p := range []provider.Provider{
|
||||
{ID: "main", Name: "Main", Key: "main-key", Models: []string{"m"}, Anthropic: mu.URL + "/v1", Fallback: []string{"spare/s"}, Affinity: provider.AffinityStrict},
|
||||
{ID: "spare", Name: "Spare", Key: "spare-key", Models: []string{"s"}, Anthropic: su.URL + "/v1"},
|
||||
} {
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
s := New()
|
||||
if code, body := postAs(t, s, "s1", chatTurns("main/m", 1)); code != 200 || !strings.Contains(body, "from spare-key") {
|
||||
t.Fatalf("first turn %d %s, want the fallback's answer", code, body)
|
||||
}
|
||||
mainReady(main)
|
||||
code, body := postAs(t, s, "s1", chatTurns("main/m", 2))
|
||||
if code != 200 || !strings.Contains(body, "from spare-key") {
|
||||
t.Fatalf("next turn %d %s, want the fallback kept (Strict)", code, body)
|
||||
}
|
||||
a := s.trace.routes[len(s.trace.routes)-1].Affinity
|
||||
if a == nil || a.Why != "strict" || a.Main == nil || a.Main.Provider != "main" {
|
||||
t.Fatalf("affinity %+v, want strict naming main as ready", a)
|
||||
}
|
||||
if code, body := postAs(t, s, "s2", chatTurns("main/m", 1)); code != 200 || !strings.Contains(body, "from main-key") {
|
||||
t.Fatalf("new conversation %d %s, want main's answer", code, body)
|
||||
}
|
||||
if a := s.trace.routes[len(s.trace.routes)-1].Affinity; a == nil || a.Main != nil {
|
||||
t.Fatalf("new conversation's affinity %+v, want no main named", a)
|
||||
}
|
||||
}
|
||||
@@ -164,10 +164,17 @@ func TestWholeSessionSpreadLeavesTheNearlyUsedAndFallbacks(t *testing.T) {
|
||||
if got[0].who() != cs[0].who() {
|
||||
t.Errorf("a new session went to %s, %s", got[0].who(), c.name)
|
||||
}
|
||||
// in turn spreads to it as it did
|
||||
// in turn spreads to one used past lowShare as it did, but
|
||||
// never to a fallback while the provider's own model leads
|
||||
// (standsIn; 01huadalang on Discord, 10-31): then to the one
|
||||
// of the provider's the fewest are on, k2 (k1 holds a and c)
|
||||
want := cs[2]
|
||||
if c.last.Fallback {
|
||||
want = cs[1]
|
||||
}
|
||||
got, _ = leastHeld(scope, scope+"|d", cs, planned{order: []Weighed{{}, {}, c.last}}, false)
|
||||
if got[0].who() != cs[2].who() {
|
||||
t.Errorf("in turn, a new conversation went to %s, not the one none are on", got[0].who())
|
||||
if got[0].who() != want.who() {
|
||||
t.Errorf("in turn, a new conversation went to %s, want %s", got[0].who(), want.who())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -941,6 +941,7 @@ function routingPage(part) {
|
||||
case "session": return t("Kept on {who}: it answered this conversation before, and affinity keeps a session with one account.", { who: last });
|
||||
case "turn": return t("Kept on {who}: {agent} is handing back tool results within turn {n}, and moving now would lose what the vendor cached of it.", { who: last, agent: agentName(r.agent), n: a.turn });
|
||||
case "cache": return t("Kept on {who}: {d} ago the vendor read {r} tokens of this conversation from its cache and wrote {w} to it; anyone else would be sent them afresh and paid in full.", { who: last, r: tokens(a.cacheRead || 0), w: tokens(a.cacheWrite || 0), d: ago });
|
||||
case "strict": return a.main ? t("{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.", { who: last, first: who(a.main) }) : null;
|
||||
case "new-turn": return routing === "rotate"
|
||||
? t("Turn {n} begins: in turn, it goes to the one after {who}, which answered the last turn — {next}.", { n: a.turn, who: last, next: who(r.order[0]) })
|
||||
: lead ? null : t("Turn {n} begins: affinity keeps a conversation only within a turn, so routing decides afresh.", { n: a.turn });
|
||||
|
||||
@@ -579,6 +579,7 @@ magpie.strings({
|
||||
"{who} answered this conversation last, but it is no longer one to route to.": "此会话上次由 {who} 回答,但它已不可路由。",
|
||||
"{who} answered this conversation last, but the group goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "此会话上次由 {who} 回答,但该组按顺序路由,排在它前面的 {first} 已恢复可用,所以第 {n} 轮回到 {first}。",
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "此会话上次由备用 {who} 回答,但提供商自己的 {first} 已恢复可用,所以第 {n} 轮回到它。",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "此会话上次由备用 {who} 回答。提供商自己的 {first} 已恢复可用,但会话保持设为严格,从不移动会话,所以它留在备用上;新会话会走 {first}。",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "此会话上次由 {who} 回答,但当时厂商只从缓存读取了 {r} tokens、写入了 {w} tokens,不值得保留。",
|
||||
"{who} answered this conversation {d} ago, longer than the 5 minutes a vendor keeps a prompt cached — so routing decides afresh.": "此会话 {d}前由 {who} 回答,已超过厂商缓存提示词的 5 分钟,路由重新决定。",
|
||||
"Affinity is off: each request is routed afresh, whoever answered its conversation before.": "亲和性已关闭:每个请求都重新路由,不论之前由谁回答。",
|
||||
@@ -1203,6 +1204,7 @@ magpie.strings({
|
||||
"{who} answered this conversation last, but it is no longer one to route to.": "此會話上次由 {who} 回答,但它已不可路由。",
|
||||
"{who} answered this conversation last, but the group goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "此會話上次由 {who} 回答,但該群組按順序路由,排在它前面的 {first} 已恢復可用,所以第 {n} 輪回到 {first}。",
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "此會話上次由備用 {who} 回答,但供應商自己的 {first} 已恢復可用,所以第 {n} 輪回到它。",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "此會話上次由備用 {who} 回答。供應商自己的 {first} 已恢復可用,但會話保持設為嚴格,從不移動會話,所以它留在備用上;新會話會走 {first}。",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "此會話上次由 {who} 回答,但當時廠商只從快取讀取了 {r} tokens、寫入了 {w} tokens,不值得保留。",
|
||||
"{who} answered this conversation {d} ago, longer than the 5 minutes a vendor keeps a prompt cached — so routing decides afresh.": "此會話 {d}前由 {who} 回答,已超過廠商快取提示詞的 5 分鐘,路由重新決定。",
|
||||
"Affinity is off: each request is routed afresh, whoever answered its conversation before.": "親和性已關閉:每個請求都重新路由,不論之前由誰回答。",
|
||||
@@ -1825,6 +1827,7 @@ magpie.strings({
|
||||
"{who} answered this conversation last, but it is no longer one to route to.": "この会話に前回応答したのは {who} ですが、もうルーティング対象ではありません。",
|
||||
"{who} answered this conversation last, but the group goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "この会話に前回応答したのは {who} ですが、このグループは順番どおりにルーティングし、その前にある {first} が再び使えるため、ターン {n} は {first} に戻ります。",
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "この会話に前回応答したのは代替の {who} ですが、プロバイダー自身の {first} が再び使えるため、ターン {n} はそちらに戻ります。",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "この会話に前回応答したのは代替の {who} です。プロバイダー自身の {first} は再び使えますが、維持が「厳格」で会話を移さないため、代替のままです。新しい会話は {first} に行きます。",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "この会話に前回応答したのは {who} ですが、そのときベンダーがキャッシュから読んだのは {r} トークン、書き込んだのは {w} トークンだけでした — 留まる価値はありません。",
|
||||
"{who} answered this conversation {d} ago, longer than the 5 minutes a vendor keeps a prompt cached — so routing decides afresh.": "この会話に {who} が応答したのは {d} 前で、ベンダーがプロンプトをキャッシュする 5 分を超えています — そのためルーティングを新たに決めます。",
|
||||
"Affinity is off: each request is routed afresh, whoever answered its conversation before.": "アフィニティはオフです:以前誰が会話に応答したかに関係なく、各リクエストを新たにルーティングします。",
|
||||
@@ -2449,6 +2452,7 @@ magpie.strings({
|
||||
"{who} answered this conversation last, but it is no longer one to route to.": "{who} hat diese Unterhaltung zuletzt beantwortet, kommt aber für die Weiterleitung nicht mehr in Frage.",
|
||||
"{who} answered this conversation last, but the group goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "{who} hat diese Unterhaltung zuletzt beantwortet, aber die Gruppe geht der Reihe nach vor und {first}, das davor steht, ist wieder bereit, daher geht Runde {n} zurück an {first}.",
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "{who}, ein Ersatz, hat diese Unterhaltung zuletzt beantwortet, aber {first} des Anbieters selbst ist wieder bereit, daher geht Runde {n} dorthin zurück.",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "{who}, ein Ersatz, hat diese Unterhaltung zuletzt beantwortet. {first} des Anbieters selbst ist wieder bereit, aber Bleibt steht auf Strikt, das eine Unterhaltung nie verschiebt, daher bleibt sie beim Ersatz; neue Unterhaltungen gehen an {first}.",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "{who} hat diese Unterhaltung zuletzt beantwortet, aber der Anbieter hat damals nur {r} Token davon aus seinem Cache gelesen und {w} hineingeschrieben – das lohnt das Bleiben nicht.",
|
||||
"{who} answered this conversation {d} ago, longer than the 5 minutes a vendor keeps a prompt cached — so routing decides afresh.": "{who} hat diese Unterhaltung vor {d} beantwortet, länger als die 5 Minuten, die ein Anbieter einen Prompt im Cache hält – daher entscheidet die Weiterleitung neu.",
|
||||
"Affinity is off: each request is routed afresh, whoever answered its conversation before.": "Affinität ist aus: Jede Anfrage wird neu weitergeleitet, egal wer ihre Unterhaltung vorher beantwortet hat.",
|
||||
|
||||
@@ -9,24 +9,27 @@ const { chromium, webkit } = require("playwright");
|
||||
// (yyhhyyyyyy on Discord: an API key first, a Claude subscription second,
|
||||
// 8 of 10 requests on the subscription). The Routing page says why it
|
||||
// moved, as it does for a provider's fallback giving one back ("main"),
|
||||
// which said nothing before.
|
||||
// which said nothing before. A conversation Stays: Strict keeps on the
|
||||
// fallback, the provider ready again, says that too ("strict" with main;
|
||||
// 01huadalang on Discord, 10-31).
|
||||
const words = {
|
||||
en: { order: ["goes in order", "turn 2 goes back"], main: ["a fallback", "turn 2 goes back"] },
|
||||
zh: { order: ["按顺序路由", "第 2 轮回到"], main: ["备用", "第 2 轮回到它"] },
|
||||
"zh-TW": { order: ["按順序路由", "第 2 輪回到"], main: ["備用", "第 2 輪回到它"] },
|
||||
ja: { order: ["順番どおり", "ターン 2 は"], main: ["代替", "ターン 2 は"] },
|
||||
de: { order: ["der Reihe nach", "Runde 2 zurück"], main: ["ein Ersatz", "Runde 2 dorthin zurück"] },
|
||||
en: { order: ["goes in order", "turn 2 goes back"], main: ["a fallback", "turn 2 goes back"], strict: ["a fallback", "Strict", "new conversations go to"] },
|
||||
zh: { order: ["按顺序路由", "第 2 轮回到"], main: ["备用", "第 2 轮回到它"], strict: ["备用", "严格", "新会话会走"] },
|
||||
"zh-TW": { order: ["按順序路由", "第 2 輪回到"], main: ["備用", "第 2 輪回到它"], strict: ["備用", "嚴格", "新會話會走"] },
|
||||
ja: { order: ["順番どおり", "ターン 2 は"], main: ["代替", "ターン 2 は"], strict: ["代替", "厳格", "新しい会話は"] },
|
||||
de: { order: ["der Reihe nach", "Runde 2 zurück"], main: ["ein Ersatz", "Runde 2 dorthin zurück"], strict: ["ein Ersatz", "Strikt", "neue Unterhaltungen gehen an"] },
|
||||
};
|
||||
|
||||
function routes(now, why) {
|
||||
const time = new Date(now.getTime() - 5000).toISOString();
|
||||
const at = new Date(now.getTime() - 65000).toISOString();
|
||||
const k1 = { id: "cw#k1", provider: "cw", name: "CW", kind: "key", who: "k1", model: "m" };
|
||||
const k2 = { id: "cw#k2", provider: "cw", name: "CW", kind: "key", who: "k2", model: "m", fallback: why === "main" };
|
||||
const order = [k1, k2];
|
||||
const k2 = { id: "cw#k2", provider: "cw", name: "CW", kind: "key", who: "k2", model: "m", fallback: why !== "order" };
|
||||
// Strict leaves the plan the one it keeps, and names the main beside it
|
||||
const order = why === "strict" ? [k2] : [k1, k2];
|
||||
return [{ id: 1, seq: 1, time, agent: "claude", model: "cw/m", provider: "cw", order, done: true, status: 200, ms: 20,
|
||||
group: why === "order" ? { id: "g", name: "G", routing: "order" } : undefined,
|
||||
affinity: { mode: "", turn: 2, last: "cw#k2", lastTurn: 1, at, cacheRead: 20000, cacheWrite: 3000, why },
|
||||
affinity: { mode: why === "strict" ? "strict" : "", turn: 2, last: "cw#k2", lastTurn: 1, at, cacheRead: 20000, cacheWrite: 3000, why, main: why === "strict" ? k1 : undefined },
|
||||
tries: [{ id: order[0].id, model: "m", start: time, done: true, status: 200, ms: 20 }] }];
|
||||
}
|
||||
|
||||
@@ -71,7 +74,7 @@ for (const engine of process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.waitForFunction(() => /\d/.test(document.body.innerText) && document.querySelector(".rt-cap")?.textContent);
|
||||
return page.evaluate(() => document.body.innerText + "\n" + document.querySelector(".rt-cap").textContent);
|
||||
};
|
||||
for (const why of ["order", "main"]) {
|
||||
for (const why of ["order", "main", "strict"]) {
|
||||
rs = routes(now, why);
|
||||
const text = await story();
|
||||
for (const w of words[lang][why]) assert.ok(text.includes(w), `${why}: ${w} not in\n${text}`);
|
||||
|
||||
Reference in New Issue
Block a user