magpie icon indicating copy to clipboard operation
magpie copied to clipboard

Codex provider returns opaque 400: synthetic same-size input control

Open adlternative opened this issue 3 weeks ago • 3 comments

Summary

A Pi session using Magpie's Codex provider failed with the same opaque error reported in #6214:

{"error":{"code":null,"message":"Codex: Bad Request","param":null,"type":"invalid_request_error"}}

The affected session received HTTP 400 twice, several minutes apart. A later continuation succeeded. The exact upstream cause is unknown: the response recorded by Magpie contains no further explanation. This report provides a synthetic reproduction of the same error, not proof that it has the same root cause as the session failure.

Reproduction with synthetic input

Start Magpie locally with a signed-in Codex provider. The script below sends no session history or source code. It uses an intentionally nonexistent model so that a request reaching model validation should return model_not_found.

python3 - <<'PY'
import json
import random
import string
import urllib.error
import urllib.request

rng = random.Random(11)
chars = string.ascii_letters + string.digits
cases = [
    ("repeated", "a" * 899_968),
    ("random", "".join(rng.choice(chars) for _ in range(899_968))),
]
for name, text in cases:
    body = json.dumps({
        "model": "codex/does-not-exist",
        "input": text,
        "stream": False,
    }).encode("utf-8")
    req = urllib.request.Request(
        "http://127.0.0.1:3425/v1/responses",
        data=body,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=120) as response:
            status, result = response.status, response.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as error:
        status, result = error.code, error.read().decode("utf-8", "replace")
    print(name, "request bytes:", len(body), "HTTP:", status, "response:", result[:500])
PY

In my run, both request bodies were 900,031 bytes:

  • Repeated input: HTTP 400, Codex: Bad Request, code: null.
  • Random input: HTTP 400 with model_not_found and an explicit unsupported-model message.

The results show that a fixed limit based only on the client-side JSON body length does not explain these two observations. Compression, intermediary behavior, upstream validation, or another factor could explain the difference; I have not isolated the cause or measured the bytes actually sent upstream.

Expected behavior

If available, preserve useful, sanitized upstream error details and include diagnostic metadata such as request size. An opaque 400 should not be presented as a conclusive diagnosis of an invalid conversation. Please consider whether a narrowly scoped, bounded retry or an actionable error suggesting compaction is appropriate; repeated retries also fail for the synthetic repetitive case, so retries alone are not a complete solution.

Environment

  • Magpie v0.1.1330, macOS
  • Client: Pi, OpenAI-compatible /v1/responses
  • Provider/model for the session: codex/gpt-6.1-sol
  • Synthetic probe model: codex/does-not-exist

Related: #6214. This is an additional reproduction with a same-length control, not a claim that all cases in that issue share one cause.

adlternative avatar Nov 12 '26 09:11 adlternative

take

ggbdpq avatar Nov 12 '26 18:11 ggbdpq

What's wrong

chatgpt.com's Codex backend refuses a request body of about 880 KB and more with a bare 400, its body empty, and says nothing of a cap (#6214, where the ceiling was measured at about 130 K tokens of real traffic — a thread past it is refused on every turn, and Codex's own compaction, triggered on tokens a third of the window in, never comes). The same bytes as random text reach the model check and are refused with a word (model_not_found, your control), so the refusal is of the body, before any of the API's own errors are said. magpie's byte-cap machinery never matched it: byteCapRefusal wants a 413 or words saying "too large", pageOverSize wants a proxy's page at 4 MiB and more — a bare 400 at 900 KB is neither, so the request failed as "Codex: Bad Request" and every turn of the thread after it died the same way.

Repro (assertion-level test on upstream/main f8a00a3be)

TestBigBodyBare400IsByteCap sends a text turn of about 800 KB to an upstream that answers big requests with a bare 400 and nothing else. Without the fix the client is told 400 … refused with no details (an empty reply …); with the fix the refusal is said as a 413 request_too_large that names the size — and for Codex's own client that is the cue to compact, which the thread never had. TestBare400NotAByteCap keeps the two neighbors as they were: a bare 400 with words in it, however big the request (your control's model_not_found), and a small request's bare 400 (both green before the fix, kept as guards).

Root cause and fix

The byte-cap machinery recovers a thread two ways already: a vendor's words (byteCapRefusal, learned) and a proxy's page for a big request (pageOverSize, a guess, kept for no later request). The ChatGPT backend's bare 400 is the second kind — a refusal of the body that names nothing — and is now read as one (bareCapRefusal: status 400, the body empty, the request 768 KB or more, under the about 880 KB the ceiling was measured at): the cap it implies is a guess, the oldest images are left out and the request asked again (a thread of screenshots fits under it and goes on), and when nothing more can go the refusal is said as a 413 naming the size, the cap, and that nothing could be left out — Codex's cue to compact, summaryTooLarge's for the compaction ask. The threshold sits under the measured ceiling, so a request the backend takes is never misread, and a bare 400 with words in it, or to a small request, is never touched: those are the API's own answers, said as they came.

