From 9a51d644d65f26e7e73f72344fd4b3ac63ede856 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 5 Nov 2026 01:26:09 +0800 Subject: [PATCH] gateway: a compaction's summary late past 4 minutes is magpie's own, sent before Codex gives up (#5275) hayden4608 on Discord (#5275, asked as urgent): Codex Desktop compacting a ~108k-token conversation on volcengine/deepseek-v4.1-flash. The ~3.1MB summary request was still being written to Ark at 299s (TryNet Send ~299s, no first byte), Codex gave up at 300s (499), and only then did magpie log "the reply ended before it was complete; compacting locally". That local summary went to a request nobody was reading, and compactFails.done cleared the conversation's count as if it had worked. Codex sent the same history again, three times, 300s each, and the conversation never got shorter. - codexCompact gives the summary compactWithin (4 minutes, a minute short of Codex's 300s stream idle timeout, as agentQuietMost). Past it the vendor is no longer waited on (the ask's context ends with a sideTimedOut cause, so the usage log says "magpie stopped waiting: its compaction summary had no answer in 4m0s", not the agent canceling), and magpie's own summary (localSummary, saying "no summary came in 4m0s") goes to Codex while it still waits. Checked after the first ask, the ask as plain text, and the as-text ask after tool calls, so a late first ask is never followed by another ask of the same body. - A compaction Codex left before it was answered is counted a failure (499, "Codex left before the summary reached it") and nothing is written; done() is no longer called for it. After compactFailsMost in a row, the next is held with a 400 at once instead of another 300s. Why the upload was slow: not shown to be magpie's. From here a 3.1MB whitespace-padded chat request to ark.cn-beijing.volces.com/api/v3 was read whole in ~1.5s by curl over HTTP/2 and HTTP/1.1, and Go's client with vendorTransport's settings (HTTP/2, ping health) wrote it in 0.89s (HTTP/1.1 0.17s) from mote. The reporter's ~10KB/s, and their own 4MiB control not finishing in 40s by any route, point at the uplink or the Shadowrocket TUN in their path. Not tried through a TUN. Run (mote): TestCodexCompactLateSummaryCompactsLocallyInTime and TestCodexCompactLeftBeforeAnsweredStillCounts green with the fix; both red on the old code (the first: no answer before the client's 10s; the second: a completed compaction written to a Codex that left, and the next not held). go test -run Compact ./internal/gateway ok; go vet of internal/gateway for darwin, linux and windows ok; gofmt clean. Full suite: run after the push (go test -timeout 45m ./... on mote, log teed), result on #5275. Not tried: a real Codex Desktop session against a slow uplink; a reporter-side stream_idle_timeout_ms shorter than 4 minutes (then Codex still leaves first, and the count holds the conversation after 3). --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/codex_backend.go | 50 +++++++- internal/gateway/codex_compact_late_test.go | 129 ++++++++++++++++++++ 3 files changed, 178 insertions(+), 3 deletions(-) create mode 100644 internal/gateway/codex_compact_late_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index e8e708525..00d811381 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -264,7 +264,7 @@ recorded as a prediction failure (`noPrediction`). - 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`. - A thinking block DeepSeek's Anthropic endpoint made is signed with its reply's id, a UUID, which Claude refuses ("Invalid `signature` in `thinking` block"). A routing group whose conversation ran on DeepSeek and goes on to Claude (DeepSeek unticked; GgbondHi6930 on X) holds such blocks, so before any refusal, `forwardOnce` leaves them out of every request to an upstream serving Claude (api.anthropic.com, or a `claude-` model name; `withoutForeignThinking` in [`thinking_bound.go`](../../internal/gateway/thinking_bound.go)), and `refuseBoundThinking` reads a refusal's indices against that same body. Claude's own signatures (base64), unsigned blocks, redacted_thinking and other vendors' signatures go as they were; DeepSeek's endpoint and every other upstream get the body byte for byte. `TestDeepSeekThinkingThenClaude`, `TestDeepSeekThinkingThenClaudeResponses`, `TestWithoutForeignThinking`. - 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). 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 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 summary is waited for `compactWithin` (4 minutes) at most: Codex hears nothing while it is made and gives up on a stream silent for 300s, so a later summary, and a local one made after Codex left, reached nobody, and Codex sent the same history again, 300s each time (#5275, hayden4608: a ~3.1MB summary request still going up a ~10KB/s uplink at 299s). Past it the ask ends (`sideTimedOut`, logged as magpie's own limit, not the agent leaving) and magpie's own summary goes to Codex while it still waits. A compaction Codex left before it was answered writes nothing and counts as a failure (499), never clearing the count. `TestCodexCompactLateSummaryCompactsLocallyInTime`, `TestCodexCompactLeftBeforeAnsweredStillCounts`. - An `output_text` annotation without the offsets OpenAI's schema wants of its kind (a `url_citation` or `container_file_citation` with no `start_index`/`end_index`, as Volcengine Ark's Responses endpoint writes its url citations) cannot be replayed where that schema holds: the ChatGPT backend refuses the whole request, every turn of the thread, with "Missing required parameter: 'input[n].content[m].annotations[k].start_index'" (#4921; `withoutOffsetlessCitations` in [`codex_backend.go`](../../internal/gateway/codex_backend.go), the same leaving-out as a reasoning item's text, #1411). A whole reply streamed as the vendor's own events drops such an annotation in every place a client reads one (`dropOffsetlessCitations` beside `responsesWholeEvents` in [`whole_stream.go`](../../internal/gateway/whole_stream.go), the #2855 rule: what magpie hands a client must be something it could send again); a history that carries one goes to the ChatGPT backend, OpenAI's API and a relay that has turned one away without it, and a refusal naming the parameter is asked again without it (`refusesCitationOffsets`). The text, a citation with its offsets, and a `file_citation` or `file_path`, which OpenAI places by a single `index`, go as they came (`TestCitationsWithoutOffsetsAskedAgainWithout`, `TestWholeAsStreamDropsCitationsWithoutOffsets`, `TestCitationsWithOneIndexKept`). - 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`. - A conversation that moves to another key, account or vendor carries what the one before sealed (`encrypted_content`): its reasoning, and the sealed copy an answer's other items may carry: a web search's (`web_search_call`), and with Codex's output token replay on, each message's and call's (Codex keeps those for a provider named "OpenAI" only, and signed in it reaches magpie as that provider). `forVendor` takes the copies out for a vendor not OpenAI's, reasoning and compactions aside; between ChatGPT accounts, or a ChatGPT account and an OpenAI API key, all of it goes as it came. One that can't read it says so (`foreignReasoning`: OpenAI's `invalid_encrypted_content`, "could not be verified" of reasoning and "Encrypted content could not be decrypted or parsed." of a web search; xAI's "Could not decrypt"), as a 400 or as the stream's error, and `serve` asks it again without them (`withoutSeals`): a reasoning item goes whole, any other item keeps all but its `encrypted_content` (`withoutItemSeal`), and a compaction keeps its seal. Refused again, or with nothing else sealed, the compaction OpenAI sealed goes (`withoutCompaction`), unless native compaction is on (below). What was taken out is remembered by its hash for the conversation and the key or account that refused it, for `stickKeep` (`refused`, `refusedSeals`), and its later requests there leave it out up front (`withoutRefused`); what that one sealed itself still goes along, and a request that stays where its seals were made goes as it came. A refusal doesn't say whose seal it couldn't read, so every one goes, the asked one's own from an earlier stay in the conversation too, and all are remembered. It is the same whatever moved the conversation: a key or account resting, used up or rate limited, the next member of a group, or routing's own pick once its affinity went cold, on the backend path and on `/v1/responses` alike (#3887, hheei: after such a move a `web_search_call` another ChatGPT account of the group had sealed was refused, only the reasoning was left out, and every turn failed). Codex's own sign-in, relayed as it came (`codexUpstreamOn`), is asked again the same way when the backend answers its `/responses` with a 400 (`withoutUnreadable`, after the item the refusal names, if any); it keeps no record of what was refused, and a refusal in the stream reaches Codex as it came. `TestForeignSealAcrossGroupMembers`, `TestForeignSealGrokToCodexAccount`, `TestForeignSealedItemsMoveToAnotherAccount`, `TestForeignSealedItemsAfterAColdSwitch`, `TestForeignSealedItemsRelayedToAnotherSignIn`, `TestSealsTakenOutLeaveTheRest`. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 46ad1b257..7d1322dad 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -3463,6 +3463,16 @@ func developerItemsAsSystem(body []byte) []byte { func userMessage(text string) map[string]any { return codexsummary.UserMessage(text) } +// compactWithin is how long a compaction's summary is waited for before +// magpie's own goes in its place. Codex hears nothing while the summary is +// made, and gives up on a stream that says nothing for 300s +// (stream_idle_timeout_ms; agentQuietMost): a summary later than that is +// never read, and the local one written after it reached nobody, so Codex +// sent the same ~3MB history again, each time waiting 300s (#5275, +// hayden4608: a slow uplink still sending it at 299s). A minute short of +// it, as agentQuietMost. +var compactWithin = 4 * time.Minute + // codexCompact compacts a conversation held by a magpie model: the model // summarises it, and the summary goes back to Codex as the compaction item // the backend would have made, marked as magpie's so magpie reads it back @@ -3509,6 +3519,22 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt r = r.Clone(r.Context()) r.Header.Set(turnMetadataHeader, turn) } + // the summary has compactWithin, Codex hearing nothing meanwhile: past + // it, the summary is magpie's own, which Codex still takes (#5275) + client := r.Context() + budget, stop := context.WithCancelCause(client) + timer := time.AfterFunc(compactWithin, func() { stop(sideTimedOut{"compaction summary", compactWithin}) }) + defer func() { + timer.Stop() + stop(context.Canceled) + }() + late := func() bool { _, ok := sideTimeout(budget); return ok } + lateSummary := func() string { + why := fmt.Sprintf("no summary came in %s, and Codex stops waiting at 5 minutes", compactWithin) + log.Printf("codex compaction: %s: %s; compacting locally", model, why) + return localSummary(body, why) + } + r = r.WithContext(budget) r = askWhole(r) r = askCompaction(r) ask := func(b []byte) (*recorder, compactResult, error) { @@ -3527,7 +3553,10 @@ 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()) || + if late() { + local = lateSummary() + rec, res, err = &recorder{header: http.Header{}, status: 200}, compactResult{}, nil + } else if first := rec.status; lacksEndpoint(first) || itemNotFound(rec) || upstreamFailed(rec) || protectionRefused(first, rec.body.Bytes()) || summaryTooLarge(rec) || err != nil && protectionWords.MatchString(err.Error()) { who, msg := compactFailure(body, rec) if err != nil { @@ -3535,7 +3564,10 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt } log.Printf("codex compaction: %s answered %d (%s); asking again with the conversation as text", who, first, msg) rec, res, err = ask(plainCompact(body)) - if rec.status >= 400 || err != nil { + if late() { + local = lateSummary() + rec, res, err = &recorder{header: http.Header{}, status: 200}, compactResult{}, nil + } else if rec.status >= 400 || err != nil { again := "" if err != nil { again = "broken off: " + err.Error() @@ -3634,6 +3666,8 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt log.Printf("codex compaction: %s wrote no summary%s; asking again with the conversation as text", who, called) prec, pres, perr := ask(plainCompact(body)) switch { + case late(): + local = lateSummary() case perr == nil && prec.status < 400 && pres.Status != "incomplete" && strings.TrimSpace(pres.summary()) != "": rec, res = prec, pres default: @@ -3663,6 +3697,18 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt writeError(w, provider.Responses, 502, "compaction: "+why) return } + if client.Err() != nil { + // Codex left before it was answered: what was made never reaches + // it, so the conversation is no shorter and is no success; Codex + // asks the same huge summary again (#5275) + why := "Codex left before the summary reached it" + if local != "" { + why += " (magpie's own)" + } + log.Printf("codex compaction: %s: %s", model, why) + s.compactFails.failed(key, 499, why) + return + } s.compactFails.done(key) id := res.ID if id == "" { diff --git a/internal/gateway/codex_compact_late_test.go b/internal/gateway/codex_compact_late_test.go new file mode 100644 index 000000000..0465af08a --- /dev/null +++ b/internal/gateway/codex_compact_late_test.go @@ -0,0 +1,129 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// #5275 (hayden4608): Codex Desktop compacting on a Volcengine model, its +// ~3MB history still going up a slow uplink when Codex gave up at 300s. +// magpie made its own summary only after that, for nobody, and counted +// the compaction a success; Codex sent the same history again, another +// 300s, and the conversation never got shorter. + +// silentUpstream is a provider whose vendor never answers: each request +// is held until it is given up on, as one whose body is still going up. +func silentUpstream(t *testing.T) (asked chan struct{}) { + t.Helper() + noRests() + t.Cleanup(noRests) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + asked = make(chan struct{}, 16) + release := make(chan struct{}) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + asked <- struct{}{} + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(func() { + close(release) + up.Close() + }) + p := provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: up.URL + "/v1"} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + return asked +} + +func withCompactWithin(t *testing.T, d time.Duration) { + t.Helper() + was := compactWithin + compactWithin = d + t.Cleanup(func() { compactWithin = was }) +} + +// A summary that hasn't come by compactWithin is magpie's own, sent while +// Codex still waits: the compaction completes, saying why, and the vendor +// is no longer waited on. +func TestCodexCompactLateSummaryCompactsLocallyInTime(t *testing.T) { + asked := silentUpstream(t) + withCompactWithin(t, 300*time.Millisecond) + // Codex's patience, far past compactWithin here as 300s is past 4m + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(codexCompactOf("fake/m1", "thread-late"))).WithContext(ctx) + req.Header.Set("Authorization", "Bearer chatgpt-token") + began := time.Now() + New().Handler().ServeHTTP(rec, req) + if ctx.Err() != nil { + t.Fatalf("Codex gave up first, after %s: %d %s", time.Since(began), rec.Code, rec.Body) + } + select { + case <-asked: + default: + t.Fatal("the vendor was never asked") + } + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + sum := compactedText(t, rec.Body.String()) + for _, want := range []string{"no summary came in 300ms", "fix the login bug", "now add a test"} { + if !strings.Contains(sum, want) { + t.Errorf("summary %q, want it to say %q", sum, want) + } + } +} + +// A compaction Codex left before it was answered is no success: what was +// made reached nobody, so the conversation's failures still count and its +// compaction is held after compactFailsMost of them, rather than cleared +// for the next to wait as long again. +func TestCodexCompactLeftBeforeAnsweredStillCounts(t *testing.T) { + asked := silentUpstream(t) + withCompactWithin(t, time.Minute) + s := New() + key := compactKey([]byte(codexCompactOf("fake/m1", "thread-left"))) + for range compactFailsMost - 1 { + s.compactFails.failed(key, 502, "the reply ended before it was complete") + } + ctx, cancel := context.WithCancel(context.Background()) + go func() { + <-asked + cancel() // Codex gives up while the vendor says nothing + }() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(codexCompactOf("fake/m1", "thread-left"))).WithContext(ctx) + req.Header.Set("Authorization", "Bearer chatgpt-token") + s.Handler().ServeHTTP(rec, req) + if strings.Contains(rec.Body.String(), "response.completed") { + t.Errorf("a compaction written to a Codex that left: %s", rec.Body) + } + // held, it is answered at once; asked, the vendor would hold it + actx, acancel := context.WithTimeout(context.Background(), 5*time.Second) + defer acancel() + again := httptest.NewRecorder() + areq := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(codexCompactOf("fake/m1", "thread-left"))).WithContext(actx) + areq.Header.Set("Authorization", "Bearer chatgpt-token") + s.Handler().ServeHTTP(again, areq) + if again.Code != 400 || !strings.Contains(again.Body.String(), "times in a row") { + t.Fatalf("after Codex left a third time: %d %s", again.Code, again.Body) + } + select { + case <-asked: + t.Error("the vendor was asked again while the conversation is held") + default: + } +}