diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 39721b08c..ba519c6e1 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -204,7 +204,7 @@ recorded as a prediction failure (`noPrediction`). - A provider whose keys are on different plans (`KeyAccount.Plan`, `PlansMixed`; yckonnnn on X) sends each key to its plan's endpoints: every key path takes its copy through `WithKey`, which moves it there (`atKeyPlan`), on the first try and on a failover alike. `perKeyBarred` leaves out a key whose plan's list lacks the model (`PlanServing`: a pay-as-you-go model id at the Agent Plan's endpoint only answers 404), not shown in the trace; only when no key's plan has it are those keys asked. Embeddings and drawing go through the same `perKeyBarred` and `WithKey`; a video started on a mixed provider names its key in the task id (`videoStart.onKey`, `keyMark`) so its poll goes to that key's plan. `TestKeyPlansEachToItsOwnEndpoint`. - A subscription's account whose own model list lacks the model (`Account.Lists`: an Antigravity account's `fetchAvailableModels`, a plugin account's `models`) isn't planned while another of its accounts lists it (`perKeyBarred`'s `left`, `planned.unlisted`, the Routing page's "unlisted, skipped"). It is the next asked when every account of the subscription that lists the model has been asked and one refused it as a model it doesn't serve (`unservedTry`: `modelRefused`, or Code Assist's 404 NOT_FOUND, `codeAssistModelMissing`), before any later member or fallback (`unlistedNext`, `askUnlisted` moves its row from the route's left to its order after the one that refused). A list is fetched once and can be stale: 01huadalang's Gemini 4 was served by one Antigravity account of several, and the one whose list named it refused it with a 404 the agent got while the other could answer. The one that refused rests for that model alone. Not for another refusal (a 403, a quota), a request pinned to an account, a native compaction sealed to one, or a conversation kept strictly on one; a gateway key held to some accounts narrows the unlisted ones too (`allowedCandidates`). `TestUnlistedAccountAskedAfterModelRefused`, `TestUnlistedAccountNotAskedForOtherRefusals`. - 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`. +- 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 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`. diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index ef03b9a8b..3eca4c5ef 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -63,6 +63,14 @@ const ( // reasoning the first had sealed was refused there (leelantao on X: // two Plus accounts' allowance spent 90% in a day). chatGPTCold = time.Hour + // deepseekCold is how long DeepSeek's own API keeps a conversation's + // prefix cached without it being read. Its context caching guide + // (api-docs.deepseek.com/guides/kv_cache, read 10-31) says an unused + // cache is cleared "usually within a few hours to a few days", and a + // real Claude Code conversation on deepseek-v4-pro (10-31) read back + // 98–99% of its prompt after 7 and 26 minutes idle. Moving it to + // another DeepSeek key after five minutes sent it all again uncached. + deepseekCold = time.Hour // cacheHour is how long Anthropic keeps what was written with // cache_control's ttl "1h" (cache_creation's ephemeral_1h_input_tokens) // without it being read, as Claude Code asks of a subscription (#2302) @@ -74,11 +82,15 @@ const ( ) // coldAfter is how long p's vendor keeps a prompt cached without it being -// read: cacheCold, or chatGPTCold for a ChatGPT account. +// read: cacheCold, chatGPTCold for a ChatGPT account, or deepseekCold on +// DeepSeek's own API. func coldAfter(p provider.Provider) time.Duration { if p.Account != nil && p.Account.Agent == "codex" { return chatGPTCold } + if p.Host() == deepseekHost { + return deepseekCold + } return cacheCold } diff --git a/internal/gateway/deepseek_cold_test.go b/internal/gateway/deepseek_cold_test.go new file mode 100644 index 000000000..c1086c163 --- /dev/null +++ b/internal/gateway/deepseek_cold_test.go @@ -0,0 +1,85 @@ +package gateway + +import ( + "net/http" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// A Claude Code conversation on one of two DeepSeek keys stays on it +// across a pause DeepSeek still has it cached through (on X: "Claude code +// 通过 Magpie 链接 DeepSeek 缓存命中率只有 50%"). DeepSeek clears an unused +// cache after hours, and a real conversation read 98–99% back after 7 and +// 26 minutes idle, but five minutes was its cold, so routing moved the +// conversation to the other key, which read none of it from cache. +// Another vendor's key is cold at five minutes as before. +func TestDeepSeekConversationStaysPastFiveMinutes(t *testing.T) { + deepseek := func(key string) candidate { + return candidate{p: provider.Provider{ID: "deepseek", Key: key, Chat: "https://api.deepseek.com/v1", Anthropic: "https://api.deepseek.com/anthropic"}, model: "deepseek-v4-pro", rest: "deepseek"} + } + other := func(key string) candidate { + return candidate{p: provider.Provider{ID: "ant", Key: key, Anthropic: "https://api.anthropic.com"}, model: "claude-sonnet-5-5", rest: "ant"} + } + first := []byte(`{"messages":[{"role":"user","content":"fix the bug"}]}`) + again := []byte(`{"messages":[{"role":"user","content":"fix the bug"},{"role":"assistant","content":"done"},{"role":"user","content":"now the tests"}]}`) + for i, c := range []struct { + name string + last, next candidate + ago time.Duration + why string + }{ + {"DeepSeek, 6 minutes on", deepseek("sk-a"), deepseek("sk-b"), 6 * time.Minute, "cache"}, + {"DeepSeek, 26 minutes on", deepseek("sk-a"), deepseek("sk-b"), 26 * time.Minute, "cache"}, + {"DeepSeek, past its window", deepseek("sk-a"), deepseek("sk-b"), deepseekCold + time.Minute, "cold"}, + {"another vendor, 6 minutes on", other("sk-a"), other("sk-b"), 6 * time.Minute, "cold"}, + {"another vendor, 4 minutes on", other("sk-a"), other("sk-b"), 4 * time.Minute, "cache"}, + } { + h := http.Header{} + h.Set("x-claude-code-session-id", "deepseek-cold-"+string(rune('a'+i))) + cs := []candidate{c.next, c.last} + pl := planned{order: []Weighed{{}, {}}} + _, _, _, key := affine("t", "", false, false, false, h, provider.Anthropic, first, first, cs, pl) + answered(key, c.last, 1, Usage{Input: 300, CacheRead: 13696}) + t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() }) + sticks.Lock() + st := sticks.m[key] + st.at = st.at.Add(-c.ago) + sticks.m[key] = st + sticks.Unlock() + got, _, a, _ := affine("t", "", false, false, false, h, provider.Anthropic, again, again, cs, pl) + if a.Why != c.why || a.Kept != (c.why == "cache") { + t.Fatalf("%s: why %q kept %v, want %q", c.name, a.Why, a.Kept, c.why) + } + want := c.next + if c.why == "cache" { + want = c.last + } + if got[0].who() != want.who() { + t.Fatalf("%s: went to %s, want %s", c.name, got[0].who(), want.who()) + } + } +} + +// A group's rules keep a DeepSeek conversation's effort through the same +// pause (keepsEffort): the window comes from coldAfter. +func TestDeepSeekColdAfter(t *testing.T) { + ds := provider.Provider{ID: "deepseek", Anthropic: "https://api.deepseek.com/anthropic"} + if got := coldAfter(ds); got != deepseekCold { + t.Fatalf("DeepSeek's cold is %v, want %v", got, deepseekCold) + } + for _, p := range []provider.Provider{ + {ID: "ant", Anthropic: "https://api.anthropic.com"}, + {ID: "relay", Chat: "https://relay.example.com/v1"}, + } { + if got := coldAfter(p); got != cacheCold { + t.Fatalf("%s's cold is %v, want %v", p.ID, got, cacheCold) + } + } + at := time.Date(2026, 10, 31, 9, 0, 0, 0, time.UTC) + tr := turnRule{effort: "high", at: at, answered: at, size: 40_000, cold: coldAfter(ds)} + if !keepsEffort(tr, "low", 41_000, at.Add(26*time.Minute)) { + t.Fatal("a DeepSeek conversation 26 minutes on dropped its effort") + } +}