From b58669eb094ec0c70890dbe389d7bcea824b1acb Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 2 Nov 2026 18:24:14 +0800 Subject: [PATCH] gateway: an overload told in Codex's stream says server_is_overloaded (wjh66) wjh66 on Discord (Windows, v0.1.2710, Codex on the ChatGPT sign-in, gpt-6.1-sol): every turn showed "reconnecting 5/5", and app.log had the backend's "Our servers are currently overloaded" again and again. With one ChatGPT account, magpie asks an overloaded turn again (lastRetries) and keeps Codex alive past keepHeldAfter with the stream's 200 and comments. When the retries ran out, the backend's busy status (529, or a 503 saying overloaded) went to Codex in that stream as response.failed with code server_error. Codex reads server_error as Retryable (codex-rs codex-api sse/responses_error.rs) and sent the turn five more times, each one asked three times by magpie: 18 asks of an overloaded model, then the last error alone. The backend itself says an overload in a stream as server_is_overloaded (#1418), which Codex reads as ServerOverloaded: "Selected model is at capacity. Please try a different model.", without the reconnects. streamError now gives a Responses client server_is_overloaded when the status is 529, or a 5xx whose words say overloaded (saidOverloaded). Other failures keep server_error, which Codex retries. A routing group or the codex subscription's fallbacks still take an overload before any of this, as before. This does not explain the earlier "error decoding response body". Codex says that only when the body of a 2xx fails to read. magpie's streams read clean over real TCP in every overload shape tried (see 07f4d46c5, which logs a reply cut early). Ran on mote at this change rebased on 1cb4d4301: gofmt; go vet darwin, GOOS=linux -tags nogui, GOOS=windows; go test -count=1 -timeout 45m ./internal/gateway: ok but for TestCodexPoolSaysTheClientsVersion, the known #4807 (the machine's own Codex 0.165.0 identity reaches it). At the pushed head (rebased on f95bacdfb, whose new commits add hub_mcp.go to the gateway, nothing of streamError): go vet darwin, linux, windows, and the overload, StreamError and Hub tests: ok. On Windows (win-run): TestCodexKeptAliveOverload*, TestStreamErrorOverloadOnly, TestCodexOneAccount*, TestCodexOwnModel*, *Overload*, *StreamError*, TestCodexReplyBrokenOffLogged, TestCodexClientGoneLogged: ok, 50 tests. Broken by hand: with the else-if turned off, TestCodexKeptAliveOverloadSaysServerIsOverloaded is red in both subtests (503 message, 529): code "server_error". Not tried: a real ChatGPT account or the real Codex client against this build. Whether gpt-6.1-sol is busy for this account only, or the same request without magpie. The Windows system proxy between Codex and 127.0.0.1 as the cause of the decode error. --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/codex_overload_shape_test.go | 77 +++++++++++++++++++ internal/gateway/gateway.go | 15 ++++ 3 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 internal/gateway/codex_overload_shape_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 4262910e8..4d4b7451d 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -199,7 +199,7 @@ recorded as a prediction failure (`noPrediction`). - 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, 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`). 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). +- 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. - 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'`. diff --git a/internal/gateway/codex_overload_shape_test.go b/internal/gateway/codex_overload_shape_test.go new file mode 100644 index 000000000..e541af36e --- /dev/null +++ b/internal/gateway/codex_overload_shape_test.go @@ -0,0 +1,77 @@ +package gateway + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +// The ChatGPT backend too busy for a turn, said as a status, once Codex +// has been kept alive with the stream's headers, reaches it as the +// backend says an overload in a stream: response.failed with +// server_is_overloaded, which Codex shows as the model at capacity. As +// server_error, Codex took it for a dropped stream and sent the turn +// five more times ("reconnecting 5/5", wjh66 on Discord). +func TestCodexKeptAliveOverloadSaysServerIsOverloaded(t *testing.T) { + for name, failed := range map[string]reply{ + "503 message": {503, "application/json", `{"message":"Our servers are currently overloaded. Please try again later."}`}, + "529": {529, "application/json", overloadedStatus}, + } { + t.Run(name, func(t *testing.T) { + k, w := keepHeldAfter, watchEvery + keepHeldAfter, watchEvery = time.Millisecond, time.Millisecond + t.Cleanup(func() { keepHeldAfter, watchEvery = k, w }) + o := &overloadedBackend{replies: []reply{failed}} + oneCodexAccount(t, o) + retryPause = 20 * time.Millisecond // past keepHeldAfter: Codex is sent the headers + code, body := codexPost(t, oneAccountTurn) + if code != 200 || o.asked() != 1+lastRetries { + t.Fatalf("%d %q, asked %d times", code, body, o.asked()) + } + var got string + for _, l := range strings.Split(body, "\n") { + data, ok := strings.CutPrefix(l, "data: ") + if !ok { + continue + } + var ev struct { + Type string `json:"type"` + Response struct { + Error struct{ Code, Message string } `json:"error"` + } `json:"response"` + } + if json.Unmarshal([]byte(data), &ev) == nil && ev.Type == "response.failed" { + got = ev.Response.Error.Code + if !strings.Contains(ev.Response.Error.Message, "overloaded") { + t.Errorf("message %q", ev.Response.Error.Message) + } + } + } + if got != "server_is_overloaded" { + t.Fatalf("response.failed code %q, want server_is_overloaded:\n%s", got, body) + } + }) + } +} + +// Only an overload is said as one: another failure told in a stream +// keeps server_error, which Codex retries. +func TestStreamErrorOverloadOnly(t *testing.T) { + for _, c := range []struct { + status int + msg string + want bool + }{ + {529, "busy", true}, + {503, "Our servers are currently overloaded.", true}, + {503, "Service Unavailable", false}, + {502, "upstream connect error", false}, + {429, "overloaded with requests", false}, + {400, "overloaded", false}, + } { + if got := saidOverloaded(c.status, c.msg); got != c.want { + t.Errorf("%d %q: %v, want %v", c.status, c.msg, got, c.want) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 1c418e60e..9d59860a6 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -8872,6 +8872,15 @@ func streamError(w http.ResponseWriter, proto provider.Protocol, model string, s overflow := tooLong(status, msg) if overflow { ev.Code = "context_length_exceeded" + } else if proto == provider.Responses && saidOverloaded(status, msg) { + // The ChatGPT backend says its overload in a stream as + // response.failed with server_is_overloaded (#1418), which Codex + // reads as the model at capacity and stops on (codex-rs codex-api + // sse/responses_error.rs). A busy status told once Codex has the + // stream's headers went as server_error, which Codex retries as a + // dropped stream: five more turns, each asked again by magpie, + // "reconnecting 5/5" and the last error alone (wjh66 on Discord) + ev.Code = "server_is_overloaded" } // A 413 before the headers go out is typed request_too_large // (writeErrorSaid). Once they have, Pi reads only this event's text @@ -8897,6 +8906,12 @@ func streamError(w http.ResponseWriter, proto provider.Protocol, model string, s makeEncoder(proto, sw, &Request{Model: model}).event(ev) } +// saidOverloaded says a failure is the vendor too busy for the request: +// a 529, or a 5xx whose words say overloaded. +func saidOverloaded(status int, msg string) bool { + return status == 529 || (status >= 500 && strings.Contains(strings.ToLower(msg), "overloaded")) +} + // passingSaid matches the words an agent that reads only an error's text // takes for a failure worth asking again (Pi's isRetryableError, #2372): // one of the usual statuses, a timeout, a rate limit, a busy or