Verification (darwin, toolchain per go.mod, base f8a00a3be, head cb904432e3cc3682)

Check Result
go test ./internal/gateway -run 'TestBigBody|TestBare400|TestByteCap|TestOverByteCap|TestCompactionOverByteCap|TestTurnOverByteCap|TestPageOverSize|TestWithoutOldImages' ok, 12 tests incl. the 2 new ones
Ablation: bareCapRefusal answered false ...Bare400IsByteCap FAIL: client told 400 … refused with no details again
Ablation: the 413's bare-400 wording dropped (the page's said instead) same test FAIL at the wording
Restored ok
go test ./internal/gateway (full package) ok 897.0s, zero failures
Body-cap family, -race -count=2 ok 447.9s
gofmt, go vet clean
GOOS=linux/windows/darwin GOFLAGS=-tags=nogui go build ./... ok
git am of the patch replays to the delivered tree tree 0a44131ca3ad280f both sides

Siblings: rg "bareCapRefusal|bareCapLeast" → the two gates in refitOverCap and the tail after its tries, overCap's wording. The 400 paths after refitOverCap in forward (p.Retry's mending, the effort retries, retryTokenField) all read the body's words to decide — an empty body gave them nothing to act on, so saying the refusal as a 413 loses them nothing. byteCapRefusal, pageOverSize and withinCap's pre-fitting untouched: a cap learned from a vendor's word still pre-fits, a guess never does.

When the read fails: the recognition wants the body empty — a page, an error of the API's own, anything with words, is the vendor's to say and goes as it came. The guessed cap is never persisted, so a misread bare 400 costs one refit try and a 413, not a learned cap that fits every later request.

Not verified: chatgpt.com itself — the ceiling is the two reports' measurements (#6214's real-traffic thread, your synthetic control); the tests use the repository's fixtures against local fakes.


Source: reported in #6305 (adlternative, with the same-size control) on the thread #6214 (guanwenpeng2001-bot) measured; the surfacing gap reproduced here at the assertion level.

Red without the fix (base f8a00a3be, tests kept, internal/gateway/body_cap.go reverted): TestBigBodyBare400IsByteCap fails:

body_cap_test.go:318: Codex wasn't told to compact: 400 {"error":{"code":null,"message":"1017dp: 400 Bad Request: refused with no details (an empty reply, often from a firewall or proxy in front of the API rather than the API itself)","param":null,"type":"invalid_request_error"}}

With the fix: ok. TestBare400NotAByteCap is protective only, green before the fix.

Siblings: listed above.

When the read fails: listed above.

Not verified: chatgpt.com itself, a real Codex CLI run.

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

Branch with the commit: hunt-20261112-t1-6305 (head cb904432e3cc3682).

Patch:

patch: gateway: the ChatGPT backend's bare 400 to a big request is read as its byte cap (#6305) — git am applies it as is; SHA-256 first 16: 77cd49062f57003b

