ac4af582301a4e8a29245dbba767eba31334ddf9
57
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
40cbdaa7e8 |
provider: an account's window can be capped at a fixed amount of its unit
A window magpie reads with a total and a unit (a day's 1000 credits, a
plan's requests) can now be capped at an amount of that unit, not only
a share: 9won_25273 asked to stop an account at 300 of its day's credits.
- AccountWindowAmounts keeps it per account and window (capId). An
amount and a window's own share replace each other.
- WindowCaps.limitShare turns it into a share of the total for the mark
and NearCap. CapHeld and capReached hold the account once the window's
count reaches the amount (past), and rest it as the percentage cap
does: the next account takes the request. cappedError and the trace
say "has used 300 credits ... past its cap of 300".
- A reading with no total ignores the amount; the account's share
applies.
- GUI: the window meter's menu has one more item, Amount..., typed in
place (provider/windowcap with amount). It shows only on a window
with a unit and total. Strings in zh, zh-TW, ja, de.
- CLI: magpie provider account-cap <id> <account> --window <name>
--amount <n|off>.
Usage outside magpie counts: every cap reads the vendor's own count, so
what the account spent in the vendor's app or on another machine counts
from the next reading on. magpie can only hold back its own requests.
Run, at this head on Linux (wsl-run, magpie-desktop):
- gofmt -l: clean; go vet ./... for linux (-tags nogui) and windows: ok (darwin
vet needs cgo, so it runs with the full suite on mote afterwards)
- go test -run 'Lang|ToolLoop|LoopGuard|Cap|Amount' ./internal/gateway
./internal/provider ./internal/cli: ok (TestWindowAmountCapHeld,
TestSetWindowAmount, TestWindowAmountHoldsTheAccount, the CLI cases)
- GUI window-cap, window-cap-pool, account-cap in chromium and webkit,
420 and 1100 wide, en zh zh-TW ja de: 78 of 78 in each engine. An
earlier webkit run lost the amount test's page once ("Target page,
context or browser has been closed"); it passed in 2 more full-file
runs and 60 of 60 alone
- i18n-keys: only "a plugin's words are its own" red, words that aren't
this change's (#5332, #5426, #5482)
Broken by hand: limitShare ignoring amounts (of < 0): TestWindowAmountCapHeld
and TestWindowAmountHoldsTheAccount go red.
Not tried: the full go test ./... at this head (queued on mote, runs
after); a real account at an amount cap.
iFlytek: 9won's 讯飞 overshoot isn't covered. Loomy's daily window sends
used as a count and amount as what is left (plugins#889); AStudio's
wallets tell a balance only, which no cap can hold (#5770).
Reported-by: 9won_25273 (Discord)
|
||
|
|
82ca554be9 |
routing: a provider's accounts routed In order give a conversation back to the first
CryptoSarom on X: with a provider's accounts set to In order, a
conversation that had moved to the second account (the first was
resting) stayed on the second once the first was ready again. Only a
group's members went back to the first; a provider's own accounts never
did, because inOrder was read from the group's routing alone.
- gateway.go: inOrder comes from the provider's routing, or the group's
when the request is to a group.
- affinity.go: backToFirst compares accounts (who()) for a provider's
own accounts. For a provider it overrides only a cache that would have
kept the conversation (cacheHolds: worth keeping and still warm), so a
cold or empty cache keeps its own "cold"/"new" label.
- plugin_factory_cap_test.go: "auto, cached on B" pinned the old
stay-on-B behaviour; it now expects A, the first account, on purpose.
- GUI: the Routing affinity line for "order" without a group says the
provider goes in order and the first is ready again (all languages).
- docs/subsystems/gateway-routing.md: the In order bullet covers a
provider's own accounts.
Run on mote at this tree on aa3d11d5b; rebased onto
|
||
|
|
00198b26e0 |
gateway: a session's side call goes on the account its main conversation is on (#5655)
With two Claude accounts, Claude Desktop's own Sonnet calls beside an
Opus chat (desktop-beside), and Claude Code's auto mode classifier, ran
on account B while the chat was on A. Each model's conversation is kept
under its own scope (p.ID/model), so the side call was routed as a
session of its own: leastHeld, or Smart's order once its cache was cold,
put it on the account the fewest others held, and B's 5 hours drained on
calls the user never made there.
Decided (product call delegated): one session goes on one account. The
user picked one, the vendor sees one client, and the cost is one cache
write of the side call where the session goes on reading it.
withSession (affinity.go) puts first, for a request whose session a
header names, the key or account of that session's largest conversation
under another model's scope (answered within heldFor, at least
cacheWorth kept, larger than this one's own). It acts for Why first,
gone, cold, no-cache, cache and session; never mid-turn, under Strict,
for a subagent (withLead), past a rest, reserve, credits or a fallback
routing put first, nor to an account that isn't readyForNew. The trace
says Why "lead" with LeadModel, and the Routing page says "Put on
{first}, where this session's {model} is: one session goes on one
account." in en, zh, zh-TW, ja and de. docs/subsystems/gateway-routing.md
says the same.
Not fixed here: the classifier's ~110-130K cache write per call. That one
is ours too: in Claude Code's interactive mode the bridge pastes the
classifier's transcript as one block without the client's marks
(claudetui userPieces, clientCache.pasted), so only the fixed prefix
(Claude Code's system plus the appended rules, the 68,925) is read and
the rest is written again on every call. The cause and a candidate fix
are on #5585. It changes what a real Claude Code sends and can't be
checked without a real account.
Run (mote, through mote-run), at this head (aeeeed54a's tree, origin/main
|
||
|
|
a754660b2a |
gateway: requests that come together spread over a pool's accounts (#5242)
Moody-Sin and Tericerice (#5242, magpie 0.1.3072 on Linux): an antigravity provider with three accounts and affinity turn sent four requests at once all to one account, under In turn and By pace alike, each request with its own X-Magpie-Session. Cause: - Nothing counted the requests in flight when a request was planned. Pace (internal/routes/strategies.go:348) goes by pace, wallet and Tokens, all of which move only once a reply ends; a key's lane counts a request only once its try starts, after planning. Requests that came together were planned on the same figures and all went to the first. - In turn's next turn (affinity.go:685 "new-turn" → after(), :937) reads a stick that moves only when an answer comes back, so a burst of turns of conversations already answered all went to the one next account. - conversationID (gateway.go:9160 on origin/main) ignored X-Magpie-Session, so callers that named their own sessions but opened alike were one conversation and kept together. Fix: - burst.go: burstSpread, called in serve once the candidates are planned (gateway.go:3013), counts each request on the account it goes to until it ends, and puts first, among the accounts routing would as soon pick (burstAlike: In turn any ready one; By pace a pace within a tenth, no wallet told apart, none near its cap; Least used within a point), the one with the fewest in flight. A kept conversation (session, turn's stick, strict), a pin, a lead's account, a checkpoint and a new conversation leastHeld spread are counted where they are, not moved. Fallbacks, reserved, aside, resting, held, barred and capped accounts, other routings (Smart, In order, ...) and a group in a group keep their order. In a group, a member routed its own way is alike only to its own provider's. The one step covers direct models, groups, plugin providers and a remote magpie. - affinityID: the stick key (stickKey), a group rule's key (ruleKey) and the sealed lead's stick read X-Magpie-Session after an agent's own session header. conversationID, which Kilo and a plugin are sent as the conversation, is unchanged, so the caller's session never goes upstream. - docs/subsystems/gateway-routing.md says both. Not done: putting a markedly slower account behind by its TTFT. A first token's wait goes with the prompt's size and the vendor's queue more than with the account, so a small sample would move turns away from a fine account and off its cache; it needs its own design. Run (mote, mote-run): - go test ./internal/gateway -run 'TestABurst|TestBurst|TestMagpieSession| Kilo|Sealed|Rule|Stick|Affinity|Conversation': ok - go test ./internal/gateway ./internal/routes: ok (654s, 0.3s) - GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok; gofmt -l: clean New tests (burst_spread_test.go): six at once over three keys, rotate and pace × affinity turn/off/auto × x-session-id / X-Magpie-Session / same body × fresh and warm; over a group of three providers and of one provider's keys; behind a remote magpie; over a plugin's three accounts (fake plugin, streaming); a kept session stays on one account; paces {10, 9.5} spread and {10, 5} don't; three X-Magpie-Sessions in turn get an account each under session affinity, and conversationID never returns X-Magpie-Session. On the old code every pace case went 6 of 6 to k1, and rotate's warm cases 6 of 6 to the next account. Broken by hand: - reorder forced false: every pace case, rotate's warm cases, the group pace cases, the remote and the plugin tests red. - !aff.Kept dropped: TestABurstKeepsAKeptConversation red (map[k1:2 k2:2 k3:2]). - affinityID without X-Magpie-Session: TestMagpieSessionIsTheConversation red (map[k1:3]); the burst tests stay green, as the count covers them. Not tried: real Antigravity accounts, a run on Linux, a real remote magpie on another machine. |
||
|
|
9095fd82d8 |
gateway: a conversation kept for its cache is asked again once on a passing 5xx before it moves (jiabubu)
jiabubu on Discord: a channel that errs once and answers a moment later had the conversation moved off it at the first error, under every rule, and the next one was sent it all uncached. Only the last candidate left (or Strict's lone one) was ever asked again. Now when the conversation is kept where it is (Affinity.Kept: Auto with a warm cache, Session, or within a turn) and that key or account fails in a way that passes (busy: overloaded 503/529, another 5xx that says nothing of quota, 408), and not as a 429, quota, refusal or sign-in, it is asked once more after retryPause (or a Retry-After up to longestPause) without resting. Once per request; failing again it rests and the next is asked as before. A conversation nobody answered yet, or under Stays Off, moves at once (keptAgain in affinity.go). The trace marks the try (Try.Kept) and the Routing page says it was asked again for what its vendor cached, not "nobody else is left to ask", in en, zh, zh-TW, ja and de. TestFixedMemberEffort and TestHeldRuleFailsOverWithinItsMember had a kept member fail with a lasting 500; they now expect it asked once more (kq1 kq1 kq2) before it moves, the outcome unchanged. Run on mote (mote-run): - TestKeptConversationAskedAgainBeforeItMoves (7 cases: Auto, Use before expiry, Session, failing twice, 429, new conversation, Off), TestFixedMemberEffort, TestHeldRuleFailsOverWithinItsMember: ok. - go test -count=1 -timeout 45m ./internal/gateway/: all ok but TestGroupBackupStandingInWhileTheFirstIsBackAndBehind and TestGroupMemberPutFirstOnItsMeritsKeepsItsCache, red with keptAgain switched off too: #5209. - routing-kept-again.test.cjs: 20 of 20 (chromium + webkit, en zh zh-TW ja de, 1100 and 420 wide). - GUI routing-*, group-*, i18n*, gui-* (2967 tests, concurrency 4): 42 red, all in files this doesn't touch; 14 of those files alone: 28 red, and the same files at origin/main |
||
|
|
d5d48f4f9b |
routing: a week at 90% renewing soonest is spent before its reset, not kept for last (ysicing_01858)
ysicing_01858 on Discord (Use before expiry, three accounts): the
account at 90% of its week, renewing today, took few requests, while most
went to one renewing tomorrow. Smart and Use before expiry put every
account at 90% of any window into tier 1 ("kept for last"), behind every
one with room, so what that week had left was lost at its reset.
Now 90% means "kept for last" only for a rate cap: the five hours, or a
window that doesn't say how long it runs (Allowance.CapUsed). An account
at 90% of its week alone (Seat.WeekLow) keeps its place: by its reset
(Smart) or by share left per hour (Use before expiry). 98% of any window
still puts it last. A new conversation kept for its session may go to
such an account (readyForNew). The trace carries weekLow, so the Routing
row doesn't call it "kept for last" and doesn't dim it. Least used first,
In order and the others are unchanged. The Pace description in Settings
says so in every language.
Their later report ("90% 额度账号已经自然重置了 现在的调度机制又默认主要调度到刚重置的
账号了") is not this bug, and this change doesn't alter it. Use before
expiry orders by share left / hours to reset. A fresh week is about
0.6%/h (100/168h), so it goes ahead of any account with less than that
per hour, e.g. 30% left in six days. Conversation affinity and the
fewest-tokens tie-break, for paces within a tenth, keep it there. Smart
is the routing that goes by the soonest reset alone. Their numbers would
tell whether a pace is wrong there.
Run on mote:
- At 49d6ad779, the same tree on
|
||
|
|
b59e4b747f |
gateway: a conversation on a new account leaves out the old one's seals (#3887)
hheei (#3887): a Codex conversation with a web search in it (OpenAI's own web_search, a web_search_call in its history) failed on every turn with "HTTP 400: Codex: Encrypted content could not be decrypted or parsed. (code: invalid_encrypted_content)" once magpie had moved it to another ChatGPT account of the same routing group: after its affinity went cold ("why": "cold", over two hours on), or after the account it was on was used up or rate limited. What an account's turn wrote comes back sealed for that account (encrypted_content): its reasoning, a web search, and with Codex's output token replay on (codex-rs core/src/client.rs: only for a provider named "OpenAI", which Codex signed in reaches magpie as) each message and call. Codex hands it all back on every turn, and between ChatGPT accounts, or a ChatGPT account and an OpenAI API key, magpie sends it as it came (forVendor, |
||
|
|
95d0c97bf9 |
routing: "Use before expiry" counts credits that expire before the reset (lcyksp)
lcyksp on Discord: the 「重置前用完」 strategy (pace) ranked a WorkBuddy
account by its monthly 500 credits ("积分 0 / 500 · 已用 0% · 28 天后重置").
WorkBuddy spends check-in credits first because they expire sooner
("70.85 积分 将于 2026/11/3 09:28:52 过期"), and the account was ranked as
if nothing would be lost for 28 days.
What changed:
- provider.Allowance.Pace takes a budget window's soonest expiry into
account (Limit.RunsOut, from QuotaWindow.RunsOutAt, which the
WorkBuddy plugin and others set on the credits window). When that
expiry comes before the window's reset, the window's pace is the
higher of:
- what is left per hour until the reset;
- the share that expires (QuotaWindow.RunsOut, now carried as
Limit.RunsOutLeft) per hour until it expires. When the amount isn't
told, all that is left counts. A share is capped at 100%, and the
hours at no less than one.
The account whose credits are lost soonest per hour goes first.
Expiry at or after the reset, or already past, changes nothing.
Zero-config: nothing new to set.
- The trace says DueBy "expiry" when the expiry set the deadline. The
Routing page's reason then reads "Use before expiry: {who} has the most
credits expiring per hour until they expire — {n} of its allowance
expires in {d}."
- Label: "Weekly pace" / 重置前用完 / 週ペース / Wochentempo becomes
"Use before expiry" / 到期前用完 (zh, zh-TW) / 期限前に使い切る /
Vor Ablauf aufbrauchen. Product call: the strategy's goal was always
"lose nothing at the deadline". A reset and an expiry are both such a
deadline, and "到期" covers both, where 「重置」 names only one. The id
stays pace, so saved groups are unchanged.
- The descriptions (Routing, Settings, group editor), docs/reference.md,
docs/subsystems/gateway-routing.md and the site's start page (en, zh,
ja) say the same.
Go, run on mote at base
|
||
|
|
c875e66c24 |
gateway: reasoning a Chat, Messages or Gemini client's calls carry, refused by another Responses upstream, is asked again without (#4798)
Since |
||
|
|
0639fdd8f9 |
fix(gateway): a Grok key relay's compaction-blob refusal now strips the sealed reasoning and asks again (#4412)
What changed: foreignReasoning — the words that mark a vendor's refusal of sealed reasoning it cannot read, and put the conversation on the asked-again-without-it path (strip, retry, and the seal left out of later turns up front) — gains one alternative for xAI's "Could not decode the compaction blob. Ensure it is unmodified from the compact response." A key relay that proxies Grok (an opencode-go-style member, no account, any base URL) hands back exactly that for the reasoning item Codex writes with "content": null beside its encrypted_content, and until now the 400 went to the client after a single try: the #3392 shaping (xaiBody's null-content removal) never runs on such a relay because its host is not api.x.ai, and the refusal named no item and nothing of encrypted content, so foreignReasoning passed it by. The wording anchors on "could not decode/decrypt ... compaction blob", so a refusal at fault some other way still is not taken for one. Run: go test ./internal/gateway/ -run 'TestForeignSealGrokRelayCompactionBlob|TestForeignReasoningWords' -tags nogui (both fail on the parent, pass here; the ablation — reverting internal/gateway/affinity.go alone — turns both red again); go test ./internal/gateway/ -tags nogui; gofmt clean on both files; go vet -tags nogui on internal/gateway for darwin, linux and windows; go build -tags nogui for all three. Generated-by: GLM-5.3-Flash (ZCode) |
||
|
|
ec104b8625 |
gateway: a Codex account can spend its credits before magpie moves to another account (jojonas_xyz on X)
jojonas_xyz on X: "我账号额度用完了自动给我切了别的号…找不到怎么关掉设置…你怎么知道 我不是想用 credits 呢". (Roughly: "my account ran out of quota and magpie switched me to another account by itself; I can't find a setting to turn that off; how do you know I didn't want to use the credits?") Cause. At 90% or 98% of a window, smart routing's tier put the account behind every account that still had room, whether or not it had ChatGPT credits. Codex's own sign-in (NextLogin / SwitchWhenSpent) moved at the spent share in the same way. The account's credits were spent only once every other account was used up, and the switch was a log line. The Use credits switches that existed (on, and "Only after other accounts" from |
||
|
|
3af592f587 |
gateway: the overflow memory is read under its lock, so two requests of one conversation don't crash the gateway (#3453)
Review follow-up to ggbdpq's 075aaef62. behindOverflow took the conversation's inner map under overflowLearned's lock, let go, and then read it, while noteOverflow and forgetOverflow write that same map under the lock. Two requests of one conversation at once (a turn beside its title ask, a client's retry) read and wrote one Go map together, which is a fatal "concurrent map read and map write", the whole gateway gone. The loop now runs under the lock. TestOverflowMemoryReadWhileNoted notes and forgets on one goroutine while another orders members by the memory. Before this commit, on mote: go test -tags nogui -race -count=1 -run TestOverflowMemoryReadWhileNoted ./internal/gateway/ -> "--- FAIL: TestOverflowMemoryReadWhileNoted ... race detected during execution of test". With it, -race -count=20 of that test, TestOverflowRefusedOnceIsAskedLast and TestRelayInputCapGoesToTheNextMember: ok. Also: behindOverflow's comment said resting members keep their order; the code moves a refused member behind every other one, resting or not, so the sentence is dropped. gateway-routing.md now describes the memory beside withRoom's overflow paragraph. |
||
|
|
e0a5091b7d |
gateway: a member that refused this conversation as too long is asked last, not first
What changed: an overflow (400, "prompt is too long") is the request's
length, not the account's, so it rests nobody — and left no trace: the
next request of the same conversation tried the member again, failed the
same way, and fell back again, for every request (#3453: a rule sent
every turn to a Claude subscription bridge that answered "Prompt is too
long" and DeepSeek answered; two consecutive requests of one turn each
paid the refused try first). Now the conversation remembers, per
provider's model, how large the request was when it was refused, and the
member is put behind the others — behind, not out: it is still asked
when every other member has failed, a rule that names it is still
heard (ruleOver has run), and what it answers makes magpie forget the
refusal. A request smaller than what was refused — the agent has
compacted the conversation — finds the member where the rule put it.
Another conversation is unaffected, and a byte cap (413) is not
remembered: it is not the conversation too long for the model.
TestRelayInputCapGoesToTheNextMember's second phase shares its server
with the first, whose overflow left this conversation's memory of a's
refusal behind; as that phase says how a plain bad request is classed,
its memory starts empty.
Run: go test -tags nogui -count=1 -run
'TestOverflowRefusedOnceIsAskedLast' ./internal/gateway/ (red on
|
||
|
|
8d8df06399 |
plugin, gateway: a plugin reports its models' load, and busy models can go last (axelburks on Discord)
axelburks (Discord #feedback): an in-house vendor queues requests to
its busy models, and the plugin could only put the load in the model's
name, which changed only when magpie re-read the list.
- A provider plugin calls input.magpie.load(provider, {"<model id>":
0-100 | null}) whenever it likes, from its own timer. host.js
(reportLoad) clamps each number to 0-100, null clears a model, every
other value is dropped, at most 1000 a call, and it returns the count
taken. A provider that isn't a string or loads that isn't an object
throws a TypeError. It goes to Go as an unasked {event:"load"}.
- internal/plugin/load.go keeps each by provider and lowercased model
id. ModelLoad answers unknown once a load is older than LoadFresh
(5 minutes), never idle. model@size falls back to its model.
- The provider editor shows it by the model as a grey ctx badge
("87%", titled "87% busy now, as its plugin says").
- Settings > Network and sharing > Busy models last (settings.BusyLoad,
POST /api/settings/busy-load, Off by default, over 50/70/80/90% or
1-99 by hand): restLast puts a model reported over it behind the
ready candidates, ahead of the resting. The trace row has busy:<load>.
At a new turn affine moves a conversation off it (Why "busy",
busyBehind); within a turn it stays. after, readyForNew and leastHeld
skip it. Unknown load, a lone candidate, or all busy: nothing moves.
- Docs: site plugins page (en, zh, ja) "Model load" section and input
table; docs/subsystems provider-plugins.md and gateway-routing.md.
Run, all on mote via mote-run at a42736807's tree rebased on
origin/main
|
||
|
|
699ddf1524 |
gateway: a Codex account can spend its credits only after every other account, key and fallback (gokoshiki on Discord)
gokoshiki wants a Codex subscription first, then an OpenAI API key, then the subscription's credits. Until now an account at 100% that holds credits either kept its place and spent them there (on) or was held (off). This adds a third way per account, "last": - settings: CodexCreditsLast []string, empty by default, so a setting saved before it keeps its order. provider.CodexCreditsLast, CodexCreditsMode and SetCodexCreditsMode(user, on|last|off); SetCodexCredits(on) still means "in its place" and clears last. - gateway: candidate.creditsLast is true for such an account once a window for the model is used up and it is going on its credits (a call ChatGPT counts in no window stays in its place). restLast orders ready, then resting, then those, and marks Weighed.CreditsLast. restLast runs over the asides too, so such an account goes behind a provider's reserves (Accounts at once, |
||
|
|
2c6b7c0632 |
gateway, provider, gui: Accounts at once keeps the first N accounts taking requests, the others in reserve
01huadalang on Discord (#feedback 1566170404542742740): three ZCode
accounts used at once from one address got the address refused with a
405; two were served. They asked for one account to be used until it
runs out, then the next. Even under "In order", ZCode's maxConcurrency 3
spilled a full lane onto the next account (laneMate) and rests spread
the load, so every account was in use at once.
A provider's MaxAccounts (the editor's Advanced → "Accounts at once",
beside Concurrency; `magpie provider at-once <id> [n|off|default]`) is
how many of its accounts or keys take requests at the same time.
provider.AtOnce() is the user's own value, else what its plugin
declares (maxAccounts on the auth hook or package.json magpie, read by
host.js atOnceOf), else no limit; the user's 0 is no limit over the
plugin's. perKeyBarred keeps the first N in the user's own order
(rank), preferring ones not resting, and keepAtOnce puts the rest after
everything as asides with candidate.reserve (Weighed.Reserve). So in any
routing mode a reserve is asked only once the kept ones failed or rest,
and a kept one that rests gives its seat to the first reserve next time.
Guards: laneMate never spills onto a reserve; a full queue (laneErr)
drops the provider's reserves (dropReserves) and turns the request away
with the 429; session affinity moves a conversation off a reserve once
the kept ones can take it (affine "reserve"; Strict still holds).
Routing says "in reserve · {n} at once" on the row and why in the
request's story. zcode 0.1.40 (plugins 26864ec, on npm) declares 2, and
its mover min is raised to 0.1.40 two commits on.
Known leak, in docs/subsystems/gateway-routing.md: a failure that rests
nobody (a 5xx on one try) still passes that one request to the reserve,
as it does to any next candidate.
Tests: TestAtOnceKeepsFirstInUserOrder (every routing mode, a dragged
order, a resting key handing over its seat), TestAtOnceFullLaneWaitsForTheKept,
TestAtOnceReserveTakesOverAndGivesBack, provider TestAtOnce, plugin
host maxAccounts (hook and package.json), gui TestAtOnceSave, cli
TestAtOnceCmd, provider-at-once.test.cjs (both engines, five languages,
900 and 360px).
Broken by hand, each red then restored: laneMate's reserve guard
removed (FullLane times out); affine's reserve case removed
(ReserveTakesOver answers on k3); keepAtOnce disabled (all three red);
dropReserves disabled (FullLane gets no reply); the Routing row's
reserve branch removed (provider-at-once's Routing test red in all 10
engine/language runs).
Core budget: the field adds ~530 bytes to app.js; the neighbouring
editor comments are cut to fit, so TestCoreScriptBudget passes with no
raise.
Run on mote, Go 1.26.8:
- full suite, -timeout 45m, at a7d4c662d (on origin/main
|
||
|
|
5bfa9f0762 |
gateway: a group's backup gives the conversation back once the member listed ahead of it is ready again (01huadalang on Discord)
01huadalang on Discord, after |
||
|
|
76e4494dbd |
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 on |
||
|
|
ccc791231f |
gateway: a long turn sent to a Chat upstream is copied once, not five times
A 3.2 MB Codex /v1/responses request served by a Chat provider allocated about 70 MB in the gateway, and that garbage, at GOGC 100 over the app's live heap, set the peak footprint. Four copies went: - unquoteJSON built an escaped string (any text with a newline) in a buffer and then copied it into a string; the buffer is the string now (unsafe.String, nothing writes to it again), with a copy only when \u escapes left more than a quarter of it unused. - turnIn joined every user text of the conversation (userSaid) only to see whether any was there; saysAnything stops at the first. - buildChat's user message grew a strings.Builder part by part across a merged turn; joinTexts sizes it once and takes a lone part as it is. - marshalItems ran json.Marshal, whose buffer doubles and is then copied out, over one message that holds the whole turn. marshalSized sizes the maps, lists, strings, bools and ints a body is made of first and writes them into one slice of that size, as encoding/json writes them (HTML escaped, � for bad UTF-8, U+2028/2029); any other value is json.Marshal's own. A []any item, reached by its address, is a *any, which went to json.Marshal twice (to size, then to write) until it was dereferenced; TestMarshalBodyAllocatesTwoBodies caught that at 154 MiB for a 47 MiB body, now 52. Run on mote (M5 Pro), at this tree: - TestLongTurnCopiedFewTimes, a 2.0 MB 300-turn Responses body with CJK and newlines: read 6.72 MB -> 4.76 MB (3.4x -> 2.4x), turnIn 1.93 MB -> 10 KB, buildChat 27.3 MB -> 6.06 MB (13.7x -> 3.0x). Broken by hand one at a time in the mote copy, each red on its own bound: unquote back to string(b) 3.4x; userSaid back in turnIn 1.9 MB; the Builder back 7.4x; json.Marshal back 6.2x. - TestMarshalSizedIsJSONMarshal: byte for byte against json.Marshal over all 256 bytes, bad UTF-8, a lone surrogate, U+2028/2029, HTML characters, keys needing escapes, nil maps and lists, floats, RawMessage, pointers, and a func json.Marshal refuses. - go test -count=1 -timeout 45m ./internal/gateway/: ok (582.9s). - go vet ./internal/gateway/ for darwin, linux and windows; gofmt clean. - Gateway bench (120 requests of a 3.2 MB Responses body, 4 at a time, through a fake Chat provider, 200 MB ballast held live), 3 runs each, old/new: TotalAlloc 8368-8403 MB -> 5889-5891 MB (-30%), GCs 26-27 -> 18-19, phys_footprint_peak 795/806/807 MB -> 763/762/749 MB, CPU 7.89-7.92 s -> 8.01-8.17 s (the size pass costs about what the copies saved). Real use: this build (go build -tags nogui) in a sandbox HOME with the owner's DeepSeek key only, magpie serve on 127.0.0.1:3581. A 180 KB /v1/responses request (a long CJK turn with <tag> & "quotes" \ tabs, a function_call and its output holding U+2028, then a question) to deepseek/deepseek-flash, served through buildChat: answered with both code words as sent (<ZEBRA&42>, MANGO), non-streamed and streamed. Not tried: an Anthropic-in, Chat-out request, and the live app's own peak (the bench stands in for it). |
||
|
|
f63cf0bfc2 |
affinity: a DeepSeek conversation stays on its key past five minutes, as DeepSeek keeps it cached for hours
On X: "Claude code 通过 Magpie 链接 DeepSeek 缓存命中率只有 50% 怎么解决呀".
Measured with a real DeepSeek key, Claude Code 2.1.314 in a sandbox
HOME through a sandbox magpie (usage cache_read / in per request):
- one interactive conversation on one key, Anthropic path: 0% on its
first request (13.7k system + tools), then 90–99% on every turn; the
Chat path (a chat-only provider) the same, 90–99%;
- masking on (redact + personal + local model): 98–99%;
- left idle 7 minutes: 99%, 98%; left idle 26 minutes: 99% (14336 of
14468);
- the misses are Claude Code's own requests: each session's first one,
the title call, an Explore subagent's first (5.6k, 0%), the auto
mode classifier's first (31.7k, 0%, and it misses again when Claude
Code changes its rules in that prompt), and --resume, where Claude
Code drops the thinking blocks from the history (76% on that turn).
A session with auto-mode tool calls and a subagent came to 76%.
Cause in magpie: affinity treated every vendor but the ChatGPT backend
as cold after five minutes (cacheCold). With two or more DeepSeek keys
or accounts (or a group over them), a conversation paused over five
minutes was handed to routing again and could go to another key, which
reads none of it from cache. DeepSeek's kv_cache guide (read 10-31)
says an unused cache is cleared "usually within a few hours to a few
days", and the 7 and 26 minute pauses above read 98–99% back.
Fix: coldAfter gives DeepSeek's own API (api.deepseek.com, Anthropic and
Chat paths alike) an hour, deepseekCold, as chatGPTCold does for Codex.
A group's rules read the same window for keepsEffort. Other vendors,
Anthropic included, keep five minutes. Nothing sent upstream changes.
Run (mote):
- TestDeepSeekConversationStaysPastFiveMinutes and TestDeepSeekColdAfter
red on the old code ("DeepSeek, 6 minutes on: why "cold" kept false";
"DeepSeek's cold is 5m0s"), green with the fix, beside the ChatGPT
cold, effort and affinity tests;
at this tree, rebased on origin/main
|
||
|
|
2f40cf4280 |
gateway: an In order group gives a conversation back to its first member at the next turn
yyhhyyyyyy on Discord made an Opus 5.5 group In order: an API key first,
a Claude subscription second, and 8 of 10 Claude Code requests went to
the subscription. With both healthy the plan is in order and every
request goes to the key. The cause is affinity: one failure of the key
(a 429, a 5xx, a rest) sent a conversation to the subscription, and Auto
affinity's "cache" kept it there at every turn after, since each turn
reads what the last wrote, while the key stood first and ready. A
provider's fallback already gave a conversation back (backToMain, "main");
a group's later member never did.
Now, in a group routed In order with Stays left on Auto, a new turn goes
back to the first ready member when that is another member than the one
that answered last (backToFirst, Affinity.Why "order"). Another key or
account of the same member, or a group in the group, keeps its own
affinity. Within a turn the conversation stays, on the reasoning the
later member sealed, as with "main". Stays: Session and Strict are the
user's own setting and keep it where it is. Smart and the other routings
keep it by its cache as before.
The Routing page says why it moved, for "order" and for a fallback's
"main", which showed no reason at all before (affWhy), in en, zh, zh-TW,
ja and de.
What was run (at the rebased head unless said):
- go test ./internal/gateway -run 'TestOrderedGroupGivesTheConversationBackToItsFirstMember|TestGroupMemberKeepsTheConversationOnceAnotherIsBack|TestFallbackGivesTheConversation|ChatGPTCold|LoginSwitch|LoneAllowance|Affinity' on mote: ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
GOOS=windows go build on mote, before the rebase: all ok.
- GUI in WSL magpie-desktop, Chromium and WebKit, 1100 and 420 wide,
every language: routing-affinity-order, routing-affinity-cache-write and
i18n-keys 44 of 44 before the rebase; routing-affinity-order and
i18n-keys again at the rebased head.
Broken by hand:
- the "order" case turned off (old behaviour): the new Go test fails,
"answered by ssssssssss, want ssskkkkkkk" and why "cache", want "order".
- the Within and Session guards removed: "the key failed once" fails with
skkkkkkkkk, and "Stays: Session" with skkkkkkkkk, want ssssssssss.
- client.js put back: routing-affinity-order 0 of 10 in Chromium
("order: goes in order not in").
Not tried: the reporter's own key and subscription (the subscription is
the test's fake Claude Code); that a failure of the key is what moved the
reporter's sessions is the likeliest cause the code shows, not confirmed
from their trace.
Full suite: go test -tags nogui -timeout 45m ./... on mote at the
pre-rebase head: 80 packages ok, two red. TestRuleTimeWindowAtTurnStart
("a 5 b 2") was this change: its group is In order, so turn 2 of "sess",
after the rule's hours, now goes back to a; the test now asserts that
turn's answerer and counts a 5 b 2. TestNoCommandBypassesProc
(internal/claudetui/child_unix.go:32) is red on main, #4491. At the
rebased head, go test ./internal/gateway -run
'Rule|Affin|Order|Group|Stay|Sticky|Cache|Turn|Fallback|Main|Cold|Login|Lone'
on mote: ok (107s).
|
||
|
|
460687ff57 |
gateway: Azure's "invalid encrypted summary" reads as foreign reasoning (#3994)
What changed: a Codex thread the ChatGPT backend served, resumed on a
relay in front of an Azure OpenAI deployment, is refused there with
{"error":{"message":"invalid encrypted summary",...}} - wording the
foreignReasoning table didn't read, so withoutReasoning was never tried
and the 400 reached Codex on every turn of the thread. The refusal is
spelled with spaces, says summary instead of content, and names no item,
so none of the table's branches took it. An alternative
invalid[ _]encrypted[ _](summary|content) now sits beside
invalid_encrypted_content; the named-item reader (unreadableItem) is
untouched, as this refusal names none, which withoutReasoning already
covers by leaving out the whole reasoning set. The ChatGPT-backend
reader (withoutUnreadable) shares the table and takes the same turn.
Run (base
|
||
|
|
06d36d4142 |
gateway: Stays: Session spreads new sessions over the accounts (connor_yang)
connor_yang on Discord: three sessions on one provider's three accounts,
Stays: Session (整个会话), ended up on two accounts. Under Smart routing a
conversation nobody had answered yet went wherever routing put first,
whatever other sessions were on; only In turn counted the sessions each
account holds (leastHeld, #946).
Kept for the whole session (Stays: Session or Strict) under a routing that
picks by what is left (Smart, Least used first, Weekly pace;
spreadsSessions), a new conversation now goes to the key, account or
group member the fewest other conversations of the last 30 minutes are on.
It passes over one routing keeps new conversations off (readyForNew:
resting, an aside key, a fallback while the provider's own model leads,
one used past lowShare), counts leads only, and keeps routing's order on a
tie. A Claude Code subagent's first request goes to its lead's account
(withLead), not to another as a session of its own. An answered
conversation is kept as before, and resting, spent and the rest/quota
fallback are unchanged. In order, By weight, Free first, Speed first,
Cheapest, Manual and plugin routings keep their order. Docs: reference,
gateway-routing, site start.html (en, zh, ja).
Run (mote, at this head on
|
||
|
|
2c89794acb |
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/main |
||
|
|
b5582912af |
gateway: a conversation on a ChatGPT account stays on it for an hour unread, not five minutes (leelantao)
leelantao on X: two Plus accounts on in magpie lost 90%+ of their
allowance in a day. Affinity let a conversation leave its account after
cacheCold, five minutes, for every vendor. Under Smart the other account
then had more left and went first, so after any pause over five minutes
the next turn went to the other account. That account read none of the
conversation from cache and refused the reasoning the first had sealed.
Each time, the whole context was paid again uncached, on whichever
account was fuller.
Measured on a real ChatGPT account (Pro, gpt-5.6-terra, low effort,
sandbox HOME, Codex 4-turn task): a thread left 7, 12, 25, 45 and 60
minutes still read everything it had sent before from cache (17152 of
21514, 21248 of 21532, 21248 of 21550, 17152 of 17291, 20224 of 20953).
So the ChatGPT backend keeps it at least the hour measured. coldAfter
gives a ChatGPT account (Account.Agent "codex") chatGPTCold, an hour;
every other vendor keeps cacheCold. A group's rules read the same window
for keepsEffort (turnRule.cold, set from the answering candidate in
ruleAnswered), so they don't drop a ChatGPT conversation's effort after
five minutes and lose its cache that way either.
Also measured: the same task direct, through magpie's relay (Codex's
own sign-in) and through the pool path (codex/gpt-5.6-terra). Direct
and relay send 10 requests each, with 166.7k/166.2k input and
154.1k/148.0k cached. The pool path sends 11 requests: 223.1k input,
196.1k cached. Its requests are ~3.5k larger and its first one reads
nothing from cache. usage.jsonl matches the rollouts one for one. No
hidden retries, titles or warmups were sent.
Run, at
|
||
|
|
ff16f6c552 |
gateway: a remote magpie's providers are each a vendor of their own to a conversation (fremontdango)
fremontdango on Discord ran two magpies. On the local one, a routing
group held one model from two providers of the remote magpie
(office/first/m, office/second/m). Its conversations were kept as if the
two were one vendor, because both are the one remote-magpie key here
(candidate.who()). The same group made on the remote behaved
differently:
- strict: when the first provider ran out, the conversation failed over
to the second, though strict means it never moves
- session/auto: with the first gone, the "same account, other model"
match kept the conversation on the second as "session", though nothing
of it was cached there
- the second's refusal of the first's sealed reasoning was recorded
against the whole remote, so the first's own seals were then taken out
of requests to it
- a native compaction one sealed went to the other too
There is now a vendor identity for these: candidate.vendor() and
sameVendor(who, model). Behind a remote magpie it is the key plus the
remote's provider, the model id's first part (remoteUpstream). A remote
group is one vendor by its whole id, and a model named without a
provider is the key alone. It is used by:
- affine's widest match
- strictOnly and strictKeep
- unanswered
- refused/withoutRefused
- checkpointReaders (native compaction)
- Codex leadFirst
Lanes, requests a minute and leastHeld's per-model seat stay on who(),
the limits the user set on the key here. Sticks and compaction writers
are stored as before (who plus model), so the sticks saved on disk still
match after the update. Only the local magpie (the one with the group)
needs this version.
Run:
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok
(559s) at 040a4ec29. After rebasing onto
|
||
|
|
3b717d5e0d |
affinity: a Claude Code subagent's answer no longer moves its lead off its account's cache
Claude Code sends its session's id (x-claude-code-session-id) with every
request of the session, its subagents' too; only x-claude-code-agent-id
says a request is a subagent's. Affinity kept one stick per scope and
session, so a subagent on the lead's model wrote its own answer over the
lead's stick. The lead's next turn was then judged by the subagent's cache
("no-cache" for a small one, "cold" for a 5-minute write past five
minutes) or kept wherever the subagent had gone, and with two Claude
accounts it moved to the other one: a new Claude Code there was told the
whole conversation and Anthropic wrote it all to that account's cache
again, at the 1-hour write price (slkassinthehood on X: two Pro accounts'
5 hours spent in ten minutes, ~318k tokens a request).
stickKey keeps a subagent's stick apart, by its agent id. The lead's key
is the session's, as before: sticks on disk are found after the upgrade,
and Codex's leadFirst, which reads a lead's stick by its thread id, is
unchanged. strictKeep reads the same key.
Run, at this commit's tree (base
|
||
|
|
254461829b |
gateway: a Codex Lite request is no longer decoded whole, nor parsed twice for its facts
XiaoYin_OK on X: after a long run the app's memory climbs toward 2 GB. The owner's own app (26h up) showed RSS 550 MB, HeapInuse 317 MB but HeapSys 992 MB: the heap peaks while requests are in flight. Its profile had 209 GB allocated, ~94 GB of it under codexBackend/serve, of which: - parseResponses 24.7 GB, liftAdditionalTools 14.9 GB of it; - factsOf 24.6 GB, reached from turnOf (13.6 GB) and dirOf (11.0 GB), the same conversation parsed twice per request. Three causes, each fixed where it is: 1. liftAdditionalTools decoded the whole Lite request into maps to move its additional_tools item, and wrote it all again: ~7.6x the body. Now only that item and the tools are decoded; every other item and member goes byte for byte as it came, written once into one buffer. 2. affine counted the turn in the masked body while dirOf read the plain one, two different slices, so factsOf's memo could never serve both. affine now counts it in the body as the agent wrote it. 3. That body is rarely the one readRequestBody held (requestModel, spawnAgentModels and the lift each write a new one), so factsOf's memo missed for it anyway. serve now holds it (holdBody), and holdBody lists a body once when it is held twice. Tests (internal/gateway/lite_lift_test.go), each red on the old code: - TestLiteLiftMovesOnlyTheTools: same result as the old whole decode (liftWhole, kept in the test) on testdata/context/codex.json, the merged-namespace case, a 2,000-word conversation and the no-op shapes; an item with its keys unsorted, \u escapes and 2.50 goes as written. Old: the kept item came back re-sorted and re-escaped. - TestLiteLiftAllocatesAboutTheBody: under 2x a 1.35 MB body. Old: 14,126,976 B (10.4x). - TestMaskedRequestParsedOnceForItsFacts: a served masked Lite request is parsed once for its turn and folder (factsParsed hook in readFacts). Old: 2. With only change 2 it was still 2 (cause 3). Measured (darwin/arm64, a 4,012,240 B Lite body): - liftAdditionalTools: 30.46 MB/op, 98,560 allocs -> 5.17 MB/op, 6,609. - readFacts of it: 54.0 MB/op -> 26.7 MB/op. - Served through New().Handler() with masking on, 8 concurrent x 5 rounds of a 4,010,268 B body, two runs each: allocated per request 215.6 / 220.7 MB -> 116.2 / 116.2 MB; peak HeapInuse 993 / 802 MB -> 612 / 561 MB; HeapSys 1001 / 892 MB -> 699 / 674 MB. - The live app's WebKit processes were ~8-9 MB RSS each, so the webview is not where the memory went on macOS; the live pid sat at 476-596 MB RSS over a 15-minute sample. Run at this head: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; go build (gui and nogui); go test -tags nogui -timeout 45m ./... in a sandbox HOME at |
||
|
|
e57e785633 |
gateway: a rewritten body is written back by marshalJSON, not json.Marshal (#3394)
withReasoningText runs on every replayed request to DeepSeek and the
like (#1104), and wrote the whole body back with json.Marshal twice:
once for the input list, once for the body around it. encoding/json
writes a json.RawMessage through its scanner, a call a byte, so a long
conversation was compacted twice a request. marshalJSON (marshalRaw,
#1532) writes the same bytes, checked by jsonCheck and copied, and
falls back to json.Marshal for any other value; TestMarshalRawIsEncodingJSON
holds the two equal. The same body rewrites in affinity.go,
anthropic.go, codex_backend.go and limit.go took json.Marshal of a
map[string]json.RawMessage too, and use marshalJSON now. Nothing a
body goes out as changes.
Run:
- Real DeepSeek account in a sandbox HOME, magpie serve on 3482, 12
streamed /v1/responses requests of a synthetic 1.5MB conversation with
Codex 0.162.0's real tools and a codex_cli_rs/0.162.1 User-Agent, CPU
time from ps, two rounds each:
|
||
|
|
1859da57bd |
gateway: readers of a rewritten request see its input in place (#3383)
Only the body a request arrived with is held (holdBody), so decodeJSON
shares a raw value with it and copies one from any other body. Once a
route rewrites a Codex request (its model, its fields), the new body is
held by nobody, and each reader that only looks at it copied the whole
input to do so: conversationID, hasSealedAgentMessage,
orphanedToolOutputs, joinToolRuns, pairToolItems, withReasoningText,
and affinity's seal and kind strippers. Each such copy was ~0.4 to
0.5 MB on a 680 KB request.
decodeJSONView is decodeJSON whose raw values always share the bytes
they came from, capped, for a reader that keeps nothing it decodes and
writes none of it. Those readers use it. Each one only reads, or builds
a new body with json.Marshal or marshalPlain (which copy), or returns
the body it was given. promptBuilder keeps raw parts past its return,
and parseResponses keeps its result, so both stay on decodeJSON.
Measured on the 680 KB Codex request benchmark (30x, 3 runs):
16.37 MB/op, 54,703 allocs/op -> 14.96 MB/op, 54,222 allocs/op (-8.6%).
What was run:
- TestDecodeJSONViewShares: q["input"], q["tools"] and an item's
content from decodeJSONView point into the body and are capped, and
decodeJSON still copies from a body that isn't held. With `share ||`
taken out of fillJSONIn it is red ("tools []: not body's own bytes,
capped"); restored, green.
- fjCompare checks decodeJSONView against json.Unmarshal on every seed
as it does decodeJSON.
- Real DeepSeek A/B through a recording proxy in a sandbox HOME, Codex
UA, 5 requests with a tool-call history:
|
||
|
|
d7ad3f2a3e |
gateway: input scanners read a request's items in place, not copied (#3383)
Seven readers of a Responses request's input (the seal stripper and withoutKinds in affinity, hasSealedAgentMessage, joinToolRuns, orphanedToolOutputs, pairToolItems, withReasoningText) and the prompt builder decoded `input` into a []json.RawMessage. fillJSONIn clones each RawMessage under a sixteenth of the held body, so every item of a long Codex history was copied once per reader, per request. None of them keeps an item past its return (they marshal new output or assign into the slice), so inputList hands them elementsOf's capped subslices of the raw input instead. hasSealedAgentMessage reads an item's content the same way. Run at |
||
|
|
41147956d2 |
gateway: a conversation's turn count and folder come from one parse of it, not one each (yg6888 on X: ~1 GB)
turnOf (affinity), dirOf (the trace's folder) and tellWorkPlace (a plugin's work-place headers) each parsed the whole conversation for a number and a folder. A parse decodes every message and tool output into strings of its own, so a long conversation was decoded twice over on every request for them. In the 60-min soak before ( |
||
|
|
a1118187b5 |
gateway: who answered a conversation is written to affinity.json behind the answer, once in a while, not on every answer
answered() (and unanswered()) called saveSticks on every request answered: up to 512 conversations sorted, marshalled, written to a temp file and renamed, one answer after another under sticksSaving. Now the stick is in memory at once (stickOf reads the map first) and the file follows within sticksFlushAfter (2s): what is answered meanwhile goes in one write. The gateway's drain (ListenAndServe) and magpie ending on a signal (cli/signals.go, beside FlushServed) write what is waiting, so a restart or the magpie handed over to reads every answer. A crash loses the last 2s, as served.json does since 4f9e8331a. In a test binary the wait is 0 and the file is written at once, as it was (no timer outlives a test; 8215e8275 did the same for served.json). A write waiting for another HOME's file (a test's) is dropped, not written into this one. Test: TestSticksWrittenBehind (2s set by the test): 200 answers write no file, the last is known in memory, flushSticks writes all 200, and a short wait writes by itself. Broken by hand (noteSticks calling saveSticks always): red, "affinity.json written on a request answered". BenchmarkAnswered (512 sticks kept, 200x, 2 runs; load average ~450): old (saveSticks inline) 21.3 / 25.0 ms/op 506KB/op 2140 allocs/op new 2.5 / 5.6 us/op 392-434B/op 8 allocs/op Run: go test ./internal/gateway -run '^TestSticksWrittenBehind$' -count 1: ok. go test ./internal/gateway -run 'TestSticksWrittenBehind|Affinity| Sealed|Stick|Strict' -count 1: ok (57.8s). |
||
|
|
ef49011448 |
gateway: Stays: Auto keeps a conversation on Claude's 1-hour cache for the hour, not 5 minutes (#2302, j3r0lin)
affine called a conversation "cold" once its last reply was more than
cacheCold (5 minutes) ago, whatever the reply said of its cache. A Claude
reply that wrote with cache_control ttl "1h" (cache_creation's
ephemeral_1h_input_tokens, already parsed into Usage.CacheWrite1h; Claude
Code asks for it on a subscription) keeps that prefix for an hour, so the
next turn 5-60 minutes on lost its priority and could move to another
account or model that has none of the cache.
answered now keeps an hourCache on the stick: the tokens read plus the
1-hour write (Anthropic puts 1-hour breakpoints before any 5-minute one,
so what was read lies inside that prefix), and when. A later reply on the
same account and model that reads at least all of it starts the hour
again; one that reads less (moved, compacted) drops it. affine's "cold"
now needs both past 5 minutes and no warm hourCache (>= cacheWorth tokens,
within cacheHour). It is saved in affinity.json (cacheHour, cacheHourAt;
absent in older files, read as none). Sibling: keepsEffort, which lets a
group's effort drop only once the cache is lost, used the same 5 minutes;
turnRule now carries the same hourCache from ruleAnswered.
Vendors that report no 1-hour write never have an hourCache, so their
behaviour is unchanged; resting, spent, strict and the other reasons are
judged before this as before.
Tests: TestAffinityKeepsAnHourCachePastFiveMinutes (real server stack, an
Anthropic upstream reporting cache_creation: 1h write at 20 min -> cache,
at 59 min across a restart -> cache, at 61 min -> cold, 5-minute write at
6 min -> cold, a 1h write under cacheWorth -> cold), TestHourCacheAfter,
and two TestKeepsEffort cases. With affine's and keepsEffort's old
conditions put back, both fail ("an hour's write, 20 minutes on: ...
Why:cold, want cache"; "an hour's cache: warm at 20 minutes: false, want
true"); with the file's cacheHour left unread, the restart case fails.
Real data: the owner's usage.jsonl has 166 Claude subscription replies
with cache_write_1h > 0, e.g. cache_read 57901 + cache_write_1h 336, the
shape hourCache takes. Not tried live past 5 minutes against Anthropic.
Ran: gofmt -l, go vet -tags nogui for darwin/linux/windows on
internal/gateway, go test -tags nogui ./internal/gateway (full package).
Full suite: SUITE_LINE
|
||
|
|
7c5bfd7a1d |
gateway: auto affinity keeps a conversation where a vendor's cache is kept without saying so (#2230, JasonBuildAI)
A vendor that keeps the prompt cached by itself and reports nothing of it —
OpenAI's automatic prefix cache, Gemini — says neither a read nor a write of
the turn that built the cache. affine judged that turn's stick by what the
reply read and wrote (0 + 0), found it under cacheWorth and moved the
conversation's second turn as "no-cache": the whole prompt went afresh to
another key or account and was paid for in full, on every turn after the
first, for anyone with more than one key or account and Affinity auto (the
default).
7f968b95b named this as not covered: "a vendor that caches without reporting
a write (OpenAI's automatic prefix cache, Gemini) still reports CacheWrite 0
on a first turn, so its second turn may still move".
What such a vendor holds of the conversation after a turn is the prompt that
turn was sent, which is what its cache now has. answered takes the reply's
usage rather than its two cache counts, and where the reply reports neither
a read nor a write, the prompt it was sent (Input) stands for the write: the
second turn stays to read it, as it does for a turn that wrote its cache. A
reply that reports no usage at all (Input 0) counts as no cache, as before,
and a prompt under cacheWorth (1024) still moves. A read or a write the
vendor does report is used as it was, and resting, spent, cold, strict, turn
and rotate are judged before this, so nothing else changes.
The observable change: with Affinity auto, a conversation whose last reply
reported neither a cache read nor a cache write, and was sent at least 1024
tokens, is kept where it was (Why "cache", Kept true) rather than moved
(Why "no-cache"). Its stick, affinity.json and the trace's
Affinity.CacheWrite carry the prompt sent, and Affinity.CacheRead stays 0,
which is what the Routing page shows as read and written; the page itself is
unchanged.
Tests:
- affinity_silent_cache_test.go (new): TestAffinityKeepsACacheTheVendorKept
Silently. Two keys, least-used routing, and a Chat vendor reporting
prompt_tokens 3000 with cached_tokens 0 — what OpenAI and Gemini send of a
first turn — keeps the second turn on k1 as "cache", with the trace
telling CacheRead 0 and CacheWrite 3000; a vendor reporting no usage at
all still moves to k2 as "no-cache".
- TestAffinityKeepsACacheJustWritten, its "too little either way" (300/300,
no-cache) case included, passes as it did.
Run:
- go test -tags nogui -count=1 -run TestAffinity ./internal/gateway: ok,
80.982s (TestAffinity 39.36s, TestAffinityKeepsACacheJustWritten 26.54s,
TestAffinityKeepsACacheTheVendorKeptSilently 9.68s).
- go test -tags nogui -count=1 -timeout 45m ./...: every package passes
except 21 tests red on this Windows machine — agent 4
(TestInstallWithoutNodeParses, TestWSLClaudeFollowerOnTheMainModelIsNoDrift,
TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
TestQoderSettingsFromAnIDEPluginIsNotTheCLI), gui 4
(TestGatewayHeldByAContainer, TestGatewayFixQuitsOnlyAMagpie,
TestFXStateDoesNotWait, TestUpdateThatWontStart), library 3
(TestAgentsSkillsFolders, TestRemoveFoundSkill,
TestHooksCodexTrustMovesWithTheGroups), gateway 2 (TestClaudeAsRootEnv,
TestSweepBridgeProjectsTakesOnlyTheBridgesFolders) and one each in backup,
davsync, pluginrt, provider, sessions, update and usage. A fresh worktree
at the base
|
||
|
|
7f968b95dd |
gateway: auto affinity keeps a conversation on the cache its last reply wrote, not only one it read (vilicvane on Discord)
Affinity's auto mode kept a conversation on its last answerer across turns only while that reply had read at least cacheWorth (1024) tokens from the vendor's cache. A first turn reads nothing and writes the whole prompt (Anthropic's cache_creation_input_tokens), so the second turn was moved as "no-cache" and the cache just built was thrown away (vilicvane on Discord, 「会话保持 → 自动」: 「新的 cache 都建好了,再切走不可惜吗?」). answered() is now given the usage's CacheWrite beside CacheRead (both already parsed at that call site for every route: Anthropic, Chat's cache_write_tokens / cache_creation_input_tokens, Cursor, Command Code, plugins), and affine counts read + written against cacheWorth. The stick keeps cacheWrite in memory and in affinity.json (`cacheWrite`, omitempty); a file from before has no such field and reads as 0, so an old stick is judged by its read alone, as before. The trace's Affinity carries CacheWrite, and the Routing page's "cache" and "no-cache" explanations say what was read and what was written (en, zh, zh-TW, ja, de). Not covered: a vendor that caches without reporting a write (OpenAI's automatic prefix cache, Gemini) still reports CacheWrite 0 on a first turn, so its second turn may still move. Noted in gateway-routing.md. Docs: docs/subsystems/gateway-routing.md (affinity bullet), docs/reference.md (step 6 of how magpie picks an account). Run: - TestAffinityKeepsACacheJustWritten (new): an Anthropic Messages upstream streaming cache_creation_input_tokens 3000 / read 0; the second turn is kept as "cache", also across a restart (affinity.json reloaded); 600+600 is kept, 300+300 moves as "no-cache". Broken by hand twice and watched red: the old `st.cacheRead < cacheWorth` (written: why no-cache), and stickOf not reading CacheWrite from the file (restarted: no-cache). - routing-affinity-cache-write.test.cjs (new): chromium and webkit, 1100 and 420 wide, en/zh/zh-TW/ja/de, 20/20 pass; red on the old routing.js and i18n.js. i18n-keys.test.cjs and routing-account-identity.test.cjs pass. - gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows for internal/gateway. - go test ./internal/gateway/...: all pass except TestAgentGoneInTheRetryPause/group_replan, which failed in two full runs at load average 150-380 and passes alone (-count=3); its fixed 100ms sleep before cancelling assumes the pause has begun. Filed as #2175; it never reaches the affinity path this changes (a first request). - go test -timeout 40m ./... at load ~300-377: 50 packages ok; agent and gateway hit the 40m package timeout (no test failed before it); gui's TestSetAnswersWhileDevinAndProvidersHang (#1375) and TestMainWindowCorners (#1936) failed, both filed load reds. internal/agent rerun alone: ok (1008s at load ~200). - Not tried against a real Anthropic account. |
||
|
|
a1c30b5be9 |
gateway: a user message the agent wrote alone is no new turn, and routing asks about and keys on the user's own words (#1826)
What: one helper, userWords/userSaid in prompt.go, says what the user
said in a text: it drops <system-reminder …> blocks (now with a source=
attribute too, as ZCode sends) and any text that begins as an agent
writes for the model alone, and keeps only what follows the Codex app's
"## My request (for Codex):". The leads, beside agentsFor: Codex's
<environment_context>, <user_instructions>, <turn_aborted>,
<user_shell_command>, <subagent_notification>; Claude Code's and
ZCode's <task-notification>, <subagent-notification>, agent lists
("Available agent types …", "New agent types are now available …"),
TodoWrite and task-tool nudges, rewind notices; ZCode's
<plugin_reference>; the Codex app's <in-app-browser-context …>. Each
was taken from the clients' own code or a real transcript (Claude Code
2.1.296, ZCode.app's zcode.cjs, Codex CLI 0.162.1, ChatGPT.app).
Everything that asks "did the user say something" now goes by it:
- turnIn: a user message with nothing of the user's (and no image or
file) begins no turn. After an answer or a tool round it carries the
turn on (within), so the turn's rule and stick hold and the classifier
isn't asked; right after the user's own message it leaves that turn as
it began.
- userText: the classifier is asked about the last user message with
words of the user's, only those words (it was the last user message,
ZCode's agent list after the user's plugin question).
- firstWords (ruleKey and the affinity scope): the words of the first
user message that has any, so an instruction file or notice the agent
changes beside them no longer moves a conversation to a new key
mid-turn. A conversation with no words yet keys on its first message
as before.
- lastUserText (Copilot's Auto, a sibling): the same.
- userSays (the prompt breakdown's turns) is userWords != "".
Why: #1826 (ZCode) and @321sssrt-bit's comment (Codex): a TodoWrite
nudge was classified as a new, harder turn and sent a 常规 turn to the
复杂 member; a task notification or agent list re-classified the turn;
one ZCode session had three firstWords keys, and the turn that lost its
key fell to the group's first member.
Upgrade: a conversation whose first user message held injected text
gets a new key once (its words only), so its stick and turn rule are
looked up afresh on the first request after the upgrade.
Run: user_said_test.go (TestTurnInSkipsWhatTheAgentPutIn,
TestUserTextSkipsWhatTheAgentPutIn, TestFirstWordsAreWhatTheUserSaid,
TestLastUserTextSkipsWhatTheAgentPutIn,
TestIntentHoldsPastWhatTheAgentPutIn end to end through the server,
TestUserSaysPastAReminderWithASource) fails on the old code (all six
red with the five source files put back) and passes now; go test
./internal/gateway -count=1 green (323s); gofmt -l clean; go vet ./...
on darwin, GOOS=linux -tags nogui and GOOS=windows clean.
Not tried: a live ZCode, Claude Code or Codex session against a
group with intent rules; fixtures are the clients' literal strings.
Not done here: persisting turnRules beside the sticks (the issue's
idea 3); the classifier-failure fallback is the next commit.
|
||
|
|
908c910931 |
gateway, gui: Stays: Strict keeps a conversation on the account or key that answered it, even past its cap, and passes its error on rather than moving it (#1797)
miniers asked that a conversation never move to another account: a
move changes the account a vendor sees mid-conversation and loses its
prompt cache. Session affinity keeps the account while it can answer,
then moves on.
The new affinity mode "strict" (Stays: Strict) does what session does
for a new conversation. Once one has an account, strictKeep asks that
account alone (its other models too) and no other account, key or
provider:
- one resting or spent is still asked, and its error (429, 402, 5xx)
goes to the agent rather than to the next candidate;
- one over a user cap is asked past it (plan's capped candidates,
capHeldOnly);
- one held for credits answers 429 naming Stays: Strict rather than
moving;
- one removed, turned off, barred or not allowed for the key counts as
gone, and the conversation is routed as usual.
A last try that fails verification is not rested for a strict
conversation that had nowhere else to go.
Set in the provider editor and the Routing page's pool row (GUI, all
five languages), `magpie groups ... stays=strict` (strict-session,
never-move), and the TUI ("stays strictly"). Documented in
gateway-routing.md, reference.md and the site's start pages (en, zh,
ja).
Run:
- go test -tags nogui ./internal/gateway (-timeout 30m under load ~150),
./internal/provider ./internal/tui ./internal/cli: ok. The three
TestStrictAffinity* tests fail on the code before this commit (200
where 429 was expected, acct-2 answering).
- GUI: stays-strict.test.cjs, chromium and webkit, 900 and 560px, en,
zh, zh-TW, ja, de: 30 of 30. On the assets before this commit it
fails 15 of 15 in chromium. routing-*.test.cjs pass but for
routing-steady's webkit 1.69px shift, which fails on the old assets
too: filed as #1804.
- gofmt -l, go vet (darwin, linux, windows), full go test ./... before
the push.
Not tried: a real agent conversation held on a real rate-limited
account.
Known and left: planLevel doesn't merge a nested group's sub.held, as
before this commit.
|
||
|
|
5feadabef6 |
gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.
decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.
Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:
CPU in the request's handler time per request
(pprof, per request) (ns/op)
anthropic 154ms -> 45ms 208-212ms -> 52ms
anthropic, group 178ms -> 51ms 249-262ms -> 65-67ms
chat 122ms -> 35ms 167-254ms -> 50-54ms
responses 215ms -> 56ms 294-452ms -> 70ms
TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).
Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
Responses; direct, through a group, translated to each other protocol,
with images, thinking, escapes, odd spacing, a repeated key, and four
2 MB conversations) and compares what the vendor gets with
testdata/upstream_bodies, recorded on the code before this change
(all 18 identical; three runs agreed). Breaking decodeJSON's \n
unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
the gateway's, and jsonValid with json.Valid, over seeds, every cut
and a changed byte at every place of each seed, and 2.5 minutes of
fuzzing (~1.75M inputs). Breaking the validator's control-byte check
by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
origin/main
|
||
|
|
35eea09464 |
gateway: a provider routed its own way keeps that order inside a group that routes another way (kchen0x on X)
kchen0x had a Smart routing group with Antigravity (9 accounts, set to 按顺序) and a Business account. Requests still went to the 9th account, the one renewing soonest. planLevel pooled every member's keys and accounts into one list for any group not routed in order, so the provider's own routing was never read; Smart then put the soonest renewal first. Now a member whose provider routes other than Smart, and other than the group does (ownRouting), is planned as a nested group already is: a unit weighed by the first account or key it would try (firstAwake), then tried whole in its own order. A provider left on Smart is pooled as before. leastHeld, which reorders a rotate group's first request, leaves such a group alone as it does one holding a nested group (without that, a rotate group still came back "k2 k1 k3 kb"). GUI hint (GROUP_NEST, 4 languages), start docs (en, zh, ja) and gateway-routing.md say so. Run: - TestProviderKeepsItsOwnRoutingInAGroup covers outer Smart, rotate, usage, pace and manual, plus a Smart provider still being pooled. On the old planLevel it fails with "k3 k2 k1 kb" (the reported order). - go test -tags nogui -count=1 -timeout 40m ./...: all ok. - gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/gateway. - GUI: i18n-keys, gui-ja/de/zh-tw and every *group*/*routing* test, both engines: 765 pass. A first run beside the full go test had 9 webkit timing reds (routing-group-fold, routing-keys-fold, routing-ctx-still, gateway-key-groups); each file passes alone, and the whole set passes when nothing else runs. |
||
|
|
0d20aaba45 |
gateway: under In turn routing, new conversations sent at once spread over the accounts instead of all going to the one least held, which held one Antigravity account busy while the others sat idle (#1342, handong66)
leastHeld counted only conversations already answered, so every new
conversation in a burst saw the same counts and picked the same account.
A conversation that is opening now counts until it is answered or its
request ends.
Run: go test -tags nogui ./internal/gateway (ok); -race -count=5 on the
rotate/affinity tests (ok); go vet darwin, linux, windows (ok).
TestRotateSpreadsABurstOfNewConversations fails without the fix
("k1 got none of 6 new conversations sent at once ...: map[k2:4 k3:2]",
3 of 3 runs).
Not tried: a real burst on Antigravity accounts. The default (smart)
routing keeps using the first account while it has quota, by design.
|
||
|
|
555f570660 | gateway, provider: the Routing page says what a lone key or account has left, and a key bought as a plan (Kimi Code, GLM Coding Plan, MiniMax, OpenCode Go, Command Code) is weighed by its plan's windows (#1016, gphysign: Kimi Code (China) with one key on, Smart routing; the card said only "Kimi Code (China) 只启用了一个 Key,无需选择。" while /v1/magpie/quotas had its 5 hours 49 used, 51 left and its 7 days 45 used) — two gaps. weighRouted returned before reading anyone's allowance when there was one candidate, so a lone key or a lone subscription account was never known in the trace, and the Routing page, which shows a bar and "{n} used · renews in {d}" for a known row, had nothing to show; every single-account subscription said "what's left not known yet" the same way. And KeyAllowance read only a sub2api key's limits, so a key whose plan the Usage page reads (planQuotaSourceOf: Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code) was never known to routing, with one key or several. weighRouted now reads what each candidate has left before returning a lone one (one alone is still weighed against nobody). readsKeyWindows takes a plan key too; keyWindows reads it through planKeyWindows (planWindows, with Zhipu's team quota behind a key that has none of its own, as PlanQuotas does), and PlanQuotas' own read of a card is noted for routing at once (noteKeyAllowance), so the Usage page and routing never ask twice; the card kept on disk seeds it after a restart (keyCardTag keys a plan card as plan:, a sub2api one as balance:). A key at such a vendor that turns out to be pay-as-you-go, with no windows, is asked again every 30 minutes (keyNoWindowsAge), not every minute it is used. So, beyond the issue: several plan keys on one provider are now weighed by their windows under Smart, usage and pace, and a plan key the vendor refuses as out of quota rests until its window renews and comes back once read short of full, as a sub2api key does. affine no longer says a lone key or account all but used up "moved" its conversation: there is nobody to move to (at > 0). The GUI needed no change. TestLoneOneTellsWhatItHasLeft (a lone Kimi key known at 49% with both renews, the week first; a lone Codex account known; a plain DeepSeek key not), TestLoneSpentKeyKeepsItsConversation (fails with the at > 0 guard taken out), TestPlanKeyAllowance (the windows read behind the request, asked once; DeepSeek and Moonshot keys never asked), TestPlanKeyAllowanceFromItsCard (PlanQuotas' read known at once without a second ask; after a restart with the vendor down, the card on disk stands in and a failed read keeps it) and TestPayAsYouGoKeyAskedSeldom (a GLM pay-as-you-go key asked once, not two minutes on, again 31 minutes on) all fail without the change and pass -race -count=20 (provider) / -count=10 (gateway). routing-key-windows.test.cjs gains a lone Kimi Code key at 1100px and 440px (the one-key story, the row's bar at 49%, its provider row "49% used · renews in …" fitting, no sideways scroll) and passes in full on Chromium and WebKit in en, zh, ja and de; routing-quota-left and panel-routing pass. go test -tags nogui ./internal/..., go test -race on ./internal/provider and ./internal/gateway in full, go vet, gofmt -l, darwin, linux and windows (nogui) builds pass. Not tried with a real Kimi Code key. StepFun's Step Plan is read through a sign-in, not the key, so it isn't one of these. docs/subsystems/gateway-routing.md, providers-accounts.md and docs/reference.md say it. | ||
|
|
aab93f9fa8 | gateway: in turn, a new conversation goes to the model or account the fewest live conversations are on, so two sessions of one routing group kept for the session no longer share a model (#946, Moody-Sin) — in turn counts requests, not conversations, so a second session started after the first had sent an even number of requests went to the model the first was kept on. leastHeld counts the conversations of the scope answered in the last 30 minutes per key/account and model and puts the least held first; ties, resting ones and a group with a group in it keep routing's order. TestRotateSpreadsSessions is new and fails (after 2 and 4 requests) without the change. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows), the gateway package and go test -race -count=20 of TestRotateSpreadsSessions/TestAffinity pass; go test -tags nogui ./... under a temp HOME failed only TestWSLProbeFindsBunOmp, TestProvidersAnswerWhileListsComeIn, TestUserPath and TestClaudeSignedOut under the full run's load, each passing on its own. | ||
|
|
3ec6b4da27 | gateway, gui: a provider's keys can be routed by weight, a key weighing 3 taking three requests for every one a key weighing 1 takes (dengtongcai, #841) — Routing already spread requests over a provider's keys in order, in turn, least used first or by pace, but never in a set proportion: two team keys meant to split 75/25 could only go evenly or one after the other. Routing now has By weight (routing "weight") for a provider with keys: each key that's on shows its weight and its share beside it in the editor (Weight 3 · 75%), a click edits it in place and posts keys/weight (provider.SetKeyWeight, 1 to 1000; none or 0 counts as 1, kept out of the file), and providers.json takes it as "weight" on each of keys (keyWeight for the first). The gateway picks as NGINX's smooth weighted round robin does (weighted.go): 3, 1 and 4 go round in every 8 requests in that ratio, never bunched; the others follow in their order for failover. A key resting after a failure is left out of the round while it rests, the others taking its share by their weights, and goes last. A conversation still stays with its key as Stays says (cache-warm across turns by default, within a turn always), and a request kept so is counted against the key that took it, not the one the round picked, so new conversations make up the share; Stays Off gives the ratio request by request. The weight goes with its key through Make first, the editor's Save, backups and WebDAV sync. The Routing page offers By weight for key pools and explains a pick by it; sink (Goes to the back) is off for it as for In turn. zh, ja, de strings. TestWeightedKeys (3:1:4 exact in each of 50 rounds of 8 through perKey and route; with one resting the other two 75/25 and the resting one last; a kept request made up by the next picks) and TestSetKeyWeight fail on the old code (no Weighted); key-weight.test.cjs (WebKit, en and zh: By weight shows the weights and shares, a click sets one and the shares redraw, Smart hides them, no scroll) fails on the old code (no By weight). key-import, panel-routing, routing-save, rate-limited-sink, routing-reset-deadline, account-arrange, gui-ja, gui-de and click-scroll pass on WebKit. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. | ||
|
|
dd4801e92a |
fix(gateway): forget a broken-off reply's stick by the account alone (#776)
affine keeps a conversation on the account that answered it three ways: the account and the model, the account and the model without its effort, and the account alone — "the account alone when the model is gone", for a group whose answerer's model has since left it. unanswered, which takes the stick away when that reply breaks off (#733), asked for the model to match as well. So a conversation kept on an account by the widest match — the model it answered as has left the group — kept its stick when the reply broke off with nothing resting it (a refusal, a request too long for the model), and the agent's retry, which routing would have sent elsewhere, went straight back to the account whose reply had just broken off. The same stick a rest would have protected was left standing with no rest at all. unanswered forgets a stick whose account matches, whatever model it answered as: the stick is one record of "this conversation stays with this account", and a reply that broke off books nothing. A stick of another account, or another conversation's, is left alone. TestUnansweredForgetsTheAccountWhenItsModelIsGone fails on the old rule ("the conversation is still kept on the account whose model has left the group") and passes: a stick kept by the account alone is forgotten when the model that answered is gone from the group, and another account's stick and another conversation's are not. TestLateStreamErrorNotKept, TestAffinity and the rest of the gateway's affinity tests pass unchanged. Validation on Windows: go test ./internal/gateway ./internal/provider under a temp HOME — the gateway package's failures are the Unix-only ones the base commit leaves there (TestSweepBridgeProjectsTakesOnlyThe BridgesFolders); go vet ./internal/..., the darwin, GOOS=linux and GOOS=windows builds pass. |
||
|
|
7cfb6d35e7 | gateway: a reply that breaks off after it began isn't booked as an answer, and the conversation's retry goes to another member (#733, congee949 on v0.1.801: Codex on group/grok4-7 got Cursor's "Unable to reach the model provider" eleven times in a row, each retry kept on Cursor by the turn's affinity, last:cursor kept:true why:turn, while the group's Grok member was fine) — after hw.release() the call.Status < 400 branch took any try whose status was under 400 for an answer, and a stream that has sent its 200 and some text and then fails comes back from translate/relay as 200 with call.Error set: servedCandidate ended the member's rest and its failure count, answered() remembered it as the conversation's answerer, and ruleAnswered booked it for the rule, so the agent's retry went straight back to the member that had just failed. Such a try (status under 400, error set) now books none of that: unanswered() forgets the conversation's stick when it names that account and model (and rewrites affinity.json), and when the error reads as the vendor failing, not a conversation too long for the model (tooLong) or a request it refuses as it reads (refusedWords) — lateRests — and the agent hasn't gone, the member rests as restAfter says for the error at that status (a minute's cooldown, longer each time it fails again; out of credit or quota as those read), so the next request in the conversation goes to another member first; a group of one still asks it, at the back. A reply the agent stopped itself (its request context ended) is booked as before, its stick kept. The partial stream stays as it was, its error event included: nothing is spliced in or replayed. The trace's try keeps status 200 and its error, and gains a Fail (the rest's why) and the Rest; the Routing page reads a try with status under 400 and a fail as broken off (tryOk), not answered: its line says it began answering and broke off, and how long it rests, with the vendor's words below it (zh strings), the row and the member's tally count it as failed, and its rest isn't taken for lifted. Usage is kept as it was, error included, as the tokens were spent; the trace's Served/Swapped/Routed still name the model that began the reply. TestLateStreamErrorNotKept (a group of two, the first member streams text then an error with status 200, for a Chat and a Responses client; the same conversation's next request must go to the second, with no stick left and the try told as failed and resting) fails on the old code (tried broken,broken; no Fail, no Rest) and passes. go vet ./internal/..., builds (darwin nogui, GOOS=windows, GOOS=linux nogui) and go test -tags nogui -count=1 ./internal/gateway/ ./internal/provider/ under a temp HOME pass; node --check on routing.js and i18n.js, the Playwright GUI tests not run (no playwright in the worktree). Not tried with the reporter's Cursor plugin; why Cursor's backend broke off is not known. | ||
|
|
817a5f50d5 | routing: In order keeps sending to the first account until it is used up or refused, and a tick keeps Codex or Claude Code signed in to the first account (#530: an account In order at 98% of its week, its five hours untouched, stopped getting requests; #524: "不允许切换首选账号的登录状态", the agent's own sign-in must stay on the account made first while the gateway still spreads requests) — since #209 magpie signs Codex and Claude Code in to the next ticked account with room once the one they are on reaches 98% (provider.SpentShare, the share Smart counts an account spent at), and since #408 back once the first is under 90%. The account the agent is signed in to is the one every routing tries first (the others stand behind it, AlsoOn), so In order the 98% switch put the second account ahead of the first, which is what #530 saw as the first being dropped; and the gateway counted an account at 98% as full whatever the routing, so a passing failure on it (a 502) rested it until its week renewed (39 hours there), not for the usual backoff. Now SpentShareOf gives 100 In order and 98 otherwise: the login switch moves the agent off an account In order only once a window of it is used up, the gateway's full (the rest after a failure, the quota rest's window) and affinity's "spent" go by the same share, and a vendor's 429 or usage-limit refusal still rests the account until it says it's back, as Smart does; a window used up is out, as before. Smart, In turn and Least used are unchanged. For #524, the subscription keeps KeepLogin (providers.json, beside Routing, kept across an editor Save; POST provider/keeplogin, only for Codex and Claude Code): with it on, magpie never moves the agent off the account it is signed in to, however used up, while the gateway still routes requests through magpie to the other ticked accounts; a pending return to the first (#408) still happens, that being the first. The tick sits at the foot of the Accounts list, under the rows where Make first is, shown only for Codex and Claude Code with more than one account on: "Keep {agent} signed in to the first account" / "{agent} 始终登录首选账号", its tooltip saying requests through magpie still go to the other ticked accounts. The Routing note follows it: kept, it says the agent stays signed in to the first whatever it has left; In order, that magpie moves it on once it is used up; otherwise the 98% wording as before. TestCodexLoginOrderedAndKept (In order stays at 98% and moves at 100%, back once renewed; Smart moves at 98%; kept, it stays at 100% and the setting survives a SetRouting; let go, it moves) and TestOrderedKeepsAnAccountAt98 (In order an account at 98% isn't full and a 502 rests it by backoff, Smart rests it to its week, a refusal rests it either way) fail without the change. keep-login.test.cjs (en and zh, Chromium and WebKit: the tick, its tooltip and Chinese strings, the post, the note when kept and In order, no tick with one account, the page doesn't move) fails without the UI and passes with it (12/12, Playwright 1.61); account-return, routing-account-order and account-arrange pass; click-scroll fails in Chromium here on origin/main too and passes in WebKit. No request was made to any vendor and no live agent config was touched. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestClaudeRunEndsWhenTheClientLeaves, TestClaudeAccountNamedAsItsLogin and TestClaudeIdentityServedWhileAsked failed once under the full run and pass alone). Turned on after magpie has moved the agent off the first, it goes back to it at once rather than once that has room again. | ||
|
|
f45e9737b3 | gateway: a conversation stays with the account that answered it across a restart of magpie, and routing goes by each account's last known allowance until the first reading since the start is back (vincentzhang on Discord: in smart routing a restart moved a session to the first account, an update and restart back to the second, and the prompt cache was read by neither) — who answered a conversation last was kept in memory only, so after a restart every conversation was "first" and went to whoever routing put first; and until the accounts' allowances were read again (a first wait of 3s, the read itself up to 30s) none was known, every account counted as unused and the first in order went first, until the reading came back and put the one renewing soonest first again. Who answered is now also kept in affinity.json next to the providers (0600, written atomically, the latest 512 conversations, none older than the 24h a conversation is remembered), read again when a conversation isn't known here and the file changed — after a restart, or written by the magpie handing over. The rules for when a conversation moves are unchanged: within a turn it stays, across turns while the vendor read enough from its cache within the last five minutes, and never to an account resting, all but used up or gone. While the first reading is out, Allowances returns each account's last reading kept in quotas.json, its windows past their reset counted empty. Prompts and headers are unchanged. TestAffinitySurvivesRestart and TestAllowancesBeforeFirstReading fail without the change; TestAffinityFileBounded keeps the file bounded. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestFetchNewLeavesListedPlugins and TestFXInState flake under load on main too, pass alone). | ||
|
|
e0e93c2ec5 |
gateway: a Codex conversation compacted on GPT goes on after switching to Grok (waroy on Discord: Grok (SuperGrok): Could not decrypt the provided encrypted_content) — when Codex compacts on OpenAI's own models, the earlier turns become a compaction item sealed by OpenAI (encrypted_content), which magpie kept for magpie models. Grok can't read it, any more than another vendor's reasoning. The retry after such a refusal (2476cd5) left out only the sealed reasoning and asked once, so Grok refused the compaction too and Codex got xAI's error. It now asks again without the compaction when the refusal comes back (or there was no reasoning to leave out), and remembers the compaction with the reasoning as refused for that conversation and account, so later turns leave both out up front while Grok's own reasoning goes along; each step remembers only what it took out. The summary of the turns before the compaction is lost to Grok; what was said since stays. TestForeignCompactionToGrok (Codex path, a SuperGrok-like upstream refusing in the stream) fails without the change with the reporter's error. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestClaudeSignedOut, TestClaudeAccountNamedAsItsLogin, TestClaudeIdentityServedWhileAsked, known flakes under load, pass alone). Not tested against xAI itself.
|
||
|
|
ba9f0c610d | routing: a group's member may be a model at an effort of its own, provider/model:low (#189, @luw2007: model + effort 才是完整的组合项) — a member was only a model, reasoning as the agent asked or as the group's classifier picked, so "the same model, cheap and quick" and "the same model, thinking hard" could not both be in a group, nor could a rule send to one of them. A member now may carry an effort (none … max): a request routed to it is asked for that much reasoning whatever the agent asked or effort=auto picked, at the level the model has nearest, while the vendor is asked for the model's own id. The same model at two efforts is two members that rules (use=m:high), stickiness and the trace tell apart; an id whose own last part is a colon (a :free, :7b, :0) stays the model's. The group's reasoning levels are those of its members that follow the agent, and the editor has a reasoning button on each member. Tested with a fake provider through a sandbox magpie: the upstream bodies carry the fixed effort in Chat, Responses and Anthropic shapes, and the routing view shows m1:low / m1:high as two seats, light and dark |