From c0cf352a8d1c3a3e897f0f2ff60b4f10b544eae7 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 15 Nov 2026 05:51:08 +0800 Subject: [PATCH] gateway: a group member's reply that ends with nothing in it goes to the next member (#6712) shawn8888's ai-studio (magpie-gemini-web 0.14.0, aistudio2api 0.3.8) answered a streamed request with 200, a role chunk with "" content, then finish_reason "stop" and 0 output tokens when Google's every regeneration came back malformed_response. streamEvent read that Chat finish chunk as content, so the hold let the stream through as an answer and group/auto-gemini-4-hydrogen (routing order) never asked agy-cli or google; the agent got no reply. A reply's end in an event that says nothing itself is now eventEmptyEnd: 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. The hold fails the try with a 502 "empty reply: it ended with nothing in it" only when nothing was said before it, reasoning included, and only for a group member with another member after it and errors not passed through (holdWriter.emptyFails). The group's existing empty-reply branch then asks the next member and rests nobody. A reply held whole is judged in the one parse settle already made (refusedReply is now readWhole, which also says empty), so a passing reply is read no more than before. The last member's empty reply, or a model asked alone, goes to the agent as it came, so an empty answer can't loop. Changed on purpose: a Claude member's empty end_turn inside a group with members left now asks the next member; TestStreamEventRefusals' three rows for an empty end now say eventEmptyEnd. Not handled: a stream the hold already let through on its timer (a Gemini client after 15s) before the empty end came. The plugin side is BUKOWSKIREAL/magpie-gemini-web#61 (a 502 or error event, not 200 + stop). Run, on mica: - new tests red on 369ec0418's fallback.go/gateway.go (checked out over the new ones, the unit tables left out): TestEmptyStopFailsOverToTheNextMember (chat, messages, responses, gemini), TestEmptyWholeReplyFailsOverToTheNextMember, TestEmptyStopEndsAtTheLastMember, TestEmptyEndFromEachUpstreamFailsOver (Messages and Responses upstreams) all FAIL; TestReasonedThenStoppedStaysTheAnswer passes on both (a guard against reaching too far). All green on the new code. - go test ./internal/gateway -count=1 (whole package): one red, TestStreamEventRefusals' three empty-end rows, updated here; then -run 'StreamEvent|Refusal|Empty|FinishReason|Overload|Overflow|ReadWhole|Reasoned|Responses' ok. - go vet ./internal/gateway, GOOS=linux (nogui) and GOOS=windows vet ok; gofmt -l clean. - The full go test ./... -timeout 45m runs after the push (ship-at-once); its result goes on #6712. --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/empty_end_test.go | 235 +++++++++++++++++++++++++++++ internal/gateway/fallback.go | 136 +++++++++++++++-- internal/gateway/gateway.go | 4 + internal/gateway/refusal_test.go | 6 +- internal/gateway/retry_test.go | 2 +- 6 files changed, 370 insertions(+), 15 deletions(-) create mode 100644 internal/gateway/empty_end_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index cf3e12dea..c755c814e 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -268,7 +268,7 @@ recorded as a prediction failure (`noPrediction`). - 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 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 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 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/empty_end_test.go b/internal/gateway/empty_end_test.go new file mode 100644 index 000000000..870e5b7be --- /dev/null +++ b/internal/gateway/empty_end_test.go @@ -0,0 +1,235 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// emptyStop is #6712's stream, as aistudio2api (magpie-gemini-web) sent +// it when Google's every regeneration came back malformed: keepalive +// comments while it waited, its role chunk with an empty content, then +// finish_reason "stop" and usage that counted the prompt and no output. +var emptyStop = sse(`: keepalive`, + `data: {"id":"chatcmpl_1794688838638417321_17","object":"chat.completion.chunk","model":"gemini-4-hydrogen","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}`, + `: keepalive`, + `data: {"id":"chatcmpl_1794688838638417321_17","object":"chat.completion.chunk","model":"gemini-4-hydrogen","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + `data: {"id":"chatcmpl_1794688838638417321_17","object":"chat.completion.chunk","model":"gemini-4-hydrogen","choices":[],"usage":{"prompt_tokens":2048,"completion_tokens":0,"total_tokens":2048,"prompt_tokens_details":{"cached_tokens":61004}}}`, + `data: [DONE]`) + +var chatFromB = sse(`data: {"id":"c2","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"}}]}`, + `data: {"id":"c2","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"from b"}}]}`, + `data: {"id":"c2","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2,"total_tokens":7}}`, + `data: [DONE]`) + +// threeGroup saves group/g of a, b and c, each a scripted Chat provider +// answering with its own replies. +func threeGroup(t *testing.T, a, b, c *scripted) { + t.Helper() + scriptedOn(t, "a", provider.Chat, a) + scriptedOn(t, "b", provider.Chat, b) + scriptedOn(t, "c", provider.Chat, c) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m", "c/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } +} + +// A group member's 200 stream that ends with finish_reason "stop" having +// said nothing at all — no text, no reasoning, no call — is no answer +// (#6712): the held stream fails before anything of it reaches the agent, +// the group's next member answers, and nobody rests. So in each protocol +// an agent speaks, the reply relayed as it came (Chat) or translated. +func TestEmptyStopFailsOverToTheNextMember(t *testing.T) { + for _, x := range []struct { + name, path, body string + }{ + {"chat", "/v1/chat/completions", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`}, + {"messages", "/v1/messages", `{"model":"group/g","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"hi"}]}`}, + {"responses", "/v1/responses", `{"model":"group/g","stream":true,"input":"hi"}`}, + {"gemini", "/v1beta/models/group/g:streamGenerateContent?alt=sse", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`}, + } { + t.Run(x.name, func(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{{200, "text/event-stream", emptyStop}}} + b := &scripted{replies: []reply{{200, "text/event-stream", chatFromB}}} + c := &scripted{replies: []reply{{200, "text/event-stream", chatFromB}}} + threeGroup(t, a, b, c) + s := New() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", x.path, strings.NewReader(x.body))) + code, body := rec.Code, rec.Body.String() + if code != 200 || !strings.Contains(body, "from b") || strings.Contains(body, "chatcmpl_1794688838638417321_17") { + t.Fatalf("%d %s %+v", code, body, s.trace.routes[len(s.trace.routes)-1]) + } + if b.n != 1 || c.n != 0 { + t.Fatalf("a asked %d, b asked %d, c asked %d", a.n, b.n, c.n) + } + r := s.trace.routes[len(s.trace.routes)-1] + if len(r.Tries) != 2 || r.Tries[0].Status != 502 || r.Tries[0].Fail != failOther || r.Tries[0].Rest != nil || + !strings.Contains(r.Tries[0].Error, emptyReply) { + t.Fatalf("tries: %+v", r.Tries) + } + }) + } +} + +// The same reply given whole, to an agent that didn't ask for a stream, +// goes to the next member too. +func TestEmptyWholeReplyFailsOverToTheNextMember(t *testing.T) { + fresh(t) + empty := `{"id":"x","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":2048,"completion_tokens":0,"total_tokens":2048}}` + a := &scripted{replies: []reply{{200, "", empty}}} + b := &scripted{replies: []reply{{200, "", chatOK}}} + c := &scripted{replies: []reply{{200, "", chatOK}}} + threeGroup(t, a, b, c) + s := New() + code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "hello") || b.n != 1 || c.n != 0 { + t.Fatalf("%d %s (a %d, b %d, c %d)", code, body, a.n, b.n, c.n) + } + r := s.trace.routes[len(s.trace.routes)-1] + if len(r.Tries) != 2 || r.Tries[0].Fail != failOther || r.Tries[0].Rest != nil || !strings.Contains(r.Tries[0].Error, emptyReply) { + t.Fatalf("tries: %+v", r.Tries) + } +} + +// A reply meant to be empty doesn't go round for ever: every member is +// asked once, and the last one's empty reply is the agent's, a 200 as it +// came. A model asked alone, outside a group, answers empty as before. +func TestEmptyStopEndsAtTheLastMember(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{{200, "text/event-stream", emptyStop}}} + b := &scripted{replies: []reply{{200, "text/event-stream", emptyStop}}} + c := &scripted{replies: []reply{{200, "text/event-stream", emptyStop}}} + threeGroup(t, a, b, c) + s := New() + code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, `"finish_reason":"stop"`) || strings.Contains(body, emptyReply) { + t.Fatalf("%d %s", code, body) + } + if a.n != 1 || b.n != 1 || c.n != 1 { + t.Fatalf("a asked %d, b asked %d, c asked %d", a.n, b.n, c.n) + } + + fresh(t) + a = &scripted{replies: []reply{{200, "text/event-stream", emptyStop}}} + scriptedOn(t, "a", provider.Chat, a) + code, body = postAs(t, New(), "", `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, `"finish_reason":"stop"`) || a.n != 1 { + t.Fatalf("alone: %d %s (asked %d)", code, body, a.n) + } +} + +// A reply that only reasoned and then stopped said something: the agent +// has its reasoning, and the next member isn't asked. +func TestReasonedThenStoppedStaysTheAnswer(t *testing.T) { + fresh(t) + reasoned := sse(`data: {"id":"r","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}`, + `data: {"id":"r","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"reasoning_content":"thinking it over"}}]}`, + `data: {"id":"r","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + `data: [DONE]`) + a := &scripted{replies: []reply{{200, "text/event-stream", reasoned}}} + b := &scripted{replies: []reply{{200, "text/event-stream", chatFromB}}} + c := &scripted{replies: []reply{{200, "text/event-stream", chatFromB}}} + threeGroup(t, a, b, c) + code, body := postAs(t, New(), "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "thinking it over") || b.n != 0 { + t.Fatalf("%d %s (b asked %d)", code, body, b.n) + } +} + +// streamEvent tells a reply's end with nothing in its event apart, in +// each protocol, from one that ends a reply with something in it or for +// a reason of its own. +func TestStreamEventEmptyEnd(t *testing.T) { + for _, x := range []struct { + ev string + kind int + }{ + {`data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, eventEmptyEnd}, + {`data: {"choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":"stop"}]}`, eventEmptyEnd}, + {`data: {"choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}]}`, eventContent}, + {`data: {"choices":[{"index":0,"delta":{"reasoning_content":"hm"},"finish_reason":"stop"}]}`, eventContent}, + {`data: {"choices":[{"index":0,"delta":{},"finish_reason":"length"}]}`, eventContent}, + {`event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":0}}`, eventEmptyEnd}, + {`event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"max_tokens"}}`, eventContent}, + {`event: response.completed` + "\n" + `data: {"type":"response.completed","response":{"status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":0}}}`, eventEmptyEnd}, + {`event: response.completed` + "\n" + `data: {"type":"response.completed","response":{"status":"incomplete","output":[]}}`, eventContent}, + {`data: {"candidates":[{"content":{"role":"model","parts":[{"text":""}]},"finishReason":"STOP"}]}`, eventEmptyEnd}, + {`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"hi"}]},"finishReason":"STOP"}]}`, eventContent}, + {`data: {"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MAX_TOKENS"}]}`, eventContent}, + } { + if k, _, _ := streamEvent([]byte(x.ev)); k != x.kind { + t.Errorf("streamEvent(%s) = %d, want %d", x.ev, k, x.kind) + } + } +} + +// readWhole tells a whole reply with nothing in it apart from one with +// something, or one cut at its length, in each protocol. +func TestReadWholeEmpty(t *testing.T) { + for _, x := range []struct { + body string + empty bool + }{ + {`{"choices":[{"message":{"role":"assistant","content":""},"finish_reason":"stop"}]}`, true}, + {`{"choices":[{"message":{"role":"assistant","content":null},"finish_reason":"stop"}]}`, true}, + {`{"choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`, false}, + {`{"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[{"id":"t"}]},"finish_reason":"tool_calls"}]}`, false}, + {`{"choices":[{"message":{"role":"assistant","content":"","reasoning_content":"hm"},"finish_reason":"stop"}]}`, false}, + {`{"choices":[{"message":{"role":"assistant","content":""},"finish_reason":"length"}]}`, false}, + {`{"type":"message","content":[],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":0}}`, true}, + {`{"type":"message","content":[{"type":"text","text":"hi"}],"stop_reason":"end_turn"}`, false}, + {`{"type":"message","content":[],"stop_reason":"max_tokens"}`, false}, + {`{"status":"completed","output":[]}`, true}, + {`{"status":"completed","output":[{"type":"message","content":[{"type":"output_text","text":"hi"}]}]}`, false}, + {`{"candidates":[{"content":{"parts":[{"text":""}]},"finishReason":"STOP"}]}`, true}, + {`{"candidates":[{"content":{"parts":[{"functionCall":{"name":"f"}}]},"finishReason":"STOP"}]}`, false}, + {`{"error":{"message":"boom"}}`, false}, + } { + if _, _, empty := readWhole([]byte(x.body)); empty != x.empty { + t.Errorf("readWhole(%s) empty = %v, want %v", x.body, empty, x.empty) + } + } +} + +// A Messages or Responses upstream that ends its turn with nothing in it, +// though it counted the prompt's tokens, is no answer either: the +// group's next member gives the agent its reply. +func TestEmptyEndFromEachUpstreamFailsOver(t *testing.T) { + for _, x := range []struct { + name string + proto provider.Protocol + body string + }{ + {"messages", provider.Anthropic, sse( + "event: message_start\ndata: "+`{"type":"message_start","message":{"id":"m","type":"message","role":"assistant","content":[],"usage":{"input_tokens":2048,"output_tokens":0}}}`, + "event: ping\ndata: "+`{"type":"ping"}`, + "event: message_delta\ndata: "+`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":0}}`, + "event: message_stop\ndata: "+`{"type":"message_stop"}`)}, + {"responses", provider.Responses, sse( + "event: response.created\ndata: "+`{"type":"response.created","response":{"id":"r","status":"in_progress","output":[]}}`, + "event: response.completed\ndata: "+`{"type":"response.completed","response":{"id":"r","status":"completed","output":[],"usage":{"input_tokens":2048,"output_tokens":0,"total_tokens":2048}}}`)}, + } { + t.Run(x.name, func(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{{200, "text/event-stream", x.body}}} + b := &scripted{replies: []reply{{200, "text/event-stream", chatFromB}}} + scriptedOn(t, "a", x.proto, a) + scriptedOn(t, "b", provider.Chat, b) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "from b") || a.n != 1 || b.n != 1 { + t.Fatalf("%d %s (a %d, b %d) %+v", code, body, a.n, b.n, s.trace.routes[len(s.trace.routes)-1].Tries) + } + if r := s.trace.routes[len(s.trace.routes)-1]; r.Tries[0].Rest != nil || !strings.Contains(r.Tries[0].Error, emptyReply) { + t.Fatalf("tries: %+v", r.Tries) + } + }) + } +} diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 3362c4f1e..86704873f 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -2753,6 +2753,13 @@ type holdWriter struct { // the tier the request went out at (stampTier), once it has a status tierStamp func(http.Header) + // emptyFails: a routing group's member stands behind the try, and a + // reply of it that ends having said nothing at all fails it, for that + // member to answer instead (emptyEnded, #6712); spoke says the held + // reply has said something, read whole (wantWhole) past its first + // content + emptyFails, spoke bool + // over, when another candidate stands behind the try, reads what // passes before its answer begins for a refusal to hand to the next // one in the same stream (refusalHandover); handedOver says it was @@ -3215,7 +3222,18 @@ func (h *holdWriter) scan() { // protocol's terminator after it; an error above cannot. h.failure, h.failMsg, h.refused = status, msg, true return + case eventEmptyEnd: + if h.emptyFails && !h.spoke && !h.thinking { + // nothing said, not even reasoning, and the reply over: + // its usage and terminator may follow, which nobody gets + h.failure, h.failMsg = http.StatusBadGateway, emptyEnded + if h.stop != nil { + h.stop() + } + return + } } + h.spoke = true if h.wantWhole { if why, ok := endedIncomplete(rest[:end]); ok { h.failure, h.failMsg = http.StatusBadGateway, why @@ -3597,10 +3615,17 @@ func (h *holdWriter) settle() { if !h.whole { return } - if msg, ok := refusedReply(h.held.Bytes()); ok { + msg, refused, empty := readWhole(h.held.Bytes()) + if refused { h.failure, h.failMsg, h.refused = refusedStatus, msg, true return } + if empty && h.emptyFails && h.status < 400 { + // a reply given whole that said nothing at all (emptyEnded), read + // in the same parse as for a refusal + h.failure, h.failMsg = http.StatusBadGateway, emptyEnded + return + } if h.status < 400 { // a 200 that is only an error fails as that error's own status // would (errorReply): asked again, or of the next, not handed on @@ -3933,8 +3958,46 @@ const ( eventRefusalError // the filter's error event: canceled like eventError eventBuffering // a lead saying the reply is held back for safety checks eventThinking // reasoning, before anything is said: a refusal may yet end it + // eventEmptyEnd is a reply's end as it ends a whole turn — a stop, + // not a cut at its length nor a filter's — in an event that says + // nothing itself. The hold reads one only before anything was said + // (scan): such a reply answered nothing at all (#6712, emptyEnded) + eventEmptyEnd ) +// emptyEnded is what a try whose reply ended with nothing in it at all — +// no text, no reasoning, no call — fails with while a routing group's +// next member stands behind it (holdWriter.emptyFails, #6712): the +// empty reply's error, which the group answers with its next member and +// rests nobody for (#1221). aistudio2api, behind the magpie-gemini-web +// plugin, ended a 200 stream with only its role chunk and finish_reason +// "stop" when Google's every regeneration came back malformed, and the +// try stood as answered, the agent's turn ending with no reply and the +// group's agy-cli and google never asked. The last member's goes as it +// came: a reply meant to be empty ends there, asked of each member once. +const emptyEnded = emptyReply + ": it ended with nothing in it" + +// endsEmptyChat, endsEmptyAnthropic and endsEmptyGemini tell whether a +// stop reason ends a turn a reply had nothing in (eventEmptyEnd): not one +// cut at its length (answersNothing) nor one a filter or an error ended, +// which say why themselves. +func endsEmptyChat(fin string) bool { + _, filtered := filterReasons[fin] + return fin != "" && fin != "length" && fin != "error" && !filtered +} + +func endsEmptyAnthropic(stop string) bool { + switch stop { + case "end_turn", "stop_sequence", "tool_use": + return true + } + return false +} + +func endsEmptyGemini(fin string) bool { + return fin == "STOP" +} + // refusedStatus is what a refusal with nothing said is answered as: a // request the agent is told not to send again as it is, rather than a // reply that looks whole but empty, which Codex asks for again and again, @@ -4222,6 +4285,9 @@ func streamEvent(ev []byte) (kind, status int, msg string) { if json.Unmarshal(v.Delta, &d) == nil && d.StopReason == "refusal" { return eventRefusal, refusedStatus, refusedDetail(d.StopReason, d.StopDetails) } + if endsEmptyAnthropic(d.StopReason) { + return eventEmptyEnd, 0, "" + } case typ == "response.incomplete" || typ == "response.completed" && v.Response.Status == "incomplete": if d := v.Response.IncompleteDetails; d != nil { if r, ok := filterReasons[d.Reason]; ok { @@ -4238,6 +4304,9 @@ func streamEvent(ev []byte) (kind, status int, msg string) { // beside it — so nothing of the try has reached the agent, and // the failure is still held for the group's next candidate return eventError, streamStatus(emptyCompleted), emptyCompleted + case typ == "response.completed" && v.Response.Status == "completed": + // a reply's end; read before anything was said, it said nothing + return eventEmptyEnd, 0, "" case typ == "" && v.Candidates != nil: // a Gemini chunk if r, ok := filterReasons[v.PromptFeedback.BlockReason]; ok { @@ -4261,6 +4330,9 @@ func streamEvent(ev []byte) (kind, status int, msg string) { if r, ok := filterReasons[c.FinishReason]; ok { return refusal(r) } + if !thinks && endsEmptyGemini(c.FinishReason) { + return eventEmptyEnd, 0, "" + } if c.FinishReason != "" { return eventContent, 0, "" } @@ -4318,6 +4390,9 @@ func streamEvent(ev []byte) (kind, status int, msg string) { // stood as a success return eventError, streamStatus(finishFailed), finishFailed } + if !thinks && endsEmptyChat(*c.FinishReason) { + return eventEmptyEnd, 0, "" + } return eventContent, 0, "" } } @@ -4545,6 +4620,15 @@ func refusedCode(data string) string { // "refusal", Chat's finish_reason "content_filter", Responses' incomplete // for content_filter, Gemini's SAFETY — with no text or call in it. func refusedReply(b []byte) (string, bool) { + msg, refused, _ := readWhole(b) + return msg, refused +} + +// readWhole reads a whole reply, not streamed, once: whether it is a +// refusal with nothing said (refusedReply), and whether it is a turn +// ended with nothing in it at all — no text, no reasoning, no call — as +// a stream's eventEmptyEnd is (#6712). +func readWhole(b []byte) (msg string, refused, empty bool) { var v struct { // Anthropic's StopReason string `json:"stop_reason"` @@ -4554,8 +4638,10 @@ func refusedReply(b []byte) (string, bool) { Choices []struct { FinishReason string `json:"finish_reason"` Message struct { - Content any `json:"content"` - ToolCalls []any `json:"tool_calls"` + Content any `json:"content"` + ToolCalls []any `json:"tool_calls"` + ReasoningContent string `json:"reasoning_content"` + Reasoning string `json:"reasoning"` } `json:"message"` } `json:"choices"` // Responses' @@ -4576,33 +4662,63 @@ func refusedReply(b []byte) (string, bool) { } `json:"promptFeedback"` } if json.Unmarshal(b, &v) != nil { - return "", false + return "", false, false } none := func(ps []streamPart) bool { return !slices.ContainsFunc(ps, streamPart.said) } if r, ok := filterReasons[v.StopReason]; ok && r == "refusal" && none(v.Content) { - return refusedDetail(r, v.StopDetails), true + return refusedDetail(r, v.StopDetails), true, false } for _, c := range v.Choices { if r, ok := filterReasons[c.FinishReason]; ok && (c.Message.Content == nil || c.Message.Content == "") && len(c.Message.ToolCalls) == 0 { - return refusedNote(r), true + return refusedNote(r), true, false } } if d := v.IncompleteDetails; v.Status == "incomplete" && d != nil && none(v.Output) { if r, ok := filterReasons[d.Reason]; ok { - return refusedNote(r), true + return refusedNote(r), true, false } } if r, ok := filterReasons[v.PromptFeedback.BlockReason]; ok { - return refusedNote(r), true + return refusedNote(r), true, false } for _, c := range v.Candidates { if r, ok := filterReasons[c.FinishReason]; ok && len(c.Content.Parts) == 0 { - return refusedNote(r), true + return refusedNote(r), true, false } } - return "", false + switch { + case endsEmptyAnthropic(v.StopReason): + empty = none(v.Content) + case len(v.Choices) > 0: + empty = true + for _, c := range v.Choices { + m := c.Message + if !endsEmptyChat(c.FinishReason) || m.Content != nil && m.Content != "" || len(m.ToolCalls) > 0 || m.ReasoningContent != "" || m.Reasoning != "" { + empty = false + } + } + case v.Status == "completed" && v.Output != nil: + empty = none(v.Output) + case len(v.Candidates) > 0: + empty = true + for _, c := range v.Candidates { + if !endsEmptyGemini(c.FinishReason) || slices.ContainsFunc(c.Content.Parts, geminiPartSays) { + empty = false + } + } + } + return "", false, empty +} + +// geminiPartSays tells whether a Gemini part has anything in it: text, +// reasoning, or anything that isn't text (a call, an image). +func geminiPartSays(p json.RawMessage) bool { + var part struct { + Text string `json:"text"` + } + return json.Unmarshal(p, &part) != nil || part.Text != "" || !bodyHas(p, `"text"`) } // errorReply says whether a reply that came whole under a success status diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 06a90520a..691820260 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3837,6 +3837,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // a compaction's summary is held to its end, for a cut or an // error halfway to go to the next candidate (#2274) hw.wantWhole = wantWhole && !pass + // a group member's reply that said nothing at all goes to the + // next member while one is left (emptyEnded, #6712); the last + // one's goes as it came + hw.emptyFails = isGroup && !last && !pass // Claude's and GPT's reasoning is held for a refusal after it only // while another candidate could answer instead: the last one's // refusal isn't asked again, so holding it only kept a lone relay's diff --git a/internal/gateway/refusal_test.go b/internal/gateway/refusal_test.go index 3d41e675a..1548bf182 100644 --- a/internal/gateway/refusal_test.go +++ b/internal/gateway/refusal_test.go @@ -396,10 +396,10 @@ func TestStreamEventRefusals(t *testing.T) { {`event: content_block_delta` + "\n" + `data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"hm"}}`, eventThinking}, {`event: content_block_delta` + "\n" + `data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":""}}`, eventContent}, {`event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"refusal"}}`, eventRefusal}, - {`event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}`, eventContent}, + {`event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}`, eventEmptyEnd}, {`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"content_filter"}]}`, eventRefusal}, {`data: {"id":"c","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"content_filter"}]}`, eventContent}, - {`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, eventContent}, + {`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, eventEmptyEnd}, {`data: {"type":"response.output_item.added","item":{"type":"reasoning","summary":[]}}`, eventThinking}, {`data: {"type":"response.reasoning_summary_text.delta","delta":"**Plan**"}`, eventThinking}, {`data: {"id":"c","choices":[{"index":0,"delta":{"reasoning_content":"hm"}}]}`, eventThinking}, @@ -411,7 +411,7 @@ func TestStreamEventRefusals(t *testing.T) { {`data: {"type":"response.reasoning_summary_part.added","part":{"type":"summary_text","text":""}}`, eventThinking}, {`data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"content_filter"}}}`, eventRefusal}, {`data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"}}}`, eventContent}, - {`data: {"type":"response.completed","response":{"status":"completed"}}`, eventContent}, + {`data: {"type":"response.completed","response":{"status":"completed"}}`, eventEmptyEnd}, {`data: {"type":"error","error":{"code":"content_filter","message":"filtered"}}`, eventRefusalError}, {`data: {"candidates":[{"content":{"parts":[]},"finishReason":"SAFETY"}]}`, eventRefusal}, {`data: {"candidates":[{"content":{"parts":[{"text":"hi"}]},"finishReason":"SAFETY"}]}`, eventContent}, diff --git a/internal/gateway/retry_test.go b/internal/gateway/retry_test.go index 46695dae4..daac40fc0 100644 --- a/internal/gateway/retry_test.go +++ b/internal/gateway/retry_test.go @@ -168,7 +168,7 @@ func TestStreamErrorBeforeContentFailsOver(t *testing.T) { {`: keep-alive`, eventLead}, {`data: {"id":"c","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}`, eventLead}, {`data: {"id":"c","choices":[{"index":0,"delta":{"content":"hi"}}]}`, eventContent}, - {`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, eventContent}, + {`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, eventEmptyEnd}, {`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"error"}]}`, eventError}, {`data: {"error":{"message":"upstream failed"}}`, eventError}, {`event: response.created` + "\n" + `data: {"type":"response.created","response":{"id":"r"}}`, eventLead},