magpie icon indicating copy to clipboard operation
magpie copied to clipboard

gateway: a Codex compaction cut on every candidate returns 502 instead of compacting locally

Open Edward4226 opened this issue 1 month ago • 9 comments

Summary

When Codex compaction goes through a single model with no remaining fallback candidate, and every summary stream ends before its terminal event, codexCompact returns 502 even though all candidates have already been tried. Codex retries it three times, then Magpie's 5-minute compaction guard answers 400; the conversation cannot compact or continue.

This is the remaining no-candidate case after #2274. It is not a request-shape refusal such as #3106.

Observed environment

  • Magpie v0.1.1327 on Windows (magpie-windows-amd64.exe).
  • Codex using openai_base_url = http://127.0.0.1:3425/backend-api/codex.
  • The conversation's model was the direct provider model commandcode/deepseek/deepseek-v4.1-flash; it was not a routing group and had no fallback model configured.
  • Reasoning effort was max.
  • The Command Code provider had two keys; Magpie tried both.

Evidence

Three compaction requests returned 502 after about 150 seconds each. The final UI error was:

compaction: commandcode/deepseek/deepseek-v4.1-flash failed to summarise this conversation 3 times in a row
(last: Command Code: the reply ended before it was complete)

The summary request was about 123,353 tokens; tool results were about 68,033 of them. Magpie's usage.jsonl records both Command Code keys failing for the same conversation, so this is not one bad credential and not a user-side download failure.

I checked the current origin/main at 7d67910f (v0.1.1438): the no-candidate behavior is still present. askWhole correctly holds the summary until it ends, and serve correctly fails over candidates. Once all candidates are exhausted, however, codexCompact omits this cut-summary 502 from the existing plain-text/local fallback condition and returns the 502 to Codex.

Expected

A cut summary must never be reused as the summary. But once every candidate has already failed with the reply ended before it was complete, Magpie should make a local handoff summary and return a successful compaction item, as it already does after the plain-text retry fails for the 404/protection cases. The local summary already says it is not a model summary and tells the next agent to inspect the workspace.

This avoids paying for the same large prompt three times while still preserving the "never use partial output" rule.

Proposed fix

In codexCompact, recognise the exact errEndedShort failure returned from serve after candidate exhaustion and fall back to localSummary. Do not treat a partial model reply as complete, and do not change the handling of 401/403/429 or request-shape failures.

The regression test should use a single fake provider whose Responses stream ends without response.completed. Before the fix it returns 502; after the fix it should return one Magpie compaction item containing the local handoff, while never including the partial stream text. The existing fallback test with a second working candidate must still use that candidate's complete summary.

Related

  • #2274: added whole-summary holding, candidate failover, and the compaction guard. This issue covers the case left with nobody to fail over to.
  • #3125: the same final error on gpt-6.1-sol; no comments or fix yet.
  • #2790: Command Code compaction failure, but its last error is a Chat message-shape refusal rather than a cut stream.

Verification plan

  • Add a test that fails on 7d67910f with 502, then passes with the local handoff.
  • Keep TestCodexCompactCutSummaryFailsOver green: a complete fallback summary still wins.
  • Confirm the local summary excludes the partial words from the cut stream and records why compaction was local.
  • Run the gateway compaction tests, the full Go suite under a sandboxed HOME, go vet for the required platforms, and the Windows build.

AI disclosure: investigated and drafted with AI assistance under the reporter's direction; the claims above are backed by local Magpie usage logs and the current origin/main source.

Edward4226 avatar Oct 24 '26 22:10 Edward4226

take

