diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index fa2796b39..3d9f9dbae 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -188,7 +188,7 @@ recorded as a prediction failure (`noPrediction`). - An error status whose body holds no message of its own says what it was (`provider.Unsaid`, through `APIError` and the plan-quota and drawing readers): a web page by its title as plain words, a firewall's block page (`EdgeBlocked`: Alibaba Cloud's, Cloudflare's "you have been blocked", "used Cloudflare to restrict access" and `error code: 1005`–`1020`) with `BlockedHint` after it, and an empty body under an HTTP status as refused with no details, often a firewall or proxy in front of the API (`NoDetails`; an empty `response.failed` event, whose fallback is no status, still reads "upstream stream failed"). A bare "403 Forbidden" told a relay's user nothing (maralica on Discord). A JSON error still reads as its message. `TestAPIErrorUnsaid`, `TestRelayRefusalSaysWhatItWas`. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. - A 2xx from Zhipu or Z.ai holding the platform's refusal envelope (`{"code":1000,"msg":…,"success":false}`, which their Responses API at `/api/v1` answers a refused key) is the refusal it stands for (`provider.ZhipuEnveloped` in `forwardOnce`): 401 for a key refused, 429 for a limit or no balance, as Zhipu's error codes give, so it fails over and rests as those do and the agent is told why. `TestZhipuResponsesRefusalIsRefusal`. - 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`. -- 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, #2446, `TestPassthroughStreamCutMidLine`, `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`). 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. 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 reply passed through in its own protocol isn't read this way. +- 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`). 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. 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 reply passed through in its own protocol isn't read this way. - A vendor's error keeps its `code` and `param` on its way to an OpenAI-shaped client (`writeVendorError`), where `writeError` used to set both to null: a status error relayed or translated, and a request refused inside a Responses stream. A Responses stream's `error` event or failed response whose error is of type `invalid_request_error` is the request at fault (`requestRefused`, read by its type, not its words): its `Event` carries status 400 and the vendor's error (`Event.Said`), so a client answered whole gets the vendor's 400 with its code and param (the whole-translated path wrote 502 `api_error`), a reply cut by it isn't resumed (`continuation.again`), and a translated stream's error says the vendor's type, code and param (`saidError`), so `holdWriter` reads it as the 400 it is. Before, the hold read magpie's `api_error` as a 502: the same request was sent three times, then to the other accounts, and every one rested (magpie-releases#18: the ChatGPT backend answers `access_programs` naming a program the workspace hasn't got with a 200 stream whose error is `access_program_not_enabled`). Asked once, nobody rests ([`codex_access_programs_test.go`](../../internal/gateway/codex_access_programs_test.go)). - An error that reaches the agent in a stream already begun can't carry its status, so `streamError` says it in the words (`saysPassing`, #2372, zminds): for a status that may pass (408, 429, 5xx) whose text names none of the words a text-judging agent retries on (Pi decides by its `errorMessage` alone), it appends `(: you can retry your request)`; a request's own fault (400, 401, 404 …) and a text that already says so are left as they were. `TestStreamErrorSaysItPasses` holds Pi's own lists; `TestGroupLastFailureInStreamSaysItPasses` runs a group whose last member fails after the keepalive. A 413 byte cap in that stream says `request_too_large` in the error text, and Chat and Anthropic name that type, so Pi compacts; Gemini keeps its own status shape (`TestStreamedByteCapSaysRequestTooLargeToPi`, `TestStreamErrorByteCapInEveryShape`). Wherever the protocol says a model with the error (Chat's first chunk, Anthropic's `message_start`, Responses' `response.created` and the events after it), it is the model the agent asked for, as `serve` has it, an effort on it kept (`keptAlive.model`; on Codex's own sign-in, the one Codex wrote) (#3728, jilen: with `"model":""` fx took Chat's first chunk for a broken one and stopped there; `TestStreamErrorNamesTheModel`, `TestKeptAliveChatErrorNamesTheModel`, `TestKeptAliveChatOnCodexErrorNamesTheModel`, `TestKeptAliveCodexErrorNamesTheModel`). An error after a reply that already went, a loop cut's, still starts a message of its own after the vendor's, under a new id and no model (#3792). - Claude's, GPT's, Gemini's and DeepSeek's reasoning is held (`refusesAfterThinking`, up to `holdThinking`, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so their reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's streams there too: a reply that only reasoned is asked again in place by `streamTranslated`, the reasoning the agent has kept and the next try's after it (#667), so holding it only kept Codex on a Gemini model with nothing at all, not even `response.created`, for the whole of its thinking (LuckymanJC on Discord; `TestThinkingStreamsWithNoOneElse`'s gemini cases). DeepSeek's is held since plugins #540: deepseek-v4.1-flash on WorkBuddy reasoned, then ended `content_filter` with nothing said (the WorkBuddy plugin takes the filter's canned "Sorry, I can't respond to this question." out of such a reply), and with its reasoning already through, the group's next member was never asked (`TestDeepSeekRefusalAfterThinkingFailsOver`). Any other model's reasoning (GLM's, Kimi's…) is never held. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index e3d505dad..a7274d508 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5478,11 +5478,56 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. // client reads one event it can't parse where the protocol's error was // meant (TestPassthroughStreamCutMidLine) atLine := true + // pending is the line the upstream has begun but not ended: a stream + // read stops there on a failure, and what of it went out already is + // data the client's SSE parser dies on — a half event's JSON doesn't + // parse — so the error event appended after it is never reached + // (#2580: a stream Z.ai reset mid-line reached pi as "malformed + // server-sent event JSON"). Only lines that ended go out as they + // come; the half line waits for its rest, unheld puts it out when + // the reply ends whole, and dropHalf throws it away when the failure + // is appended, for no client can read it and the error is what there + // is left to say + var pending []byte write := func(b []byte) (int, error) { - if len(b) > 0 { - atLine = b[len(b)-1] == '\n' + if !sse { + if len(b) > 0 { + atLine = b[len(b)-1] == '\n' + } + return w.Write(b) } - return w.Write(b) + pending = append(pending, b...) + i := bytes.LastIndexByte(pending, '\n') + var err error + if i >= 0 { + _, err = w.Write(pending[:i+1]) + pending = pending[i+1:] + atLine = true + } + return len(b), err + } + // unheld puts out the half line a whole reply ended inside: it goes + // as it came, as a stream the upstream itself ended short + unheld := func() { + if len(pending) > 0 { + w.Write(pending) + pending = nil + } + } + // dropHalf throws the line still pending away, unless it is a whole + // event's data the upstream stopped short of ending (its JSON parses, + // or [DONE]): that one is no half event, and goes out as before, with + // apart putting the blank line after it + dropHalf := func() { + if l := bytes.TrimSpace(pending); bytes.HasPrefix(l, []byte("data:")) { + if d := bytes.TrimSpace(l[5:]); string(d) == "[DONE]" || json.Valid(d) { + unheld() + atLine = false + return + } + } + pending = pending[:0] + atLine = true } // apart is what goes before an event magpie appends: a blank line, // after the line still pending if the upstream's last write stopped @@ -5619,6 +5664,10 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. sniff.settleWhole() } if gather != nil { + // the gathered stream is read here, not by the client: it gets + // every byte, a last line the upstream never ended included, as + // readSSE reads an event that ends with the body + unheld() cut := "" if rerr != nil && rerr != io.EOF { cut = cutMidReply(p.Name, rerr) @@ -5631,7 +5680,10 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. unfinished := proto == provider.Chat && sniff.failed == "" && sniff.u.Stop == "" && saysItsEnd(p, proto, upstream) if fin := sniff.tail.finish(); sse && unfinished && fin != "" && (rerr == nil || rerr == io.EOF) && r.Context().Err() == nil { // only the finish_reason was lost, after the generation was done - // (chatTail): the client gets it, and the reply is whole + // (chatTail): the client gets it, and the reply is whole. The + // event the upstream began and never ended has no rest coming: + // dropped when it is nothing a client can parse (dropHalf) + dropHalf() w.Write(append(apart(), "data: "+string(finishChunk(fin))+"\n\n"...)) if !sniff.ended { w.Write([]byte("data: [DONE]\n\n")) @@ -5657,9 +5709,11 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. failed = p.Name + ": " + errEndedShort.Error() } if failed != "" { - // what is appended begins after a blank line: the event still - // pending is left to stand, and the failure is read as an - // event of its own (TestPassthroughStreamEndsOnLineEnd) + // what is appended begins after a blank line, as an event of + // its own (TestPassthroughStreamEndsOnLineEnd); the half + // event the upstream left is dropped (#2580): a client + // reading it dies on its JSON before the error is reached + dropHalf() w.Write(append(apart(), streamFailure(proto, failed)...)) if f != nil { f.Flush() @@ -5667,6 +5721,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. return res.StatusCode, failed, true } } + if sse { + unheld() + } return res.StatusCode, sniff.failed, true } diff --git a/internal/gateway/passthrough_severed_test.go b/internal/gateway/passthrough_severed_test.go index 853590c70..c6f6c94f7 100644 --- a/internal/gateway/passthrough_severed_test.go +++ b/internal/gateway/passthrough_severed_test.go @@ -5,6 +5,8 @@ import ( "net/http/httptest" "strings" "testing" + + "github.com/yetone/magpie/internal/provider" ) // postMessages sends an Anthropic Messages request to the gateway, as dsh's @@ -24,7 +26,7 @@ func postMessages(t *testing.T, body string) (int, string) { // retry and which says nothing of what went wrong (#370). func TestPassthroughStreamSeveredUpstream(t *testing.T) { fresh(t) - severed(t, anthropicStart, anthropicText) + severed(t, provider.Anthropic, anthropicStart, anthropicText) code, body := postMessages(t, `{"model":"up/m","stream":true,"max_tokens":8,"messages":[{"role":"user","content":"hi"}]}`) if code != 200 { t.Fatalf("status = %d, want 200; body: %s", code, body) @@ -165,3 +167,61 @@ func TestPassthroughResponsesBigLastEvent(t *testing.T) { t.Fatalf("a whole stream with a big last event was changed: %d, %d bytes added", code, len(body)-len(reply)) } } + +// The upstream reset inside an event (#2580: Z.ai cut a glm-5.3 stream +// mid-line under pi): the half event went to the client as data, and the +// client's SSE parser died reading it — "malformed server-sent event +// JSON" — so the error event magpie appended after it was never reached, +// and the turn failed without a word of what went wrong. A line the +// upstream never ended is no event of its own: the client reads the +// events that were whole and then the error, nothing it has to fail on. +func TestChatStreamCutMidLineLeavesNoHalfEvent(t *testing.T) { + fresh(t) + severed(t, provider.Chat, sse(chatThink("glm-5.3", "thinking")), + `data: {"id":"c1","model":"glm-5.3","choices":[{"index":0,"delta":{"reasoning_content":"the VM program itself hit an undefined`) + code, body := post(t, "/v1/chat/completions", `{"model":"up/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 { + t.Fatalf("status = %d, want 200; body: %s", code, body) + } + if !strings.Contains(body, "connection lost mid-reply") { + t.Fatalf("a cut Chat stream ended without the error event: %s", body) + } + if strings.Contains(body, "undefined") { + t.Fatalf("a half event the upstream never ended went to the client as data: %s", body[max(0, len(body)-300):]) + } + // every event the client reads parses, the error included: the + // stream is one a strict SSE reader goes through to the end of + readSSE(strings.NewReader(body), func(_, data string) error { + if data != "[DONE]" && !json.Valid([]byte(data)) { + t.Errorf("an event the client reads is no JSON: %q", data) + } + return nil + }) +} + +// A reset that comes after an event's JSON is whole but before the line +// ends leaves no half event: that event parses, so it goes to the client +// as before, and the error after it is an event of its own. Only a line +// whose data doesn't parse is dropped (#2580). +func TestChatStreamCutAfterWholeEventKeepsIt(t *testing.T) { + fresh(t) + severed(t, provider.Chat, sse(chatThink("glm-5.3", "thinking")), `data: `+chatText("glm-5.3", "kept to the end")) + code, body := post(t, "/v1/chat/completions", `{"model":"up/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 { + t.Fatalf("status = %d, want 200; body: %s", code, body) + } + if !strings.Contains(body, "connection lost mid-reply") { + t.Fatalf("a cut Chat stream ended without the error event: %s", body) + } + var got []string + readSSE(strings.NewReader(body), func(_, data string) error { + if data != "[DONE]" && !json.Valid([]byte(data)) { + t.Errorf("an event the client reads is no JSON: %q", data) + } + got = append(got, data) + return nil + }) + if !strings.Contains(strings.Join(got, "\n"), "kept to the end") { + t.Fatalf("the last whole event was dropped: %q", body) + } +} diff --git a/internal/gateway/plugin_grok_parity_test.go b/internal/gateway/plugin_grok_parity_test.go index d2ebe7fd1..512e52050 100644 --- a/internal/gateway/plugin_grok_parity_test.go +++ b/internal/gateway/plugin_grok_parity_test.go @@ -323,6 +323,26 @@ func TestGrokPluginNonStreamEndedShort(t *testing.T) { } } +// A gathered stream whose last line the upstream never ended, its +// response.completed with no newline after it, is still read whole: a +// relayed stream holds an unended line back from the client (#2580), but +// what is gathered is read here, every byte of it. +func TestGrokPluginNonStreamLastLineUnended(t *testing.T) { + done := `{"id":"r1","object":"response","status":"completed","model":"grok-4.7","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Found it.","annotations":[]}]}],"usage":{"input_tokens":5,"output_tokens":3,"total_tokens":8}}` + pid := besideFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`)+ + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":`+done+`}`) + })) + body := `{"model":"` + pid + `/fake-resp","stream":false,"input":"hi"}` + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Found it.") { + t.Fatalf("%d %s", rec.Code, rec.Body) + } +} + // A stream whose response.completed names no output, and which sent no // output_item.done either, still gives the client the text it streamed. func TestGatheredTextOnlyStream(t *testing.T) { diff --git a/internal/gateway/stream_cut_test.go b/internal/gateway/stream_cut_test.go index 8a534ee28..a146ea97b 100644 --- a/internal/gateway/stream_cut_test.go +++ b/internal/gateway/stream_cut_test.go @@ -41,7 +41,7 @@ func TestStreamCutSaysConnection(t *testing.T) { if err := provider.Save(provider.Provider{ID: "go", Name: "OpenCode Go", Key: "k", Models: []string{"m"}, Chat: up.URL + "/v1"}); err != nil { t.Fatal(err) } - severed(t, anthropicStart, anthropicText) // up/m, spoken to in Messages: the reply translated + severed(t, provider.Anthropic, anthropicStart, anthropicText) // up/m, spoken to in Messages: the reply translated cases := []struct{ model, name string }{{"go/m", "OpenCode Go"}, {"up/m", "UP"}} var wg sync.WaitGroup diff --git a/internal/gateway/translate_severed_test.go b/internal/gateway/translate_severed_test.go index a947f3532..b0d687f61 100644 --- a/internal/gateway/translate_severed_test.go +++ b/internal/gateway/translate_severed_test.go @@ -14,7 +14,7 @@ import ( // severed speaks HTTP until it doesn't: it writes headers that promise more // body than it sends, delivers the events given, then closes the connection. // The client's stream read fails the way an upstream dying mid-reply fails. -func severed(t *testing.T, events ...string) { +func severed(t *testing.T, proto provider.Protocol, events ...string) { t.Helper() up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.ReadAll(r.Body) @@ -33,7 +33,13 @@ func severed(t *testing.T, events ...string) { buf.Flush() })) t.Cleanup(up.Close) - p := provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"m"}, Anthropic: up.URL} + p := provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"m"}} + switch proto { + case provider.Chat: + p.Chat = up.URL + "/v1" + default: + p.Anthropic = up.URL + } if err := provider.Save(p); err != nil { t.Fatal(err) } @@ -54,7 +60,7 @@ const ( // upstream died, as if the reply were whole. func TestTranslateBufferedSeveredUpstream(t *testing.T) { fresh(t) - severed(t, anthropicStart, anthropicText) + severed(t, provider.Anthropic, anthropicStart, anthropicText) code, body := postAs(t, New(), "", `{"model":"up/m","messages":[{"role":"user","content":"hi"}]}`) if code != 502 { t.Fatalf("status = %d, want 502; body: %s", code, body) @@ -68,7 +74,7 @@ func TestTranslateBufferedSeveredUpstream(t *testing.T) { // [DONE] - over a reply the upstream never finished. func TestTranslateStreamSeveredUpstream(t *testing.T) { fresh(t) - severed(t, anthropicStart, anthropicText) + severed(t, provider.Anthropic, anthropicStart, anthropicText) code, body := postAs(t, New(), "", `{"model":"up/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`) if code != 200 { t.Fatalf("status = %d, want 200; body: %s", code, body)