gateway: a provider's fallback gives the conversation back once the provider is ready (01huadalang)
01huadalang on Discord (#feedback): once a provider's main model works again, a conversation that went to its Fallback while it was down stayed on the fallback, with no switch to stop it. affine treated the fallback as any answerer: Auto kept it while its cache was worth reading (each turn read it again, so it never went cold), Session for the session, and a rotating provider's new turn went to the one after the fallback. A provider's fallback is now its emergency path. When the last answerer is a Fallback row and the provider's own model stands first in the plan, ready (restLast put it ahead, so its rest is over), the next turn goes to the provider (backToMain, Affinity.Why "main"), in every mode but Strict, which the user set never to move a conversation. Within a turn 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 either way. A routing group's members are never Fallback rows, so a group's own affinity is unchanged. No switch was added. "Ready" is unchanged: a rest ends when restAfter set it to (a minute and backing off for a plain failure; the vendor's reset or Retry-After for a quota or rate limit; quotaRest 15 minutes when nothing names a time), or earlier when renewed or a background probe lifts it. docs/subsystems/gateway-routing.md says this beside Strict. Run (mote, at this commit's tree on origin/main3ce2a9819, rebased onto774baed6d(a one-line Qoder mover min); the new tests and internal/provider run again there, then onto13b4a29ab(Desktop tier calls in internal/gateway): go vet and TestFallback|TestAffinity|TestDesktop|the new tests ok there): - TestFallbackGivesTheConversationBackOnceTheMainIsReady red on the old affinity.go: "next turn, main ready" and "..., session" answered from spare-key, want main. Green with the change. With !a.Within dropped by hand, "within the turn, main ready" goes red. - TestGroupMemberKeepsTheConversationOnceAnotherIsBack green before and after (a group member stays by its cache once another is back). - gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of internal/gateway: ok. - go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider: ok internal/gateway 551.7s, ok internal/provider 108.4s Not tried: a real account. The fake upstreams answer as Anthropic does (a 429, then cache_creation_input_tokens 3000).
This commit is contained in:
@@ -204,6 +204,7 @@ 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: `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`. 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`.
|
||||
- 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.
|
||||
- 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).
|
||||
|
||||
@@ -98,7 +98,9 @@ type Affinity struct {
|
||||
// (nobody has answered it yet), "new-turn", "no-cache" (the vendor
|
||||
// read and wrote too little of its cache to keep, or was sent too
|
||||
// little for a cache it keeps without saying so), "cold" (too long
|
||||
// ago), "resting", "spent", "gone" (no longer one to route to).
|
||||
// ago), "resting", "spent", "gone" (no longer one to route to),
|
||||
// "main" (a provider's fallback answered it, and the provider's own
|
||||
// model is ready again: backToMain).
|
||||
Why string `json:"why"`
|
||||
}
|
||||
|
||||
@@ -541,6 +543,16 @@ func affine(scope, mode string, rotate bool, in http.Header, from provider.Proto
|
||||
a.Why = "strict"
|
||||
case pl.order[at].Rest != nil:
|
||||
a.Why = "resting"
|
||||
case !a.Within && backToMain(pl.order, at):
|
||||
// a provider's fallback is its emergency path, not a place a
|
||||
// conversation stays: once one of the provider's own keys or
|
||||
// accounts is ready again (its rest over, its quota back) the
|
||||
// user's next turn goes to it, whatever the fallback has cached
|
||||
// (01huadalang on Discord). Within a turn it stays where it is:
|
||||
// the turn's tool loop runs on the reasoning the fallback sealed
|
||||
// for it, which the provider can't read, and the whole prompt is
|
||||
// sent afresh to the provider at the next turn all the same
|
||||
a.Why = "main"
|
||||
case at > 0 && pl.order[at].Known && pl.order[at].Used >= provider.SpentShareOf(cs[at].p.Routing):
|
||||
// all but used up, and put behind another: first still — the
|
||||
// one key or account it has (#1016), or every one used up — it
|
||||
@@ -594,6 +606,15 @@ func affine(scope, mode string, rotate bool, in http.Header, from provider.Proto
|
||||
return cs, pl, a, key
|
||||
}
|
||||
|
||||
// backToMain says whether the one that answered last, order[at], is a
|
||||
// provider's fallback while the provider's own model stands first, ready:
|
||||
// restLast puts a resting one behind every ready one, so the first is the
|
||||
// provider's own only when it can take the request. A routing group's
|
||||
// members are never fallbacks, so its own affinity is as it was.
|
||||
func backToMain(order []Weighed, at int) bool {
|
||||
return at > 0 && at < len(order) && order[at].Fallback && !order[0].Fallback && order[0].Rest == nil
|
||||
}
|
||||
|
||||
// heldFor is how long after its last answer a conversation still counts as
|
||||
// holding the one that answered it: a session whose user is reading or
|
||||
// typing is still going.
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// downThenUp is an Anthropic Messages upstream that refuses with a 429
|
||||
// while down is set, and otherwise answers as cacheWriter does, writing
|
||||
// the whole prompt to its cache.
|
||||
type downThenUp struct {
|
||||
cacheWriter
|
||||
mu sync.Mutex
|
||||
down bool
|
||||
asked int
|
||||
}
|
||||
|
||||
func (d *downThenUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
d.mu.Lock()
|
||||
down := d.down
|
||||
d.asked++
|
||||
d.mu.Unlock()
|
||||
if down {
|
||||
io.ReadAll(r.Body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
io.WriteString(w, `{"type":"error","error":{"type":"rate_limit_error","message":"rate limited"}}`)
|
||||
return
|
||||
}
|
||||
d.cacheWriter.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// A provider's fallback is its emergency path: a conversation that went to
|
||||
// it while the provider was down goes back to the provider at its next
|
||||
// turn once the provider can serve again, however much the fallback
|
||||
// cached (01huadalang on Discord: "主模型恢复后备用模型还在走缓存逻辑").
|
||||
// Within a turn it stays on the fallback, whose sealed reasoning the turn
|
||||
// runs on. A provider still resting keeps the conversation on the
|
||||
// fallback, cached there.
|
||||
func TestFallbackGivesTheConversationBackOnceTheMainIsReady(t *testing.T) {
|
||||
const (
|
||||
first = `{"model":"main/m","messages":[{"role":"user","content":"hi"}]}`
|
||||
again = `{"model":"main/m","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"yo"},{"role":"user","content":"more"}]}`
|
||||
tool = `{"model":"main/m","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"ls","arguments":"{}"}}]},{"role":"tool","tool_call_id":"c1","content":"a.go"}]}`
|
||||
)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
next string
|
||||
mainBack bool
|
||||
mode string
|
||||
want string // who answers the next request
|
||||
why string
|
||||
}{
|
||||
{"next turn, main ready", again, true, "", "main", "main"},
|
||||
{"next turn, main ready, session", again, true, provider.AffinitySession, "main", "main"},
|
||||
{"within the turn, main ready", tool, true, "", "spare", "turn"},
|
||||
{"next turn, main still resting", again, false, "", "spare", "cache"},
|
||||
} {
|
||||
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)
|
||||
for _, p := range []provider.Provider{
|
||||
{ID: "main", Name: "Main", Key: "main-key", Models: []string{"m"}, Anthropic: mu.URL + "/v1", Fallback: []string{"spare/s"}, Affinity: c.mode},
|
||||
{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", first); code != 200 || !strings.Contains(body, "from spare-key") {
|
||||
t.Fatalf("first turn %d %s, want the fallback's answer", code, body)
|
||||
}
|
||||
if c.mainBack {
|
||||
// its rest over, as when the minute or the reset passes
|
||||
main.mu.Lock()
|
||||
main.down = false
|
||||
main.mu.Unlock()
|
||||
restingUntil.Lock()
|
||||
for k := range restingUntil.m {
|
||||
restingUntil.m[k] = time.Now().Add(-time.Second)
|
||||
}
|
||||
restingUntil.Unlock()
|
||||
}
|
||||
code, body := postAs(t, s, "s1", c.next)
|
||||
if code != 200 || !strings.Contains(body, "from "+c.want+"-key") {
|
||||
t.Fatalf("next request %d %s, want %s's answer", code, body, c.want)
|
||||
}
|
||||
a := s.trace.routes[len(s.trace.routes)-1].Affinity
|
||||
if a == nil || a.Why != c.why {
|
||||
t.Fatalf("affinity %+v, want why %q", a, c.why)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A routing group keeps its own affinity: of two members, the one that
|
||||
// answered while the other was down keeps the conversation, cached, once
|
||||
// the other is back. Only a provider's fallback gives it back.
|
||||
func TestGroupMemberKeepsTheConversationOnceAnotherIsBack(t *testing.T) {
|
||||
fresh(t)
|
||||
const (
|
||||
first = `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`
|
||||
again = `{"model":"group/g","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"yo"},{"role":"user","content":"more"}]}`
|
||||
)
|
||||
a := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}, down: true}
|
||||
b := &downThenUp{cacheWriter: cacheWriter{wrote: 3000}}
|
||||
au, bu := httptest.NewServer(a), httptest.NewServer(b)
|
||||
t.Cleanup(au.Close)
|
||||
t.Cleanup(bu.Close)
|
||||
for _, p := range []provider.Provider{
|
||||
{ID: "pa", Name: "A", Key: "a-key", Models: []string{"m"}, Anthropic: au.URL + "/v1"},
|
||||
{ID: "pb", Name: "B", Key: "b-key", Models: []string{"m"}, Anthropic: bu.URL + "/v1"},
|
||||
} {
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: []string{"pa/m", "pb/m"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
if code, body := postAs(t, s, "s1", first); code != 200 || !strings.Contains(body, "from b-key") {
|
||||
t.Fatalf("first turn %d %s, want b's answer", code, body)
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.down = false
|
||||
a.mu.Unlock()
|
||||
restingUntil.Lock()
|
||||
for k := range restingUntil.m {
|
||||
restingUntil.m[k] = time.Now().Add(-time.Second)
|
||||
}
|
||||
restingUntil.Unlock()
|
||||
code, body := postAs(t, s, "s1", again)
|
||||
if code != 200 || !strings.Contains(body, "from b-key") {
|
||||
t.Fatalf("next turn %d %s, want b kept", code, body)
|
||||
}
|
||||
if aff := s.trace.routes[len(s.trace.routes)-1].Affinity; aff == nil || aff.Why != "cache" {
|
||||
t.Fatalf("affinity %+v, want cache", aff)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user