Root cause confirmed against current origin/main: with no candidate left to fail over to, serve releases the last candidate's held partial stream as a 200, so codexCompact's ask returns errEndedShort ("the reply ended before it was complete"), which matches none of the existing plain-text/local fallback conditions and lands on the 502 — Codex retries it three times at full prompt cost until compactFails holds the conversation at 400 (#2274's remaining no-candidate case). Plan: recognise the exact errEndedShort after candidate exhaustion and fall back to magpie's own local summary, never reusing the cut stream's words; 401/403/429 and request-shape refusals stay as they are.

ggbdpq avatar Oct 24 '26 23:10 ggbdpq

Your reading is right, and I can add the one piece the outside view couldn't see: what the cut looks like when it reaches codexCompact. The relay ends a held summary stream that stopped short of its last event with a response.failed event of its own saying <provider>: the reply ended before it was complete (the words are errEndedShort, #2274). So after candidate exhaustion compactReply returns that message as the error, and it matched none of the four fallback conditions — 404, an item not found, "Upstream request failed", "response protection is unavailable" — so it fell out of the 404/protection family and went to Codex as the 502 at the plain err branch. On current main (43239321) the fake-upstream shape of this report reproduces it verbatim: 502 "compaction: …: the reply ended before it was complete, so there is no summary", then the guard's 400 after Codex's three tries. I took the report's scope as it stands and made one boundary explicit: only the bare break-off turns local. A summary that failed halfway (a 429 in the stream) and one that ended incomplete — the output limit's own terminal event — are still told to Codex as they came, and the incomplete one still drives the guard; the local turn for those would be a product call on #2274's explicit "with nobody left, the cut/incomplete summary is a 502 saying so", so it is left for you to make (one line on the same branch if you want it).

What changed

  • internal/gateway/codex_backend.go: in codexCompact, after the 404/protection retry block and before the failure passthrough, an error ending in errEndedShort — the exhausted-candidates break-off, with no failure status behind it (the vendor answered 200 and the stream stopped) — logs why, and the summary becomes localSummary built from the request's own items, the why saying what broke off. The plain-text retry is deliberately not tried: the cut was in what the model wrote, not in what it was asked, and that would be another full-price ask of the same huge prompt, as the report says. The words before the cut are never taken — the local summary never reads the reply. 401/403/429 and request-shape refusals keep their paths (the branch's condition excludes them: their errors don't end in that phrase, and 4xx answers never reach it). The function's doc comment says the new terminal state.
  • internal/gateway/codex_compact_whole_test.go: TestCodexCompactCutAloneCompactsLocally (new) — one fake whose Responses stream stops after output_item.done with no response.completed; it wants 200 with one magpie compaction holding the local handoff (why included), the cut stream's PARTIAL words in none of it, and the last ask the fake saw still the original summary request, not the text form. The two #2274 tests keep their shape: TestCodexCompactCutSummaryFailsOver (a whole fallback summary still wins) is unchanged and green; TestCodexCompactCutSummaryIsNoSummary now covers the halfway and incomplete shapes alone (the cut one moved to the new test); TestCodexCompactKeepsFailingIsHeld holds on the incomplete shape, which still fails and rests nobody, so the guard's 3-in-a-row still happens.
  • docs/subsystems/gateway-routing.md: the terminal-state sentence now says a bare break-off with nobody left is followed by magpie's own summary, beside #2274's 502 for the rest.

Verification

(darwin/arm64, go 1.26.8; baseline 43239321, current main when this opened)

Check Result
after, go test -tags nogui -run 'TestCodexCompact…' ./internal/gateway/ (all five compaction tests) ok
before (baseline), TestCodexCompactCutAloneCompactsLocally FAIL: 502 … "compaction: fake (fake/m1, http://127.0.0.1:…/v1): Fake: the reply ended before it was complete, so there is no summary"
ablation: only codex_backend.go reverted to the baseline, tests kept FAIL, same 502; restored from the commit, ok again
go test -tags nogui -p 2 -count=1 ./internal/gateway/ (full package) ok, 350.8s, no red
targeted TestCodexCompact… with -race -count=2 ok
go test -tags nogui ./internal/usage/ (its compaction ledger tests) ok
gofmt -l internal/gateway/ clean
go vet -tags nogui ./internal/gateway/, GOOS=linux, GOOS=windows clean
CGO_ENABLED=0 go build -tags nogui . (darwin, linux, windows) ok

Not verified

  • Not exercised against the report's Command Code relay or a live Codex: the cut shape is the synthetic SSE #2274's tests already use (stream stops after output_item.done, no response.completed), and the appended response.failed event is read from the relay path this patch consumes, not guessed.
  • The incomplete (max_output_tokens) case keeps its 502 on purpose; if you want it local too, it is the same branch with incompleteReply added to the condition — the test that locks its 502 (TestCodexCompactCutSummaryIsNoSummary/incomplete) is where it would change.
  • The report's 7d67910f check was re-run against the current main head instead; the no-candidate 502 reproduces there, and serve's failover shapes were read from the same head.

Attribution: AI-written; I've read the whole diff and the tests pass. Please keep the author (ggbdpq) or add Co-authored-by: ggbdpq <[email protected]>.

patch: gateway: a Codex compaction cut short with no candidate left compacts locally (#3526, Edward4226) — git am applies it as is; SHA-256 first 16: fd33e416cc863e00
From 48d863c9198e2c21a27c1892db7437fb0a3cb0bb Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Sun, 25 Oct 2026 07:20:46 +0800
Subject: [PATCH] gateway: a Codex compaction cut short with no candidate left
 compacts locally (#3526, Edward4226)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

A summary wanted whole whose stream every candidate broke off reached
codexCompact as an error none of its fallback conditions name: not a
404, not an unreadable item, not "Upstream request failed", not
"response protection is unavailable". The relay ends such a stream with
a response.failed event saying "the reply ended before it was complete"
(#2274), and with nobody left to fail over to, that error fell out of
the 404/protection family and went to Codex as a 502. Codex asked the
same huge summary over, three times, each paying for the whole
conversation, until compactFails answered 400 and held it: the
conversation could neither compact nor go on. That is the no-candidate
case #2274 left, after it made a cut summary fail over where there was
someone to fail over to.

The summary is magpie's own then, as when no model can be asked at all
(#866, #1008, #1270 end so). The summary as text isn't tried either:
the cut was in what the model wrote, not in what it was asked, and that
would be another ask of the same huge prompt. The words before the cut
are never taken: the local summary is built from the request's own
items. A summary that failed halfway, or ended incomplete — the output
limit's own event — is still told to Codex as it came and still counts
the guard; only the bare break-off turns local. 401, 403, 429 and
request-shape refusals are untouched.

Run: TestCodexCompactCutAloneCompactsLocally (new) is red on the parent
with the issue's 502 ("the reply ended before it was complete, so there
is no summary") and green here — 200, one magpie compaction holding the
local handoff, the cut stream's words in none of it, the last ask the
fake saw still the original summary request (no plain-text retry). The
#2274 tests keep their shape: TestCodexCompactCutSummaryFailsOver (a
whole fallback summary still wins) green unchanged;
TestCodexCompactCutSummaryIsNoSummary now covers the halfway and
incomplete shapes alone (the cut one moved to the new test);
TestCodexCompactKeepsFailingIsHeld holds on the incomplete shape, which
still fails and rests nobody. Ablation: only codex_backend.go put back
to the parent, tests kept — the new test is red again, restored, green.
go test -tags nogui -p 2 -count=1 ./internal/gateway: ok (350.8s).
Targeted TestCodexCompact with -race -count=2: ok. ./internal/usage:
ok. gofmt -l clean; go vet -tags nogui on darwin, linux and windows
clean; CGO_ENABLED=0 go build -tags nogui on all three ok.
docs/subsystems/gateway-routing.md says the new terminal state.

Fixes #3526
Generated-by: GLM-5.3-Flash (ZCode)
---
 docs/subsystems/gateway-routing.md           |  2 +-
 internal/gateway/codex_backend.go            | 23 ++++++++--
 internal/gateway/codex_compact_whole_test.go | 47 +++++++++++++++++---
 3 files changed, 63 insertions(+), 9 deletions(-)

diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index bc6fe1bc..8af3cf0b 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -165,7 +165,7 @@ recorded as a prediction failure (`noPrediction`).
 - A relayed Chat reply whose choice made calls and ended `stop` ends `tool_calls`, streamed (`chatTidy`) and whole (`chatWhole`), as the translations' collector already ends it (`collector.finish`): told it stopped, a client that reads `finish_reason` ends its turn with the calls not run (喜欢一个人 on Discord, a relay in front of deepseek-v4.1-flash). Any other reason stays as it came. `TestChatCallsEndToolCalls` in [`chattidy_finish_test.go`](../../internal/gateway/chattidy_finish_test.go).
 - Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models kept out of agents' lists for routing groups (`provider.CodexNativeUnlisted`) are dropped from it too, hidden ones kept: every one when the codex provider is "Only through routing groups" (`Provider.Unlisted`), and those a group that unlists its members names (`Group.Unlists`). A Codex there only for failover keeps them, as it is handed no groups; `spawnChoices` drops the same ones (#1602, `TestCodexModelListUnlistedForGroups`).
 - 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<n>__`), 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/<key>`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__<key>`), 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. Carrying reasoning across APIs (an envelope) isn't done.
-- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; 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`). When a provider answers its summary request 404, 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 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). 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; 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`). When a provider answers its summary request 404, 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 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. 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 <id> 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 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)). 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. It 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 bf0a19e7..666551e4 100644
--- a/internal/gateway/codex_backend.go
+++ b/internal/gateway/codex_backend.go
@@ -2592,9 +2592,13 @@ func userMessage(text string) map[string]any { return codexsummary.UserMessage(t
 //
 // The summary is asked for whole (askWhole): a reply that breaks off, or
 // ends incomplete, is a failure the next account or member answers, as
-// one that fails before it begins, and is never taken for the summary;
-// when none is left Codex is told so. One conversation's compaction that
-// keeps failing stops being asked for a while (compactFails, #2274).
+// one that fails before it begins, and is never taken for the summary.
+// When none is left and the last one's stream broke off, the summary is
+// magpie's own (#3526): Codex, told a 502, asked the same huge summary
+// over until the guard held it, and the conversation could neither compact
+// nor go on. One that ended incomplete is still told so. One conversation's
+// compaction that keeps failing stops being asked for a while
+// (compactFails, #2274).
 func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byte) {
 	key, model := compactKey(body), modelOf(body)
 	if msg, held := s.compactFails.held(key, model); held {
@@ -2643,6 +2647,19 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt
 			rec, res, err = &recorder{header: http.Header{}, status: 200}, compactResult{}, nil
 		}
 	}
+	if err != nil && strings.HasSuffix(err.Error(), errEndedShort.Error()) {
+		// nobody left, and the last one's stream broke off before its end
+		// (#2274): the words before the cut are no summary, and Codex,
+		// told a 502, asked the same huge summary over, three times, until
+		// the guard held it and the conversation could neither compact nor
+		// go on (#3526). The summary is magpie's own, as when no model can
+		// be asked at all; the summary as text isn't tried, the cut was in
+		// what the model wrote, not in what it was asked
+		who, _ := compactFailure(body, rec)
+		log.Printf("codex compaction: %s: %s; compacting locally", who, err)
+		local = localSummary(body, err.Error())
+		rec, res, err = &recorder{header: http.Header{}, status: 200}, compactResult{}, nil
+	}
 	if rec.status >= 400 {
 		_, msg := compactFailure(body, rec)
 		s.compactFails.failed(key, rec.status, msg)
diff --git a/internal/gateway/codex_compact_whole_test.go b/internal/gateway/codex_compact_whole_test.go
index 0f8dc058..9a45a126 100644
--- a/internal/gateway/codex_compact_whole_test.go
+++ b/internal/gateway/codex_compact_whole_test.go
@@ -113,10 +113,15 @@ func TestCodexCompactCutSummaryFailsOver(t *testing.T) {
 	}
 }
 
-// With nobody left, a cut summary is no summary: Codex is told why, and
-// not handed the words before the cut as the conversation's summary.
+// With nobody left, a summary that failed or ended incomplete is no
+// summary: Codex is told why, and not handed the words before the failure
+// as the conversation's summary. (One whose stream merely broke off is
+// followed by magpie's own summary, TestCodexCompactCutAloneCompactsLocally.)
 func TestCodexCompactCutSummaryIsNoSummary(t *testing.T) {
 	for name, cut := range cutReplies(provider.Responses) {
+		if name == "cut" {
+			continue
+		}
 		t.Run(name, func(t *testing.T) {
 			f := &fake{t: t, reply: cut}
 			setup(t, provider.Responses, f)
@@ -128,12 +133,44 @@ func TestCodexCompactCutSummaryIsNoSummary(t *testing.T) {
 	}
 }
 
+// With nobody left to fail over to, a summary stream the candidate cut
+// short is followed by magpie's own summary, as when no model can be asked
+// at all (#3526): Codex, told a 502, asked the same huge summary over three
+// times and the guard then held the conversation, unable to compact or go
+// on. The words before the cut are never the summary, and the cut summary
+// isn't asked again as text — the cut was in what the model wrote, not in
+// what it was asked.
+func TestCodexCompactCutAloneCompactsLocally(t *testing.T) {
+	f := &fake{t: t, reply: cutReplies(provider.Responses)["cut"]}
+	setup(t, provider.Responses, f)
+	code, body := codexPost(t, compact404Request)
+	if code != 200 {
+		t.Fatalf("%d %s", code, body)
+	}
+	sum := compactedText(t, body)
+	if strings.Contains(sum, "PARTIAL") {
+		t.Errorf("the cut stream's words are the summary: %q", sum)
+	}
+	for _, want := range []string{"no summary", "the reply ended before it was complete", "fix the login bug", "now add a test"} {
+		if !strings.Contains(sum, want) {
+			t.Errorf("summary %q, want it to say %q", sum, want)
+		}
+	}
+	if f.calls < 1 || strings.Contains(string(f.got), "This is the conversation so far") {
+		// the summary as text is another ask of the same huge prompt: it
+		// isn't tried, the last one the fake saw is the summary request
+		t.Errorf("the summary was asked again as text (%d asks, last %q)", f.calls, f.got)
+	}
+}
+
 // One conversation's compaction that fails compactFailsMost times in a
 // row is answered at once after, with a 400 Codex doesn't ask again on,
 // no model asked; another conversation's still is, and one that worked
 // clears the count.
 func TestCodexCompactKeepsFailingIsHeld(t *testing.T) {
-	f := &fake{t: t, reply: cutReplies(provider.Responses)["cut"]}
+	// a summary that ended incomplete still fails: only one whose stream
+	// merely broke off is magpie's own now (#3526)
+	f := &fake{t: t, reply: cutReplies(provider.Responses)["incomplete"]}
 	setup(t, provider.Responses, f)
 	s := New()
 	for i := range compactFailsMost {
@@ -155,7 +192,7 @@ func TestCodexCompactKeepsFailingIsHeld(t *testing.T) {
 
 	// a summary that came clears it
 	s2 := New()
-	f.reply = cutReplies(provider.Responses)["cut"]
+	f.reply = cutReplies(provider.Responses)["incomplete"]
 	for range compactFailsMost - 1 {
 		codexPostTo(s2, codexCompactOf("fake/m1", "thread-3"))
 	}
@@ -163,7 +200,7 @@ func TestCodexCompactKeepsFailingIsHeld(t *testing.T) {
 	if rec := codexPostTo(s2, codexCompactOf("fake/m1", "thread-3")); rec.Code != 200 {
 		t.Fatalf("whole: %d %s", rec.Code, rec.Body)
 	}
-	f.reply = cutReplies(provider.Responses)["cut"]
+	f.reply = cutReplies(provider.Responses)["incomplete"]
 	codexPostTo(s2, codexCompactOf("fake/m1", "thread-3"))
 	if rec := codexPostTo(s2, codexCompactOf("fake/m1", "thread-3")); rec.Code == 400 {
 		t.Errorf("held after a summary came: %s", rec.Body)
-- 
2.50.1 (Apple Git-155)

Branch with the commit: hunt81-a-3526 (head 48d863c9198e2c21a27c1892db7437fb0a3cb0bb).

ggbdpq avatar Oct 24 '26 23:10 ggbdpq

Revised implementation: every shape of errEndedShort

@ggbdpq's patch above covers the response.failed shape, and I kept its central choice: never reuse the cut words, never ask the same large prompt again as plain text, and return magpie's local handoff. While checking the sibling paths I found that the same sentinel can reach codexCompact in three shapes:

  • a 200 stream that simply stops before response.completed;
  • a 200 stream ending in response.failed / error;
  • an exact HTTP 502 body, which is rejected before compactReply gets to look for a stream error.

The patch normalizes only those exact cut shapes to errEndedShort. A summary that fails halfway or ends incomplete keeps its existing 502 and guard path. 401/403/429, other 5xx, and a 502 with extra text after the cut phrase stay unchanged. localSummary is built from the request's items only.

Commit: 06ebeb75e0987f4ca615dfa8b5d277b503d225de Branch: https://github.com/Edward4226/magpie/tree/codex/fix-3526-compact-cut Compare: https://github.com/yetone/magpie/compare/main...Edward4226:magpie:codex/fix-3526-compact-cut?expand=1 Patch SHA-256: 777DCDD4278C36E589EC410E6DD35FB34284FD6F3AA7A3759764C04F432AEE15

Verification

  • Old backend with the new tests kept: TestCodexCompactCutSummaryCompactsLocally fails all three subtests with the issue's 502, including ...the reply ended before it was complete, so there is no summary.
  • Patched: the same test and TestCodexCompactOther502IsNoSummary pass.
  • go test -tags nogui ./internal/gateway -run '^TestCodexCompact' passes in 5.346s.
  • go vet -tags nogui ./internal/gateway passes. Earlier runs on this tree also passed go vet ./..., Linux/Windows vet and builds, the three go build variants, and the TestCodex gateway subset with the known #3045 red skipped.
  • The unconditional full suite is not green on this Windows/Go 1.27.0 host. Separate gateway allocation/JSON-escaping, GUI plugin-page, provider, SQLite and usage tests fail; I am recording that as a limitation rather than calling the suite green.
  • Not tried against a live Command Code account or a real Codex compaction. The cut shapes are httptest fixtures; the reporter's real case should remain the acceptance check. I am leaving #3526 open.

The repository README says it does not accept pull requests, so this is a branch plus patch rather than a PR.

patch: gateway: compact locally when every summary stream ends short (#3526)
From: Edward4226 <[email protected]>
Date: Sun, 25 Oct 2026 08:05:19 +0800
Subject: [PATCH] gateway: compact locally when every summary stream ends short
 (#3526)

A Codex compaction summary is wanted whole. When no candidate is left and
the last stream stops before response.completed, magpie's hold writer
reports errEndedShort. codexCompact did not match that error to any of its
fallback paths, so it returned 502. Codex paid for the same large summary
request again, three times, then compactFails held the conversation at 400.
Depending on where the relay ends the reply, the same failure reaches
codexCompact as a bare cut stream, a response.failed event, or an exact 502
body; the 502 shape bypassed the existing reply parsing.

Normalize those three shapes to errEndedShort and build magpie's local
handoff once. It never uses the cut reply's words and never asks the same
large prompt again as plain text. A summary that fails halfway or ends
incomplete keeps its existing 502 and guard path. 401/403/429, other 5xx,
and a 502 whose message has more after the cut phrase stay unchanged.

Baseline with only codex_backend.go replaced from HEAD and the new tests
kept: TestCodexCompactCutSummaryCompactsLocally fails all three subtests
with 502, including "...the reply ended before it was complete, so there
is no summary". With the patch, that test and
TestCodexCompactOther502IsNoSummary pass. All ^TestCodexCompact tests pass
in 5.346s, and go vet -tags nogui ./internal/gateway passes. Earlier runs
on this tree also passed go vet ./..., Linux and Windows vets/builds, and
the go build variants. The TestCodex gateway subset passes with the known
TestCodexFittedImagesPastTheBudget red skipped (80.043s; #3045).

The unconditional full suite is not green on this Windows/Go 1.27.0 host:
unrelated gateway allocation/JSON-escaping, GUI plugin-page, provider,
SQLite, and usage tests also fail. That run is recorded as a limitation,
not as a green suite. Not tried against a live Command Code account or a
real Codex compaction; the three shapes are covered by httptest fakes.

Co-authored-by: ggbdpq <[email protected]>
Generated-by: Codex
Refs #3526
---
 docs/subsystems/gateway-routing.md           |  2 +-
 internal/gateway/codex_backend.go            | 33 ++++++++-
 internal/gateway/codex_compact_whole_test.go | 70 +++++++++++++++++---
 3 files changed, 93 insertions(+), 12 deletions(-)

diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index d5838704..cbb8caf4 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -165,7 +165,7 @@ recorded as a prediction failure (`noPrediction`).
 - A relayed Chat reply whose choice made calls and ended `stop` ends `tool_calls`, streamed (`chatTidy`) and whole (`chatWhole`), as the translations' collector already ends it (`collector.finish`): told it stopped, a client that reads `finish_reason` ends its turn with the calls not run (喜欢一个人 on Discord, a relay in front of deepseek-v4.1-flash). Any other reason stays as it came. `TestChatCallsEndToolCalls` in [`chattidy_finish_test.go`](../../internal/gateway/chattidy_finish_test.go).
 - Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models kept out of agents' lists for routing groups (`provider.CodexNativeUnlisted`) are dropped from it too, hidden ones kept: every one when the codex provider is "Only through routing groups" (`Provider.Unlisted`), and those a group that unlists its members names (`Group.Unlists`). A Codex there only for failover keeps them, as it is handed no groups; `spawnChoices` drops the same ones (#1602, `TestCodexModelListUnlistedForGroups`).
 - 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<n>__`), 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/<key>`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__<key>`), 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. Carrying reasoning across APIs (an envelope) isn't done.
-- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; 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`). When a provider answers its summary request 404, 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 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). 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; 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`). When a provider answers its summary request 404, 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 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, a summary that failed halfway or ended incomplete is answered 502 and the words before the failure are never handed to Codex as the summary (#2274, huangzuomin: Antigravity cutting each summary short). One cut by the end of its stream instead gets the local handoff magpie makes (`localSummary`), as the failure of the plain-text retry does: all candidates have already been asked, so repeating the same large summary request would only pay for it again (#3526). 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`, `TestCodexCompactCutSummaryCompactsLocally`, `TestCodexCompactOther502IsNoSummary`, `TestCodexCompactFailedSummaryIsNoSummary`, `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 <id> 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 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)). 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. It 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 bf0a19e7..727ba015 100644
--- a/internal/gateway/codex_backend.go
+++ b/internal/gateway/codex_backend.go
@@ -2593,8 +2593,10 @@ func userMessage(text string) map[string]any { return codexsummary.UserMessage(t
 // The summary is asked for whole (askWhole): a reply that breaks off, or
 // ends incomplete, is a failure the next account or member answers, as
 // one that fails before it begins, and is never taken for the summary;
-// when none is left Codex is told so. One conversation's compaction that
-// keeps failing stops being asked for a while (compactFails, #2274).
+// when none is left, a cut becomes magpie's local handoff, and one that
+// failed halfway or ended incomplete is told to Codex as no summary. One
+// conversation's compaction that keeps failing stops being asked for a
+// while (compactFails, #2274).
 func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byte) {
 	key, model := compactKey(body), modelOf(body)
 	if msg, held := s.compactFails.held(key, model); held {
@@ -2611,9 +2613,15 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt
 		rec := &recorder{header: http.Header{}, status: 200}
 		s.serve(rec, r, provider.Responses, b)
 		if rec.status >= 400 {
+			if summaryEndedShort(rec) {
+				return rec, compactResult{}, errEndedShort
+			}
 			return rec, compactResult{}, nil
 		}
 		res, err := compactReply(rec.body.Bytes())
+		if replyEndedShort(err) {
+			err = errEndedShort
+		}
 		if t := bytes.TrimSpace(rec.body.Bytes()); err == nil && res.Status == "" && (len(t) == 0 || t[0] != '{') {
 			// a stream with no response.completed stopped before its end:
 			// what it had said is no summary (#2274)
@@ -2623,7 +2631,12 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt
 	}
 	rec, res, err := ask(body)
 	local := ""
-	if first := rec.status; first == http.StatusNotFound || itemNotFound(rec) || upstreamFailed(rec) || protectionRefused(first, rec.body.Bytes()) ||
+	if errors.Is(err, errEndedShort) {
+		who, _ := compactFailure(body, rec)
+		log.Printf("codex compaction: %s ended before its summary was complete; compacting locally", who)
+		local = localSummary(body, who+": "+errEndedShort.Error())
+		rec, res, err = &recorder{header: http.Header{}, status: 200}, compactResult{}, nil
+	} else if first := rec.status; first == http.StatusNotFound || itemNotFound(rec) || upstreamFailed(rec) || protectionRefused(first, rec.body.Bytes()) ||
 		err != nil && protectionWords.MatchString(err.Error()) {
 		who, msg := compactFailure(body, rec)
 		if err != nil {
@@ -2731,6 +2744,20 @@ func upstreamFailed(rec *recorder) bool {
 		upstreamFailedWords.Match(rec.body.Bytes())
 }
 
+// summaryEndedShort is the 502 serve returns when a whole summary's
+// stream ended before its last event and no candidate was left to answer.
+// It is not any other 502: the words are the cut's own (#3526).
+func summaryEndedShort(rec *recorder) bool {
+	return rec.status == http.StatusBadGateway &&
+		strings.HasSuffix(provider.APIError(rec.body.Bytes(), ""), errEndedShort.Error())
+}
+
+// replyEndedShort is a stream's own error saying it ended before its last
+// event, after its provider's prefix.
+func replyEndedShort(err error) bool {
+	return err != nil && strings.HasSuffix(err.Error(), errEndedShort.Error())
+}
+
 var upstreamFailedWords = regexp.MustCompile(`(?i)upstream request failed`)
 
 // itemNotFound is a 400 refusing an item of the input by its id, as Azure
diff --git a/internal/gateway/codex_compact_whole_test.go b/internal/gateway/codex_compact_whole_test.go
index 0f8dc058..16146ec2 100644
--- a/internal/gateway/codex_compact_whole_test.go
+++ b/internal/gateway/codex_compact_whole_test.go
@@ -113,12 +113,14 @@ func TestCodexCompactCutSummaryFailsOver(t *testing.T) {
 	}
 }
 
-// With nobody left, a cut summary is no summary: Codex is told why, and
-// not handed the words before the cut as the conversation's summary.
-func TestCodexCompactCutSummaryIsNoSummary(t *testing.T) {
-	for name, cut := range cutReplies(provider.Responses) {
+// With nobody left, a summary failed halfway or ended incomplete is no
+// summary: Codex is told why, and not handed the words before the failure
+// as the conversation's summary.
+func TestCodexCompactFailedSummaryIsNoSummary(t *testing.T) {
+	replies := cutReplies(provider.Responses)
+	for _, name := range []string{"quota halfway", "incomplete"} {
 		t.Run(name, func(t *testing.T) {
-			f := &fake{t: t, reply: cut}
+			f := &fake{t: t, reply: replies[name]}
 			setup(t, provider.Responses, f)
 			code, body := codexPost(t, compact404Request)
 			if code < 400 || strings.Contains(body, magpieCompaction) {
@@ -128,12 +130,64 @@ func TestCodexCompactCutSummaryIsNoSummary(t *testing.T) {
 	}
 }
 
+// #3526: every candidate ended before its summary was complete. The cut
+// words are not a summary, but with nobody left to fail over to, the
+// conversation still gets magpie's local handoff instead of a 502 that
+// Codex retries three times and then stops on.
+func TestCodexCompactCutSummaryCompactsLocally(t *testing.T) {
+	for _, tc := range []struct {
+		name string
+		f    *fake
+	}{
+		{"stream ends", &fake{t: t, reply: cutReplies(provider.Responses)["cut"]}},
+		{"stream error", &fake{t: t, reply: sse(`data: {"type":"error","message":"fake: ` + errEndedShort.Error() + `"}`)}},
+		{"HTTP 502", &fake{t: t, code: 502, ctype: "application/json", reply: `{"error":{"message":"fake: ` + errEndedShort.Error() + `"}}`}},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			f := tc.f
+			setup(t, provider.Responses, f)
+			code, body := codexPost(t, compact404Request)
+			if code != 200 {
+				t.Fatalf("%d %s", code, body)
+			}
+			got := compactedText(t, body)
+			for _, want := range []string{"fix the login bug", "now add a test", "I fixed main.go", errEndedShort.Error()} {
+				if !strings.Contains(got, want) {
+					t.Errorf("local summary lacks %q:\n%s", want, got)
+				}
+			}
+			if strings.Contains(got, "PARTIAL summary of") {
+				t.Errorf("cut words were taken as the summary:\n%s", got)
+			}
+			if f.calls != 1+lastRetries {
+				t.Errorf("provider asked %d times, want the last candidate's %d tries and no plain-text request", f.calls, 1+lastRetries)
+			}
+		})
+	}
+}
+
+// A 502 that mentions a cut in some other words is still the provider's
+// failure: the local handoff is only for a reply that ended on the cut
+// itself.
+func TestCodexCompactOther502IsNoSummary(t *testing.T) {
+	f := &fake{t: t, code: 502, ctype: "application/json",
+		reply: `{"error":{"message":"fake: ` + errEndedShort.Error() + `; retry later"}}`}
+	setup(t, provider.Responses, f)
+	code, body := codexPost(t, compact404Request)
+	if code != 502 || strings.Contains(body, magpieCompaction) {
+		t.Fatalf("%d %s", code, body)
+	}
+	if f.calls != 1+lastRetries {
+		t.Errorf("provider asked %d times, want %d", f.calls, 1+lastRetries)
+	}
+}
+
 // One conversation's compaction that fails compactFailsMost times in a
 // row is answered at once after, with a 400 Codex doesn't ask again on,
 // no model asked; another conversation's still is, and one that worked
 // clears the count.
 func TestCodexCompactKeepsFailingIsHeld(t *testing.T) {
-	f := &fake{t: t, reply: cutReplies(provider.Responses)["cut"]}
+	f := &fake{t: t, reply: cutReplies(provider.Responses)["incomplete"]}
 	setup(t, provider.Responses, f)
 	s := New()
 	for i := range compactFailsMost {
@@ -155,7 +209,7 @@ func TestCodexCompactKeepsFailingIsHeld(t *testing.T) {
 
 	// a summary that came clears it
 	s2 := New()
-	f.reply = cutReplies(provider.Responses)["cut"]
+	f.reply = cutReplies(provider.Responses)["incomplete"]
 	for range compactFailsMost - 1 {
 		codexPostTo(s2, codexCompactOf("fake/m1", "thread-3"))
 	}
@@ -163,7 +217,7 @@ func TestCodexCompactKeepsFailingIsHeld(t *testing.T) {
 	if rec := codexPostTo(s2, codexCompactOf("fake/m1", "thread-3")); rec.Code != 200 {
 		t.Fatalf("whole: %d %s", rec.Code, rec.Body)
 	}
-	f.reply = cutReplies(provider.Responses)["cut"]
+	f.reply = cutReplies(provider.Responses)["incomplete"]
 	codexPostTo(s2, codexCompactOf("fake/m1", "thread-3"))
 	if rec := codexPostTo(s2, codexCompactOf("fake/m1", "thread-3")); rec.Code == 400 {
 		t.Errorf("held after a summary came: %s", rec.Body)
-- 
2.51.0.windows.1


AI disclosure: implemented and verified with AI assistance; the commands and failures above are recorded verbatim from this tree.

Edward4226 avatar Oct 25 '26 00:10 Edward4226

Confirmed — the three-shape finding is right, and the shape our patch missed is exactly the one only a sibling-path check catches. We normalized the error after the candidate loop, where err is already nil for any status >= 400 reply — so the exact HTTP 502 body slipped past our HasSuffix before compactReply ever saw it. Your summaryEndedShort inside ask is where that check belongs. Thanks for the co-author credit; the central choices (no cut words, no plain-text re-ask of the same large prompt, magpie's local handoff, halfway/incomplete carve-out) are indeed shared.

We re-verified your branch independently on our side (macOS, Go furnished by the repo toolchain), Edward's commit 06ebeb75 checked out as-is:

  • Ablation: only codex_backend.go reverted to your base 611b9e17, tests kept — TestCodexCompactCutSummaryCompactsLocally fails all three subtests with the 502. The captured bodies also confirm your detection is faithful: the relayed 502 body for the third shape ends exactly on the bare cut phrase ("Fake: fake: the reply ended before it was complete"), so HasSuffix matches what magpie's own chain writes; TestCodexCompactFailedSummaryIsNoSummary and TestCodexCompactOther502IsNoSummary are green on the unpatched backend, i.e. they pin unchanged behavior, not the fix.
  • Patched: all three subtests green, and the whole ^TestCodexCompact family passes (28 tests/subtests, ~1.1s).
  • Combination with our patch's test: TestCodexCompactCutAloneCompactsLocally from our 48d863c9 passes unchanged on your tree — your branch covers everything our patch covered, plus the 502 shape ours missed.
  • gofmt clean, go vet -tags nogui ./internal/gateway clean, CGO_ENABLED=0 go build -tags nogui ./... ok. Full go test -tags nogui -p 2 ./...: 69 packages ok, two failures that are pre-existing on this macOS host — internal/agent.TestMothX and internal/gui.TestProxyCheckSaysAProxyPassedBy both fail on pristine main (b1f44d09) with the same output, no gateway compaction test among them — recorded as a host limitation, same as your Windows note, not as a green suite.

Boundary checks we ran against your own claims, all holding: quota-halfway and incomplete still answer 502 and count the guard (green before and after); 401/403/429, other 5xx, and a 502 with text after the cut phrase stay unchanged (Other502IsNoSummary); the provider is asked 1+lastRetries times with no plain-text request; localSummary is built from the request's items only, and the local 200 clears rather than counts compactFails.

For the maintainers: the two patches are independent — your branch is a single commit on upstream main (611b9e17), not stacked on our fork branch — but semantically yours is a strict superset of ours (same normalization target, plus the exact-502 shape, plus the doc sentence). We'd rather see yours carried forward as the complete fix and ours withdrawn as its subset, whichever way is easier for review. One note for whoever takes it: your base is 15 commits behind current main; nothing touched codex_backend.go in between (only an unrelated gateway-routing.md bullet), so it rebases clean. The remaining acceptance check is the one you already named — the reporter's real relay.

Attribution: written with GLM-5.3-Flash (ZCode); I've verified the revised patch against both test suites.

ggbdpq avatar Oct 25 '26 00:10 ggbdpq

Rebased and re-verified on current main

The base/evidence correction is right. My previous head, 06ebeb75, was based on 611b9e17 (v0.1.1457) and its verification record is now obsolete. I have rebased rather than stacking anything on the other fork branch:

  • base: 9277c256731ca18a14f798fc2b5b0fa4cf948d09 (v0.1.1513, current origin/main)
  • new head: 82c0cf4f48c3c427ac2f18dd77d715aa3e9419ed
  • branch: https://github.com/Edward4226/magpie/tree/codex/fix-3526-compact-cut
  • patch: https://github.com/Edward4226/magpie/commit/82c0cf4f48c3c427ac2f18dd77d715aa3e9419ed.patch
  • regenerated local patch SHA-256: B4CCA36341DAE542829A8CA25A68F70B0E7A651B2C7B9991E05AC0932A758C4D

The rebase was clean. Upstream has since changed codex_backend.go in unrelated earlier sections, but the codexCompact region is unchanged. The new commit's parent is exactly the current upstream main above. The old 06ebeb75 head, old patch, and old verification comment are superseded by this version.

Verification at 82c0cf4f

Go 1.27.0, windows/amd64, isolated HOME with pinned GOPATH, GOMODCACHE, and GOCACHE:

  • Ablation with only codex_backend.go restored from HEAD^: all three TestCodexCompactCutSummaryCompactsLocally subtests fail with 502 (bare stream end, stream error, exact HTTP 502).
  • Patched: go test -tags nogui ./internal/gateway -run '^TestCodexCompact' -count=1 passes (5.363s at the final head).
  • go test -tags nogui ./internal/gateway -run '^TestCodex' -skip '^TestCodexFittedImagesPastTheBudget$' -count=1 passes in 74.688s; the skipped red is tracked by #3045.
  • gofmt -l prints nothing and git diff --check passes.
  • Native, Linux nogui, and Windows go vet ./... pass. Native and both cross-builds pass.
  • The unconditional go test -tags nogui ./... -count=1 -timeout 45m is not green on this Windows host: 61 packages pass and 10 fail. internal/gateway reaches the 45m timeout in TestClaudeMemRunsFromTheCgroup; agent, gui, library, omarchy, plugin, proc, provider, sqlitedb and usage also fail. This is recorded as a host/toolchain limitation, not as a green suite; the broader Windows-only test class is tracked by #1388 and #1827.

The behavioral boundaries remain as described: only the three exhausted-candidate errEndedShort shapes take the local handoff; halfway and incomplete summaries keep the 502/guard path; exact 502 suffix matching leaves 401/403/429, other 5xx, and a 502 with additional text unchanged. I did not replay this against a live Command Code account or a real Codex relay. #3526 should remain open for the reporter's confirmation.

Edward4226 avatar Oct 25 '26 10:10 Edward4226

For anyone picking this up: take Edward4226's rebased head 82c0cf4f (on 9277c256, current main) — it supersedes both his earlier 06ebeb75 and my 48d863c9, which it already carries as co-author. Nothing else on this thread should be applied.

Attribution: written with GLM-5.3-Flash (ZCode); no new code in this comment.

ggbdpq avatar Oct 25 '26 12:10 ggbdpq

Rebased onto current main (fb29cd30f, 2026-10-31). codexCompact has been restructured since — the ask is a closure now, upstream grew the previous-model compaction local answer (2768f04f9, hiwise_aigc) right beside it — so the patch was re-anchored: the catch for a stream that broke off with nothing failed or incomplete in it now sits between the previous-model block and the final 502, same shape, same words, and the askWhole comment paragraph carries it again. The docs row in gateway-routing.md was rewritten around (that row grew the calledTool, lacksEndpoint and previousModelCompaction sentences); the rebase folds this patch's one sentence into the row as it stands now.

New head: f03b17066 (hunt81-a-3526)

Verification (rebase-sweep scope):

  • gofmt -l internal/gateway clean; go build ./internal/gateway ok;
  • the patch's own test on the new tree, beside its neighbours and the newer previous-model one: go test ./internal/gateway -run 'TestCodexCompactCutAloneCompactsLocally|TestCodexCompactCutSummaryFailsOver|TestCodexCompactCutSummaryIsNoSummary|TestCodexCompactKeepsFailingIsHeld|TestCodexLeavingModelCompactsLocally' -count=1 — ok.
  • The broken-by-hand runs (502 on the old code at the anchor, and the header-less client_metadata variant) are recorded in the commit; not re-run in this sweep — stated as is.

git am-ready; branch: https://github.com/ggbdpq/magpie/tree/hunt81-a-3526

Attribution: ggbdpq (branch author; report by Edward4226), rebased with ZCode.

ggbdpq avatar Oct 31 '26 14:10 ggbdpq

Rebased onto 606743831 (current main) with no conflict — git range-diff shows zero drift from the patch as posted, and TestCodexCompactCutSummaryFailsOver / TestCodexCompactCutAloneCompactsLocally pass at the new head. New head bd2e55976, git am applies clean on a fresh tree, patch sha256 16=7ede23fad179c5e7.

Branch with the commit: hunt81-a-3526 (head bd2e559767ba07dffb5c15cc5b41b179d46304a9).

Attribution: ggbdpq (branch author; report by Edward4226); refreshed with AI assistance (GLM-5.3-Flash via ZCode).

ggbdpq avatar Oct 31 '26 20:10 ggbdpq

Landed in v0.1.2492. Thanks @ggbdpq, and @Edward4226 for pointing at the 502 shape.

  • 78632d4b8 (ggbdpq): when every compaction candidate is cut short, magpie compacts locally instead of answering a 5xx.
  • cbefb6598 (follow-up): the same cut can come back as a recorded 502 that says the reply ended short. That case now compacts locally too. A 502 that says anything else still goes to the client.

Not tried: a real ChatGPT summary ask that ends short. The cut comes from a fake upstream in the tests. I'm leaving this open until you confirm, @Edward4226.

yetone avatar Oct 31 '26 22:10 yetone