From 2be5d206e18bd53f95d5c364c2b0c80e69f7ee34 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 1 Nov 2026 11:14:43 +0800 Subject: [PATCH] gateway: a Codex summary request too large for the vendor is asked again as text, then compacted locally (celestial_eagle_99230 on Discord) celestial_eagle_99230 (Discord #general, v0.1.2403) runs Codex on official DeepSeek (DeepSeek-V4.1-Flash, 1M window) and gets "413 Request Entity Too Large: Failed to buffer the request body: length limit exceeded". The turn path was fixed by 2cca11176 (v0.1.2419): Codex gets context_length_exceeded and compacts. But the compaction is the problem. Codex (openai/codex main, compact_remote_v2.rs) sends its summary request through the same /responses route, trims only by its token estimate against the catalog's 1M window, and on ContextWindowExceeded does not trim and retry. A conversation that is over DeepSeek's byte cap (base64 images and long tool outputs sent each turn) is under 1M tokens, so the summary request was the same oversize body. magpie passed the 413 (or overflow) back, compaction failed each time, compactFails held later tries, and the session could neither compact nor go on. codexCompact now counts a 413 or an overflow on the summary request (summaryTooLarge) with the failures it already asks again as text (plainCompact: images left out, tool outputs over 4000 chars cut, at most 400K chars), then compacts without a model (localSummary) when that is refused too. This is keyed on the status and overflow words, not on DeepSeek: a summary request refused for its size means the same thing for every vendor, and the old result (a session stuck) is never better. Any other refusal goes back unchanged (TestCodexCompactOtherRefusalStays, TestCodexCompactOtherFailuresStay), and a non-Codex client still gets the 413 as request_too_large (TestDeepSeekByteCapTurn's opencode case, TestByteCapBeforeStreamStaysStatusForOthers). DeepSeek probed without a key (no tokens): bodies of 1 to 40MB to api.deepseek.com/chat/completions get 401 "Authentication Fails"; 80MB and 120MB get openresty's text/html 413 page. The reporter's text is axum's body-limit error, which sits behind auth, so its value is unknown. DeepSeek's docs list no 413 and no byte limit. Run, mote (mote-run): - Red at origin/main fb3942ee6 with only the new test file: TestCodexCompactTooLargeAsksSmaller (all 4: Chat/Responses x byte cap/overflow) got 413 "compaction: ... answered the summary request 413" or 400 context_length_exceeded; TestCodexCompactTooLargeCompactsLocally got 413. TestDeepSeekByteCapTurn passed (2cca11176's turn path). - Green with the fix; broken by hand (summaryTooLarge returning false): all 4 AsksSmaller subtests and CompactsLocally red again. - At the pushed head (rebased on 90c02326b): go test -count=1 -run 'Codex|Compact|Overflow|ByteCap|TooLarge|DeepSeek|StreamError' ./internal/gateway ok (90s). go vet ./internal/gateway on darwin, GOOS=linux -tags nogui and GOOS=windows ok. gofmt -l clean. Not tried: the whole internal/gateway package and ./... (mote was running another session's 45m multi-package suite at load ~210, and one suite runs at a time); a real Codex binary end to end (its compaction was read from source); a real signed-in DeepSeek request (the cap's value is unknown). --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/codex_backend.go | 16 +- .../gateway/codex_compact_too_large_test.go | 211 ++++++++++++++++++ 3 files changed, 227 insertions(+), 2 deletions(-) create mode 100644 internal/gateway/codex_compact_too_large_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f26e93900..e952c4fc0 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -251,7 +251,7 @@ recorded as a prediction failure (`noPrediction`). - Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming Messages request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. The signature itself is kept in magpie's folder, `gemini-signatures/`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__`), so an id stays under 64 characters however long the step's signature (#2411: LobeHub's PostgreSQL index turned away a 3KB id). A key magpie no longer has, or whose file doesn't hash to it, reads as no signature; one not read for 90 days is removed. Where the folder can't be written, the id carries the signature as before. Across APIs, only Claude's reasoning is carried to a Responses client, below. - Claude signs a thinking block for the conversation and the account it was made in. When an Anthropic upstream answers 400 that a block's signature is invalid, "bound to a different conversation" or "not created in this conversation" (`boundRefusal`: a conversation moved between accounts or providers, or a relay that serves Claude from several accounts of its own; ferock on Discord, through Command Code's plugin), `forward` asks once more without the block it names (`messages..content.`) and every thinking block after it, whose signatures cover it, and remembers those signatures for that provider and account (`refuseBoundThinking`, `withoutRefusedThinking` in [`thinking_bound.go`](../../internal/gateway/thinking_bound.go)), so the conversation's later turns go without them the first time. Every route to an Anthropic upstream (relayed, translated, a plugin's fetch, count_tokens) passes there. Blocks before it, other providers and accounts, and every other refusal (DeepSeek's wanting its thinking back among them) are left as they are. magpie doesn't send the `thinking-binding-controls` beta's `drop_block` for an agent. `TestBoundThinkingLeftOut`, `TestPluginBoundThinkingLeftOut`, `TestOtherRefusalKeepsThinking`. - Claude's reasoning goes to a Responses client (Codex) in an envelope and comes back as Claude wrote it (mysterious_dove_96933 on Discord). Anthropic wants a tool loop's next request to have the turn's thinking blocks, signed, and its `redacted_thinking` whole, or answers 400; Codex with `store: false` keeps only a reply's items, and of a reasoning item only `encrypted_content` is opaque. So the Anthropic decoders name a signature as Claude's (`KSig` with `sealAnthropic`, `Part.SignedBy`), and the Responses encoder and `renderResponses` give each thinking block a reasoning item whose `encrypted_content` is `magpie-claude1:` and the block's JSON in base64 (`claudeThinking`, [`internal/claudeseal`](../../internal/claudeseal/claudeseal.go)): its summary with it, an empty summary for a block signed with no text, and a `redacted_thinking` block as an item of its own. `parseResponses` reads such an item back into the block (`claudePart`), in order, so `anthropicBody` sends it as it was; an envelope that can't be read is its summary, as before. A Gemini thought's signature isn't named, and isn't sealed. The envelope goes to no Responses API: `passthrough` and `forwardOnce` take it out (`withoutClaudeSeals`: the item keeps its summary, one with none goes), `codexInputAs` leaves such an item out for Codex's own models as it does one with nothing sealed, and `codexUpstreamOn` takes it out before the ChatGPT backend; OpenAI's own `encrypted_content` is untouched. `redact.MaskJSON` keeps it whole (a reasoning item's seal), so the placeholders Claude was sent stay in what its signature covers. Claude's subscription names its signatures too, so Codex gets the same items, though its tool loop goes on inside Claude Code's own run, which keeps the thinking itself. `TestCodexToolLoopGivesClaudeItsThinkingBack`, `TestClaudeBlocksNeverGoToAResponsesAPI`, `TestGeminiSignatureIsNotSealedAsClaudes`, `TestMaskJSONKeepsClaudeBlocks`. -- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them — one that carries its text in it (content parts, another vendor's shape) made over into one magpie could have, its text a summary and nothing sealed, in a reply translated or relayed as it came, for the client to store and replay where OpenAI's rules hold even with magpie disconnected (#2855, the reporter's rollout: 25 reasoning items a DeepSeek phase had left, each with its text in it and a seal of the vendor's own, stuck every later turn on OpenAI with a 400 `array too long` nothing of magpie's could strip then); any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. The summary request magpie makes offers none either: `codexInputAs` sends `tools: []` and leaves out the `additional_tools` input item, where Codex's Responses Lite (the entry of a ChatGPT account's gpt-6 model, copied from Codex's own) puts every tool; left in, the model may call one in place of the summary (the likely cause of WuSix's codex/gpt-6-astra "the model wrote no summary" on Discord, not confirmed on a real reply), and a reply with no summary says what it held instead (`answeredWith`). A reply that called a tool instead (`calledTool`) is asked once more with the conversation as text (`plainCompact`), and compacted locally when that writes no summary either: a model deep in an exchange of calls goes on with it whatever it is offered (Lucy on Discord: DeepSeek through group/auto-deepseek-v4-1-flash answered reasoning and an `exec_command` call 3 times in a row; `TestCodexCompactToolCallAsksAgainAsText`, `TestCodexCompactToolCallEveryTimeCompactsLocally`, over Chat, Responses and Messages, a group and a single model). When a provider answers its summary request 404, 405 or 501 (`lacksEndpoint`), or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). Any other failure goes back with its status, said as the compaction's with who answered it (`compactFailed`: "compaction: (, ) answered the summary request 502 Bad Gateway: …"), the vendor's code, param and Retry-After kept. Not so the compaction Codex runs before a turn on another model, on the model the thread was on: a switch to a smaller window (`compaction.reason` `model_downshift` in the turn metadata) or to another compaction hash (`comp_hash_changed`), the only places Codex names either (`maybe_run_previous_model_inline_compact` in codex-rs `core/src/session/turn.rs`). When it fails, Codex asks the turn's own model instead only under its provider named "OpenAI" (`compact_model_fallback.rs`). Under magpie's provider, the one Codex has while its sign-in is used up (codex.out), the refusal was the turn's, and every turn of that thread asked the used-up account again, restarts or not, while a new thread worked (hiwise_aigc on X). Off `CodexPath`, `codexCompact` compacts such a failure locally (`previousModelCompaction`), whatever the failure, the compaction-failure hold included, and the thread goes on on the model it was switched to. On `CodexPath` the provider is Codex's own "OpenAI", which asks the turn's model itself, so the failure goes back as before. `TestCodexLeavingModelCompactsLocally`; Codex 0.162.1 in a sandbox sent the old model's `compaction_trigger` to `/v1` and failed the turn on a 429, and went on to the new model once the trigger was answered. A compaction relayed to OpenAI (`/responses/compact` on Codex's own model, as a `/responses` turn) that OpenAI answers with an error status and an empty body, which Codex shows as "unexpected status 502 Bad Gateway: Unknown error", or with a web page, is said in words naming the model, the status, and the account it went to (`codexSaidNothing`, outrageous_piglet on Discord); an error OpenAI says in JSON goes as it came. `TestCodexOwnCompactFailureIsSaid`, `TestCodexCompactFailureSaysCompaction`, `TestCodexCompactNoEndpointCompactsLocally`. So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301). A summary is wanted only whole (`askWhole`, `holdWriter.wantWhole`): its stream is held to its end, not let through at its first words, so a reply cut short (`errEndedShort`), failed halfway (a 429 "Individual quota reached" after some of it) or ended `incomplete` (`endedIncomplete`, `incompleteReply`) fails over to the next candidate like a failure before any of it, and rests the account as that failure would; one that reached its output limit rests nobody. With nobody left, `codexCompact` answers 502 and never hands Codex the words before the cut as the summary (#2274, huangzuomin: Antigravity cutting each summary short) — but one whose stream merely broke off, with nothing failed or incomplete in it, is followed by magpie's own summary (#3526, Edward4226: Codex told a 502 asked the same huge summary over three times and the guard then held the conversation), as when no model can be asked at all. So is a translated summary serve found cut and answered 502 "the reply ended before it was complete" (`summaryEndedShort`).. Codex with context_management's experimental mode compacts in the background at every step while the conversation is over its threshold and drops a failed compaction without a word, so a conversation whose summaries keep failing is asked again every few seconds, each paying for the whole history (1169 compactions in 6 hours there). After `compactFailsMost` (3) failed summaries in a row of one conversation (`prompt_cache_key`) on one model, each within `compactHeldFor` (5 minutes) of the last, the next is answered at once with a 400 naming the last failure, which Codex doesn't ask again, and no model is asked until 5 minutes have passed (`compactFails` in [`codex_compact_guard.go`](../../internal/gateway/codex_compact_guard.go)); a summary that comes clears the count, and a sign-in's 401 or 403 isn't counted. `TestCodexCompactCutSummaryFailsOver`, `TestCodexCompactCutSummaryIsNoSummary`, `TestCodexCompactKeepsFailingIsHeld`. +- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them — one that carries its text in it (content parts, another vendor's shape) made over into one magpie could have, its text a summary and nothing sealed, in a reply translated or relayed as it came, for the client to store and replay where OpenAI's rules hold even with magpie disconnected (#2855, the reporter's rollout: 25 reasoning items a DeepSeek phase had left, each with its text in it and a seal of the vendor's own, stuck every later turn on OpenAI with a 400 `array too long` nothing of magpie's could strip then); any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. The summary request magpie makes offers none either: `codexInputAs` sends `tools: []` and leaves out the `additional_tools` input item, where Codex's Responses Lite (the entry of a ChatGPT account's gpt-6 model, copied from Codex's own) puts every tool; left in, the model may call one in place of the summary (the likely cause of WuSix's codex/gpt-6-astra "the model wrote no summary" on Discord, not confirmed on a real reply), and a reply with no summary says what it held instead (`answeredWith`). A reply that called a tool instead (`calledTool`) is asked once more with the conversation as text (`plainCompact`), and compacted locally when that writes no summary either: a model deep in an exchange of calls goes on with it whatever it is offered (Lucy on Discord: DeepSeek through group/auto-deepseek-v4-1-flash answered reasoning and an `exec_command` call 3 times in a row; `TestCodexCompactToolCallAsksAgainAsText`, `TestCodexCompactToolCallEveryTimeCompactsLocally`, over Chat, Responses and Messages, a group and a single model). When a provider answers its summary request 404, 405 or 501 (`lacksEndpoint`), or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). So does a summary request refused for its size (`summaryTooLarge`): a 413 byte cap, or an overflow of the model's window. Codex's remote compaction trims only by its own token estimate against the catalog's window and asks nothing smaller after either, so the turn's `context_length_exceeded` led to a compaction refused the same way, every time, and the session could neither compact nor go on (celestial_eagle_99230 on Discord: DeepSeek's own API, 1M window, answered 413 "Failed to buffer the request body: length limit exceeded"). The text ask leaves images out, keeps the ends of a long output and the latest 400K characters. `TestCodexCompactTooLargeAsksSmaller`, `TestCodexCompactTooLargeCompactsLocally`, `TestCodexCompactOtherRefusalStays`. Any other failure goes back with its status, said as the compaction's with who answered it (`compactFailed`: "compaction: (, ) answered the summary request 502 Bad Gateway: …"), the vendor's code, param and Retry-After kept. Not so the compaction Codex runs before a turn on another model, on the model the thread was on: a switch to a smaller window (`compaction.reason` `model_downshift` in the turn metadata) or to another compaction hash (`comp_hash_changed`), the only places Codex names either (`maybe_run_previous_model_inline_compact` in codex-rs `core/src/session/turn.rs`). When it fails, Codex asks the turn's own model instead only under its provider named "OpenAI" (`compact_model_fallback.rs`). Under magpie's provider, the one Codex has while its sign-in is used up (codex.out), the refusal was the turn's, and every turn of that thread asked the used-up account again, restarts or not, while a new thread worked (hiwise_aigc on X). Off `CodexPath`, `codexCompact` compacts such a failure locally (`previousModelCompaction`), whatever the failure, the compaction-failure hold included, and the thread goes on on the model it was switched to. On `CodexPath` the provider is Codex's own "OpenAI", which asks the turn's model itself, so the failure goes back as before. `TestCodexLeavingModelCompactsLocally`; Codex 0.162.1 in a sandbox sent the old model's `compaction_trigger` to `/v1` and failed the turn on a 429, and went on to the new model once the trigger was answered. A compaction relayed to OpenAI (`/responses/compact` on Codex's own model, as a `/responses` turn) that OpenAI answers with an error status and an empty body, which Codex shows as "unexpected status 502 Bad Gateway: Unknown error", or with a web page, is said in words naming the model, the status, and the account it went to (`codexSaidNothing`, outrageous_piglet on Discord); an error OpenAI says in JSON goes as it came. `TestCodexOwnCompactFailureIsSaid`, `TestCodexCompactFailureSaysCompaction`, `TestCodexCompactNoEndpointCompactsLocally`. So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301). A summary is wanted only whole (`askWhole`, `holdWriter.wantWhole`): its stream is held to its end, not let through at its first words, so a reply cut short (`errEndedShort`), failed halfway (a 429 "Individual quota reached" after some of it) or ended `incomplete` (`endedIncomplete`, `incompleteReply`) fails over to the next candidate like a failure before any of it, and rests the account as that failure would; one that reached its output limit rests nobody. With nobody left, `codexCompact` answers 502 and never hands Codex the words before the cut as the summary (#2274, huangzuomin: Antigravity cutting each summary short) — but one whose stream merely broke off, with nothing failed or incomplete in it, is followed by magpie's own summary (#3526, Edward4226: Codex told a 502 asked the same huge summary over three times and the guard then held the conversation), as when no model can be asked at all. So is a translated summary serve found cut and answered 502 "the reply ended before it was complete" (`summaryEndedShort`).. Codex with context_management's experimental mode compacts in the background at every step while the conversation is over its threshold and drops a failed compaction without a word, so a conversation whose summaries keep failing is asked again every few seconds, each paying for the whole history (1169 compactions in 6 hours there). After `compactFailsMost` (3) failed summaries in a row of one conversation (`prompt_cache_key`) on one model, each within `compactHeldFor` (5 minutes) of the last, the next is answered at once with a 400 naming the last failure, which Codex doesn't ask again, and no model is asked until 5 minutes have passed (`compactFails` in [`codex_compact_guard.go`](../../internal/gateway/codex_compact_guard.go)); a summary that comes clears the count, and a sign-in's 401 or 403 isn't counted. `TestCodexCompactCutSummaryFailsOver`, `TestCodexCompactCutSummaryIsNoSummary`, `TestCodexCompactKeepsFailingIsHeld`. - A reasoning item with its text in it (`content` parts: DeepSeek's Responses API writes `reasoning_text`, relayed to Codex as it came) is another vendor's. OpenAI's API and the ChatGPT backend take a reasoning item's `content` only empty, and refuse the whole request over one with 400 "Invalid 'input[n].content': array too long. Expected an array with maximum length 0" (`array_above_max_length`). Codex hands the item back on every later turn, so it never goes to them: for one of Codex's own models, `codexInput(body, false)` leaves it out (and a reasoning item with nothing sealed in it) on `/backend-api/codex`'s `/responses` and on `/responses/compact`, before Codex's own sign-in, its API key or a magpie Codex account (`compactOn`) is asked. Codex compacts a thread before its first turn back on its own model, and a refused compaction shows as that turn's error (jue on Discord). `passthrough` leaves it out for OpenAI, Azure OpenAI and a Codex account (`withoutReasoningText`), and for any other upstream once it has refused one (`refusesReasoningText`, `reasoningTextRefused`, #1411). OpenAI's own sealed reasoning (`encrypted_content`, no text) stays, and a DeepSeek model (`replaysReasoning`) still gets the text. `TestForeignReasoningNeverReachesOpenAI`, `TestReasoningTextLeftOutWhereRefused`, `TestReasoningTextNotSentToCodexAccount`. - Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The trigger is kept only when a key or account the request would go over (the provider's and its fallbacks', or a group's members', held and capped ones too, not one whose own list lacks the model) can be asked it on Responses (`plannedCarrier`, read from `perKeyBarred` without weighing, so a provider routed in turn isn't moved along by the decision). When the vendor lists the model only to keys that speak no Responses there, a key set to Chat say, `codexCompact` gives magpie's summary through the listed key, as with native compaction off; before, the trigger was kept and refused 400 `carrierError` with no upstream asked (#2725, ggbdpq; `TestNativeCompactionTriggerSummarisedWhenNoListedKeyCarriesIt`, `TestNativeCompactionTriggerThroughTheListedKeyThatCarriesIt`, `TestNativeCompactionDecisionLeavesTheTurnsAlone`). The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); a writer whose own list has since dropped the model is tried still, as the last resort an account whose list lacks the model is — it sealed the model's compaction, and no other can read it (`planned.unlisted`, `TestNativeCompactionWriterWhoseListLacksTheModel`, #2642: it was refused as "switched off, removed, or no longer serves" though it was on, and switching it on changed nothing). With the writer gone from the candidates, magpie answers 400 `checkpointError` with the reason its settings give (`checkpointGone`: the provider removed, the account signed out, its sign-in lapsed, paused while others are on, switched off, kept from the model in Names & levels, the key off or gone, the model disabled, or the model or group asked for not going to it), what lets the conversation go on, and whether native compaction is on for the writer's provider now, and never sends it to another key, drops it, or summarises it in its place (`TestNativeCompactionWriterGoneSaysWhy`). One of Codex's own models asked on the backend path is decided as a magpie model is when magpie's Codex accounts serve it (`codexAccounts`): the trigger is kept only with the codex provider's native compaction on, else `codexCompact` gives magpie's summary, which any account reads, and no writer is recorded (#2582, ump45nose; before, every such compaction was sealed natively whatever the setting, and the conversation was held to its account; `TestCodexOwnModelCompactionHonoursTheToggle`). Codex's own sign-in alone, relayed as it came, still compacts natively, unrecorded, as does `/responses/compact`; but a request carrying a compaction magpie recorded the writer of goes through routing even then (`codexSealedFor`), so with the writer switched off the one account left isn't sent it. A legacy `/responses/compact` carrying one is judged at its passthrough (`sealedCompact`): the writer on in magpie answers it signed as the writer — its own seal while the sign-in can be asked, a key's seal, a request signing with its own `chatgpt-account-id`, or an unreadable sign-in state relays as it came — and a writer gone is refused with `checkpointError`'s reason, the same words as on `/responses` (`TestNativeCompactionCompactJudgesItsWriter`, #2727). The writer matched is the account user the record holds, so two Team seats of one email read as one and such a compact relays as it came. A gateway key held to some accounts (#905) is asked of the account the compact goes to (`compactSigninHeld`): the writer when it answers it, so a writer the key may not use is refused 403 (`sealedCompactHeldError`) with nothing asked, and one it may use answers though the sign-in isn't the key's (`TestNativeCompactionCompactKeepsTheKeysAccounts`). With the writer held at its usage cap or for credits it may not spend, the answer is 429 `checkpointCappedError` (record `checkpointCappedRecord`, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; `TestNativeCompactionWriterAtItsCap`). `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A route carrying a compaction names its sealer (`Route.Compaction`), and Routing says that is why no other account was asked, not that it is "the only account on" for the model (#2639; `TestNativeCompactionRouteNamesItsWriter`, `routing-compaction.test.cjs`). A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`. - A compaction magpie answers itself (`codexCompact`: a magpie model, Codex's own models through magpie's Codex accounts, a CC Switch table) goes to Codex as a `compaction` item whose `encrypted_content` is `magpie1:` and the summary in base64 (`codexsummary.Encrypted`), and `codexInputAs` sends Codex's own summary message in its place (`codexsummary.Message`: Codex's summary prefix, a newline and the summary, as a user message). Codex keeps the item in its rollout and replays it, and OpenAI refuses it once Codex talks to OpenAI itself (`invalid_encrypted_content`, LukeMa on X). So `sessions.PortCodexRollouts` writes that same message into the rollouts in its place ([`codex_portable.go`](../../internal/sessions/codex_portable.go)). A reasoning item carrying Claude's block (`magpie-claude1:`, above) is written as its summary, as the gateway sends it to OpenAI (`TestPortLineDropsClaudeBlocks`). It changes only magpie's items, keeps every other line's bytes and the file's line count, mode and time, and drops an unreadable item together with its `replacement_history_metadata` entry. Every rewritten line keeps its length (`fitLine`: a shorter one padded with spaces after its JSON, a longer one in a paginated rollout not written), as Codex keeps places in a rollout by byte: a fork's `history_base.end_byte_offset` and the state database's turn and projection offsets. A shorter parent left a fork's place past its end, and Codex refused to open the fork ("cutoff byte offset is past the source rollout", xybio on Discord); once per Codex home a pass sets each such fork's place again from the ordinal it names (`repairLineages`). `MoveCodexProvider` keeps the session_meta line's length the same way and refuses a longer provider id for a paginated rollout. It and `MoveCodexThreads` (Codex stepping off magpie) hold the thread's writer lock as Codex's own archive does, from before a file is copied until the thread's row has moved: a Codex that has the thread open writes on to the file it opened, and what it wrote after a move was lost (#3751). Such a thread is refused as one written to in the last minute is (`ErrActive`), and a Codex home without writer locks moves as before. A pass publishes as Codex publishes a compressed rollout: under `thread-writer-locks/.coordination.lock`, only with the thread's lock free, through a temp file and a rename. A thread a Codex has open is left for a later pass, and a Codex home without writer locks is left alone. It runs 2 minutes after the GUI or `magpie serve` starts and every 10 minutes after, on Codex Disconnect (3s), and as the GUI quits (3s). Each pass reads what changed since the last whole pass, plus what was held (`codex-portable.json`). A ported thread was resumed by Codex 0.162.1 against an upstream that refuses `magpie1:` as OpenAI does. Not tried: a Codex in a WSL distro, whose locks this machine can't take, so it is skipped. `TestPortCodexRollouts*`, `TestPortedCompactionReadsTheSame`. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 5e3a1f261..29d9c499a 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -3218,7 +3218,7 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt rec, res, err := ask(body) local := "" if first := rec.status; lacksEndpoint(first) || itemNotFound(rec) || upstreamFailed(rec) || protectionRefused(first, rec.body.Bytes()) || - err != nil && protectionWords.MatchString(err.Error()) { + summaryTooLarge(rec) || err != nil && protectionWords.MatchString(err.Error()) { who, msg := compactFailure(body, rec) if err != nil { msg = "broken off: " + err.Error() @@ -3421,6 +3421,20 @@ func upstreamFailed(rec *recorder) bool { var upstreamFailedWords = regexp.MustCompile(`(?i)upstream request failed`) +// summaryTooLarge is a summary request refused for its size: past the +// vendor's byte cap (413; DeepSeek's "Failed to buffer the request body: +// length limit exceeded", celestial_eagle_99230 on Discord) or past the +// model's window. Codex's remote compaction asks nothing smaller after +// either (it trims only by its token estimate against the catalog's +// window, and a 1M window holds more bytes than the cap takes), so told +// of it, Codex could neither compact nor go on. The summary is asked +// again as text, its images left out and long outputs cut +// (plainCompact), and compacted without a model when that is refused +// too. +func summaryTooLarge(rec *recorder) bool { + return rec.status == http.StatusRequestEntityTooLarge || overflowed(rec.status, rec.body.Bytes()) +} + // itemNotFound is a 400 refusing an item of the input by its id, as Azure // OpenAI's and OpenAI's API answer one they never stored ("Item with id // 'rs_…' not found", #1008), which a relay in front of them passes on. diff --git a/internal/gateway/codex_compact_too_large_test.go b/internal/gateway/codex_compact_too_large_test.go new file mode 100644 index 000000000..2486b5871 --- /dev/null +++ b/internal/gateway/codex_compact_too_large_test.go @@ -0,0 +1,211 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// deepseekBodyCap is what DeepSeek's API answered a Codex user's long +// session with (celestial_eagle_99230 on Discord: "1017dp: 413 Request +// Entity Too Large: Failed to buffer the request body: length limit +// exceeded"): axum's text for a body past its byte limit, as text/plain. +// It is a cap on the request's bytes, which DeepSeek documents nowhere; +// its 1M-token window is not what was full. +const deepseekBodyCap = "Failed to buffer the request body: length limit exceeded" + +// deepseekOverflow is DeepSeek's own 400 for a prompt past the model's +// window, OpenAI's words. +const deepseekOverflow = `{"error":{"message":"This model's maximum context length is 1048576 tokens. However, you requested 1100000 tokens (1100000 in the messages, 0 in the completion). Please reduce the length of the messages or completion.","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}` + +// capped is an upstream that refuses a body of more than most bytes with +// status and body (as ctype), and answers any other with a summary in its +// protocol's stream. Every body it is sent is kept. +type capped struct { + proto provider.Protocol + most int + status int + ctype string + body string + mu sync.Mutex + got [][]byte +} + +func (c *capped) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + c.mu.Lock() + c.got = append(c.got, b) + c.mu.Unlock() + if len(b) > c.most { + w.Header().Set("Content-Type", c.ctype) + w.WriteHeader(c.status) + io.WriteString(w, c.body) + return + } + w.Header().Set("Content-Type", "text/event-stream") + if c.proto == provider.Chat { + io.WriteString(w, sse( + `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"SUMMARY"}}]}`, + `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":1}}`, + `data: [DONE]`)) + return + } + io.WriteString(w, sse( + `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"SUMMARY"}]}}`, + `data: {"type":"response.completed","response":{"id":"resp_s","status":"completed","output":[]}}`)) +} + +func (c *capped) calls() [][]byte { + c.mu.Lock() + defer c.mu.Unlock() + return append([][]byte(nil), c.got...) +} + +// cappedOn saves provider "fake" (model m1) on c, as setup does. +func cappedOn(t *testing.T, c *capped) { + t.Helper() + noRests() + t.Cleanup(noRests) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + up := httptest.NewServer(c) + t.Cleanup(up.Close) + p := provider.Provider{ID: "fake", Name: "1017dp", Key: "k", Models: []string{"m1"}} + if c.proto == provider.Chat { + p.Chat = up.URL + "/v1" + } else { + p.Responses = up.URL + "/v1" + } + if err := provider.Save(p); err != nil { + t.Fatal(err) + } +} + +// bigCompaction is Codex's summary request (remote compaction v2: a +// /responses stream ending in compaction_trigger) of a session holding a +// pasted screenshot as base64 and a long tool output: well over the cap +// below, while the conversation as text is well under it. +func bigCompaction() string { + img := strings.Repeat("iVBORw0KGgo", 60_000) // ~660KB of base64 + out := strings.Repeat("log line\\n", 40_000) // ~400KB of tool output + return `{"model":"fake/m1","stream":true,"store":false,"prompt_cache_key":"thread-ds","include":["reasoning.encrypted_content"], + "input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"fix the login bug"},{"type":"input_image","image_url":"data:image/png;base64,` + img + `"}]}, + {"type":"function_call","call_id":"call_1","name":"shell","arguments":"{\"cmd\":\"cat build.log\"}"}, + {"type":"function_call_output","call_id":"call_1","output":"` + out + `"}, + {"type":"message","role":"assistant","content":[{"type":"output_text","text":"I fixed main.go"}]}, + {"type":"message","role":"user","content":[{"type":"input_text","text":"now add a test"}]}, + {"type":"compaction_trigger"}]}` +} + +const cappedMost = 256 << 10 + +// A summary request too large for the vendor — past DeepSeek's byte cap +// (413), or past the model's window — went back to Codex as that +// failure. Codex's remote compaction has no way to shrink it (it trims +// only by its token estimate against the catalog's 1M window, and asks +// nothing smaller on context_length_exceeded), so every compaction failed +// the same way and the session could neither compact nor go on. magpie +// asks again with the conversation as text, its images left out and its +// long outputs cut, and Codex installs the model's summary. +func TestCodexCompactTooLargeAsksSmaller(t *testing.T) { + for _, proto := range []provider.Protocol{provider.Chat, provider.Responses} { + for _, c := range []struct { + name, ctype, body string + status int + }{ + {"byte cap", "text/plain; charset=utf-8", deepseekBodyCap, 413}, + {"overflow", "application/json", deepseekOverflow, 400}, + } { + t.Run(string(proto)+" "+c.name, func(t *testing.T) { + up := &capped{proto: proto, most: cappedMost, status: c.status, ctype: c.ctype, body: c.body} + cappedOn(t, up) + code, body := codexPost(t, bigCompaction()) + if code != 200 { + t.Fatalf("Codex's compaction failed: %d %s", code, body) + } + if got := compactedText(t, body); got != "SUMMARY" { + t.Fatalf("summary %q", got) + } + calls := up.calls() + // the last ask is the smaller one (a Chat overflow is + // asked once more by serve itself before) + if len(calls) < 2 || len(calls[0]) <= cappedMost { + t.Fatalf("asked %d times", len(calls)) + } + small := string(calls[len(calls)-1]) + if len(small) > cappedMost || strings.Contains(small, "iVBORw0KGgo") { + t.Fatalf("asked again as large (%d bytes) or with the image", len(small)) + } + for _, want := range []string{"fix the login bug", "now add a test", "I fixed main.go"} { + if !strings.Contains(small, want) { + t.Errorf("the smaller ask lacks %q", want) + } + } + }) + } + } +} + +// When the conversation as text is refused too, magpie compacts without a +// model, so Codex still goes on. +func TestCodexCompactTooLargeCompactsLocally(t *testing.T) { + up := &capped{proto: provider.Chat, most: 0, status: 413, ctype: "text/plain; charset=utf-8", body: deepseekBodyCap} + cappedOn(t, up) + code, body := codexPost(t, bigCompaction()) + if code != 200 { + t.Fatalf("Codex's compaction failed: %d %s", code, body) + } + got := compactedText(t, body) + for _, want := range []string{"fix the login bug", "now add a test", "I fixed main.go", "413", "length limit exceeded"} { + if !strings.Contains(got, want) { + t.Errorf("local summary lacks %q:\n%s", want, got) + } + } + if strings.Contains(got, "iVBORw0KGgo") { + t.Error("local summary holds the image") + } +} + +// A refusal of the summary request that says nothing of its size goes +// back to Codex as before, not asked again as text: only a request too large is asked +// again smaller. +func TestCodexCompactOtherRefusalStays(t *testing.T) { + up := &capped{proto: provider.Chat, most: 0, status: 400, ctype: "application/json", + body: `{"error":{"message":"Invalid tool schema","type":"invalid_request_error"}}`} + cappedOn(t, up) + code, body := codexPost(t, bigCompaction()) + if code != 400 || !strings.Contains(body, "Invalid tool schema") { + t.Fatalf("%d %s", code, body) + } + for _, b := range up.calls() { + if strings.Contains(string(b), "This is the conversation so far") { + t.Fatalf("asked again as text: %.200s", b) + } + } +} + +// The turn itself, refused with DeepSeek's byte cap before Codex's stream +// began, reaches Codex as response.failed context_length_exceeded, the +// code it compacts on; another client keeps the 413. +func TestDeepSeekByteCapTurn(t *testing.T) { + for _, proto := range []provider.Protocol{provider.Chat, provider.Responses} { + t.Run(string(proto), func(t *testing.T) { + fresh(t) + up := &capped{proto: proto, most: 0, status: 413, ctype: "text/plain; charset=utf-8", body: deepseekBodyCap} + cappedOn(t, up) + code, ctype, body := askCodexStream(t, New(), "fake/m1", codexUA, nil) + if code != 200 || !strings.HasPrefix(ctype, "text/event-stream") || failedCode(body) != "context_length_exceeded" { + t.Fatalf("Codex wasn't told to compact: %d %s %s", code, ctype, body) + } + code, _, body = askCodexStream(t, New(), "fake/m1", "opencode/1.4.0 ai-sdk/openai", nil) + if code != 413 || !strings.Contains(body, "request_too_large") { + t.Fatalf("another client's 413: %d %s", code, body) + } + }) + } +}