diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 7856b60bc..3c5fa6685 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -303,7 +303,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`). - A request refused for its bytes (`byteCapRefusal` in [`body_cap.go`](../../internal/gateway/body_cap.go): a 413, or words such as Command Code's 400 "Request body is 40.1 MB, over the 32 MB limit for one request (33554432 bytes)", EDwinpzy on Discord; never a 401, 403, 429 or a context overflow) is asked again in `forward` with its oldest history images left out (`refitOverCap`), up to three times. The cap is the smallest size the refusal names below what was sent, else three quarters of what was sent, and it is kept per provider id for as long as magpie runs (`bodyCaps`), so the next request near it is fitted in `forwardOnce` before it goes (`withinCap`). A request is fitted to three quarters of the cap. Each left-out image becomes a text part, "[An earlier image was left out here to keep this request under its size limit.]", which names neither magpie nor the vendor. The latest user message's images (`latestUser`: not a tool result, not Codex's compaction prompt) and every text, tool output included, stay; the rest of the body keeps its bytes. When leaving out every earlier image can't bring it under, or it is refused at every size, the agent gets a 413 `request_too_large` naming the size, the cap and what was kept (`overCap`), so Codex is told `context_length_exceeded` and its compaction goes on to the text-only ask (`summaryTooLarge`, `plainCompact`) instead of sending the same body into the compaction guard's hold. Every route reaches it, magpie's own (compaction, titles, the classifier, search, vision) included, since they all go through `forward`. - The vendor's reply headers a provider passes on (`ReplyHeaders` and the default request ids, see [providers and accounts](providers-accounts.md), #4145) reach the agent from the reply it is given alone. Every request that can become the agent's reply goes out through `forward` (relayed, translated, a plugin's fetch, a signed-in account) or `retrieveAs`/`retrieveOpen` (embeddings, audio), and each tells its reply's passed headers to the try that asked through the try's context (`withReplySink`, `heardReply` in [`reply_headers.go`](../../internal/gateway/reply_headers.go)). The sink is the try's `holdWriter` (`heardUpstream`), so a try that fails and is let go takes its vendor's headers with it, a fallback's reply carries the provider that answered's, and a failure `release`d to the agent carries its own vendor's. A reply to another provider (a side model, a searcher) is not heard: the sink takes its own provider's alone. Within a try the last reply replaces the earlier ones (an ask again without a refused beta, a Mantle reroute), and once the try has its status nothing more is heard (a cut reply's continuation). count_tokens writes them straight (`passReplyHeaders`), and embeddings through `heardHeaders`. A stream whose headers `keepAlive` sent before the vendor answered (past `keepHeldAfter`) has none: they can't follow a status already sent. Not carried: images, video and the Codex backend relay, which copies its reply's headers whole already. `TestReplyHeadersPassedOn`, `TestReplyHeadersOfTheReplyGiven`, `TestReplyHeadersOnCountTokens`, `TestReplyHeadersOnEmbeddings`. - The agent's request headers a provider passes on (`PassHeaders`, see [providers and accounts](providers-accounts.md); 3jRzfF52Qx on X) go with every try `forwardOnce` makes, so chat, responses, messages, count_tokens, a group's members, fallbacks, signed-in accounts and a plugin's fetch all take them: `forwardOnce` puts the agent's headers in the try's context under the try's provider id (`provider.WithClientHeaders`), and `Provider.Sign` passes the ones that provider lists and no other's. Not carried: embeddings, images, video and the Codex backend relay, which don't go through `forwardOnce`. `TestPassHeadersReachTheProvider`, `TestPassHeadersOnlyToTheirProvider`. -- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (3s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), one every `keepHeldEvery` (5s), none of the try, so another candidate may still answer in the same stream. It was 15s, and a proxy between the agent and magpie that hangs up on a request with nothing back for about 10s ended every turn slower to its first event: Codex on Windows sends 127.0.0.1 through a Clash-style app's system proxy, `127.*` in its bypass list or not, and its turns ended 499 (mrten_95615 on Discord; `TestHeldStreamHeardBeforeAProxyCuts`). A failure before it is still a status; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A translated stream (`streamTranslated`) whose upstream has begun its reply and then says nothing at all, not even a comment (a relay that sends the rest of a long reply in one burst at its end), is kept alive in the client's own protocol by a ticker beside its reader (`keepThroughSilence`): every `keepaliveEvery` it sends the client's keepalive (`enc.keepalive`: a ping for Anthropic, `response.in_progress` for Responses, a comment for Chat, nothing for Gemini), which also counts as the try heard from, so the held stream's comments go on too; it stops once the upstream has been silent for `translatedQuietLongest` (30 minutes), past the 10 minutes `upstreamHeaderWait` gives a vendor to begin and long enough for a long reasoning turn sent whole at its end, after which the client's own timeout ends the wait (youyo.p on Discord: before, Claude Code heard only comments, which its event watchdog doesn't count, and gave up 300s on; `TestTranslatedSilenceKeptAliveForABound`). An upstream that has answered its headers but sent no byte yet is still waited for under the held stream's comments alone (`notAnAPIReply` reads its first bytes before the reply is translated). An Anthropic client is sent a ping at most once each `pingEvery` (1 minute), comments between, and none before `message_start`: Claude Code's watchdog counts only 30 pings in a row as life, and a ping on every upstream keepalive spent them in the first minute; the SDKs' `MessageStream` fails on any event before `message_start` (`anthropicEncoder.keepalive`, `TestTranslatedStreamKeepsClientAlive`). A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a Chat stream a vendor ends with `finish_reason:"error"` — WorkBuddy's and a DeepSeek harness's word for a turn it failed, not finished (#2471) — is the failure the word says, held for the group's next candidate, and nobody rests, as an empty reply's (`TestFinishReasonErrorFailsOver`); a group member's reply that ends having said nothing at all — no text, no reasoning, no call, in an event that says nothing itself: a Chat `finish_reason` other than `length`, `error` or a filter, Messages' `end_turn`, `stop_sequence` or `tool_use`, a `completed` Responses reply, Gemini's `STOP` — is held as no answer while a member is left (`eventEmptyEnd`, `holdWriter.emptyFails`, 502 `emptyEnded`), so the next member answers and nobody rests; a reply held whole is judged in the one parse `settle` already makes (`readWhole`), and the last member's empty reply, or a model asked alone, goes as it came (#6712: an AI Studio plugin's 200 with a role chunk and `stop`; `TestEmptyStopFailsOverToTheNextMember`, `TestEmptyStopEndsAtTheLastMember`); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`; whatever a relayed stream gets appended, that error or a filled-in `finish_reason`, begins after a blank line, two newlines when the upstream's last write stopped inside a line, so it is an event of its own rather than more of the half-written one, and the half event itself is dropped: a relayed stream holds the line the upstream never ended back, puts it out when the reply ends whole or is gathered (`TestGrokPluginNonStreamLastLineUnended`), and throws it away when a failure is appended in its place, for no client can parse it — pi read "malformed server-sent event JSON" off a stream Z.ai reset mid-line, and died before the error after it; a line whose data parses (its JSON whole, or `[DONE]`) is no half event and goes out before the failure (#2446, #2580, `TestPassthroughStreamCutMidLine`, `TestChatStreamCutMidLineLeavesNoHalfEvent`, `TestChatStreamCutAfterWholeEventKeepsIt`, `TestGeminiCompatFinishAfterPartialLine`), and a Chat one from Gemini's OpenAI-compatible API (`geminiCompat`) with no `finish_reason`, relayed or translated (`saysItsEnd`; Linka on Discord: the upstream hung up between a whole function call and its `finish_reason`, and Pi threw the call away as "Stream ended without finish_reason"; that API counts the usage only once the generation is done, so when the last chunk carried it only the `finish_reason` was lost and it is filled in, `tool_calls` after a call and `stop` otherwise, as a relayed chunk before `[DONE]` or a translated reply's end, and the reply counts as whole (`chatTail`); only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`), and a Chat one from Command Code's API (`commandCodeHost`), whose slow starts a killed worker ends with no closing chunk at all, relayed (esp32gallery on #2471: 20 of 665 requests in a day, every ledger row a 200 with no stop and no error while the client read "Stream ended without finish_reason"; `TestCommandCodeRelayEndedShort`, `TestCommandCodeTaillessFailsOver`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. One such ending is not a cut: a request capped at a short probe's worth (`cutVoidTokens`, 1024) whose reply spent some of it (thought, said or called something) and then ended cleanly with no end said ended at its length (`endsAtProbeCap`), and goes as a `length` stop, translated whole or streamed, and as a `response.incomplete` at `max_output_tokens` when a Responses plugin's stream is asked whole (`gathered`). Open Design's glm-5.3-flash always thinks, spent a model test's 16 tokens on it and ended after `content_block_stop`, so every plain test of it was this 502, waited out through the patience (plugins#827; `TestProbeCapEndsAtLength`, `TestGatheredProbeCapIncomplete`). A reply asked for more, one that spent nothing, or a Gemini or Code Assist one (Gemini ends every reply with its finishReason, `MAX_TOKENS` included, so one without it was cut: `TestGeminiUpstreamEndedShort` asks for 256) is still the cut. A relayed stream (passthrough to an agent of the same protocol) is still relayed as it came, with no end added (#5736). A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A relayed one is read the same way once: a Responses stream whose `response.completed` carries no output and counted no token is no reply either, failed before it is let through, held for the group's next candidate, and nobody rests (#2471, MurmuredVelpro: WorkBuddy AI's account ended Codex's turn completed with `output: []` and all-zero usage three times running, the healthy members never asked; `TestEmptyCompletedFailsOver`). A reply passed through in its own protocol isn't read this way, but for that completed. +- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (3s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), one every `keepHeldEvery` (5s), none of the try, so another candidate may still answer in the same stream. It was 15s, and a proxy between the agent and magpie that hangs up on a request with nothing back for about 10s ended every turn slower to its first event: Codex on Windows sends 127.0.0.1 through a Clash-style app's system proxy, `127.*` in its bypass list or not, and its turns ended 499 (mrten_95615 on Discord; `TestHeldStreamHeardBeforeAProxyCuts`). A failure before it is still a status; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It goes on for as long as a translated stream's do, `translatedQuietLongest` (30 minutes) with nothing from the vendor, and then the try is ended: the client gets a 504 " sent nothing for …", as its stream's error event when the reply has passed, and nothing is tried again after so long a wait (`holdWriter.endStuck`). Before, the comments stopped at `keepaliveLongest` (5 minutes) and the client met only its own idle timeout: pi's "stream idle timeout after 300000ms" on a relayed Claude (Wing8Aqua on X; `TestQuietClaudeStreamKeptAlivePastFiveMinutes`, `TestQuietClaudeStreamStuckEndsWithAnError`). A translated stream (`streamTranslated`) whose upstream has begun its reply and then says nothing at all, not even a comment (a relay that sends the rest of a long reply in one burst at its end), is kept alive in the client's own protocol by a ticker beside its reader (`keepThroughSilence`): every `keepaliveEvery` it sends the client's keepalive (`enc.keepalive`: a ping for Anthropic, `response.in_progress` for Responses, a comment for Chat, nothing for Gemini), which also counts as the try heard from, so the held stream's comments go on too; it stops once the upstream has been silent for `translatedQuietLongest` (30 minutes), past the 10 minutes `upstreamHeaderWait` gives a vendor to begin and long enough for a long reasoning turn sent whole at its end, after which the client's own timeout ends the wait (youyo.p on Discord: before, Claude Code heard only comments, which its event watchdog doesn't count, and gave up 300s on; `TestTranslatedSilenceKeptAliveForABound`). An upstream that has answered its headers but sent no byte yet is still waited for under the held stream's comments alone (`notAnAPIReply` reads its first bytes before the reply is translated). An Anthropic client is sent a ping at most once each `pingEvery` (1 minute), comments between, and none before `message_start`: Claude Code's watchdog counts only 30 pings in a row as life, and a ping on every upstream keepalive spent them in the first minute; the SDKs' `MessageStream` fails on any event before `message_start` (`anthropicEncoder.keepalive`, `TestTranslatedStreamKeepsClientAlive`). A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a Chat stream a vendor ends with `finish_reason:"error"` — WorkBuddy's and a DeepSeek harness's word for a turn it failed, not finished (#2471) — is the failure the word says, held for the group's next candidate, and nobody rests, as an empty reply's (`TestFinishReasonErrorFailsOver`); a group member's reply that ends having said nothing at all — no text, no reasoning, no call, in an event that says nothing itself: a Chat `finish_reason` other than `length`, `error` or a filter, Messages' `end_turn`, `stop_sequence` or `tool_use`, a `completed` Responses reply, Gemini's `STOP` — is held as no answer while a member is left (`eventEmptyEnd`, `holdWriter.emptyFails`, 502 `emptyEnded`), so the next member answers and nobody rests; a reply held whole is judged in the one parse `settle` already makes (`readWhole`), and the last member's empty reply, or a model asked alone, goes as it came (#6712: an AI Studio plugin's 200 with a role chunk and `stop`; `TestEmptyStopFailsOverToTheNextMember`, `TestEmptyStopEndsAtTheLastMember`); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`; whatever a relayed stream gets appended, that error or a filled-in `finish_reason`, begins after a blank line, two newlines when the upstream's last write stopped inside a line, so it is an event of its own rather than more of the half-written one, and the half event itself is dropped: a relayed stream holds the line the upstream never ended back, puts it out when the reply ends whole or is gathered (`TestGrokPluginNonStreamLastLineUnended`), and throws it away when a failure is appended in its place, for no client can parse it — pi read "malformed server-sent event JSON" off a stream Z.ai reset mid-line, and died before the error after it; a line whose data parses (its JSON whole, or `[DONE]`) is no half event and goes out before the failure (#2446, #2580, `TestPassthroughStreamCutMidLine`, `TestChatStreamCutMidLineLeavesNoHalfEvent`, `TestChatStreamCutAfterWholeEventKeepsIt`, `TestGeminiCompatFinishAfterPartialLine`), and a Chat one from Gemini's OpenAI-compatible API (`geminiCompat`) with no `finish_reason`, relayed or translated (`saysItsEnd`; Linka on Discord: the upstream hung up between a whole function call and its `finish_reason`, and Pi threw the call away as "Stream ended without finish_reason"; that API counts the usage only once the generation is done, so when the last chunk carried it only the `finish_reason` was lost and it is filled in, `tool_calls` after a call and `stop` otherwise, as a relayed chunk before `[DONE]` or a translated reply's end, and the reply counts as whole (`chatTail`); only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`), and a Chat one from Command Code's API (`commandCodeHost`), whose slow starts a killed worker ends with no closing chunk at all, relayed (esp32gallery on #2471: 20 of 665 requests in a day, every ledger row a 200 with no stop and no error while the client read "Stream ended without finish_reason"; `TestCommandCodeRelayEndedShort`, `TestCommandCodeTaillessFailsOver`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. One such ending is not a cut: a request capped at a short probe's worth (`cutVoidTokens`, 1024) whose reply spent some of it (thought, said or called something) and then ended cleanly with no end said ended at its length (`endsAtProbeCap`), and goes as a `length` stop, translated whole or streamed, and as a `response.incomplete` at `max_output_tokens` when a Responses plugin's stream is asked whole (`gathered`). Open Design's glm-5.3-flash always thinks, spent a model test's 16 tokens on it and ended after `content_block_stop`, so every plain test of it was this 502, waited out through the patience (plugins#827; `TestProbeCapEndsAtLength`, `TestGatheredProbeCapIncomplete`). A reply asked for more, one that spent nothing, or a Gemini or Code Assist one (Gemini ends every reply with its finishReason, `MAX_TOKENS` included, so one without it was cut: `TestGeminiUpstreamEndedShort` asks for 256) is still the cut. A relayed stream (passthrough to an agent of the same protocol) is still relayed as it came, with no end added (#5736). A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A relayed one is read the same way once: a Responses stream whose `response.completed` carries no output and counted no token is no reply either, failed before it is let through, held for the group's next candidate, and nobody rests (#2471, MurmuredVelpro: WorkBuddy AI's account ended Codex's turn completed with `output: []` and all-zero usage three times running, the healthy members never asked; `TestEmptyCompletedFailsOver`). A reply passed through in its own protocol isn't read this way, but for that completed. - A vendor whose API is the client's own (a relayed request, or a translated one whose upstream error shape is the client's: Chat and Responses share OpenAI's) has its JSON error body go to the client as it came (`writeVendorErrorFrom`, ne9ko9 on Discord): its status, its own `type`, a numeric `code`, `param`, `request_id` and every field magpie knows nothing of. Only `error.message` is magpie's: the provider's name before the vendor's words (a describer asking for another model, the Claude sign-in rewording in `claude_signin.go` and the agent read it there), with a note where magpie has one (an account's `Explain`, a region note, the wrong-endpoint note, `saysBusy`, a 413's byte-limit hint). And a prompt too long for the model (`tooLong`) sets only the fields that make the client's agent compact: status 400, and `type`/`code` (OpenAI's `context_length_exceeded`), `type` and the "prompt is too long: " lead (Anthropic's), `code`/`status` (Gemini's), each spliced in place (`setErrorField`) so every other byte stays. A body that isn't JSON, or not in the client's shape, and another API's error are rebuilt in the client's shape (`writeVendorError`) as before. An error status the hold reads as the safety filter's refusal (`policyRefusal`) is still told in magpie's words once no one else answers ([`kept_error_test.go`](../../internal/gateway/kept_error_test.go)). - A reply that said nothing (`emptyReply`, #667) on `emptyAccounts` (2) accounts of one provider's model running is about the request, not the account: the candidates of that model that remain aren't asked (`emptied` in the candidate loop; other providers and the group's other members still are), and nobody rests (vhjjkkhg on X: Alma's Responses turns to Antigravity's Gemini 3.8 Flash went round 8 to 9 accounts over 10+ minutes). `TestEmptyReplyOnTwoAccountsEndsTheRequest` in `internal/gateway/antigravity_empty_bound_test.go`. - A provider of a key whose errors the user leaves to the client (`errors=pass`, `Provider.PassErrors`, set in its editor's Advanced "Errors" menu or with `magpie provider set errors=pass`; `TakesPassErrors` keeps it to a provider of a key, never a signed-in account or a plugin's; ne9ko9 on Discord) is asked once. The candidate loop's `holdWriter` holds nothing for it (`pass := c.p.PassesErrors()` at the hold choke point; only a stream already begun is held), so no retry, wait, re-plan, refusal handover or next member answers for it; `forward` asks once after `dsRetryGone` (magpie's own file ids), `passthrough` and `forwardTranslated` return the first failure without a re-ask in another shape, `streamTranslated` neither continues nor asks again after an empty reply, and `restAfterMarked` rests none of its keys. Its error goes through `passError` (`pass_errors.go`): on the client's own API the vendor's status, Content-Type and body as sent; on another, the client's shape with the vendor's status, type, code (a number too), param and words, nothing inferred (no too-long, busy or 413 words). Retry-After and the rate-limit headers go with it. `TestPassErrorsAskedOnce`, `TestPassErrorsNotInferred`, `TestPassErrorsOtherAPI` in `internal/gateway/pass_errors_test.go`. diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index be36e15dc..f299a1b20 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -2717,6 +2717,12 @@ type holdWriter struct { // takes; slow says it took longer, and was let go with nothing sent firstWait time.Duration slow bool + // stuck says the vendor said nothing for translatedQuietLongest + // while the agent was kept alive (keepQuiet), and the try was let go: + // the agent is told so as an error, never left with silence + stuck string + // name is the provider's, for what stuck tells the agent + name string // budgeted says firstWait was cut to what was left of the walk's // total time (groupBudget), so its running out is the budget's end, // not this member being slow (#5113) @@ -2863,7 +2869,7 @@ func (h *holdWriter) Write(b []byte) (int, error) { if h.slow { return 0, errSlowStart } - if h.looped != "" || h.relooped { + if h.looped != "" || h.relooped || h.stuck != "" { return 0, errLooped } if h.handedOver { @@ -3850,8 +3856,13 @@ func (h *holdWriter) watch() func() { } // keepQuiet keeps the agent of a stream alive with SSE comments while the -// vendor says nothing, every keepaliveEvery for up to keepaliveLongest -// since it last did: a vendor that sent its 200 and response.created, then +// vendor says nothing, every keepaliveEvery for up to translatedQuietLongest +// since it last did, as a translated reply's client is kept +// (keepThroughSilence), and then ends the try with an error the agent is +// told (endStuck). It stopped at keepaliveLongest (5 minutes) and left the +// agent with nothing: a Claude relay that took longer than that before its +// headers, or quiet mid-reply, had pi's 300s idle timeout end the request +// with no word of why (Wing8Aqua on X). A vendor that sent its 200 and response.created, then // nothing while it reasoned, had the stream held with none of it sent, // and Cloudflare in front of a remote magpie ended the request at 125s // (524) with the agent sent nothing at all; one quiet mid-reply was reset @@ -3859,11 +3870,12 @@ func (h *holdWriter) watch() func() { // comments only (keepAlive), none of the try, which another account may // still answer instead; passed, a comment goes between two lines of it. func (h *holdWriter) keepQuiet() { - if h.slow || h.relooped || h.ended || h.alive == nil || h.alive.proto == provider.Gemini || h.ctx != nil && h.ctx.Err() != nil { + if h.slow || h.relooped || h.ended || h.stuck != "" || h.alive == nil || h.alive.proto == provider.Gemini || h.ctx != nil && h.ctx.Err() != nil { return } - if !h.heard.IsZero() && time.Since(h.heard) >= keepaliveLongest { - return // a stream stuck this long is left for a timeout to end + if !h.heard.IsZero() && time.Since(h.heard) >= translatedQuietLongest { + h.endStuck(time.Since(h.heard)) + return } if !h.passing && h.stream && h.failure == 0 && !h.whole && !h.wantWhole && h.held.Len() > 0 && h.alive.tooQuiet(0) { // a stream held while its vendor is quiet: Codex would hang up @@ -3891,6 +3903,37 @@ func (h *holdWriter) keepQuiet() { } } +// endStuck lets a try go whose vendor said nothing for quiet +// (translatedQuietLongest), its agent kept alive all that time. Passing, +// the agent's stream ends with the error as its own event, after a blank +// line, as cutLoop ends one; held, the gateway tells it (stuck, failTo), +// and nobody else is asked: the agent has waited that long already. +func (h *holdWriter) endStuck(quiet time.Duration) { + name := h.name + if name == "" { + name = "the provider" + } + d := quiet.Round(time.Second) + if d == 0 { + d = quiet.Round(time.Millisecond) + } + h.stuck = fmt.Sprintf("%s sent nothing for %s; the request was ended", name, d) + if h.passing && strings.HasPrefix(h.w.Header().Get("Content-Type"), "text/event-stream") { + proto := h.alive.proto + if h.atLine { + io.WriteString(h.w, "\n") + } else { + io.WriteString(h.w, "\n\n") + } + streamError(h.w, proto, "", http.StatusGatewayTimeout, h.stuck) + h.ended = true + h.flush() + } + if h.stop != nil { + h.stop() + } +} + // started says whether the try has begun its reply, or ended, as far as // watch need know: its first content, anything sent on to the agent, // a failure, or a reply that isn't streamed. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index e206a6e61..85e91f950 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4408,7 +4408,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // at once instead of waiting in the queue (FallbackHeader) ctx = withFallback(ctx) } - hw.stop = stop + hw.stop, hw.name = stop, c.p.Name if magpieAsks(r) { // another magpie asked: its log is told the tier this // one sent (stampTier) @@ -4711,6 +4711,19 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) break } + if hw.stuck != "" { + // the vendor said nothing for translatedQuietLongest while the + // agent was kept alive (keepQuiet): it is told so, and nobody + // else is asked after it has waited that long + call.Status, call.Error = http.StatusGatewayTimeout, hw.stuck + try.Status, try.Error = call.Status, call.Error + watched.attempt(call, try, c.p.ID, sent, hw, capture) + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) + if !hw.ended { + failTo(w, kept, from, call.Status, hw.stuck) + } + break + } if hw.slow { // no first content in the group's FirstToken, and nothing of // it sent: the next member is asked, and this one doesn't @@ -10064,7 +10077,8 @@ var keepaliveEvery, keepaliveLongest = 15 * time.Second, 5 * time.Minute // translatedQuietLongest is how long a translated reply's upstream may // say nothing at all, its stream open, while magpie keeps the client -// alive every keepaliveEvery (keepThroughSilence). A reply that comes in +// alive every keepaliveEvery (keepThroughSilence), and a reply passed +// through or held is kept so too (keepQuiet). A reply that comes in // one burst at its end (claude-opus-5-5 at effort max, a relay that // buffers) is silent for its whole generation, which runs past 10 // minutes, longer than the 10 minutes magpie gives a vendor for its diff --git a/internal/gateway/quiet_keepalive_test.go b/internal/gateway/quiet_keepalive_test.go index 12c929003..6826d8b37 100644 --- a/internal/gateway/quiet_keepalive_test.go +++ b/internal/gateway/quiet_keepalive_test.go @@ -184,10 +184,11 @@ func TestSilentHeldStreamStillFailsOver(t *testing.T) { } } -// A vendor quiet for longer than keepaliveLongest (the held stream's -// comments) and translatedQuietLongest (a translated stream's own, -// keepThroughSilence) is no longer covered for: the comments stop, for a -// stuck stream to end at a timeout. +// A vendor quiet for longer than translatedQuietLongest, which both the +// held stream's comments (keepQuiet) and a translated stream's own +// (keepThroughSilence) cover, is let go: the client is told so as its +// stream's error, not left with comments that stop and then silence +// (Wing8Aqua on X; TestQuietClaudeStreamStuckEndsWithAnError). func TestQuietKeptAliveOnlySoLong(t *testing.T) { fresh(t) quietFast(t) @@ -199,25 +200,30 @@ func TestQuietKeptAliveOnlySoLong(t *testing.T) { quietOn(t, "fixture", quietCreated+quietDelta("hel"), quietDelta("lo")+quietDone, never) gw := httptest.NewServer(New().Handler()) t.Cleanup(gw.Close) + began := time.Now() resp, err := http.Post(gw.URL+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"fixture/gpt-test","stream":true,"messages":[{"role":"user","content":"hi"}]}`)) if err != nil { t.Fatal(err) } defer resp.Body.Close() - b, _ := io.ReadAll(resp.Body) // the vendor goes on after 3s - // counted from its first words, as readQuiet: the held stream's before - // them are kept for 200ms of their own + b, _ := io.ReadAll(resp.Body) // the vendor would go on after 3s + took := time.Since(began) body := string(b) - i, j := strings.Index(body, "hel"), strings.Index(body, `"lo"`) - if i < 0 || j < i { + i := strings.Index(body, "hel") + if i < 0 || strings.Contains(body, `"lo"`) { t.Fatalf("%q", body) } - // 200ms at one each 40ms is 5, from each of the two keepers, the - // held stream's and the translated stream's, with room; one that - // never stopped sends ~75 in the 3s - if n := strings.Count(body[i:j], ": keepalive"); n == 0 || n > 16 { - t.Fatalf("%d keepalives in 3s, kept for 200ms: %q", n, body) + if !strings.Contains(body[i:], "Fixture sent nothing for") || !strings.Contains(body[i:], `"error"`) { + t.Fatalf("the stuck vendor's stream ended with no error: %q", body) + } + if took >= 2500*time.Millisecond { + t.Fatalf("ended after %v, the vendor's own 3s: it wasn't let go", took) + } + // kept alive until then: 200ms at one each 40ms, from each keeper, + // with room + if n := strings.Count(body[i:], ": keepalive"); n == 0 || n > 24 { + t.Fatalf("%d keepalives: %q", n, body) } } diff --git a/internal/gateway/quiet_stuck_test.go b/internal/gateway/quiet_stuck_test.go new file mode 100644 index 000000000..a8199ca9c --- /dev/null +++ b/internal/gateway/quiet_stuck_test.go @@ -0,0 +1,169 @@ +package gateway + +import ( + "bufio" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +const ( + stuckStart = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"m1\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"m\",\"content\":[],\"usage\":{\"input_tokens\":3,\"output_tokens\":0}}}\n\n" + stuckRest = "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n" + + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"answered\"}}\n\n" + + "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n" + + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\n" + + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" +) + +// quietClaude serves a Claude relay on Messages that, for each request, +// sends its headers and head (none at all with noHead), says nothing for +// quiet, and then the rest of its reply. asked counts its requests. +func quietClaude(t *testing.T, head string, noHead bool, quiet time.Duration) *atomic.Int32 { + t.Helper() + asked := new(atomic.Int32) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + asked.Add(1) + if !noHead { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + io.WriteString(w, head) + w.(http.Flusher).Flush() + } + select { + case <-time.After(quiet): + case <-r.Context().Done(): + return + } + if noHead { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, stuckStart) + } + io.WriteString(w, stuckRest) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"claude-fable-5-2"}, Anthropic: up.URL}); err != nil { + t.Fatal(err) + } + return asked +} + +// askQuietClaude streams a Messages request for relay/claude-fable-5-2, as pi +// and dsh ask a Claude, and tells the body and the longest the client +// went without a byte, from the request on. +func askQuietClaude(t *testing.T) (string, time.Duration, time.Duration) { + t.Helper() + gw := httptest.NewServer(New().Handler()) + t.Cleanup(gw.Close) + began := time.Now() + resp, err := http.Post(gw.URL+"/v1/messages", "application/json", + strings.NewReader(`{"model":"relay/claude-fable-5-2","stream":true,"max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`)) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + last := time.Now() + gap := last.Sub(began) + var b strings.Builder + rd := bufio.NewReader(resp.Body) + for { + line, err := rd.ReadString('\n') + if line != "" { + gap = max(gap, time.Since(last)) + last = time.Now() + b.WriteString(line) + } + if err != nil { + break + } + } + return b.String(), gap, time.Since(began) +} + +// Wing8Aqua on X: pi asked Claude Fable 5.2 through magpie and gave up +// with "stream idle timeout after 300000ms". A relayed Claude stream, held +// before its headers or quiet after message_start, was kept alive with +// comments for keepaliveLongest (5 minutes) after the vendor was last +// heard, then left with nothing, and pi's 300s idle timeout ended it at +// ~10 minutes with no word of why. It is kept alive as long as a +// translated stream is (translatedQuietLongest): here the old 5 minutes +// is 100ms, the vendor is quiet for 1.5s, and the client, whose idle +// timeout stands for pi's, must never go 500ms without a byte. +func TestQuietClaudeStreamKeptAlivePastFiveMinutes(t *testing.T) { + for _, c := range []struct { + name string + head string + noHead bool + }{ + {"quiet after message_start", stuckStart, false}, + {"quiet before its headers", "", true}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + quietFast(t) + keepaliveLongest = 100 * time.Millisecond + was := translatedQuietLongest + translatedQuietLongest = 10 * time.Second + t.Cleanup(func() { translatedQuietLongest = was }) + asked := quietClaude(t, c.head, c.noHead, 1500*time.Millisecond) + body, gap, _ := askQuietClaude(t) + if !strings.Contains(body, "answered") || !strings.Contains(body, "message_stop") { + t.Fatalf("the reply didn't come whole:\n%s", body) + } + if gap >= 500*time.Millisecond { + t.Fatalf("the client heard nothing for %v while the vendor was quiet (an idle timeout of 500ms ends it):\n%s", gap, body) + } + if n := asked.Load(); n != 1 { + t.Fatalf("the vendor was asked %d times, want 1", n) + } + }) + } +} + +// A vendor that says nothing for translatedQuietLongest while the client +// is kept alive is let go, and the client is told so in its own protocol, +// naming the provider: before, the comments stopped and the client met +// only its own idle timeout. Nobody is asked again after so long a wait. +func TestQuietClaudeStreamStuckEndsWithAnError(t *testing.T) { + for _, c := range []struct { + name string + head string + noHead bool + }{ + {"quiet after message_start", stuckStart, false}, + {"quiet before its headers", "", true}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + quietFast(t) + keepaliveLongest = 100 * time.Millisecond + was := translatedQuietLongest + translatedQuietLongest = 400 * time.Millisecond + t.Cleanup(func() { translatedQuietLongest = was }) + asked := quietClaude(t, c.head, c.noHead, 5*time.Second) + body, gap, took := askQuietClaude(t) + if !strings.Contains(body, "event: error") || !strings.Contains(body, "Relay sent nothing for") { + t.Fatalf("no error told the client of the stuck vendor:\n%s", body) + } + if strings.Contains(body, "answered") { + t.Fatalf("the reply went on after its error:\n%s", body) + } + if took >= 4*time.Second { + t.Fatalf("the stream ended after %v, with the vendor's own end at 5s: it wasn't let go", took) + } + if gap >= 300*time.Millisecond { + t.Fatalf("the client heard nothing for %v before the error:\n%s", gap, body) + } + if n := asked.Load(); n != 1 { + t.Fatalf("the vendor was asked %d times, want 1", n) + } + }) + } +}