From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Fri, 13 Nov 2026 02:37:34 +0800
Subject: [PATCH] gateway: the ChatGPT backend's bare 400 to a big request is
 read as its byte cap (#6305)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

chatgpt.com's Codex backend refuses a request body of about 880 KB and
more with a bare 400, its body empty, and says nothing of a cap
(guanwenpeng2001-bot, #6214, where the ceiling was measured at about
130 K tokens of real traffic — a thread past it is refused on every
turn, and Codex's own compaction, triggered on tokens a third of the
window in, never comes). The same bytes as random text reach the model
check and are refused with a word (adlternative's control, #6305), so
the refusal is of the body, before any of the API's own errors are
said. byteCapRefusal never matched it: no 413, no words — the request
failed as "Codex: Bad Request" and every turn of the thread after it
died the same way.

A bare 400 to a request of 768 KB or more, its body empty, is now read
as that byte cap (bareCapRefusal), the way a proxy's page for a big
request already is (pageOverSize): the cap it implies is a guess at
one, not the vendor's word, and is kept for no later request; the
oldest images are left out and the request asked again (a thread of
screenshots fits under it and goes on), and when nothing more can go
the refusal is said as a 413 that names the size — Codex's cue to
compact, which the thread never had. A bare 400 with words in it,
however big the request, and a small request's bare 400 stay what they
were.

Run: TestBigBodyBare400IsByteCap sends a text turn past the threshold
to an upstream that answers it with a bare 400: refused with no
details on the base, said as a 413 naming the size with the fix, the
upstream asked once. TestBare400NotAByteCap keeps a bare 400 with
words and a small request's bare 400 as they were (green before the
fix, kept as guards). The body-cap family, the gateway package, gofmt
and vet stay green.

Generated-by: GLM-5.3-Flash (ZCode)
---
 internal/gateway/body_cap.go      | 53 +++++++++++++++++++------
 internal/gateway/body_cap_test.go | 66 +++++++++++++++++++++++++++++++
 2 files changed, 107 insertions(+), 12 deletions(-)

diff --git a/internal/gateway/body_cap.go b/internal/gateway/body_cap.go
index 88a5f0d17..c29bad96a 100644
--- a/internal/gateway/body_cap.go
+++ b/internal/gateway/body_cap.go
@@ -96,6 +96,27 @@ func pageOverSize(status int, errBody []byte, sent int) bool {
 	return ok
 }
 
+// bareCapLeast is the least a request weighs before a bare 400 — the
+// status, and a body with nothing in it — is read as a refusal of its
+// bytes: the ChatGPT backend refuses a request of about 880 KB and more
+// so, on every turn of the thread that sent it (#6214, where the ceiling
+// was measured at about 130 K tokens of real traffic; the same bytes as
+// random text reach the model check, so the refusal is of the body,
+// before any of the API's own errors are said, #6305's control). A
+// smaller bare 400 is the API's own answer, said as it came.
+const bareCapLeast = 768 << 10
+
+// bareCapRefusal is that bare 400: status 400, the body empty, to a
+// request of bareCapLeast or more. It names no cap and no error of its
+// own, so the cap it implies is a guess at one, not the vendor's word —
+// refitOverCap keeps no cap for it, as it keeps none for a proxy's page.
+func bareCapRefusal(status int, errBody []byte, sent int) bool {
+	if status != http.StatusBadRequest || sent < bareCapLeast {
+		return false
+	}
+	return len(bytes.TrimSpace(errBody)) == 0
+}
+
 // capSizes are the sizes a refusal names: "33554432 bytes", "32 MB",
 // "32MiB", "40.1 MB".
 var capSizes = lazyre.New(`(?i)(\d+(?:\.\d+)?)\s*(bytes|b|kb|kib|mb|mib|gb|gib)\b`)
@@ -181,10 +202,12 @@ func (s *Server) capFit(p provider.Provider, to provider.Protocol, path string,
 }
 
 // refitOverCap is forward's answer to res, a refusal of body for its
-// bytes (byteCapRefusal): the cap learned, and the request sent again
-// with its oldest images left out, as often as that brings it lower and
-// is refused again. When nothing more can go, the refusal is said as a
-// 413 that names the size, the cap and what was kept.
+// bytes (byteCapRefusal), a proxy's page for one (pageOverSize), or the
+// ChatGPT backend's bare 400 for one (bareCapRefusal): the cap learned,
+// and the request sent again with its oldest images left out, as often
+// as that brings it lower and is refused again. When nothing more can
+// go, the refusal is said as a 413 that names the size, the cap and what
+// was kept.
 func (s *Server) refitOverCap(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte, in http.Header, res *http.Response) (*http.Response, error) {
 	var err error
 	for range 3 {
@@ -194,12 +217,13 @@ func (s *Server) refitOverCap(ctx context.Context, p provider.Provider, to provi
 		b := peekError(res)
 		// body as it came is never smaller than what was sent: a page
 		// to a small one is ruled out before body is fitted
+		bare := bareCapRefusal(res.StatusCode, b, len(body))
 		page := !byteCapRefusal(res.StatusCode, b)
-		if page && !pageOverSize(res.StatusCode, b, len(body)) {
+		if page && !bare && !pageOverSize(res.StatusCode, b, len(body)) {
 			return res, nil
 		}
 		sent := s.capSent(p, to, path, body)
-		if page && sent < pageCapLeast {
+		if page && !bare && sent < pageCapLeast {
 			return res, nil
 		}
 		n := statedCap(b, sent)
@@ -218,7 +242,7 @@ func (s *Server) refitOverCap(ctx context.Context, p provider.Provider, to provi
 		fitted, left, ok := withoutOldImages(to, body, capRoom(n))
 		if !ok || len(fitted) >= sent {
 			res.Body.Close()
-			return overCap(res, b, p, len(body), statedCap(b, len(body)), images(to, body), page), nil
+			return overCap(res, b, p, len(body), statedCap(b, len(body)), images(to, body), page, bare), nil
 		}
 		log.Printf("%s refused a request of %s (HTTP %d: %s); asking again with the %d oldest images left out (%s)", p.Name, mb(sent), res.StatusCode, provider.APIError(b, ""), left, mb(len(fitted)))
 		res.Body.Close()
@@ -229,12 +253,13 @@ func (s *Server) refitOverCap(ctx context.Context, p provider.Provider, to provi
 	}
 	if res.StatusCode >= 400 {
 		b := peekError(res)
+		bare := bareCapRefusal(res.StatusCode, b, len(body))
 		page := !byteCapRefusal(res.StatusCode, b)
-		if !page || pageOverSize(res.StatusCode, b, len(body)) && s.capSent(p, to, path, body) >= pageCapLeast {
+		if bare || !page || pageOverSize(res.StatusCode, b, len(body)) && s.capSent(p, to, path, body) >= pageCapLeast {
 			// refused as often as it was asked smaller: said as a 413, so
 			// Codex's compaction asks as text (summaryTooLarge)
 			res.Body.Close()
-			return overCap(res, b, p, len(body), statedCap(b, len(body)), images(to, body), page), nil
+			return overCap(res, b, p, len(body), statedCap(b, len(body)), images(to, body), page, bare), nil
 		}
 	}
 	return res, nil
@@ -258,10 +283,14 @@ func peekError(res *http.Response) []byte {
 // request's size, the provider's cap when it named one, and that leaving
 // out its earlier images didn't bring it under.
 // page is a refusal said as a proxy's page (pageOverSize), which is named
-// for what it most likely was.
-func overCap(res *http.Response, errBody []byte, p provider.Provider, size, n, imgs int, page bool) *http.Response {
+// for what it most likely was. bare is one said as a bare 400 with
+// nothing in it (bareCapRefusal), named for what it is: the backend
+// refusing a big request without a word of its own about it.
+func overCap(res *http.Response, errBody []byte, p provider.Provider, size, n, imgs int, page, bare bool) *http.Response {
 	said := provider.APIError(errBody, http.StatusText(res.StatusCode))
-	if page {
+	if bare {
+		said = fmt.Sprintf("%s answered a bare 400 with nothing in it, as it does for a request larger than it takes", p.Name)
+	} else if page {
 		what := "an empty reply"
 		if w, ok := provider.WebPage(errBody); ok {
 			what = w
diff --git a/internal/gateway/body_cap_test.go b/internal/gateway/body_cap_test.go
index 12c973457..ab44ec4f0 100644
--- a/internal/gateway/body_cap_test.go
+++ b/internal/gateway/body_cap_test.go
@@ -289,3 +289,69 @@ func compactionOverByteCapEveryTime(t *testing.T, header ...string) {
 		}
 	}
 }
+
+// longTextTurn is a Responses turn to model of about n bytes of text, no
+// image in it: nothing its history holds can be left out to fit it.
+func longTextTurn(model string, n int) string {
+	return `{"model":"` + model + `","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("word ", n/5) + `"}]}]}`
+}
+
+// bare400Least mirrors the threshold the gate reads a bare 400 at, pinned
+// here on its own: 768 KiB, under the about 880 KB the ceiling was
+// measured at in #6214.
+const bare400Least = 768 << 10
+
+// bare400 is the ChatGPT backend's refusal of a big request: a bare 400,
+// its body empty, no error of its own in it (#6214, where the ceiling was
+// measured at about 880 KB — a thread past it is refused so on every
+// turn, and Codex's compaction, triggered on tokens, never comes;
+// #6305's control: the same bytes as random text reach the model check,
+// so the refusal is of the body, before any of the API's own errors are
+// said).
+func TestBigBodyBare400IsByteCap(t *testing.T) {
+	fresh(t)
+	up := &capped{proto: provider.Responses, most: bare400Least, status: 400, ctype: "", body: ""}
+	cappedOn(t, up)
+	body := longTextTurn("fake/m1", bare400Least+(16<<10))
+	code, out := postResponses(t, New(), body)
+	if code != 200 || failedCode(out) != "context_length_exceeded" {
+		t.Fatalf("Codex wasn't told to compact: %d %.600s", code, out)
+	}
+	for _, want := range []string{
+		"the request is " + mb(len(body)),
+		"answered a bare 400 with nothing in it",
+		"no earlier image",
+	} {
+		if !strings.Contains(out, want) {
+			t.Errorf("the error lacks %q: %.600s", want, out)
+		}
+	}
+	if n := len(up.calls()); n != 1 {
+		t.Fatalf("the same body was sent %d times", n)
+	}
+}
+
+// A refusal with words in it says what refused the request, however big
+// it is — the model check's own refusal, as #6305's random-text control
+// got — and a small request's bare 400 is the API's own answer as it
+// came. Neither is a byte cap.
+func TestBare400NotAByteCap(t *testing.T) {
+	fresh(t)
+	up := &capped{proto: provider.Responses, most: bare400Least, status: 400, ctype: "application/json",
+		body: `{"error":{"code":"model_not_found","message":"The model does-not-exist does not exist or you do not have access to it."}}`}
+	cappedOn(t, up)
+	code, out := postResponses(t, New(), longTextTurn("fake/m1", bare400Least+(16<<10)))
+	if code != 400 || !strings.Contains(out, "model_not_found") || strings.Contains(out, "no earlier image") {
+		t.Fatalf("a refusal with words in it: %d %.600s", code, out)
+	}
+	if n := len(up.calls()); n != 1 {
+		t.Fatalf("asked %d times", n)
+	}
+	fresh(t)
+	small := &capped{proto: provider.Responses, most: 64, status: 400, ctype: "", body: ""}
+	cappedOn(t, small)
+	code, out = postResponses(t, New(), `{"model":"fake/m1","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"a small ask"}]}]}`)
+	if code != 400 || !strings.Contains(out, "Bad Request") || strings.Contains(out, "no earlier image") {
+		t.Fatalf("a small request's bare 400: %d %.300s", code, out)
+	}
+}
-- 
2.50.1 (Apple Git-155)

ggbdpq avatar Nov 12 '26 18:11 ggbdpq

Additional isolation: identical JSON, zstd vs plain (v0.1.4354)

Adding a new control to this report and #6214: changing only request compression changes the rejection, even over Magpie's native HTTP/1.1 dispatch. This is a reproducible compression-sensitive failure, not a conclusive attribution of every historical opaque 400.

Environment: macOS arm64; official v0.1.4354 source; Go 1.26.8. The original real-chat incidents occurred on 0.1.4084; the synthetic isolation and local implementation below use 0.1.4354.

Observed real-upstream results

Same JSON bytes, same credentials, same endpoint (https://chatgpt.com/backend-api/codex/responses), same HTTP/1.1 path. The model is deliberately nonexistent, so there is no inference or tool execution.

Encoding Decoded JSON bytes Wire body bytes Protocol Status and body
Magpie's current zstd 900,189 249 HTTP/1.1 400 {"detail":"Bad Request"}
Plain, byte-identical JSON 900,189 900,189 HTTP/1.1 400 with explicit model_not_found and unsupported-model message

The plain control is also an HTTP 400, intentionally: its meaningful model-validation error is the control, not a claim of successful inference. No fields or history items were trimmed to obtain it.

A small compressed control reached model validation. Disabling single-segment framing and using a streaming/unknown-FCS encoder also reproduced the opaque refusal in separate synthetic probes. The encoder used the existing 2 MiB window; this is not simply the older 8 MiB-window issue (#2739). These observations do not identify the refusing upstream hop or establish that no byte limits exist; they show that a guessed limit based solely on decoded JSON size is not sufficient for this pair.

Minimal source-tree reproducer

In a checkout of v0.1.4354, save the following as cmd/codex400repro/main.go, then run go run -tags nogui ./cmd/codex400repro. It reads the existing native Codex sign-in without refreshing or printing it, sends only generated text, and performs two parse-only requests directly through the native HTTP/1.1 dispatcher. It intentionally does not call the gateway's proposed retry wrapper. The snippet is a cleaned-up form of the executed diagnostic.

Go reproducer (synthetic input only)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	"github.com/klauspost/compress/zstd"
	"github.com/yetone/magpie/internal/netproxy"
	"github.com/yetone/magpie/internal/provider"
)

func main() {
	// Read the existing native sign-in; do not refresh or print it.
	token, account, err := provider.CodexSignInAsKept()
	if err != nil {
		panic("native Codex sign-in unavailable")
	}
	body, _ := json.Marshal(map[string]any{
		"model": "does-not-exist", "stream": true, "store": false,
		"instructions": "You are Codex, an agent based on GPT-6.",
		"input":        []any{map[string]any{"role": "user", "content": strings.Repeat("a", 900000)}},
		"tools":        []any{}, "parallel_tool_calls": false,
	})
	base := http.DefaultTransport.(*http.Transport).Clone()
	base.Proxy = netproxy.Func
	// Uses Magpie's Codex HTTP/1.1 dispatch rule, not the gateway's retry.
	client := &http.Client{Transport: netproxy.Dispatch(base), Timeout: 40 * time.Second}
	defer base.CloseIdleConnections()
	for _, compressed := range []bool{true, false} {
		req, _ := http.NewRequest("POST", provider.CodexBase+"/responses", bytes.NewReader(body))
		req.Header.Set("Authorization", "Bearer "+token)
		req.Header.Set("ChatGPT-Account-Id", account)
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Accept", "text/event-stream")
		req.Header.Set("Originator", "codex_cli_rs")
		req.Header.Set("User-Agent", "codex_cli_rs/0.179.0")
		wire := len(body)
		if compressed {
			wire = provider.CodexCompressed(req, body)
			rc, err := req.GetBody()
			if err != nil {
				panic(err)
			}
			encoded, err := io.ReadAll(rc)
			rc.Close()
			if err != nil {
				panic(err)
			}
			decoder, err := zstd.NewReader(nil)
			if err != nil {
				panic(err)
			}
			decoded, err := decoder.DecodeAll(encoded, nil)
			decoder.Close()
			if err != nil || !bytes.Equal(decoded, body) {
				panic("round-trip mismatch")
			}
		}
		res, err := client.Do(req)
		if err != nil {
			fmt.Printf("compressed=%v transport_error=%v\n", compressed, err)
			continue
		}
		result, _ := io.ReadAll(io.LimitReader(res.Body, 4096))
		res.Body.Close()
		fmt.Printf("compressed=%v plain=%d wire=%d protocol=%s status=%d body=%s\n", compressed, len(body), wire, res.Proto, res.StatusCode, result)
	}
}

Narrow local repair and verification

A local patch routes all three existing HTTP branches in codexSocket through one helper:

  • Only official Codex /responses, POST, replayable body, zstd encoding, and the exact JSON object {"detail":"Bad Request"} with HTTP 400 qualify.
  • Decode the existing encoded request and retry the identical JSON once, uncompressed, retaining account/authentication and turn headers.
  • Never retry an accepted 200 stream, a meaningful API error, another provider, or an already uncompressed request here. Return a second refusal without a retry loop.
  • Preserve the existing error-body reader/restoration, decoder bounds, request-body management and upload accounting. Do not trim history or replay business tools.

TestCodexHTTPBare400RetriesIdenticalPlainBody was red before the implementation (status 400, one request) and green after it. The relevant gateway/provider selection passed 47 tests, and go vet -tags nogui ./internal/gateway passed. This was a targeted selection, not a claim that the full repository suite was run:

go test -p 2 -tags nogui ./internal/gateway ./internal/provider \
  -run '^Test(CodexHTTP|CodexSocket|CodexCompressed|CodexWarmGoesZstd|CodexAccountTextTurnGoesZstd|CodexRelayedTextTurnGoesZstd|CodexTurnAskedAgainGoesZstdAgain|CodexCompactAndAPIKeyStayPlain|KeyProviderTurnStaysPlain|CodexResetJudgedByTheBytesSent)' -count=1

The changed wrapper against the real HTTP/1.1 upstream made exactly two attempts: compressed opaque 400, then plain model_not_found. The exact final native app bundle was also exercised in an isolated profile and produced that same encoding-retry/model-validation result. A production invalid-model probe was blocked by the configured model allowlist with local 403; that is not counted as another successful transport repro and the allowlist was left intact.

Tested local Go patch against v0.1.4354 (implementation + regression tests)
diff --git a/internal/gateway/codex_http_encoding.go b/internal/gateway/codex_http_encoding.go
new file mode 100644
index 0000000..242722a
--- /dev/null
+++ b/internal/gateway/codex_http_encoding.go
@@ -0,0 +1,59 @@
+package gateway
+
+import (
+	"encoding/json"
+	"io"
+	"log"
+	"net/http"
+	"strings"
+
+	"github.com/yetone/magpie/internal/provider"
+)
+
+// overHTTP retries a turn when ChatGPT refuses a zstd request with an
+// opaque 400. The same JSON can be accepted without
+// compression. Only that opaque refusal gets one encoding retry: a model's
+// own error and every accepted response, streamed or not, are never replayed.
+// No history item, tool result, account or turn identity changes.
+func (t codexSocket) overHTTP(req *http.Request) (*http.Response, error) {
+	res, err := t.next.RoundTrip(req)
+	if err != nil || res == nil || res.StatusCode != http.StatusBadRequest ||
+		req.Method != http.MethodPost || req.GetBody == nil ||
+		!provider.CodexTurnURL(req.URL) || !strings.EqualFold(req.Header.Get("Content-Encoding"), "zstd") || req.Context().Err() != nil {
+		return res, err
+	}
+	// peekError puts all bytes back, including a longer error's unread tail.
+	var refusal map[string]json.RawMessage
+	if json.Unmarshal(peekError(res), &refusal) != nil || len(refusal) != 1 {
+		return res, nil
+	}
+	var detail string
+	if json.Unmarshal(refusal["detail"], &detail) != nil || detail != "Bad Request" {
+		return res, nil
+	}
+	rc, err := req.GetBody()
+	if err != nil {
+		return res, nil
+	}
+	retry := req.Clone(req.Context())
+	retry.Body = rc
+	decoded, err := decodedBody(retry)
+	if err != nil {
+		rc.Close()
+		return res, nil
+	}
+	limit := codexBodyLimit()
+	body, err := io.ReadAll(io.LimitReader(decoded, limit+1))
+	decoded.Close()
+	rc.Close()
+	if err != nil || int64(len(body)) > limit || req.Context().Err() != nil {
+		return res, nil
+	}
+	provider.SetBody(retry, body)
+	retry.Header.Del("Content-Encoding")
+	retry.Header.Del("Content-Length")
+	res.Body.Close()
+	log.Printf("codex: opaque 400 for zstd HTTP request; retrying the identical %d-byte JSON once uncompressed", len(body))
+	sentUp(req.Context(), len(body), len(body))
+	return t.next.RoundTrip(retry)
+}
diff --git a/internal/gateway/codex_http_encoding_test.go b/internal/gateway/codex_http_encoding_test.go
new file mode 100644
index 0000000..3a9c221
--- /dev/null
+++ b/internal/gateway/codex_http_encoding_test.go
@@ -0,0 +1,137 @@
+package gateway
+
+import (
+	"bytes"
+	"io"
+	"net/http"
+	"strings"
+	"testing"
+
+	"github.com/klauspost/compress/zstd"
+	"github.com/yetone/magpie/internal/provider"
+)
+
+type codexEncodingTransport func(*http.Request) (*http.Response, error)
+
+func (f codexEncodingTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+// A real backend parse-only probe refused zstd with {"detail":"Bad Request"}
+// while the identical JSON sent without compression reached model validation.
+// No output from an accepted response, or informative API error, may be replayed.
+func TestCodexHTTPBare400RetriesIdenticalPlainBody(t *testing.T) {
+	old := provider.CodexBase
+	provider.CodexBase = "https://codex.example/backend-api/codex"
+	t.Cleanup(func() { provider.CodexBase = old })
+	was := codexSocketOff.Swap(true)
+	t.Cleanup(func() { codexSocketOff.Store(was) })
+	t.Cleanup(provider.CodexZstdForTests(true))
+	body := []byte(`{"model":"gpt-6.1-sol","input":[{"role":"user","content":"history and completed tool results stay unchanged"}],"stream":true}`)
+	req, _ := http.NewRequest("POST", provider.CodexBase+"/responses", bytes.NewReader(body))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Authorization", "Bearer test-only")
+	req.Header.Set("X-Codex-Turn-State", "test-state")
+	provider.CodexCompressed(req, body)
+	calls := 0
+	next := codexEncodingTransport(func(r *http.Request) (*http.Response, error) {
+		calls++
+		b, _ := io.ReadAll(r.Body)
+		if r.Header.Get("Authorization") != "Bearer test-only" || r.Header.Get("X-Codex-Turn-State") != "test-state" {
+			t.Error("request identity or turn state changed")
+		}
+		if calls == 1 {
+			if r.Header.Get("Content-Encoding") != "zstd" {
+				t.Fatal("control wasn't compressed")
+			}
+			d, _ := zstd.NewReader(nil)
+			plain, e := d.DecodeAll(b, nil)
+			d.Close()
+			if e != nil || !bytes.Equal(plain, body) {
+				t.Fatal("compressed control changed")
+			}
+			return &http.Response{StatusCode: 400, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"detail":"Bad Request"}`)), Request: r}, nil
+		}
+		if calls > 2 {
+			t.Fatal("encoding retry loop")
+		}
+		if r.Header.Get("Content-Encoding") != "" || !bytes.Equal(b, body) || r.ContentLength != int64(len(body)) {
+			t.Fatal("plain retry changed input or retained its encoded length")
+		}
+		return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("data: OK\n\n")), Request: r}, nil
+	})
+	res, err := (codexSocket{next: next}).RoundTrip(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != 200 || calls != 2 {
+		t.Fatalf("compressed backend refusal stayed stuck: status=%d requests=%d", res.StatusCode, calls)
+	}
+}
+
+func TestCodexHTTPEncodingDoesNotReplayOtherAnswers(t *testing.T) {
+	for _, tc := range []struct {
+		name, base, path, encoding, body string
+		status                           int
+	}{
+		{"meaningful400", "https://codex.example/backend-api/codex", "/responses", "zstd", `{"error":{"message":"Invalid parameter","param":"tools","code":"invalid_value"}}`, 400},
+		{"uncompressed400", "https://codex.example/backend-api/codex", "/responses", "", `{"detail":"Bad Request"}`, 400},
+		{"otherProvider400", "https://codex.example/backend-api/codex", "https://other.example/v1/responses", "zstd", `{"detail":"Bad Request"}`, 400},
+		{"acceptedErrorStream", "https://codex.example/backend-api/codex", "/responses", "zstd", "data: {\"type\":\"error\",\"status\":400}\n\n", 200},
+		{"acceptedStream", "https://codex.example/backend-api/codex", "/responses", "zstd", "data: {\"type\":\"response.output_item.done\"}\n\n", 200},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			old := provider.CodexBase
+			provider.CodexBase = tc.base
+			t.Cleanup(func() { provider.CodexBase = old })
+			was := codexSocketOff.Swap(true)
+			t.Cleanup(func() { codexSocketOff.Store(was) })
+			at := tc.base + tc.path
+			if strings.HasPrefix(tc.path, "https://") {
+				at = tc.path
+			}
+			req, _ := http.NewRequest("POST", at, strings.NewReader(`{"input":"unchanged"}`))
+			req.Header.Set("Content-Encoding", tc.encoding)
+			calls := 0
+			next := codexEncodingTransport(func(r *http.Request) (*http.Response, error) {
+				calls++
+				return &http.Response{StatusCode: tc.status, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(tc.body)), Request: r}, nil
+			})
+			res, err := (codexSocket{next: next}).RoundTrip(req)
+			if err != nil {
+				t.Fatal(err)
+			}
+			defer res.Body.Close()
+			got, _ := io.ReadAll(res.Body)
+			if calls != 1 || res.StatusCode != tc.status || string(got) != tc.body {
+				t.Fatalf("non-encoding response replayed or changed: requests=%d status=%d body=%s", calls, res.StatusCode, got)
+			}
+		})
+	}
+}
+
+func TestCodexHTTPPlainRetryRefusedStopsAtTwo(t *testing.T) {
+	old := provider.CodexBase
+	provider.CodexBase = "https://codex.example/backend-api/codex"
+	t.Cleanup(func() { provider.CodexBase = old })
+	t.Cleanup(provider.CodexZstdForTests(true))
+	body := []byte(`{"input":"unchanged"}`)
+	req, _ := http.NewRequest("POST", provider.CodexBase+"/responses", bytes.NewReader(body))
+	provider.CodexCompressed(req, body)
+	calls := 0
+	next := codexEncodingTransport(func(r *http.Request) (*http.Response, error) {
+		calls++
+		if calls > 2 {
+			t.Fatal("more than one retry")
+		}
+		return &http.Response{StatusCode: 400, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"detail":"Bad Request"}`)), Request: r}, nil
+	})
+	res, err := (codexSocket{next: next}).overHTTP(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer res.Body.Close()
+	b, _ := io.ReadAll(res.Body)
+	if calls != 2 || res.StatusCode != 400 || string(b) != `{"detail":"Bad Request"}` {
+		t.Fatalf("unbounded or hidden error: %d %d %s", calls, res.StatusCode, b)
+	}
+}
diff --git a/internal/gateway/codex_socket.go b/internal/gateway/codex_socket.go
index 8b40459..cd9fe1f 100644
--- a/internal/gateway/codex_socket.go
+++ b/internal/gateway/codex_socket.go
@@ -141,11 +141,11 @@ type codexSocket struct{ next http.RoundTripper }
 
 func (t codexSocket) RoundTrip(req *http.Request) (*http.Response, error) {
 	if codexSocketOff.Load() || req.Method != http.MethodPost || req.GetBody == nil {
-		return t.next.RoundTrip(req)
+		return t.overHTTP(req)
 	}
 	turn, shun := provider.SocketTurn(req)
 	if !turn || (shun && codexShunned(req.URL.Host)) {
-		return t.next.RoundTrip(req)
+		return t.overHTTP(req)
 	}
 	res, err := t.overSocket(req, shun)
 	if res != nil && res.StatusCode == http.StatusOK && res.Header.Get("Content-Type") == "" &&
@@ -168,7 +168,7 @@ func (t codexSocket) overSocket(req *http.Request, shun bool) (*http.Response, e
 			toHTTP(req.Context())
 		}
 		overHTTP = true
-		return t.next.RoundTrip(req)
+		return t.overHTTP(req)
 	}
 	body, ok := codexSocketMessage(req)
 	if !ok {```

</details>

### Historical attribution and privacy boundary

Two original Codex chats encountered repeated opaque 400s, but their reconstructed histories pass today after native Magpie compaction expansion. Full original wire envelopes and headers were not retained. Both original chats completed normal responses on the new gateway after local deployment, with original history prefixes unchanged; **this does not prove those historical failures all had the synthetic compression cause**. No original chat messages, account identifiers, credentials, local paths or private source data are included here, and no migration, deletion or business-data write was replayed during diagnosis.

AI-assisted diagnosis and local implementation. I am reporting observed transport results and a tested local candidate, not claiming upstream acceptance or universal resolution of opaque 400s.

aboat0625-cpu avatar Nov 17 '26 10:11 aboat0625-cpu