diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 72fe873aa..bf1e4c87c 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -202,7 +202,7 @@ recorded as a prediction failure (`noPrediction`). - 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. 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'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`). Responses' `response.failed` code for it is `context_length_exceeded`, the one code Codex compacts on: with `server_error` it sent the same body five more times ("reconnecting 5/5"), each refused, and never compacted (celestial_eagle_99230 on Discord, an nginx 413 page in front of a DeepSeek model; `TestCodexByteCapInStreamCompacts`). An overload told so (a 529, or a 5xx whose words say overloaded, `saidOverloaded`) is `server_is_overloaded` there, as the ChatGPT backend says one in a stream: Codex shows the model at capacity and stops, where `server_error` had it reconnect five times, each turn asked again by magpie, and end on the last error alone (wjh66 on Discord; `TestCodexKeptAliveOverloadSaysServerIsOverloaded`). Codex reads a 413, or a 400 `context_length_exceeded`, told by HTTP status as an unexpected status or an invalid request and compacts on neither, so when Codex (`fromCodex`) asked for a stream, a byte cap or an overflow is told in a stream even before one began (`keptAlive.compactsInStream`, `failTo`; `TestCodexByteCapBeforeStreamCompacts`). Another client keeps its status (`TestByteCapBeforeStreamStaysStatusForOthers`). Nobody rests for either. 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. +- 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`). Where a refusal after the reasoning can still go to the next candidate in the same stream (`handsOver`: the agent asked for a Chat, Anthropic or Responses stream and another candidate is left; [`refusal_handover.go`](../../internal/gateway/refusal_handover.go)), a member whose thinking has gone on to an answer `thoughtCleanMost` (3) times running has its reasoning as it comes (`holdsThinking`), and a refusal after it, nothing yet said, is handed over, the next candidate's stream following as the same reply: DeepSeek's whether or not it can be handed over (#4512), Claude's, GPT's and Gemini's only where it can, so their refusal never reaches the agent while another could answer. Held whatever the member answered, a group of one model's accounts showed Claude Code its Claude's thinking only with its text, all at once, and never its `thinking with effort` (#4166). A retryable error after the reasoning, nothing yet said (Anthropic's `overloaded_error` mid-stream), is handed over the same way (`passOver`), its status and words failing the try as a held one's would, so trusting a member doesn't cost the group its failover; one the next candidate wouldn't be asked for (a request at fault) is the agent's (`TestTrustedThinkingFailsOverOnEveryPath`: Claude, GPT and Gemini members, refused, overloaded or invalid, to Claude Code, a Chat client and Codex; `TestClaudeTrustedThinkingErrorFailsOver`). A refusal takes the trust back (`thoughtRefused`), and the member's next reasoning is held again. `TestDeepSeekThinkingStreamsOnceTrusted`, `TestDeepSeekRefusalHoldsATrustedMemberAgain`, `TestClaudeThinkingStreamsOnceTrusted` and `TestClaudeTrustedThinkingStreamsThroughGroup` in [`thinking_streams_test.go`](../../internal/gateway/thinking_streams_test.go). Any other model's reasoning (GLM's, Kimi's…) is never held. - A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then, after a blank line (two newlines when that write stopped inside a line, `holdWriter.atLine`, #2446), the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop` (`usage.LoopErrType`), and Usage counts them per model (`Totals.Loops`), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, `TestLoopsCountedPerModel`, `usage-loops.test.cjs`). A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A reply passed through in the agent's own protocol is asked again once too, at the fallback loop (`holdWriter.mayReloop`, `letGoLoop`; #2436, lqisgod: pi's Chat stream to WorkBuddy was cut at once): when nothing of the try has reached the agent yet, in any protocol, its held bytes are dropped; when its reasoning is already passing, only a Chat stream goes on, written up to the end of the tripping event, with the next try's chunks after it. An Anthropic or Responses stream already passing still ends with the error, since a second `message_start` or `response.created` can't follow. Each re-ask, in place or at the fallback loop, counts in the usage record's tries. A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`). A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off. - A conversation going round one tool call is answered by magpie and sent nowhere (audie on Discord: Codex Desktop on WorkBuddy's deepseek-v4-pro read the same file 308 times in half an hour, and 340 times that evening, 537 credits). `stoppedToolLoop` ([`tool_loop.go`](../../internal/gateway/tool_loop.go)) runs in `serveAgent` before hooks, middleware and routing, and in the Codex backend's passthrough on Codex's own sign-in. It reads the request's own history, so it is per conversation and keeps no state: when the last `toolLoopRepeats` (8) turns are each the same calls (name and arguments, keys in any order, call ids ignored) answered with the same results (with Codex's `Wall time`, `Chunk ID` and `duration_seconds` taken out, `runNoise`) and nothing else from the user, the turn is answered in the agent's own protocol, streamed or whole (`writeLocalText` through `relayStatus`), with a notice naming the call. Any different result, or a word of the user's, starts the count again; the notice is a turn without calls, so the user's next word goes on. A body with fewer than 8 tool results isn't parsed (`mayLoop`), and only the newest 64 items of a long one are (`tailOf`, gjson), ~1ms for a 1.5MB turn (`BenchmarkToolLoopCheck`). The turn is recorded as Codex's title turns are (`answeredHere`): the Routing trace as "Tool loop stopped", and a usage row with provider `magpie`, rejected, its session and an error starting `tool loop:`. A poll that gets the same answer 8 times in a row is stopped too. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off with the reply guard. Verification: `go test -tags nogui ./internal/gateway -run 'TestToolLoop'`. - A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: `reasoning_content` (DeepSeek's, which OpenCode and most clients send), `reasoning` (OpenRouter's) or `reasoning_details` (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (`messageReasoning`, `reasoningText`, read by `parseChat` in [chat.go](../../internal/gateway/chat.go)); the passthrough has read all three since `mistralThinking` (#494), which was the one place that did. Before that the parse layer read `reasoning_content` alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning. diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 3ea109f68..4473488bb 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -2631,8 +2631,8 @@ func refusesAfterThinking(model string) bool { // deepseekAfterThinking tells whether the model is DeepSeek's, the one // vendor whose reasoning the refusal hold lets go once the member has // gone on from its thinking to an answer enough times running -// (holdsThinking): Claude's, GPT's and Gemini's is held whatever the -// member has answered lately (#248). +// (holdsThinking) whether or not a refusal after it can be handed over: +// Claude's, GPT's and Gemini's only where it can (#248, #4166). func deepseekAfterThinking(model string) bool { m := strings.ToLower(model) if i := strings.LastIndex(m, "/"); i >= 0 { @@ -2642,8 +2642,8 @@ func deepseekAfterThinking(model string) bool { } // thoughtCleanMost is how many thinking replies in a row that went on to -// an answer trust a DeepSeek member with its reasoning as it comes -// (holdsThinking): its filter refuses after thinking hardly ever (#4512: +// an answer trust a member with its reasoning as it comes +// (holdsThinking): DeepSeek's filter refuses after thinking hardly ever (#4512: // one content_filter in 33,245 group requests over 7 days), and held, // every one of those requests kept the agent waiting its whole thinking // out. A refusal of its own takes the trust back (thoughtRefused). @@ -2653,13 +2653,16 @@ const thoughtCleanMost = 3 // refusal after it while another candidate could answer. DeepSeek's is, // until the member's thinking has gone on to an answer thoughtCleanMost // times running; past that it goes through as it comes, GLM's way. -// Claude's, GPT's and Gemini's is held whatever the member answered -// lately (#248). -func (s *Server) holdsThinking(c candidate) bool { +// Claude's, GPT's and Gemini's is trusted the same way only where a +// refusal after it is handed to the next candidate in the same stream +// (handsOver, refusalHandover), and is held whatever the member answered +// lately where it isn't (#248): told to the agent, such a refusal would +// end the turn with nothing said (#4166). +func (s *Server) holdsThinking(c candidate, handsOver bool) bool { if !refusesAfterThinking(c.model) { return false } - if !deepseekAfterThinking(c.model) { + if !deepseekAfterThinking(c.model) && !handsOver { return true } s.thoughtMu.Lock() @@ -2670,7 +2673,7 @@ func (s *Server) holdsThinking(c candidate) bool { // thoughtAnswered counts a thinking reply that went on to an answer, for // holdsThinking's trust to run out on. func (s *Server) thoughtAnswered(c candidate) { - if !deepseekAfterThinking(c.model) { + if !refusesAfterThinking(c.model) { return } s.thoughtMu.Lock() @@ -2686,7 +2689,7 @@ func (s *Server) thoughtAnswered(c candidate) { // is held again for the next requests, until it has answered // thoughtCleanMost times running. func (s *Server) thoughtRefused(c candidate) { - if !deepseekAfterThinking(c.model) { + if !refusesAfterThinking(c.model) { return } s.thoughtMu.Lock() diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 98731fa7e..a1beaed77 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -556,9 +556,10 @@ type Server struct { // (UnixNano, 0 for never): while that is recent, a group skips it for // such a request when someone is left after it (antigravityForeseen) agTurnedAway atomic.Int64 - // thoughtMu keeps the count of each DeepSeek member's thinking replies - // that went on to an answer in a row, by "/" - // (holdsThinking, #4512) + // thoughtMu keeps the count of each member's thinking replies that + // went on to an answer in a row, by "/", for a + // vendor that may refuse after its thinking (holdsThinking, #4512, + // #4166) thoughtMu sync.Mutex thoughtClean map[string]int } @@ -3205,7 +3206,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // thoughtCleanMost times running (holdsThinking, #4512): its // filter refuses after thinking hardly ever, and held, the agent // waited every request's whole thinking out. - hw.thinkingShown = !s.holdsThinking(c) || last + // Claude's, GPT's and Gemini's go as they come the same way while + // a refusal after them can still be handed over (hw.over): held, + // a group's Claude showed Claude Code its thinking only with its + // text, all at once, and never its "thinking with + // effort" (#4166). Set below, once hw.over is. hw.ctx, hw.alive, hw.streams = r.Context(), kept, streams // a Claude subscription account's refusal of a big conversation // isn't told again to the subscription's other accounts @@ -3221,6 +3226,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // same stream (refusalHandover; yhwangl on X) hw.over = &refusalHandover{proto: from, seq: -1} } + // the reasoning's hold, above, once the handover is known + hw.thinkingShown = !s.holdsThinking(c, hw.over != nil) || last report := cacheReport if c.p.Account == nil || c.p.Account.Agent != "claude" { report = nil diff --git a/internal/gateway/refusal_handover.go b/internal/gateway/refusal_handover.go index fe1eb0abf..238267db4 100644 --- a/internal/gateway/refusal_handover.go +++ b/internal/gateway/refusal_handover.go @@ -92,7 +92,20 @@ func (h *holdWriter) passOver(b []byte) { switch kind, status, msg := streamEvent(ev); kind { case eventRefusal, eventRefusalError: o.pending = nil - h.handOver(status, msg) + h.handOver(status, msg, true) + return + case eventError: + // a failure the next candidate may answer, nothing yet said + // (Anthropic's overloaded_error after its thinking): handed + // over as a refusal is, as it went to the next candidate + // while the reasoning was held (#4166). One that isn't + // retryable is the agent's, as before. + if !retryable(status, []byte(msg)) { + o.spoke = true + break + } + o.pending = nil + h.handOver(status, msg, false) return case eventThinking, eventLead, eventBuffering: o.track(ev) @@ -124,8 +137,10 @@ func (h *holdWriter) out(b []byte) { // what went before it, an Anthropic block still open is stopped, and the // try fails as a refusal with nothing said does, for the next candidate's // stream to follow in the same response. Its account doesn't rest: the -// request was refused, not the account (#248). -func (h *holdWriter) handOver(status int, msg string) { +// request was refused, not the account (#248). A retryable error handed +// over (refused false) fails the try as one held would have, its status +// and its words for the account's rest. +func (h *holdWriter) handOver(status int, msg string, refused bool) { o := h.over if o.proto == provider.Anthropic && len(o.open) > 0 { open := make([]int, 0, len(o.open)) @@ -140,7 +155,7 @@ func (h *holdWriter) handOver(status int, msg string) { } h.flush() h.handedOver, h.passing = true, false - h.refused, h.failure, h.failMsg = true, status, msg + h.refused, h.failure, h.failMsg = refused, status, msg // the refusal's own end (message_stop, [DONE]) wasn't sent: the // reply isn't whole, and the next one's stream follows without its // 200 and headers again diff --git a/internal/gateway/refusal_handover_test.go b/internal/gateway/refusal_handover_test.go index c07046429..f7939f38c 100644 --- a/internal/gateway/refusal_handover_test.go +++ b/internal/gateway/refusal_handover_test.go @@ -274,3 +274,110 @@ func TestSensitiveContentRefusals(t *testing.T) { t.Error("Zhipu's sensitive is not the filter's stop") } } + +// A group's Claude, GPT or Gemini member trusted with its reasoning +// (holdsThinking, #4166) lets it through as it comes, and what ends the +// try before a word of the answer still goes to the next member, as it +// did while the reasoning was held (#248): a refusal and a retryable +// error alike, whose answer follows the reasoning in the same stream, as +// one reply, for Claude Code, Codex and a Chat client. An error the next +// member wouldn't answer otherwise (a request at fault) is the agent's. +func TestTrustedThinkingFailsOverOnEveryPath(t *testing.T) { + chatAnswered := sse( + `data: {"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"hm"}}]}`, + `data: {"id":"c1","choices":[{"index":0,"delta":{"content":"from a"}}]}`, + `data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`, + `data: [DONE]`) + chatThought := strings.Join(strings.SplitAfter(glmThoughtThenSensitive, "\n\n")[:2], "") + anthropicThought := strings.Join(strings.SplitAfter(glmAnthropicThoughtThenRefused, "\n\n")[:4], "") + anthropicError := func(typ, msg string) string { + return anthropicThought + sse(`event: error`+"\n"+`data: {"type":"error","error":{"type":"`+typ+`","message":"`+msg+`"}}`) + } + for _, up := range []struct { + name, model string + proto provider.Protocol + answered string + refused string + overloaded string + invalid string + }{ + {"claude", "claude-opus-5-5", provider.Anthropic, anthropicThoughtThenAnswered, glmAnthropicThoughtThenRefused, + anthropicError("overloaded_error", "Overloaded"), anthropicError("invalid_request_error", "invalid tool schema")}, + {"gpt", "gpt-5.5", provider.Chat, chatAnswered, chatThoughtThenFiltered, + chatThought + sse(`data: {"error":{"message":"Overloaded","type":"server_error"}}`), + chatThought + sse(`data: {"error":{"message":"invalid tool schema","type":"invalid_request_error"}}`)}, + {"gemini", "gemini-3-pro", provider.Chat, chatAnswered, chatThoughtThenFiltered, + chatThought + sse(`data: {"error":{"message":"Overloaded","type":"server_error"}}`), + chatThought + sse(`data: {"error":{"message":"invalid tool schema","type":"invalid_request_error"}}`)}, + } { + for _, end := range []string{"refused", "overloaded", "invalid"} { + for _, client := range []struct { + name, path, ask string + check func(t *testing.T, body string) + }{ + {"messages", "/v1/messages", claudeCodeAsk, checkAnthropicSpliced}, + {"chat", "/v1/chat/completions", chatStreamAsk, checkChatSpliced}, + {"responses", "/v1/responses", codexAsk, checkResponsesSpliced}, + } { + t.Run(up.name+" "+end+" to "+client.name, func(t *testing.T) { + fresh(t) + last := map[string]string{"refused": up.refused, "overloaded": up.overloaded, "invalid": up.invalid}[end] + a := &scripted{replies: []reply{ + {200, "text/event-stream", up.answered}, + {200, "text/event-stream", up.answered}, + {200, "text/event-stream", up.answered}, + {200, "text/event-stream", last}, + }} + scriptedOn(t, "a", up.proto, a) + pa, err := provider.Find("a") + if err != nil { + t.Fatal(err) + } + pa.Models = []string{up.model} + if err := provider.Save(*pa); err != nil { + t.Fatal(err) + } + b := &scripted{replies: []reply{{200, "text/event-stream", anthropicAnswer}}} + scriptedOn(t, "b", provider.Anthropic, b) + refusalGroup(t, "a/"+up.model, "b/m") + s := New() + for i := range thoughtCleanMost { + if code, body := sendTo(s, client.path, client.ask); code != 200 || !strings.Contains(body, "from a") { + t.Fatalf("warm-up %d: %d %s (a %d)", i+1, code, body, a.n) + } + } + code, body := sendTo(s, client.path, client.ask) + // trusted: the reasoning went through as it came + if code != 200 || a.n != thoughtCleanMost+1 || !strings.Contains(body, "first thought") { + t.Fatalf("%d (a %d, b %d): %s", code, a.n, b.n, body) + } + r := lastRoute(s) + if end == "invalid" { + if b.n != 0 || !strings.Contains(body, "invalid tool schema") || len(r.Tries) != 1 { + t.Fatalf("a request at fault isn't the agent's (b %d): %s %+v", b.n, body, r.Tries) + } + return + } + if b.n != 1 || !strings.Contains(body, "from b") { + t.Fatalf("the next member didn't answer (b %d): %s", b.n, body) + } + for _, w := range []string{"content_filter", `"refusal"`, "Overloaded", "overloaded"} { + if strings.Contains(body, w) { + t.Fatalf("the failure (%s) reached the agent: %s", w, body) + } + } + client.check(t, body) + if len(r.Tries) != 2 || r.Tries[1].Fail != "" { + t.Fatalf("tries: %+v", r.Tries) + } + if end == "refused" && (r.Tries[0].Fail != failRefused || r.Tries[0].Rest != nil) { + t.Fatalf("refused try: %+v", r.Tries[0]) + } + if end == "overloaded" && r.Tries[0].Status != 529 { + t.Fatalf("overloaded try: %+v", r.Tries[0]) + } + }) + } + } + } +} diff --git a/internal/gateway/thinking_streams_test.go b/internal/gateway/thinking_streams_test.go index a8cb8860f..faaab99b6 100644 --- a/internal/gateway/thinking_streams_test.go +++ b/internal/gateway/thinking_streams_test.go @@ -307,6 +307,190 @@ func TestDeepSeekRefusalHoldsATrustedMemberAgain(t *testing.T) { } } +// A group's Claude member is trusted as a DeepSeek one is: once its +// thinking has gone on to an answer thoughtCleanMost times running, its +// reasoning goes as it comes while a refusal after it is still handed to +// the next member in the same stream (refusalHandover). Held, Claude Code +// on a group of one model's accounts saw the thinking only with the text, +// all at once, and never its "thinking with effort" (#4166). A +// refusal takes the trust back, as DeepSeek's does. +func TestClaudeThinkingStreamsOnceTrusted(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{ + {200, "text/event-stream", anthropicThoughtThenAnswered}, + {200, "text/event-stream", anthropicThoughtThenAnswered}, + {200, "text/event-stream", anthropicThoughtThenAnswered}, + {200, "text/event-stream", anthropicThoughtThenRefused}, + {200, "text/event-stream", anthropicThoughtThenRefused}, + }} + scriptedOn(t, "a", provider.Anthropic, a) + pa, err := provider.Find("a") + if err != nil { + t.Fatal(err) + } + pa.Models = []string{"claude-opus-5-5"} + if err := provider.Save(*pa); err != nil { + t.Fatal(err) + } + b := &scripted{replies: []reply{{200, "text/event-stream", anthropicAnswer}, {200, "text/event-stream", anthropicAnswer}}} + scriptedOn(t, "b", provider.Anthropic, b) + refusalGroup(t, "a/claude-opus-5-5", "b/m") + s := New() + if !s.holdsThinking(candidate{p: *pa, model: "claude-opus-5-5"}, true) { + t.Fatal("an untried Claude member's reasoning isn't held") + } + for i := 0; i < thoughtCleanMost; i++ { + if code, body := sendTo(s, "/v1/messages", claudeCodeAsk); code != 200 || !strings.Contains(body, "from a") || strings.Contains(body, "from b") { + t.Fatalf("warm-up %d: %d %s (a %d, b %d)", i+1, code, body, a.n, b.n) + } + } + // trusted only where a refusal can still be handed over: where it + // can't, it would reach the agent and end the turn with nothing said + if s.holdsThinking(candidate{p: *pa, model: "claude-opus-5-5"}, true) { + t.Fatal("a trusted Claude member's reasoning is still held") + } + if !s.holdsThinking(candidate{p: *pa, model: "claude-opus-5-5"}, false) { + t.Fatal("a trusted Claude member's reasoning goes through with no handover behind it") + } + // trusted, the refused reply's reasoning went through as it came, and + // the refusal after it, nothing yet said, went to the next member, + // whose answer follows in the same stream, as one reply + code, body := sendTo(s, "/v1/messages", claudeCodeAsk) + if code != 200 || !strings.Contains(body, "The user wants a plan for") || !strings.Contains(body, "from b") || strings.Contains(body, `"refusal"`) || + strings.Count(body, "event: message_start") != 1 || a.n != thoughtCleanMost+1 || b.n != 1 { + t.Fatalf("trusted refusal: %d %s (a %d, b %d)", code, body, a.n, b.n) + } + if r := lastRoute(s); len(r.Tries) != 2 || r.Tries[0].Fail != failRefused || r.Tries[0].Rest != nil || r.Tries[1].Fail != "" { + t.Fatalf("tries: %+v", r.Tries) + } + // and the member is held again: the same refusal goes to the next + // member with its reasoning shown to nobody + code, body = sendTo(s, "/v1/messages", claudeCodeAsk) + if code != 200 || !strings.Contains(body, "from b") || strings.Contains(body, "The user wants a plan for") || a.n != thoughtCleanMost+2 || b.n != 2 { + t.Fatalf("held again: %d %s (a %d, b %d)", code, body, a.n, b.n) + } +} + +// Trusted, a group's Claude member's thinking reaches the agent as it +// comes, the text a good while after the first thought (#4166). +func TestClaudeTrustedThinkingStreamsThroughGroup(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{ + {200, "text/event-stream", anthropicThoughtThenAnswered}, + {200, "text/event-stream", anthropicThoughtThenAnswered}, + {200, "text/event-stream", anthropicThoughtThenAnswered}, + }} + scriptedOn(t, "a", provider.Anthropic, a) + pa, err := provider.Find("a") + if err != nil { + t.Fatal(err) + } + pa.Models = []string{"claude-opus-5-5"} + if err := provider.Save(*pa); err != nil { + t.Fatal(err) + } + scriptedOn(t, "b", provider.Anthropic, &scripted{replies: []reply{{200, "text/event-stream", anthropicAnswer}}}) + refusalGroup(t, "a/claude-opus-5-5", "b/m") + s := New() + for i := 0; i < thoughtCleanMost; i++ { + if code, body := sendTo(s, "/v1/messages", claudeCodeAsk); code != 200 || !strings.Contains(body, "from a") { + t.Fatalf("warm-up %d: %d %s (a %d)", i+1, code, body, a.n) + } + } + up := &slowThinker{events: glmThinksSlowly, gap: 200 * time.Millisecond, done: make(chan time.Time, 1)} + vendor := httptest.NewServer(up) + t.Cleanup(vendor.Close) + pa, err = provider.Find("a") + if err != nil { + t.Fatal(err) + } + pa.Anthropic = vendor.URL + if err := provider.Save(*pa); err != nil { + t.Fatal(err) + } + gw := httptest.NewServer(s.Handler()) + t.Cleanup(gw.Close) + res, err := http.Post(gw.URL+"/v1/messages", "application/json", strings.NewReader(claudeCodeAsk)) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + var firstThought, firstText time.Time + rd := bufio.NewReader(res.Body) + for { + ln, err := rd.ReadString('\n') + if firstThought.IsZero() && strings.Contains(ln, `"thinking_delta"`) { + firstThought = time.Now() + } + if firstText.IsZero() && strings.Contains(ln, `"text_delta"`) { + firstText = time.Now() + } + if err != nil { + break + } + } + select { + case <-up.done: + case <-time.After(5 * time.Second): + t.Fatal("the vendor never finished") + } + if firstThought.IsZero() || firstText.IsZero() { + t.Fatal("no thinking or no text reached the client") + } + // three thoughts 200ms apart come before the text + if firstText.Sub(firstThought) < 300*time.Millisecond { + t.Fatalf("thinking held: first thought only %v before the text", firstText.Sub(firstThought)) + } + if r := lastRoute(s); len(r.Tries) != 1 { + t.Fatalf("the trusted member's reply was asked again: %+v", r.Tries) + } +} + +// Trusted, a group's Claude member whose stream fails after its thinking +// went through, nothing yet said (Anthropic's overloaded_error), still +// fails over: the next member answers in the same stream, as one reply, +// as it did while the thinking was held (#4166). Let through, the error +// reached Claude Code and the group's next member was never asked. +func TestClaudeTrustedThinkingErrorFailsOver(t *testing.T) { + fresh(t) + overloaded := sse(`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"m1","role":"assistant","model":"m","content":[],"usage":{"input_tokens":2}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"The user wants a plan for"}}`, + `event: error`+"\n"+`data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`) + a := &scripted{replies: []reply{ + {200, "text/event-stream", anthropicThoughtThenAnswered}, + {200, "text/event-stream", anthropicThoughtThenAnswered}, + {200, "text/event-stream", anthropicThoughtThenAnswered}, + {200, "text/event-stream", overloaded}, + }} + scriptedOn(t, "a", provider.Anthropic, a) + pa, err := provider.Find("a") + if err != nil { + t.Fatal(err) + } + pa.Models = []string{"claude-opus-5-5"} + if err := provider.Save(*pa); err != nil { + t.Fatal(err) + } + b := &scripted{replies: []reply{{200, "text/event-stream", anthropicAnswer}}} + scriptedOn(t, "b", provider.Anthropic, b) + refusalGroup(t, "a/claude-opus-5-5", "b/m") + s := New() + for i := 0; i < thoughtCleanMost; i++ { + if code, body := sendTo(s, "/v1/messages", claudeCodeAsk); code != 200 || !strings.Contains(body, "from a") { + t.Fatalf("warm-up %d: %d %s (a %d)", i+1, code, body, a.n) + } + } + code, body := sendTo(s, "/v1/messages", claudeCodeAsk) + if code != 200 || !strings.Contains(body, "from b") || strings.Contains(body, "Overloaded") || + strings.Count(body, "event: message_start") != 1 || b.n != 1 { + t.Fatalf("error after trusted thinking: %d %s (a %d, b %d)", code, body, a.n, b.n) + } + if r := lastRoute(s); len(r.Tries) != 2 || r.Tries[0].Status != 529 || r.Tries[1].Fail != "" { + t.Fatalf("tries: %+v", r.Tries) + } +} + // A try that is asked again asks the same fake vendor again: a reply // that only reasoned is asked again in place (#667), and a full run's // state may have any ask retried. The fake's done holds one send, and