diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 9e8094cc1..8c73e09da 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -41,7 +41,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | 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) | | Decisions | `POST /v1/decisions` (and `/decisions`) is OpenAI's Decisions API, checked against openai-python's `decisions.create` (`DecisionCreateParams`, `Decision`): `model` (gpt-6-luna), `input` (a string, or messages and items whose parts are `input_text`, `input_image` with a data or http(s) URL, JSON), `questions` (1 to 400 predicate, choice or score questions), and `prompt_cache_key`, `prompt_cache_options`, `safety_identifier`. The answer is `{answers, model, usage}`, never streamed. `decide` passes the body through `serveRetrieval` as embeddings' is, with only `model` changed, so model resolution, a disabled model, a key's models, accounts and spent limits, pause rules, the provider's keys or accounts, masking (a data URL's image is left as it is) and the Routing page hold as on every route. It goes only to a provider `canDecide` takes: an OpenAI API key on `api.openai.com`, Azure OpenAI (`IsAzure`, at its v1 API's `/openai/v1/decisions`, the model in the body as the deployment's name), or another magpie, which routes it on. Any other, a relay, a plugin or a ChatGPT sign-in whatever its list says, is never sent it: the try is refused 400 with who serves it (`decisionRequest.refuses`, next to the no-OpenAI-API check), and a group moves on to its next member. A bare `gpt-6-luna` is the kind group `decision` (`servesDecision`: a provider `canDecide` takes that lists the model, or an OpenAI key, as the API takes it without it on the key's chat list), so a relay listing the same id is never its member. Usage is recorded as `decisions` from the answer's `usage` (`decisionRequest.counted`): `input_tokens` less `input_tokens_details`' `cached_tokens` and `cache_write_tokens` as input, those two as cache read and write, and no output, as OpenAI bills none, so gpt-6-luna's own rates price it. `native_endpoints` is about the chat APIs a model is relayed on, and stays chat/completions and responses. `TestDecisionsReachOpenAIAndAzure`, `TestDecisionsRefusedWhereNotServed`, `TestCanDecide`, `TestDecisionsThroughAnotherMagpie`, `TestDecisionsHeldByKeysAndRules`. | [`decisions.go`](../../internal/gateway/decisions.go), [`embeddings.go`](../../internal/gateway/embeddings.go), [`media_group.go`](../../internal/gateway/media_group.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`, `routeOwners`, `routeSessions`): dsh's pi-ai routes send no session header. A dsh fork repeats its source's opening, so a finished request is named by the id of the reply its client was given (`Route.ResponseID`, set from `clientResponseID` as the route is marked done), which dsh writes down on that reply (`replayState.response.responseId`, read into `Session.ResponseIDs`: a fork's own replies after its `session/end-seed` only). Vendors' reply ids can repeat, so a reply's id names a session over the opening only when the opening is that session's own or that of a session it was forked from (`ForkOf`, from the fork's `parentSession`; `ownerOf`), and Routing reads the sessions again for a reply id it has not found only up to a minute after the request ended (`looseKeys`): a title call's id is never written down (#5491, Flandern1211). A request still running or failed, and one logged before Route had the id, keeps the opening's session. 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)), and one held to HTTP/1.1 (`HTTP1`) is spoken it at those hosts alone. A TLS record error read on an HTTP/2 connection ("bad record MAC", "received record with version …": the bytes under the TLS were mangled, by the far side or a box between) drops that connection, as Go's transport does, and `netproxy.Dispatch` sends the requests to that host:port over HTTP/1.1 for 6 hours after (`markH2Broken`, `h2BrokenFor`; kepner_53726: a company gateway failed 124 turns in 3 days so, each a 200 with no output, until a restart; `TestH2RecordErrorMovesHostToHTTP1`). 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) | +| 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)), and one held to HTTP/1.1 (`HTTP1`) is spoken it at those hosts alone. A TLS record error read on an HTTP/2 connection ("bad record MAC", "received record with version …": the bytes under the TLS were mangled, by the far side or a box between) drops that connection, as Go's transport does, and `netproxy.Dispatch` sends the requests to that host:port over HTTP/1.1 for 6 hours after (`markH2Broken`, `h2BrokenFor`; kepner_53726: a company gateway failed 124 turns in 3 days so, each a 200 with no output, until a restart; `TestH2RecordErrorMovesHostToHTTP1`). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one silent for 10s (no HEADERS or DATA from the vendor since the last request) is pinged, and dropped when no answer comes within 10s, 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 silence answered is pinged again only 5 minutes on (`netproxy.CalmHTTP2`, `PingAgain`): Go's own health check pings it every 10s, its ping's answer restarting its clock, and Google's front end, holding clients to gRPC's ping policy (a ping within 5 minutes of the last with nothing sent between is a strike, and the third ends the connection), ended a turn of gemini thinking through Antigravity at ~235s with GOAWAY ENHANCE_YOUR_CALM "too_many_pings" (zdevoz on Discord; `TestLongSilenceIsNotPingedIntoGoaway`, `TestCalmFindsAPathDeadLaterInTheSilence`). The try after a GOAWAY goes on a new connection (`TestTryAfterGoawayDialsAnew`). `http.DefaultTransport`, whose requests are short, keeps Go's (`netproxy.HTTP2Health`). 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, and 200 MB for the days that are over: today's plain file, however big, takes none of it, `TestHistoryTodayTakesNoRoomFromPastDays`). 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, each inline picture's base64 swapped for a ref into `keptImages` (in memory, 128 MiB at most, least recently used first; `image_keep.go`), so a conversation of pictures, which DeepSeek's file ids let grow past 64 MiB (#5407), keeps its text and pictures (matrix0487 on Discord; the archive's copy is read the same way, `TestFileIDConversationStillShows`); 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) | | Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini for its Gemini models, chat completions for its partner models, and Anthropic's Messages API for Claude. Claude (`provider.VertexClaude`: `claude-opus-5-5`, `claude-sonnet-4-5@20250929`) is relayed or translated as at any Anthropic vendor, and `forwardOnce`, after every other change to the body, moves the request to where Anthropic's Vertex SDK sends it (`provider.VertexClaudeRequest`): `/publishers/anthropic/models/:streamRawPredict` when the body streams, `:rawPredict` when it doesn't, the model out of the body; count_tokens to `count-tokens:rawPredict` with the model kept (`countTokens` counts at a provider whose `Base(Anthropic)` is set); `anthropic_version` `vertex-2023-10-16` added unless the body has one; Claude Code's `?beta=true` never sent. `thinkingOffAsTaken` and `samplingAsTaken` run before, so they read the model from the body. Tool search's beta goes as `tool-search-tool-2025-10-19`, the name Claude Code gives it for Vertex as for Bedrock (`bedrockBetas`); Bedrock's left-out betas aren't left out for it. Gemini's effort rules (`vertexEffort`) don't touch it (`TestVertexClaudeModel`). A partner model (`provider.VertexPartner`: a `publisher/model` id such as `deepseek-ai/deepseek-v4.1-flash-maas`) goes to Google's OpenAI-compatible `/endpoints/openapi/chat/completions` (`Base(Chat)`, `ListedAPIs`), signed with the same token, its full id in the body. It is relayed or translated there as any chat completions vendor is, and none of the Gemini rules below (`vertexEffort`, `vertexThinking`, signatures) touch it (`TestVertexPartnerModel`). A Gemini model's request goes to `/publishers/google/models/:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` (or AI Studio's `Corrupted thought signature.`, `signatureRefused`) is asked again with every call sent so (`withoutSignatures`), for that request only, at any upstream Gemini's signatures reach (`signaturesReach`), relayed too; it rests no account and lets a group go on (`restAfterMarked`, `shapeRefused`). A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts; that retry is the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) | diff --git a/internal/gateway/upstream_closed_unsent_test.go b/internal/gateway/upstream_closed_unsent_test.go index 9dd7653bd..45321acfa 100644 --- a/internal/gateway/upstream_closed_unsent_test.go +++ b/internal/gateway/upstream_closed_unsent_test.go @@ -116,7 +116,7 @@ func closedUnsentClient(t *testing.T) *http.Client { was := unsentAgain unsentAgain = []time.Duration{5 * time.Millisecond, 5 * time.Millisecond} t.Cleanup(func() { unsentAgain = was }) - tr := vendorTransport(time.Minute) + tr := plainVendorTransport(time.Minute) tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} var h1 http.Protocols h1.SetHTTP1(true) diff --git a/internal/gateway/upstream_h2_calm_test.go b/internal/gateway/upstream_h2_calm_test.go new file mode 100644 index 000000000..edd748900 --- /dev/null +++ b/internal/gateway/upstream_h2_calm_test.go @@ -0,0 +1,312 @@ +package gateway + +import ( + "bytes" + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "io" + "math/big" + "net" + "net/http" + "strings" + "sync" + "testing" + "time" + + "golang.org/x/net/http2" + "golang.org/x/net/http2/hpack" + + "github.com/yetone/magpie/internal/netproxy" +) + +// pingPolicyVendor is an HTTP/2 vendor that answers each request after a +// silence, and holds its clients to gRPC's ping policy, as Google's front +// end does (grpc keepalive.md, chttp2's ping abuse policy): a ping that +// comes within minGap of the last one, with no HEADERS or DATA sent +// between, is a strike, and past two strikes the connection ends with +// GOAWAY ENHANCE_YOUR_CALM "too_many_pings". +type pingPolicyVendor struct { + ln net.Listener + cert *x509.Certificate + silence time.Duration + minGap time.Duration + + mu sync.Mutex + conns int + pings []time.Time + goaways int + wg sync.WaitGroup +} + +func newPingPolicyVendor(t *testing.T, silence, minGap time.Duration) *pingPolicyVendor { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "127.0.0.1"}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1").To4()}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + IsCA: true, + BasicConstraintsValid: true, + } + der, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + cert, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + v := &pingPolicyVendor{ln: ln, cert: cert, silence: silence, minGap: minGap} + conf := &tls.Config{ + Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}, + NextProtos: []string{"h2"}, + } + var open []net.Conn + v.wg.Add(1) + go func() { + defer v.wg.Done() + for { + c, err := ln.Accept() + if err != nil { + return + } + v.mu.Lock() + v.conns++ + open = append(open, c) + v.mu.Unlock() + v.wg.Add(1) + go func() { + defer v.wg.Done() + defer c.Close() + v.serve(tls.Server(c, conf)) + }() + } + }() + t.Cleanup(func() { + ln.Close() + v.mu.Lock() + for _, c := range open { + c.Close() + } + v.mu.Unlock() + v.wg.Wait() + }) + return v +} + +func (v *pingPolicyVendor) Addr() string { return v.ln.Addr().String() } + +func (v *pingPolicyVendor) serve(c *tls.Conn) { + preface := make([]byte, len(http2.ClientPreface)) + if _, err := io.ReadFull(c, preface); err != nil || string(preface) != http2.ClientPreface { + return + } + fr := http2.NewFramer(c, c) + var wmu sync.Mutex + write := func(f func() error) error { + wmu.Lock() + defer wmu.Unlock() + return f() + } + if write(func() error { return fr.WriteSettings() }) != nil { + return + } + // the policy's state: chttp2 resets both when it sends HEADERS or DATA + var pmu sync.Mutex + var lastPing time.Time + strikes := 0 + var lastStream uint32 + for { + f, err := fr.ReadFrame() + if err != nil { + return + } + switch f := f.(type) { + case *http2.SettingsFrame: + if !f.IsAck() { + write(fr.WriteSettingsAck) + } + case *http2.PingFrame: + if f.IsAck() { + continue + } + now := time.Now() + v.mu.Lock() + v.pings = append(v.pings, now) + v.mu.Unlock() + pmu.Lock() + if !lastPing.IsZero() && now.Sub(lastPing) < v.minGap { + strikes++ + } + lastPing = now + calm := strikes > 2 + last := lastStream + pmu.Unlock() + if calm { + v.mu.Lock() + v.goaways++ + v.mu.Unlock() + write(func() error { + return fr.WriteGoAway(last, http2.ErrCodeEnhanceYourCalm, []byte("too_many_pings")) + }) + // the in-flight stream is not answered: GFE closes it + time.Sleep(50 * time.Millisecond) + return + } + data := f.Data + write(func() error { return fr.WritePing(true, data) }) + case *http2.HeadersFrame: + id := f.StreamID + pmu.Lock() + lastStream = id + pmu.Unlock() + v.mu.Lock() + silence := v.silence + v.mu.Unlock() + go func() { + time.Sleep(silence) + var hb bytes.Buffer + enc := hpack.NewEncoder(&hb) + enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) + enc.WriteField(hpack.HeaderField{Name: "content-type", Value: "text/plain"}) + pmu.Lock() + strikes, lastPing = 0, time.Time{} + pmu.Unlock() + write(func() error { + if err := fr.WriteHeaders(http2.HeadersFrameParam{StreamID: id, BlockFragment: hb.Bytes(), EndHeaders: true}); err != nil { + return err + } + return fr.WriteData(id, true, []byte("thought it through")) + }) + }() + } + } +} + +// policyPings has the gateway's transports, made after it, trust vendor, +// and ping as the real ones do with the times scaled down: a silence's +// first ping after 100ms (PingAfter, 10s), the next 1s on (PingAgain, +// 5 minutes), against a vendor whose minimum gap is 600ms (gRPC's 5 +// minutes): room on both sides of it. +func policyPings(t *testing.T, vendor *pingPolicyVendor) { + pool := x509.NewCertPool() + pool.AddCert(vendor.cert) + wasTLS := upstreamTLS + wasAfter, wasWait, wasAgain := netproxy.PingAfter, netproxy.PingWait, netproxy.PingAgain + upstreamTLS = &tls.Config{RootCAs: pool, ServerName: "127.0.0.1"} + netproxy.PingAfter, netproxy.PingWait, netproxy.PingAgain = 100*time.Millisecond, time.Second, time.Second + t.Cleanup(func() { + upstreamTLS = wasTLS + netproxy.PingAfter, netproxy.PingWait, netproxy.PingAgain = wasAfter, wasWait, wasAgain + }) +} + +// zdevoz (Discord): gemini-4-argon through Antigravity thought for about +// four minutes before its first byte, and Google ended the connection: +// "http2: server sent GOAWAY and closed the connection; LastStreamID=3, +// ErrCode=ENHANCE_YOUR_CALM, debug=\"too_many_pings\"". The turn was lost +// at ~235s and sent again from the start. Go's HTTP/2 health check pinged +// the silent connection every PingAfter (its ping's own answer restarts +// the clock), 24 pings in four minutes; Google's front end takes pings +// that close together with nothing sent between as abuse. Now a silence +// gets its first ping at PingAfter, and the next PingAgain later, so the +// vendor thinking for 2.5 (scaled) minutes answers on the first try. +func TestLongSilenceIsNotPingedIntoGoaway(t *testing.T) { + fresh(t) + vendor := newPingPolicyVendor(t, 2500*time.Millisecond, 600*time.Millisecond) + policyPings(t, vendor) + s := New() + t.Cleanup(s.client.CloseIdleConnections) + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, http.MethodPost, + "https://"+vendor.Addr()+"/v1internal:streamGenerateContent?alt=sse", strings.NewReader(`{"request":{}}`)) + began := time.Now() + res, err := s.client.Do(req) + took := time.Since(began) + vendor.mu.Lock() + pings := append([]time.Time(nil), vendor.pings...) + goaways, conns := vendor.goaways, vendor.conns + vendor.mu.Unlock() + if err != nil { + t.Fatalf("the turn failed after %v, %d pings, %d GOAWAYs: %v", took, len(pings), goaways, err) + } + b, err := io.ReadAll(res.Body) + res.Body.Close() + if err != nil || string(b) != "thought it through" { + t.Fatalf("the turn's answer: %q, %v", b, err) + } + if goaways != 0 || conns != 1 { + t.Fatalf("%d GOAWAYs over %d connections; want the turn answered on its one connection", goaways, conns) + } + // a silence is still pinged, from PingAfter on, so a dead path is + // found as soon as before (#4936) + if len(pings) == 0 { + t.Fatal("the silent connection was never pinged") + } + if len(pings) > 4 { + t.Fatalf("%d pings in a %v silence; want one at PingAfter and one each PingAgain", len(pings), vendor.silence) + } + if d := pings[0].Sub(began); d > time.Second { + t.Fatalf("the first ping came %v into the silence; want it about PingAfter (100ms) in", d) + } +} + +// A GOAWAY ends the connection it came on, and the try sent again goes out +// on a new one, never the connection that refused it. +func TestTryAfterGoawayDialsAnew(t *testing.T) { + fresh(t) + // a vendor whose minimum gap is longer than PingAgain: the third ping + // of a silence ends the connection + vendor := newPingPolicyVendor(t, 2500*time.Millisecond, 5*time.Second) + policyPings(t, vendor) + netproxy.PingAgain = 300 * time.Millisecond + tr := vendorTransport(time.Minute) + t.Cleanup(tr.CloseIdleConnections) + cl := &http.Client{Transport: tr} + ask := func() error { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "https://"+vendor.Addr()+"/turn", strings.NewReader("{}")) + res, err := cl.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + _, err = io.ReadAll(res.Body) + return err + } + err := ask() + if err == nil || !strings.Contains(err.Error(), "too_many_pings") { + t.Fatalf("the turn on a vendor that refuses the pings: %v; want its GOAWAY", err) + } + vendor.mu.Lock() + vendor.silence = 0 + vendor.mu.Unlock() + if err := ask(); err != nil { + t.Fatalf("the try after the GOAWAY: %v", err) + } + vendor.mu.Lock() + conns := vendor.conns + vendor.mu.Unlock() + if conns != 2 { + t.Fatalf("%d connections dialled; want the try after the GOAWAY on a new one", conns) + } +} diff --git a/internal/gateway/upstream_transport.go b/internal/gateway/upstream_transport.go index 4a2c2e9c2..9c9d14c19 100644 --- a/internal/gateway/upstream_transport.go +++ b/internal/gateway/upstream_transport.go @@ -66,7 +66,16 @@ var uploadStall = time.Minute // vendorTransport is a transport to the vendors that gives one wait to // begin answering, none for 0: the request's context then bounds it. +// A silent HTTP/2 connection is pinged and dropped (#2843), by a health +// check that doesn't ping a vendor still thinking into ending the +// connection (netproxy.CalmHTTP2). func vendorTransport(wait time.Duration) *http.Transport { + t := plainVendorTransport(wait) + netproxy.CalmHTTP2(t) + return t +} + +func plainVendorTransport(wait time.Duration) *http.Transport { return &http.Transport{ Proxy: netproxy.Func, ResponseHeaderTimeout: wait, @@ -74,8 +83,6 @@ func vendorTransport(wait time.Duration) *http.Transport { IdleConnTimeout: 90 * time.Second, ForceAttemptHTTP2: true, TLSClientConfig: upstreamTLS, - // a silent HTTP/2 connection is pinged and dropped (#2843) - HTTP2: netproxy.HTTP2Health(), } } @@ -87,7 +94,7 @@ func vendorTransport(wait time.Duration) *http.Transport { // write that moves no bytes ends the connection (WriteByteTimeout), and a // vendor that never begins answering is ended by the response header wait. func uploadTransport(wait time.Duration) *http.Transport { - t := vendorTransport(wait) + t := plainVendorTransport(wait) t.HTTP2 = &http.HTTP2Config{WriteByteTimeout: uploadStall} return t } diff --git a/internal/netproxy/calm.go b/internal/netproxy/calm.go new file mode 100644 index 000000000..c1f3c9928 --- /dev/null +++ b/internal/netproxy/calm.go @@ -0,0 +1,351 @@ +package netproxy + +import ( + "context" + "crypto/tls" + "errors" + "net" + "net/http" + "sync" + "time" + + "golang.org/x/net/http2" +) + +// PingAgain is how long a connection still silent after its first health +// ping waits for the next (CalmHTTP2): gRPC's servers, Google's among +// them, count a ping that comes sooner after the last, with nothing sent +// between, as a strike, and end the connection at the third. +var PingAgain = 5 * time.Minute + +// CalmHTTP2 has t, a transport to the vendors, speak HTTP/2 with a health +// check of magpie's own instead of Go's (HTTP2Health). Go's pings a +// connection each time it has read no frame for PingAfter, and the ping's +// own answer is a frame, so a vendor silent for minutes before a turn's +// first byte is pinged every 10s for all of them. Google's front end +// counts the pings it gets while it has sent nothing and ends the +// connection: GOAWAY ENHANCE_YOUR_CALM "too_many_pings" after about four +// minutes of gemini thinking through Antigravity, and the turn was lost +// and sent again (zdevoz on Discord). gRPC's servers, Google's among them, +// take a ping as abuse when it comes within 5 minutes of the last one +// with no HEADERS or DATA sent between (keepalive.md: +// GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS). +// +// Here the first ping of a silence still goes out PingAfter into it, so a +// connection whose path died before or as a request went out is found as +// soon as before (#2843, #4936), and dropped when no answer comes within +// PingWait. A silence starts at the vendor's last HEADERS or DATA, or at a +// request handed to the connection. A ping answered shows the path alive, +// and the next waits PingAgain: a 4-minute wait for a first byte has one +// ping, not twenty-four. A path that dies later in a long wait is found at +// the next ping, or by the request's own wait for its answer. +// +// t's settings are read now: CalmHTTP2 is called once t is set up, and a +// clone of t is calmed again with its own connections (Dispatch). +func CalmHTTP2(t *http.Transport) error { + if _, ok := calmed.Load(t); ok { + return nil + } + p := &calmPool{conns: map[string][]*calmConn{}} + // set before anything clones t: a clone (or a first request) has + // net/http settle t's HTTP/2 once, and it takes the "https" protocol's + // one field as the HTTP/2 transport whose idle connections it closes + // with its own (CloseIdleConnections) + if t.TLSClientConfig == nil { + t.TLSClientConfig = &tls.Config{} + } else { + t.TLSClientConfig = t.TLSClientConfig.Clone() + } + t.TLSClientConfig.NextProtos = []string{"h2", "http/1.1"} + t.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{ + "h2": func(authority string, c *tls.Conn) http.RoundTripper { + if err := p.add(authority, c); err != nil { + go c.Close() + return erringRoundTripper{err} + } + return p.t2 + }, + } + t.RegisterProtocol("https", calmAlt{Pool: p}) + + // x/net's HTTP/2 reads its settings (ResponseHeaderTimeout, + // IdleConnTimeout, DisableCompression…) from the transport it was + // configured on; this copy is that and never dials + conf := t.Clone() + conf.TLSNextProto = nil + if t.HTTP2 != nil { + h := *t.HTTP2 + h.SendPingTimeout, h.PingTimeout = 0, 0 + conf.HTTP2 = &h + } + t2, err := http2.ConfigureTransports(conf) + if err != nil { + return err + } + t2.ReadIdleTimeout, t2.PingTimeout = 0, 0 + t2.ConnPool = p + p.t2 = t2 + calmed.Store(t, p) + return nil +} + +// calmed is every transport CalmHTTP2 set up, so a clone is set up anew. +var calmed sync.Map // *http.Transport -> *calmPool + +func isCalm(t *http.Transport) bool { + _, ok := calmed.Load(t) + return ok +} + +// calmAlt is a calmed transport's https protocol: a request goes on a +// kept HTTP/2 connection, or back to net/http to dial one. +type calmAlt struct{ Pool *calmPool } + +func (a calmAlt) RoundTrip(req *http.Request) (*http.Response, error) { + res, err := a.Pool.t2.RoundTrip(req) + if noCachedConn(err) { + return nil, http.ErrSkipAltProtocol + } + return res, err +} + +func noCachedConn(err error) bool { + var n interface{ IsHTTP2NoCachedConnError() } + return err != nil && errors.As(err, &n) +} + +type erringRoundTripper struct{ err error } + +func (e erringRoundTripper) RoundTripErr() error { return e.err } +func (e erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, e.err } + +// calmPool keeps a calmed transport's HTTP/2 connections, by host:port. +// It never dials: net/http does, through the transport's proxy, and hands +// the connection over (TLSNextProto). +type calmPool struct { + t2 *http2.Transport + mu sync.Mutex + conns map[string][]*calmConn +} + +type calmConn struct { + cc *http2.ClientConn + w *watchedConn +} + +func (p *calmPool) add(authority string, c *tls.Conn) error { + // net/http hands a connection over for a request + now := time.Now() + w := &watchedConn{Conn: c, read: now, ask: now} + cc, err := p.t2.NewClientConn(w) + if err != nil { + return err + } + p.mu.Lock() + p.conns[authority] = append(p.conns[authority], &calmConn{cc: cc, w: w}) + p.mu.Unlock() + go watch(cc, w, PingAfter, PingWait, PingAgain) + return nil +} + +func (p *calmPool) GetClientConn(req *http.Request, addr string) (*http2.ClientConn, error) { + p.mu.Lock() + defer p.mu.Unlock() + kept := p.conns[addr][:0] + var got *calmConn + for _, c := range p.conns[addr] { + if c.cc.State().Closed { + continue + } + kept = append(kept, c) + if got == nil && c.cc.ReserveNewRequest() { + got = c + } + } + p.conns[addr] = kept + if got == nil { + return nil, http2.ErrNoCachedConn + } + got.w.asked() + return got.cc, nil +} + +func (p *calmPool) MarkDead(cc *http2.ClientConn) { + p.mu.Lock() + defer p.mu.Unlock() + for addr, cs := range p.conns { + for i, c := range cs { + if c.cc == cc { + p.conns[addr] = append(cs[:i:i], cs[i+1:]...) + return + } + } + } +} + +// CloseIdleConnections shuts every connection no request is on; one a +// request takes meanwhile is let finish it. +func (p *calmPool) CloseIdleConnections() { + p.mu.Lock() + var idle []*http2.ClientConn + for addr, cs := range p.conns { + kept := cs[:0] + for _, c := range cs { + s := c.cc.State() + if s.StreamsActive == 0 && s.StreamsReserved == 0 && s.StreamsPending == 0 { + idle = append(idle, c.cc) + continue + } + kept = append(kept, c) + } + p.conns[addr] = kept + } + p.mu.Unlock() + for _, cc := range idle { + go func() { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + if cc.Shutdown(ctx) != nil { + cc.Close() + } + }() + } +} + +// errLostPing is a connection's end when its health ping went unanswered, +// in Go's own words for it (closeForLostPing), which lostPing reads. +var errLostPing = errors.New("http2: client connection lost") + +// watch is a calmed connection's health check (CalmHTTP2), until the +// connection closes. +func watch(cc *http2.ClientConn, w *watchedConn, after, wait, again time.Duration) { + tick := time.NewTicker(max(after/10, time.Millisecond)) + defer tick.Stop() + var pinged time.Time + for range tick.C { + if cc.State().Closed || w.isLost() { + return + } + read, fresh := w.times() + now := time.Now() + var due time.Time + if pinged.Before(fresh) { + // the first ping of a silence + due = later(read, fresh).Add(after) + } else { + due = pinged.Add(again) + } + if now.Before(due) { + continue + } + pinged = now + ctx, cancel := context.WithTimeout(context.Background(), wait) + err := cc.Ping(ctx) + cancel() + if err != nil { + if !cc.State().Closed { + w.lose() + } + return + } + } +} + +func later(a, b time.Time) time.Time { + if a.After(b) { + return a + } + return b +} + +// watchedConn is a calmed HTTP/2 connection's TLS connection, which notes +// when a frame came, and when the vendor last sent HEADERS or DATA. +type watchedConn struct { + *tls.Conn + mu sync.Mutex + read time.Time // the last bytes read + spoke time.Time // the last HEADERS, CONTINUATION or DATA frame read + ask time.Time // the last request handed the connection + scan frameScan + lost bool +} + +func (w *watchedConn) Read(b []byte) (int, error) { + n, err := w.Conn.Read(b) + w.mu.Lock() + defer w.mu.Unlock() + if n > 0 { + now := time.Now() + w.read = now + if w.scan.spoke(b[:n]) { + w.spoke = now + } + } + if err != nil && w.lost { + err = errLostPing + } + return n, err +} + +func (w *watchedConn) asked() { + w.mu.Lock() + w.ask = time.Now() + w.mu.Unlock() +} + +// times is when bytes last came, and when the silence began: the +// vendor's last HEADERS or DATA, or the last request, whichever is later. +func (w *watchedConn) times() (read, fresh time.Time) { + w.mu.Lock() + defer w.mu.Unlock() + return w.read, later(w.spoke, w.ask) +} + +func (w *watchedConn) lose() { + w.mu.Lock() + w.lost = true + w.mu.Unlock() + w.Conn.NetConn().Close() +} + +func (w *watchedConn) isLost() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.lost +} + +// frameScan follows HTTP/2 frames through the bytes read, by their +// 9-byte headers (RFC 9113 4.1). +type frameScan struct { + head [9]byte + have int // header bytes held + left int // payload bytes still to come +} + +// spoke says a HEADERS (1), CONTINUATION (9) or DATA (0) frame began in b. +func (s *frameScan) spoke(b []byte) bool { + saw := false + for len(b) > 0 { + if s.left > 0 { + n := min(s.left, len(b)) + s.left -= n + b = b[n:] + continue + } + n := copy(s.head[s.have:], b) + s.have += n + b = b[n:] + if s.have < len(s.head) { + break + } + s.have = 0 + s.left = int(s.head[0])<<16 | int(s.head[1])<<8 | int(s.head[2]) + switch s.head[3] { + case 0, 1, 9: + saw = true + } + } + return saw +} + +var _ net.Conn = (*watchedConn)(nil) diff --git a/internal/netproxy/calm_test.go b/internal/netproxy/calm_test.go new file mode 100644 index 000000000..1cc606306 --- /dev/null +++ b/internal/netproxy/calm_test.go @@ -0,0 +1,229 @@ +package netproxy + +import ( + "context" + "crypto/tls" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// hushPipe passes bytes between a client and to until hushed: then it +// goes on taking what either side writes and passes none of it, as a +// tunnel whose far side died does. +type hushPipe struct { + ln net.Listener + hushed atomic.Bool + mu sync.Mutex + conns []net.Conn + dials int +} + +func newHushPipe(t *testing.T, to string) *hushPipe { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + p := &hushPipe{ln: ln} + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + for { + a, err := ln.Accept() + if err != nil { + return + } + b, err := net.Dial("tcp", to) + if err != nil { + a.Close() + continue + } + p.mu.Lock() + p.conns = append(p.conns, a, b) + p.dials++ + p.mu.Unlock() + pump := func(dst, src net.Conn) { + defer wg.Done() + buf := make([]byte, 32<<10) + for { + n, err := src.Read(buf) + if n > 0 && !p.hushed.Load() { + if _, err := dst.Write(buf[:n]); err != nil { + return + } + } + if err != nil { + return + } + } + } + wg.Add(2) + go pump(a, b) + go pump(b, a) + } + }() + t.Cleanup(func() { + ln.Close() + p.mu.Lock() + for _, c := range p.conns { + c.Close() + } + p.mu.Unlock() + wg.Wait() + }) + return p +} + +func (p *hushPipe) Addr() string { return p.ln.Addr().String() } + +// slowH2 is an HTTP/2 vendor that answers after wait, and counts the +// connections it has open. +func slowH2(t *testing.T, wait time.Duration) (*httptest.Server, *atomic.Int32) { + t.Helper() + var open atomic.Int32 + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + select { + case <-time.After(wait): + case <-r.Context().Done(): + return + } + w.Header().Set("X-Conn", r.RemoteAddr) + io.WriteString(w, r.Proto) + })) + srv.EnableHTTP2 = true + srv.Config.ConnState = func(_ net.Conn, s http.ConnState) { + switch s { + case http.StateNew: + open.Add(1) + case http.StateClosed, http.StateHijacked: + open.Add(-1) + } + } + srv.StartTLS() + t.Cleanup(srv.Close) + return srv, &open +} + +func calmTransport(t *testing.T) *http.Transport { + t.Helper() + tr := &http.Transport{ForceAttemptHTTP2: true, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} + if err := CalmHTTP2(tr); err != nil { + t.Fatal(err) + } + t.Cleanup(tr.CloseIdleConnections) + return tr +} + +func calmAsk(rt http.RoundTripper, ctx context.Context, url string) (string, error) { + got, _, err := calmAskOn(rt, ctx, url) + return got, err +} + +// calmAskOn is calmAsk, and the connection the answer came on, as the +// vendor saw its far end. +func calmAskOn(rt http.RoundTripper, ctx context.Context, url string) (string, string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader("{}")) + if err != nil { + return "", "", err + } + res, err := rt.RoundTrip(req) + if err != nil { + return "", "", err + } + defer res.Body.Close() + b, err := io.ReadAll(res.Body) + return string(b), res.Header.Get("X-Conn"), err +} + +// A path that dies after the first ping of a long silence was answered is +// found at the next one, PingAgain on, and the request on it fails in +// Go's words for a lost ping, which the gateway's lostPing reads. +func TestCalmFindsAPathDeadLaterInTheSilence(t *testing.T) { + scalePings(t, 100*time.Millisecond, 300*time.Millisecond, 800*time.Millisecond) + srv, _ := slowH2(t, 30*time.Second) + pipe := newHushPipe(t, srv.Listener.Addr().String()) + tr := calmTransport(t) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + go func() { + // after the first ping (100ms) and its answer + time.Sleep(450 * time.Millisecond) + pipe.hushed.Store(true) + }() + began := time.Now() + _, err := calmAsk(tr, ctx, "https://"+pipe.Addr()+"/turn") + took := time.Since(began) + if err == nil { + t.Fatal("the turn on a dead path was answered") + } + if !strings.Contains(err.Error(), "http2: client connection lost") { + t.Fatalf("the turn failed with %v after %v; want the lost ping", err, took) + } + // the next ping goes PingAgain after the first (~900ms), and is lost + // PingWait later (~1.2s) + if took < 800*time.Millisecond || took > 10*time.Second { + t.Fatalf("the dead path was found after %v; want at the ping PingAgain after the first", took) + } +} + +// CloseIdleConnections closes a calmed transport's HTTP/2 connections, as +// it closes Go's own: the gateway drops them when the proxy or region +// moves (#4523, #5182). A Dispatch clone, for a provider's own proxy, +// keeps connections of its own, dialled through that proxy, never base's. +func TestCalmIdleConnectionsCloseAndClonesKeepTheirOwn(t *testing.T) { + srv, open := slowH2(t, 0) + u := "https://" + srv.Listener.Addr().String() + "/turn" + tr := calmTransport(t) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + for range 2 { + if got, err := calmAsk(tr, ctx, u); err != nil || got != "HTTP/2.0" { + t.Fatalf("a request: %q, %v; want HTTP/2.0", got, err) + } + } + if n := open.Load(); n != 1 { + t.Fatalf("%d connections open after two requests; want one, kept", n) + } + tr.CloseIdleConnections() + waitFor(t, func() bool { return open.Load() == 0 }, "the idle HTTP/2 connection to close") + + d := Dispatch(tr) + // the clone first: a connection it dialled and left in base's pool + // would carry base's next request + got, own, err := calmAskOn(d, With(ctx, "direct"), u) + if err != nil || got != "HTTP/2.0" { + t.Fatalf("a request through a provider's own proxy: %q, %v", got, err) + } + got, base, err := calmAskOn(d, ctx, u) + if err != nil || got != "HTTP/2.0" { + t.Fatalf("a request through base: %q, %v", got, err) + } + if base == own { + t.Fatalf("base's request went on the clone's connection (%s)", own) + } + if n := open.Load(); n != 2 { + t.Fatalf("%d connections open; want base's and the clone's own", n) + } + d.(interface{ CloseIdleConnections() }).CloseIdleConnections() + waitFor(t, func() bool { return open.Load() == 0 }, "base's and the clone's idle connections to close") +} + +func waitFor(t *testing.T, ok func() bool, what string) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for !ok() { + if time.Now().After(deadline) { + t.Fatalf("waited 10s for %s", what) + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/internal/netproxy/deadpath_test.go b/internal/netproxy/deadpath_test.go index e6070e062..51dcf0a4a 100644 --- a/internal/netproxy/deadpath_test.go +++ b/internal/netproxy/deadpath_test.go @@ -26,9 +26,44 @@ import ( // connection). The test watches the bound with the timings scaled down: a // holed connection is pinged at PingAfter, dropped at PingAfter+PingWait, // and the try on it fails with the connection, while the next one dials -// anew and succeeds. +// anew and succeeds. The same holds for Go's own health check, which +// DefaultTransport has (HTTP2Health), and for the gateway's (CalmHTTP2). func TestRequestOnAHoledConnectionFailsAtThePing(t *testing.T) { pingAfter, pingWait := time.Second, 500*time.Millisecond + t.Run("HTTP2Health", func(t *testing.T) { + holedTry(t, pingAfter, pingWait, &http.Transport{ + ForceAttemptHTTP2: true, + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + HTTP2: &http.HTTP2Config{SendPingTimeout: pingAfter, PingTimeout: pingWait}, + }) + }) + t.Run("CalmHTTP2", func(t *testing.T) { + scalePings(t, pingAfter, pingWait, time.Minute) + tr := &http.Transport{ + ForceAttemptHTTP2: true, + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } + if err := CalmHTTP2(tr); err != nil { + t.Fatal(err) + } + // the gateway's lostPing knows the ping's failure by Go's words + if said := holedTry(t, pingAfter, pingWait, tr); !strings.Contains(said, "http2: client connection lost") { + t.Fatalf("the turn failed with %q; want Go's words for a lost ping", said) + } + }) +} + +func scalePings(t *testing.T, after, wait, again time.Duration) { + wasAfter, wasWait, wasAgain := PingAfter, PingWait, PingAgain + PingAfter, PingWait, PingAgain = after, wait, again + t.Cleanup(func() { PingAfter, PingWait, PingAgain = wasAfter, wasWait, wasAgain }) +} + +// holedTry runs a request on a connection whose path died through tr, +// which pings after pingAfter and waits pingWait for the answer, and one +// after it. +func holedTry(t *testing.T, pingAfter, pingWait time.Duration, tr *http.Transport) string { + t.Cleanup(tr.CloseIdleConnections) // The vendor, speaking HTTP/2 over TLS on a listener the shim pumps // raw bytes into, as a CONNECT tunnel would. @@ -96,11 +131,7 @@ func TestRequestOnAHoledConnectionFailsAtThePing(t *testing.T) { } } - client := &http.Client{Transport: &http.Transport{ - ForceAttemptHTTP2: true, - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - HTTP2: &http.HTTP2Config{SendPingTimeout: pingAfter, PingTimeout: pingWait}, - }} + client := &http.Client{Transport: tr, Timeout: 20 * time.Second} post := func() (time.Duration, int, error) { start := time.Now() req, err := http.NewRequest("POST", "https://"+shim.Addr().String()+"/turn", nil) @@ -150,6 +181,7 @@ func TestRequestOnAHoledConnectionFailsAtThePing(t *testing.T) { if dials != 2 { t.Fatalf("the vendor was dialed %d times; want the retry on a connection of its own", dials) } + return said } func containsAny(s string, subs ...string) bool { diff --git a/internal/netproxy/netproxy.go b/internal/netproxy/netproxy.go index b92bda7f8..2f4a019c4 100644 --- a/internal/netproxy/netproxy.go +++ b/internal/netproxy/netproxy.go @@ -27,7 +27,7 @@ import ( // Install routes http.DefaultTransport (and so http.DefaultClient) through // Func, and http.DefaultClient's requests made on a provider's behalf // (With) through a transport of that provider's proxy (Dispatch). Its -// HTTP/2 connections are checked as the gateway's are (HTTP2Health), and +// HTTP/2 connections are checked by Go's own pings (HTTP2Health), and // the requests magpie sends on its own are written down (probelog). func Install() { if t, ok := http.DefaultTransport.(*http.Transport); ok { @@ -61,7 +61,10 @@ var PingAfter, PingWait = 10 * time.Second, 10 * time.Second // (#2843). A ping finds it, and the requests on it fail, so a group moves // on and the next request dials anew. A live vendor answers a ping // whatever its streams are doing, so a long wait for a first byte is -// never cut by it. +// never cut by it. But a ping's answer restarts the clock, so a wait of +// minutes is pinged every PingAfter, which Google's front end ends the +// connection for: the gateway's transports ping by CalmHTTP2 instead, and +// this is for http.DefaultTransport's short requests. func HTTP2Health() *http.HTTP2Config { return &http.HTTP2Config{SendPingTimeout: PingAfter, PingTimeout: PingWait} } @@ -282,6 +285,14 @@ func (d *dispatch) transport(r route) *http.Transport { if r.unchecked != "" { uncheckTLS(t) } + if isCalm(d.base) { + // a clone shares base's HTTP/2 connections, dialled through + // base's proxy, until it is given its own + t.TLSNextProto = nil + if !r.h1 { + CalmHTTP2(t) + } + } d.own[r] = t return t }