diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index fe88ed798..6fac69386 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -39,7 +39,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts 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 in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), 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`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the 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 on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: 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. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). DashScope (`dashScope`: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (`dashScopeDraws`) on its own API, `/api/v1/services/aigc/multimodal-generation/generation` (`drawDashScope`), as docs.qwencloud.com gives it: the prompt as the user message's `text` part after an edit's images as `image` parts (a URL or data URL), `n`, `size` as `W*H` (a ratio is a 400 that says to give WxH), `watermark: false`, no mask; the images are read from every `output.choices[].message.content[].image` (`readDashScopeAnswer`), and a refusal says its `message` and `code`. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, `TestDashScopeDrawsOnItsOwnAPI`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). A group with chat models beside its image or video ones is tried on those alone (`drawingTries`' `makes`: `drawsModel`, or `servesKind` for video), so a drawing never goes to a chat member, on its provider's images API or as a chat asked for an image (changqiu4890 on Discord: a group of three relay chat models, a DeepSeek one and the relay's gpt-image-2.5 drew on its first chat model; `TestMixedGroupDrawsOnItsImageMemberOnly`, `TestMixedGroupMakesVideoOnItsVideoMemberOnly`). Codex's image tool draws on the routing group its turn asked for when that group has an image member (`codexDrawingProvider` gives the turn's group, `GroupDraws`, then `resolveDrawing`), and only otherwise on the provider that served the turn or Settings' pick (`TestCodexDrawingTakesItsGroupsImageMember`). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. A group's Add a model picker offers each provider's image models, `/api/groups`' `drawers` (`gateway.Drawers` less hidden ones, apart from the chat `models`), said as such and with no reasoning level (jzw690 on X); such a member draws whether or not its provider's picks name it, as picks are of chat models (`provider.FindDrawingGroup`, used by `GroupDraws`, `resolveDrawing` and the image group's turns), and the group is no model agents are offered. A group named on `/v1/embeddings`, `/v1/rerank`, `/v1/audio/speech`, `/v1/audio/transcriptions` (and translations) or `/v1/videos` keeps the same way a member its provider's chat list doesn't have (`mediaMembers`: `provider.FindGroupAlso` with `offChatList`), and is tried from its first such member (`mediaGroupFirst`), so a hand-made group of embedding or speech models of providers with picks is served, not a 404 (XYenon on Discord); a chat model the user unticked stays out. `TestMediaGroupOfProvidersWithChatPicks`, `TestVideoGroupOfProvidersWithChatPicks`. The same models need no group made by hand (#5339): a fetched list keeps its models made for another API, each marked with it (`catalog.Model.Serves`, from the id: `catalog.ServesOf`; `LiveServing`), out of the chat models (`catalog.Chat`), so agents' lists, gateway keys and Routing's chat pickers never offer them, and a moderation model is still dropped. A model of one kind that more than one provider serves under exactly the same id (no other case, no other version) is a group of that kind made per request on its route (`provider.KindGroup`, `mediaMembers` and `servesKind` in [`media_group.go`](../../internal/gateway/media_group.go)): asked by the bare id there, or by `group/auto-:` (`KindGroupID`; a chat model's found group's id has no `:`), never on another kind's route, its members in the Providers order, none switched off and none the model is disabled on. It is in no list of groups (`Groups`), so no agent, key or picker offers it. Video is the kind `video` (`Videomakers`); images keep their own groups. A list saved before this is fetched again once a run, schedule or none (`refreshDueLists`, `catalog.LiveKinded`). Another magpie's list (`X-Magpie-Drawers`) is not marked; its models are found by their id (`ServesOf`). `TestKindGroupsServeEachAPIByRoute`, `TestVideoKindGroupByTheModelsID`, `TestKindGroupHoldsTheExactModel`, `TestKindlessListFetchedOnce`, `TestFetchKeepsModelsOfOtherAPIs`. `TestImageGroupOfUnpickedImageModelsDraws`, `TestGroupEditorOffersImageModels`, `group-pick-drawers.test.cjs`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`draw_dashscope.go`](../../internal/gateway/draw_dashscope.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | -| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`conversationID`): the agent's session header, else a hash of how the conversation opens, which every later turn repeats: its first user message, or, when the agent wrote that one alone (`userWords`: an `` block, Reasonix's ``, an instruction file), the user messages from it through the first that holds the user's own words, an image, a file or a recording (`conversationOpening`, `userOpens`). A system or developer message between them is passed over; a reply, a call or a tool's result ends the opening, and with none of the user's before it the first message is hashed alone. One message is hashed as the request has it; several are hashed without their cache marks and with a content of one text part read as that text (`writeOpening`), since an agent moves its mark on to each turn's newest message, some spelling a marked message as one part and an unmarked one as a string (`TestCacheMarkMovingOnKeepsTheID`). Before, the first message was always hashed alone, and every conversation an agent opened on the same message in one folder was one: kept under `session` on the account that answered the first, and never moved on by rotate (keeyangyy, #3938, `TestConversationsOnOneEnvironmentMessageAreApart`, `TestReasonixConversationsInOneWorkspaceAreApart`, `TestNewConversationsInOneFolderAreRoutedApart`). A conversation whose first user message is the user's own keeps the id it had, which the Context page and the Routing page's requests find dsh's sessions by (`dshConvs`, `convOwners`, `convSessions`): dsh's pi-ai routes send no session header. A Claude Code subagent's is kept apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its seals were refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | +| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`affinityID`, in `stickKey` and `ruleKey`): the agent's session header, else the caller's `X-Magpie-Session` (#5242: requests that each named a session of their own, and opened alike, were taken for one conversation and kept together; `TestMagpieSessionIsTheConversation`), else (`conversationID`, which is what Kilo and a plugin are sent as the conversation, so `X-Magpie-Session` never goes upstream) a hash of how the conversation opens, which every later turn repeats: its first user message, or, when the agent wrote that one alone (`userWords`: an `` block, Reasonix's ``, an instruction file), the user messages from it through the first that holds the user's own words, an image, a file or a recording (`conversationOpening`, `userOpens`). A system or developer message between them is passed over; a reply, a call or a tool's result ends the opening, and with none of the user's before it the first message is hashed alone. One message is hashed as the request has it; several are hashed without their cache marks and with a content of one text part read as that text (`writeOpening`), since an agent moves its mark on to each turn's newest message, some spelling a marked message as one part and an unmarked one as a string (`TestCacheMarkMovingOnKeepsTheID`). Before, the first message was always hashed alone, and every conversation an agent opened on the same message in one folder was one: kept under `session` on the account that answered the first, and never moved on by rotate (keeyangyy, #3938, `TestConversationsOnOneEnvironmentMessageAreApart`, `TestReasonixConversationsInOneWorkspaceAreApart`, `TestNewConversationsInOneFolderAreRoutedApart`). A conversation whose first user message is the user's own keeps the id it had, which the Context page and the Routing page's requests find dsh's sessions by (`dshConvs`, `convOwners`, `convSessions`): dsh's pi-ai routes send no session header. A Claude Code subagent's is kept apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its seals were refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | | One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A large body (64KB or more, or of no stated length) is pinged too, as a silent connection takes a body that fits its send buffer, but its ping's answer is queued behind the body's own DATA, so on a slow uplink a working connection loses it (#3909: a ~680KB turn on a 2-10KB/s uplink failed every try). Such a body whose connection was dropped for a lost ping is sent once more, through `GetBody`, on a new connection that is not pinged and is given up on when a write moves no bytes for a minute (`uploadTransport`); for 30 minutes after, large bodies go there at once (`drawsApart.slow`; `TestUploadStillUnderwayIsNotCutByHealthPing`, `TestSlowUplinkSkipsTheLostTry`, `TestLargeBodyOnSilentConnectionIsSentAgain`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`, `catalog.WrongEndpoint`: the English wordings and AgentRouter's Chinese one, #3766, read escaped too; a model's test reads them as well, see [Providers and accounts](providers-accounts.md)) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL, from the editor's Save or `magpie model api`; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. It goes to the first API `usable` gives, Chat where the provider has a Chat URL too, except one that asks an image's size or shape (`generationConfig.imageConfig`), which only a Gemini API takes: that one is translated on the Gemini URL (#3820, `TestGeminiImageConfigGoesToTheGeminiAPIBesideChat`). | [`gateway.go`](../../internal/gateway/gateway.go) | | Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) A request outside the chat path gets a route of its own too ([`media_route.go`](../../internal/gateway/media_route.go), `sideRoute`): an image (`images`, each account `drawOnAccounts` asks a try), a video's start (`videosCreate`; its polls and download are the same video and add none) and an embedding, rerank, transcription or speech (`retrieve`). Each try's key or account is put in `Order` so the page finds its seat, the route's `Kind` stays empty, and the one usage row names it in `RouteID` (zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's requests and not on Routing; `TestVideoIsOnRoutingOnce`, `TestImageIsOnRouting`, `TestEmbeddingAndRerankAreOnRouting`). | | Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the body is kept as it went and masked when `PromptText` first reads it, so the request itself never waits on masking (#3973). `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`. Once a body is dropped, or magpie quits, the GUI reads the request archive's copy when the route names one (`Route.Archive`; wangbinyq on Discord): `ArchivedPromptText` parses it the same way and masks it as the body in memory is (`maskedCopy`), and the reply beside it comes from `ReplyBody` (the Recent calls' reply) or the archive's, read into pieces by `ReplyPieces` and masked alike (`prompt_reply.go`, served as `/api/context/reply`). A body or reply that can't be masked shows nothing, and one the archive cut short isn't parsed (`TestArchivedPromptTextIsMasked`, `TestReplyPiecesAreMasked`, `TestContextTextFromTheArchive`). It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) | @@ -223,6 +223,7 @@ recorded as a prediction failure (`noPrediction`). - A routing group set to In order is tried in the order the user put its members in, and a later member keeps a conversation only until a member ahead of it is ready again (yyhhyyyyyy on Discord: an API key first and a Claude subscription second for Opus, 8 of 10 Claude Code requests on the subscription). One failure of the first member (a 429, a 5xx, a rest) sent a conversation to the second, and Auto affinity's `cache` kept it there at every turn after, since each turn read what the last had written. Now, with Stays left on Auto, a new turn goes back to the first ready member when it is another member than the one that answered last (`backToFirst` in `affine`, `Affinity.Why` `order`; another key or account of the same member, or a group in the group, keeps its own affinity). Within a turn it stays, on the reasoning the later member sealed, as with `main`. Stays: Session and Strict are the user's own and keep the conversation where it is. The Routing page says why it moved. `TestOrderedGroupGivesTheConversationBackToItsFirstMember`, `routing-affinity-order.test.cjs`. - A group routed any other way (Smart, Least used first, By weight and the rest, In turn aside) gives back a conversation a later member took only as a stand-in (01huadalang on Discord, 11-01: Codex on two accounts first in a Smart group, a MiMo key second as the backup; after an outage of Codex's 5 hours, a session that had gone to MiMo stayed there by MiMo's cache once Codex was back, while new ones went to Codex). A member stood in when, as it answered, a member the group lists ahead of its own was resting (a 429, a 5xx: `restAfter` rests the one that failed before the try goes on) or known all but used up (`Used` at `SpentShareOf`): `standsInFor`, over the plan as it was for the request, by each candidate's `place` in the group's list (`placed` in `planGroup`; a group in the group is one member). The stick keeps it (`stick.stoodIn`, and `stoodIn` in `affinity.json`, absent from a file written before and read as no stand-in) while the same account and model answer on, so a stand-in that routing still puts first after the one ahead is back (Smart's low tier, a week at 92%) gives the conversation back once routing puts the one ahead first. At a new turn, with Stays on Auto, the conversation goes to the first ready member when that one is listed ahead of the stand-in's (`backFromStandIn`, `Affinity.Why` `back`); another key or account of the same member keeps it by its cache. A member routing put first while those ahead of it were ready and had room is no stand-in and keeps its cache as before, so peers of a Smart group don't trade conversations by renewal order. Within a turn it stays; Within a turn and Off route each new turn afresh anyway; Session and Strict keep it where it is; In turn's next turn goes round (`after`). Routing still decides who is first: Least used first and Smart put a key whose usage isn't told (counted unused) ahead of accounts at 90% or more of a window, so a conversation, and every new one, goes to such a backup while the subscription's accounts are that low (routing's own choice, not affinity's; In order keeps a backup last). `TestGroupBackupGivesTheConversationBack`, `TestGroupBackupStandingInWhileTheFirstIsBackAndBehind`, `TestGroupMemberPutFirstOnItsMeritsKeepsItsCache`, `TestGroupStandInStaysWithinATurn`, `TestGroupMemberGivesTheConversationBackOnceTheOneAheadIsBack`, `routing-affinity-order.test.cjs`. - In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones, a provider's fallback while the provider's own leads (`standsIn`) and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models. +- Requests that come together spread (`burstSpread` in [`burst.go`](../../internal/gateway/burst.go), #5242: Moody-Sin and Tericerice sent four at once to three Antigravity accounts, In turn and By pace, and every one went to one account). Routing weighs what each seat served (`Tokens`) and its allowance, which move only once a reply ends, and a lane counts a request only once its try begins, so requests planned at the same moment were all planned on the same figures; In turn's next turn (`after`) reads a stick that moves only on an answer too. Once the plan is made (after affinity, rules, pinning, `roomy`, `behindOverflow`), `burstSpread` puts first, of the candidates alike to the first, the one with the fewest requests in flight (`inFlight`, by `candidate.who`), ties keeping routing's order, and counts the request there in the same hold of the lock; the count is given back when `serve` ends. Alike (`burstAlike`): ready as the first is (not resting, aside, reserved, barred, held, capped, a fallback standing in, credits-last or busy behind), the same fallback, fit, protocol, URL and `Via`, the rule's member when a group's rule picked one; In turn any of the round; By pace a pace within a tenth (`paceAlike`, routes.Pace's band), the same `Learns`, both with room (`burstTier` 0) and no wallet told apart (`sameBalance`); Least used within a point used, the same tier and known-ness. In a group, a provider routed its own way (`ownRouting`) is alike only to its own provider's keys, by its routing, and a group in the group to nothing. Smart, In order, By weight and the others keep their order. Not moved, only counted: a conversation kept (`Affinity.Kept`), Strict, an `X-Magpie-Account` pin, a sealed task's lead, a native compaction's reader, and a new conversation `leastHeld` spreads (In turn, `spreadsSessions`), which counts those in flight itself (`sticks.opening`). A plugin's provider and a remote magpie take the same path; the remote spreads over its own accounts, the sessions passed on to it (`passOnCaller`). Not done: putting a markedly slower account behind (speed is read only for Speed first, `speedOf`), as a first token's wait goes with the prompt's size and the vendor's queue more than with the account. `burst_spread_test.go`. - Stays: Session or Strict under a routing that picks by what is left (Smart, Least used first, Use before expiry: `spreadsSessions`) spreads new conversations the same way (connor_yang on Discord: three sessions over three accounts landed on two). `leastHeld` with `ready` passes over one routing keeps new conversations off (`readyForNew`: resting, a key for another protocol, a provider's fallback while its own model leads, one used past `lowShare`), counts only leads (a key without `|agent:`), and leaves the turn marks alone. A subagent's first request goes to its lead's key or account while that one is `readyForNew` (`withLead`), so a session keeps one account, its subagents included. Held is the last `heldFor` (30 minutes): a session idle longer counts no more. In order, By weight, Free first, Speed first, Cheapest, Manual and a plugin's routing keep their order. An answered conversation is kept as before; the spread only decides where a new one starts. `session_spread_test.go`. - A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again. One let spend its credits, and holding some by its last `/wham/usage` (`credits.has_credits` with a balance over 0, or `unlimited`; `QuotaWindow.Credits`, `Limit.Credits`, `Allowance.OnCredits`), is not out when a window fills (豆子 and Zhenzhen on Discord): ChatGPT may answer the turn that uses the window up 429 `usage_limit_reached` before it spends the credits, and the next turn on them. So that 429 is asked again at once, once a request, on the same account, before a reset is looked at, on the routed path (`creditsAgain`, `creditsAsked`, `Try.Credits`) and on Codex's own sign-in's relay (`relayOnCredits`), rather than ended for the agent, which ended a running session while a new one worked. Refused again, it rests `fallbackCooldown` (`Rest.By` `credits`) and is read again, not until its window renews, and its full windows rest it nowhere else (`full` is zero for it, `spendsCredits`). Smart, Pace and Least used put such an account first of the spent tier (`routes.Seat.Credits`, `spentBefore`): after those with allowance left, ahead of those used up with nothing to go on with (`Weighed.Credits`, told on the Routing page). Switching to credits early, at a few percent left, was weighed and not done: the vendor spends credits only once the allowance is used up, so it would only waste what is left. `TestCodexCreditsAskedAgainAtTheEdge`, `TestCodexCreditsNoLongRest`, `TestCodexCreditsFirstOfTheSpent`, `TestCreditsFirstOfTheSpent`, `routing-codex-credits-again.test.cjs`. - A third way, set per account, spends the credits only after everything else (gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then the subscription's credits): *Only after every other account, key and fallback* under the Usage card's *Use credits*, `magpie quota credits last`, `settings.CodexCreditsLast` (`provider.CodexCreditsLast`, `SetCodexCreditsMode`; on or off clears it, and an account never in it keeps its place, so a setting saved before keeps its order). Such an account is `creditsLast` while it goes on on its credits (`spendsCredits`) and a window for the model is used up where *off* would hold it (`Allowance.CapHeld` at `WindowCaps{Credits: true}`; a call ChatGPT counts in no window, `freeOnChatGPT`, stays). `restLast` then puts it behind every candidate of the plan, the provider's fallbacks and groups included: ready, then resting, then the credits-last ones in their own order (`Weighed.CreditsLast`). Affinity doesn't keep a conversation on one while one not on its credits leads (`Affinity.Why` `credits`, `lastBehind`), within a turn too, and In turn's next pick and Smart/Pace/Least used's spreading of new sessions never bring one forward (`after`, `leastHeld`, `readyForNew`). Strict affinity keeps it, as a rule, an `X-Magpie-Account` pin and a sealed task's lead (`leadFirst`) still put theirs first. A reset is still spent before its credits when the try reaches it (`resetBeforeCredits`). Codex's own sign-in's relay has the one account and nothing to put first, so there it is as *on*. The Routing page tells each: behind the rest, first when every one is, and the conversation moved. `TestCodexCreditsLastAfterTheOthers`, `TestCodexCreditsLastAfterTheFallback`, `TestCodexCreditsLastNotKept`, `TestCodexCreditsLastMode`, `codex-credits-last.test.cjs`. diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index 3e83485ab..a999415ec 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -522,7 +522,7 @@ func strictOnly(cs []candidate, pl planned, at int) ([]candidate, planned) { // the session's as before, so what is kept of it, and Codex's leadFirst, // which reads a lead's stick by its thread id, are as they were. func stickKey(scope string, in http.Header, body []byte) string { - key := scope + "|" + conversationID(in, body) + key := scope + "|" + affinityID(in, body) if sub := subOf(in); sub != "" { key += "|agent:" + sub } diff --git a/internal/gateway/burst.go b/internal/gateway/burst.go new file mode 100644 index 000000000..26bbc1151 --- /dev/null +++ b/internal/gateway/burst.go @@ -0,0 +1,144 @@ +package gateway + +import ( + "math" + "slices" + "strings" + "sync" + + "github.com/yetone/magpie/internal/provider" +) + +// inFlight counts, for each key or account (candidate.who), the requests +// routed to it that haven't ended. Routing weighs what each has served +// (Tokens) and its allowance, both of which move only once a reply ends, +// and a key's lane counts a request only once its try begins: requests +// that came together were all planned on the same figures and all went to +// the one first (#5242, Moody-Sin and Tericerice: four at once to one of +// three Antigravity accounts, In turn and By pace alike). +var inFlight = struct { + sync.Mutex + m map[string]int +}{m: map[string]int{}} + +// burstSpread puts first, of those alike to cs[0] under routing (burstAlike), +// the one with the fewest requests in flight, the order kept between those +// with as few, and counts the request on whichever is first then, in one +// hold of the count, so requests planned at the same moment each see the +// ones before them. The count is given back by the func it returns, when +// the request ends. reorder false counts it where it is: a conversation +// kept on its account, a request pinned to one, a new conversation that +// leastHeld spread. sameMember keeps a group's rule's member first. +func burstSpread(routing string, g *provider.Group, sameMember, reorder bool, cs []candidate, pl planned) ([]candidate, planned, func()) { + if len(cs) == 0 { + return cs, pl, func() {} + } + inFlight.Lock() + defer inFlight.Unlock() + if reorder && len(cs) > 1 && len(pl.order) >= len(cs) { + best := 0 + for i := 1; i < len(cs); i++ { + if burstAlike(routing, g, sameMember, cs, pl.order, i) && inFlight.m[cs[i].who()] < inFlight.m[cs[best].who()] { + best = i + } + } + if best > 0 { + cs = append(append([]candidate{cs[best]}, cs[:best]...), cs[best+1:]...) + pl.order = append(append([]Weighed{pl.order[best]}, pl.order[:best]...), pl.order[best+1:]...) + if routingOf(routing) == provider.Rotate { + for j := range pl.order { + pl.order[j].Turn = j == 0 + } + } + } + } + who := cs[0].who() + inFlight.m[who]++ + var once sync.Once + return cs, pl, func() { + once.Do(func() { + inFlight.Lock() + if inFlight.m[who]--; inFlight.m[who] <= 0 { + delete(inFlight.m, who) + } + inFlight.Unlock() + }) + } +} + +// burstAlike says whether cs[i] is one routing would as soon send the +// request to as cs[0]: ready as cs[0] is, on the same footing (a fallback +// as a fallback, a key fit for the protocol as well, through the same +// remote magpie), and alike by what its routing goes by — any of a round +// In turn; By pace, both on a pace alike within a tenth with no wallet +// told apart and neither near its cap; Least used, used within a point. +// Other routings pick for their own reasons and keep their order. In a +// group, one of a provider routed its own way is alike only to its own +// provider's, by its provider's routing; a group in the group keeps its +// own order. +func burstAlike(routing string, g *provider.Group, sameMember bool, cs []candidate, order []Weighed, i int) bool { + a, b := order[0], order[i] + c0, ci := cs[0], cs[i] + if a.Rest != nil || a.Aside || a.Reserve > 0 || c0.capped != nil || ci.capped != nil { + return false + } + if b.Rest != nil || b.Aside || b.Reserve > 0 || b.Barred || b.Held || standsIn(order, i) || lastBehind(order, i) || busyBehind(order, i) { + return false + } + if a.Fallback != b.Fallback || a.Fit != b.Fit || a.Speaks != b.Speaks || c0.noURL != ci.noURL || !slices.Equal(a.Via, b.Via) { + return false + } + if sameMember && c0.member != ci.member { + return false + } + if g != nil { + if strings.HasPrefix(c0.member, provider.GroupPrefix) || strings.HasPrefix(ci.member, provider.GroupPrefix) { + return false + } + if ownRouting(c0.p, *g) || ownRouting(ci.p, *g) { + if c0.p.ID != ci.p.ID { + return false + } + routing = c0.p.Routing + } + } + switch routingOf(routing) { + case provider.Rotate: + return true + case provider.Pace: + return a.Learns == b.Learns && burstTier(a) == 0 && burstTier(b) == 0 && paceAlike(a.Pace, b.Pace) && sameBalance(a, b) + case provider.LeastUsed: + return a.Known == b.Known && burstTier(a) == burstTier(b) && math.Abs(a.Used-b.Used) < 1 && sameBalance(a, b) + } + return false +} + +// burstTier is routes.seatTier of a weighed seat: 0 with room, 1 near +// its cap, 2 all but used up; 0 for an account set to spend its credits +// first, and for a week alone that low. +func burstTier(w Weighed) int { + switch { + case w.CreditsFirst: + return 0 + case w.Used >= usedShare: + return 2 + case w.Used >= lowShare && !w.WeekLow: + return 1 + } + return 0 +} + +// paceAlike says whether two paces are in a band of routes.Pace: within a +// tenth of each other, or neither one's (a key has none). +func paceAlike(a, b float64) bool { + hi, lo := max(a, b), min(a, b) + return hi <= 0 || lo >= 0.9*hi +} + +// sameBalance says whether two seats told the same of a wallet, or none. +func sameBalance(a, b Weighed) bool { + if a.Balance == nil || b.Balance == nil { + return a.Balance == nil && b.Balance == nil + } + return *a.Balance == *b.Balance +} diff --git a/internal/gateway/burst_spread_test.go b/internal/gateway/burst_spread_test.go new file mode 100644 index 000000000..421bb432f --- /dev/null +++ b/internal/gateway/burst_spread_test.go @@ -0,0 +1,400 @@ +package gateway + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/routes" + "github.com/yetone/magpie/internal/testenv" +) + +// #5242 (Moody-Sin, Tericerice): requests sent at the same moment to a +// provider with three accounts, routed to spread load, all went to one +// account, in turn and in pace, with affinity turn and off, and even when +// each request named a session of its own. +func TestABurstSpreadsOverAccounts(t *testing.T) { + const n = 6 + for _, routing := range []string{provider.Rotate, provider.Pace} { + for _, aff := range []string{provider.AffinityTurn, provider.AffinityOff, ""} { + for _, how := range []string{"x-session-id", SessionHeader, "same body"} { + for _, warm := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/%s/warm=%v", routing, aff, how, warm), func(t *testing.T) { + fresh(t) + h := &held{want: n, all: make(chan struct{}), tried: map[string]int{}} + serveOn(t, "ag", "k1", []string{"m1"}, h, "k2", "k3") + if err := provider.SetRouting("ag", routing); err != nil { + t.Fatal(err) + } + if err := provider.SetAffinity("ag", aff); err != nil { + t.Fatal(err) + } + routes.Forget("ag") + s := New() + if warm { + // the reporters' rounds: the same request answered + // before, so its conversation is held on an account + h.want = 1 + burstPost(t, s, how, 0) + h.mu.Lock() + h.want, h.in, h.all, h.tried = n, 0, make(chan struct{}), map[string]int{} + h.mu.Unlock() + } + var wg sync.WaitGroup + for i := range n { + wg.Add(1) + go func() { + defer wg.Done() + burstPost(t, s, how, i) + }() + } + wg.Wait() + h.mu.Lock() + defer h.mu.Unlock() + for _, k := range []string{"k1", "k2", "k3"} { + if h.tried[k] == 0 { + t.Errorf("%s got none of %d requests sent at once: %v", k, n, h.tried) + } + } + }) + } + } + } + } +} + +// burstPost sends the reporters' request: the same body every time, with a +// session of its own in a header, or none. +func burstPost(t *testing.T, s *Server, how string, i int) { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"ag/m1","messages":[{"role":"user","content":"hi"}]}`)) + if how != "same body" { + req.Header.Set(how, fmt.Sprintf("s-%d", i)) + } + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Errorf("%d %s", rec.Code, rec.Body.String()) + } +} + +// #5242 through a routing group: its members' keys weighed together, and +// a group of one provider's three keys, routed In turn and By pace. +func TestABurstSpreadsOverAGroup(t *testing.T) { + const n = 6 + for _, routing := range []string{provider.Rotate, provider.Pace} { + for _, shape := range []string{"three providers", "one provider's keys"} { + t.Run(routing+"/"+shape, func(t *testing.T) { + fresh(t) + h := &held{want: n, all: make(chan struct{}), tried: map[string]int{}} + members := []string{"ag/m1"} + if shape == "three providers" { + serveOn(t, "pa", "k1", []string{"m1"}, h) + serveOn(t, "pb", "k2", []string{"m1"}, h) + serveOn(t, "pc", "k3", []string{"m1"}, h) + members = []string{"pa/m1", "pb/m1", "pc/m1"} + } else { + serveOn(t, "ag", "k1", []string{"m1"}, h, "k2", "k3") + } + if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: members, Routing: routing, Affinity: provider.AffinityTurn}); err != nil { + t.Fatal(err) + } + s := New() + var wg sync.WaitGroup + for i := range n { + wg.Add(1) + go func() { + defer wg.Done() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+provider.GroupPrefix+`g","messages":[{"role":"user","content":"hi"}]}`)) + req.Header.Set(SessionHeader, fmt.Sprintf("s-%d", i)) + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Errorf("%d %s", rec.Code, rec.Body.String()) + } + }() + } + wg.Wait() + h.mu.Lock() + defer h.mu.Unlock() + for _, k := range []string{"k1", "k2", "k3"} { + if h.tried[k] == 0 { + t.Errorf("%s got none of %d requests sent at once: %v", k, n, h.tried) + } + } + }) + } + } +} + +// #5242 through a remote magpie: the sessions each request names go on +// to it, and it spreads them over its provider's keys. +func TestABurstSpreadsBehindARemoteMagpie(t *testing.T) { + const n = 6 + fresh(t) + h := &held{want: n, all: make(chan struct{}), tried: map[string]int{}} + serveOn(t, "ag", "k1", []string{"m1"}, h, "k2", "k3") + if err := provider.SetRouting("ag", provider.Pace); err != nil { + t.Fatal(err) + } + if err := provider.SetAffinity("ag", provider.AffinityTurn); err != nil { + t.Fatal(err) + } + there := New().Handler() + remote := httptest.NewServer(there) + t.Cleanup(remote.Close) + if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: "rk", Models: []string{"ag/m1"}, + Chat: remote.URL + "/v1", Responses: remote.URL + "/v1", Anthropic: remote.URL}); err != nil { + t.Fatal(err) + } + s := New() + var wg sync.WaitGroup + for i := range n { + wg.Add(1) + go func() { + defer wg.Done() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"office/ag/m1","messages":[{"role":"user","content":"hi"}]}`)) + req.Header.Set(SessionHeader, fmt.Sprintf("s-%d", i)) + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Errorf("%d %s", rec.Code, rec.Body.String()) + } + }() + } + wg.Wait() + h.mu.Lock() + defer h.mu.Unlock() + for _, k := range []string{"k1", "k2", "k3"} { + if h.tried[k] == 0 { + t.Errorf("%s got none of %d requests sent at once: %v", k, n, h.tried) + } + } +} + +// #5242 for a provider a plugin serves: three accounts of the fake plugin +// (as Factory) through a real plugin host, By pace, sent six at once. +func TestABurstSpreadsOverAPluginsAccounts(t *testing.T) { + const n = 6 + bun := testenv.Bun(t) + fresh(t) + t.Setenv("MAGPIE_BUN", bun) + t.Setenv("FAKE_ID", "factory") + t.Cleanup(plugin.Settle) + h := &held{want: n, all: make(chan struct{}), tried: map[string]int{}} + up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + who := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer fresh-r-") + h.mu.Lock() + h.tried[who]++ + if h.in++; h.in == h.want { + close(h.all) + } + h.mu.Unlock() + select { + case <-h.all: + case <-time.After(5 * time.Second): + } + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`+"\n\n") + fmt.Fprint(w, "data: [DONE]\n\n") + })) + defer up.Close() + dir := filepath.Dir(provider.Path()) + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + mig, _ := json.Marshal(map[string]any{"factory": map[string]any{"state": provider.MovePlugin}}) + if err := os.WriteFile(filepath.Join(dir, "migrations.json"), mig, 0o600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + teams := []string{"a", "b", "c"} + for _, team := range teams { + st, err := provider.StartPluginSignIn("factory", 1, map[string]string{"where": "work", "team": team}) + if err != nil { + t.Fatal(err) + } + if err := provider.SubmitSignInCallback(st.ID, "good"); err != nil { + t.Fatal(err) + } + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + if ls := provider.Logins("factory"); len(ls) != len(teams) { + t.Fatalf("accounts %+v", ls) + } + for _, team := range teams { + if err := provider.SetLoginOn("factory", team+"@fake", true); err != nil { + t.Fatal(err) + } + } + if err := provider.SetRouting("factory", provider.Pace); err != nil { + t.Fatal(err) + } + if err := provider.SetAffinity("factory", provider.AffinityTurn); err != nil { + t.Fatal(err) + } + s := New() + var wg sync.WaitGroup + for i := range n { + wg.Add(1) + go func() { + defer wg.Done() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"factory/fake-1","stream":true,"messages":[{"role":"user","content":"hi"}]}`)) + req.Header.Set(SessionHeader, fmt.Sprintf("s-%d", i)) + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Errorf("%d %s", rec.Code, rec.Body.String()) + } + }() + } + wg.Wait() + h.mu.Lock() + defer h.mu.Unlock() + for _, team := range teams { + if h.tried[team] == 0 { + t.Errorf("%s@fake got none of %d requests sent at once: %v", team, n, h.tried) + } + } +} + +// Spreading a burst leaves a conversation its affinity keeps where it is: +// one session, Stays: Session, answered once, then sent six at once. +func TestABurstKeepsAKeptConversation(t *testing.T) { + const n = 6 + for _, routing := range []string{provider.Rotate, provider.Pace} { + t.Run(routing, func(t *testing.T) { + fresh(t) + h := &held{want: 1, all: make(chan struct{}), tried: map[string]int{}} + serveOn(t, "ag", "k1", []string{"m1"}, h, "k2", "k3") + if err := provider.SetRouting("ag", routing); err != nil { + t.Fatal(err) + } + if err := provider.SetAffinity("ag", provider.AffinitySession); err != nil { + t.Fatal(err) + } + s := New() + burstPost(t, s, SessionHeader, 0) + var first string + for k := range h.tried { + first = k + } + h.mu.Lock() + h.want, h.in, h.all, h.tried = n, 0, make(chan struct{}), map[string]int{} + h.mu.Unlock() + var wg sync.WaitGroup + for range n { + wg.Add(1) + go func() { + defer wg.Done() + burstPost(t, s, SessionHeader, 0) + }() + } + wg.Wait() + h.mu.Lock() + defer h.mu.Unlock() + if h.tried[first] != n { + t.Errorf("the session's %d requests left %s, the account it is kept on: %v", n, first, h.tried) + } + }) + } +} + +// By pace a burst goes on to another account only while its pace is alike +// (within a tenth): one with markedly more of its week left per hour +// takes them all, as pace says. +func TestBurstSpreadsOnlyOverAlikePaces(t *testing.T) { + cs := []candidate{{p: provider.Provider{ID: "ag", Key: "k1"}, rest: "ag#1"}, {p: provider.Provider{ID: "ag", Key: "k2"}, rest: "ag#2"}} + for _, tc := range []struct { + paces [2]float64 + spread bool + }{{[2]float64{10, 9.5}, true}, {[2]float64{10, 5}, false}, {[2]float64{0, 0}, true}} { + inFlight.Lock() + inFlight.m = map[string]int{} + inFlight.Unlock() + pl := planned{order: []Weighed{{Pace: tc.paces[0]}, {Pace: tc.paces[1]}}} + var gone []string + var releases []func() + for range 2 { + got, _, release := burstSpread(provider.Pace, nil, false, true, slices.Clone(cs), pl) + gone, releases = append(gone, got[0].who()), append(releases, release) + } + for _, r := range releases { + r() + } + if spread := gone[0] != gone[1]; spread != tc.spread { + t.Errorf("paces %v: went to %v, spread %v, want %v", tc.paces, gone, spread, tc.spread) + } + inFlight.Lock() + left := len(inFlight.m) + inFlight.Unlock() + if left != 0 { + t.Errorf("%d still counted in flight after each ended", left) + } + } +} + +// The session a caller names in X-Magpie-Session is its conversation's, as +// the agent's own session header is: two sessions that open alike are two +// conversations, the second not kept on the first's account (#5242's +// second run: each request named a session of its own, and every one was +// taken for the first's conversation by its first message). +func TestMagpieSessionIsTheConversation(t *testing.T) { + fresh(t) + h := &held{want: 1, all: make(chan struct{}), tried: map[string]int{}} + serveOn(t, "ag", "k1", []string{"m1"}, h, "k2", "k3") + if err := provider.SetRouting("ag", provider.Pace); err != nil { + t.Fatal(err) + } + if err := provider.SetAffinity("ag", provider.AffinitySession); err != nil { + t.Fatal(err) + } + s := New() + for i := range 3 { + burstPost(t, s, SessionHeader, i) + } + for _, k := range []string{"k1", "k2", "k3"} { + if h.tried[k] != 1 { + t.Errorf("three sessions, one after another, kept for the session: %v", h.tried) + break + } + } + // an agent's own session header still names it first + in := http.Header{} + in.Set(SessionHeader, "magpie-s") + in.Set("session_id", "agent-s") + if got := affinityID(in, nil); got != "agent-s" { + t.Errorf("conversation %q, want the agent's own agent-s", got) + } + // what a vendor or plugin is sent as the conversation never is the caller's + in.Del("session_id") + if got := conversationID(in, nil); got == "magpie-s" { + t.Errorf("conversationID %q: X-Magpie-Session would go upstream", got) + } + if got := affinityID(in, nil); got != "magpie-s" { + t.Errorf("affinityID %q, want magpie-s", got) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 1296017bb..fa912b683 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2540,7 +2540,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } conv := conversationID(r.Header, body) sealedLead = leadProvider(scope, parent) - sealers = []string{sealedLead, leadProvider(scope, conv)} + sealers = []string{sealedLead, leadProvider(scope, affinityID(r.Header, body))} readable := func() bool { return isGroup && slices.ContainsFunc(ms, func(m provider.Member) bool { return s.sealedReader(m.Provider, m.Model, sealers) }) || !isGroup && s.sealedReader(p, model, sealers) } @@ -3000,6 +3000,18 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // grown conversation is refused again, and the member that answered // is asked first (#3453) cands, pl = behindOverflow(stuck, cands, pl, len(body)) + // requests that came together go to as many keys or accounts as are + // alike for them, each counted where it goes until it ends (#5242); + // one kept, pinned, sealed to its account, or a new conversation + // leastHeld spread is counted where it is + poolRouting, poolGroup := p.Routing, (*provider.Group)(nil) + if isGroup { + poolRouting, poolGroup = g.Routing, &g + } + leastHeldIt := aff.Why == "first" && (rotate || spread) + reorder := !aff.Kept && aff.Why != "strict" && pin == "" && leadAccount == "" && checkpoint == nil && !leastHeldIt + cands, pl, unburst := burstSpread(poolRouting, poolGroup, hit != nil && hit.Use != "", reorder, cands, pl) + defer unburst() // of those resting, only the one back soonest is asked (#1799); the // whole list still finds a Codex account to spend a reset on all := cands @@ -9157,6 +9169,24 @@ func nativeSessionOf(in http.Header) string { // (conversationOpening). One message is hashed as the request has it, as // it always was; several are hashed as writeOpening reads them, so the // cache mark an agent moves on from turn to turn doesn't move the id. +// affinityID is the conversation a turn's account is kept for: an agent's +// own session (conversationID), else the caller's X-Magpie-Session, else +// the conversation's hash. Two callers that send the same opening with +// their own X-Magpie-Session are two conversations (#5242). It is magpie's +// own key and never goes upstream: conversationID, which a vendor or a +// plugin is sent (Kilo, ConversationHeader), doesn't read X-Magpie-Session. +func affinityID(in http.Header, body []byte) string { + for _, h := range sessionHeaders { + if v := strings.TrimSpace(in.Get(h)); v != "" { + return v + } + } + if v := strings.TrimSpace(in.Get(SessionHeader)); v != "" { + return v + } + return conversationID(in, body) +} + func conversationID(in http.Header, body []byte) string { for _, h := range sessionHeaders { if v := strings.TrimSpace(in.Get(h)); v != "" { diff --git a/internal/gateway/rules.go b/internal/gateway/rules.go index e010df2c9..a011ffe4c 100644 --- a/internal/gateway/rules.go +++ b/internal/gateway/rules.go @@ -139,7 +139,7 @@ var turnRules = struct { // ruleKey is the conversation a group's rules keep a turn's decision for: // the agent's session and the conversation's first words (firstWords). func ruleKey(g provider.Group, in http.Header, req *Request) string { - return provider.GroupPrefix + g.ID + "|" + conversationID(in, nil) + "|" + firstWords(req) + return provider.GroupPrefix + g.ID + "|" + affinityID(in, nil) + "|" + firstWords(req) } // firstWords tells an agent's subagents from it: they share its session