gateway: a 413 byte cap or an overflow tells Codex context_length_exceeded, so it compacts instead of reconnecting 5/5 (celestial_eagle_99230 on Discord)

A Codex user on a DeepSeek model kept getting "stream disconnected
before completion: 1017dp: 413 Request Entity Too Large: a web page,
not an API reply ... (request_too_large)" with "reconnecting 5/5".
The big body took the vendor past keepHeldAfter, so Codex's stream
had begun, and streamError sent response.failed with code
server_error. Codex (codex-api sse/responses_error.rs) reads any code
it doesn't know as Retryable, so it sent the same body five more
times. Each was refused the same way, and nothing compacted.
context_length_exceeded is the one code Codex stops on: it marks the
window full and compacts, and core compact.rs trims the oldest items
for as long as the compaction is refused too.

- streamError: a 413 on the Responses shape is code
  context_length_exceeded, for every Responses client. The text still
  says request_too_large for pi.
- failTo: Codex reads a 413 told by HTTP status as UnexpectedStatus,
  and a 400 context_length_exceeded as InvalidRequest
  (api_bridge.rs). Neither compacts. So when Codex (fromCodex, or
  Claude Code's Codex plugin) asked for a stream, a byte cap or an
  overflow goes to it in a stream even before one began
  (keptAlive.compactsInStream). A vendor's own overflow, released
  until now, goes this way too. Other clients keep the status they got
  before.
- Nothing changes for resting: a 413 still rests nobody, and a group
  still tries the next member first.

Tests: codex_byte_cap_test.go. It replays the reporter's nginx page
mid-stream and before the stream, plus a vendor overflow 400, and
checks a non-Codex client keeps its 413. Red on the old code:
TestCodexByteCapInStreamCompacts got "server_error" (the reporter's
exact text), and both TestCodexByteCapBeforeStreamCompacts cases got
a 413 or 400 JSON. TestStreamErrorByteCapInEveryShape now expects
context_length_exceeded for Responses.

Run on mote (mote-run, this tree): go test ./internal/gateway on the
byte-cap, stream-error, overflow, compact and Codex tests: ok. GOOS=linux
and GOOS=windows go vet ./internal/gateway: ok. gofmt -l: clean.
Full suite: mote-run go test -timeout 45m ./... at fb29cd30f plus this
change (before the gateway-routing.md paragraph, docs only): 82 packages
ok; internal/gui red in two tests this change doesn't reach, both filed:
TestSettingsSaveKeepsWhatItDoesNotSend (SearchAll not kept, #4514) and
TestMainWindowCorners/macOS_26_SDK (macOS 27 toolbar, #3949).

Not tried: a real Codex against a real 413 vendor. Codex's handling
was read from openai/codex main, not run. DeepSeek documents no
request-body byte limit, and whether 1017dp is DeepSeek's own API or
a relay in front of it is unknown.
This commit is contained in:
yetone
2026-10-31 22:57:37 +08:00
parent c30d3b7b63
commit 2cca111764
5 changed files with 204 additions and 4 deletions
File diff suppressed because one or more lines are too long
+164
View File
@@ -0,0 +1,164 @@
package gateway
import (
"bufio"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// nginx413 is the page nginx answers a body past client_max_body_size
// with, as a key provider in front of DeepSeek's chat API gave it to a
// Codex user (celestial_eagle_99230 on Discord: "1017dp: 413 Request
// Entity Too Large: a web page, not an API reply").
const nginx413 = "<html>\r\n<head><title>413 Request Entity Too Large</title></head>\r\n<body>\r\n<center><h1>413 Request Entity Too Large</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n"
// askCodexStream posts a streamed Responses request for model as ua, and
// reads the reply whole, closing heard (when set) at its first keepalive.
func askCodexStream(t *testing.T, s *Server, model, ua string, heard chan struct{}) (int, string, string) {
t.Helper()
gw := httptest.NewServer(s.Handler())
t.Cleanup(gw.Close)
req, _ := http.NewRequest("POST", gw.URL+"/v1/responses",
strings.NewReader(`{"model":"`+model+`","stream":true,"input":[{"role":"user","content":"hi"}]}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", ua)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if heard == nil {
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, resp.Header.Get("Content-Type"), string(b)
}
var once sync.Once
var body strings.Builder
rd := bufio.NewReader(resp.Body)
for {
line, err := rd.ReadString('\n')
body.WriteString(line)
if strings.HasPrefix(line, ": keepalive") {
once.Do(func() { close(heard) })
}
if err != nil {
return resp.StatusCode, resp.Header.Get("Content-Type"), body.String()
}
}
}
// failedCode is the code of a Responses stream's response.failed, "" for
// none.
func failedCode(body string) string {
for _, line := range strings.Split(body, "\n") {
if d, ok := strings.CutPrefix(line, "data: "); ok && gjson.Get(d, "type").String() == "response.failed" {
return gjson.Get(d, "response.error.code").String()
}
}
return ""
}
func byteCapRestsNobody(t *testing.T, s *Server) {
t.Helper()
for _, try := range lastRoute(s).Tries {
if try.Rest != nil || try.Fail == failOverflow && try.Status == 413 {
t.Fatalf("a byte cap rested the provider or was booked as an overflow: %+v", lastRoute(s).Tries)
}
}
restingUntil.Lock()
n := len(restingUntil.m)
restingUntil.Unlock()
if n != 0 {
t.Fatalf("a byte cap persisted %d rests", n)
}
}
const codexUA = "codex_cli_rs/0.162.3 (Mac OS 26.6.0; arm64) kitty"
// A 413 after Codex's stream has begun (a large body takes the vendor
// past keepHeldAfter) reached Codex as response.failed with code
// server_error, which Codex reads as worth reconnecting for: it sent the
// same body five times ("reconnecting 5/5"), refused each time, and never
// compacted. context_length_exceeded is the one code Codex stops and
// compacts on (codex-api sse/responses_error.rs; core compact.rs trims the
// oldest items while its compaction gets it too), and the only one in the
// Responses API that says the input must be smaller.
func TestCodexByteCapInStreamCompacts(t *testing.T) {
quietFast(t)
fresh(t)
hang := make(chan struct{})
up := &scripted{hang: hang, replies: []reply{{413, "text/html", nginx413}}}
scriptedOn(t, "dp", provider.Chat, up)
heard := make(chan struct{})
go func() {
select {
case <-heard:
case <-time.After(5 * time.Second):
}
close(hang)
}()
s := New()
code, _, body := askCodexStream(t, s, "dp/m", codexUA, heard)
if code != 200 || !strings.Contains(body, ": keepalive") {
t.Fatalf("the stream's headers never went out ahead of the 413: %d %q", code, body)
}
if got := failedCode(body); got != "context_length_exceeded" {
t.Fatalf("Codex was told %q, which it reconnects for: %s", got, body)
}
if !strings.Contains(body, "request_too_large") {
t.Fatalf("the text no longer says request_too_large, which pi compacts on: %s", body)
}
if up.n != 1 {
t.Fatalf("the refused body was sent %d times", up.n)
}
byteCapRestsNobody(t, s)
}
// The same 413 before the stream began went to Codex as an HTTP 413,
// which Codex takes as an unexpected status: the turn ends and nothing
// compacts, and a compaction refused the same way fails outright. Codex
// asked for a stream, so it is told in one, as response.failed
// context_length_exceeded; and so is an overflow, whose 400
// context_length_exceeded Codex reads as an invalid request.
func TestCodexByteCapBeforeStreamCompacts(t *testing.T) {
for _, c := range []struct {
name string
reply reply
}{
{"nginx 413", reply{413, "text/html", nginx413}},
{"overflow 400", reply{400, "application/json", `{"error":{"message":"This model's maximum context length is 131072 tokens. However, you requested 140000 tokens.","type":"invalid_request_error","code":"invalid_request_error"}}`}},
} {
t.Run(c.name, func(t *testing.T) {
fresh(t)
up := &scripted{replies: []reply{c.reply}}
scriptedOn(t, "dp", provider.Chat, up)
s := New()
code, ctype, body := askCodexStream(t, s, "dp/m", codexUA, nil)
if code != 200 || !strings.HasPrefix(ctype, "text/event-stream") || failedCode(body) != "context_length_exceeded" {
t.Fatalf("Codex wasn't told in its stream to compact: %d %s %s", code, ctype, body)
}
if up.n != 1 {
t.Fatalf("the refused body was sent %d times", up.n)
}
byteCapRestsNobody(t, s)
})
}
}
// Another Responses client keeps the status it is told today before its
// stream begins: only Codex reads nothing but the stream's code.
func TestByteCapBeforeStreamStaysStatusForOthers(t *testing.T) {
fresh(t)
scriptedOn(t, "dp", provider.Chat, &scripted{replies: []reply{{413, "text/html", nginx413}}})
code, _, body := askCodexStream(t, New(), "dp/m", "opencode/1.4.0 ai-sdk/openai", nil)
if code != 413 || !strings.Contains(body, "request_too_large") {
t.Fatalf("another client's 413: %d %s", code, body)
}
}
+14
View File
@@ -2477,6 +2477,8 @@ type keptAlive struct {
// it asked; streams, whether it asked for a stream
told time.Time
streams bool
// codex, whether Codex sent the request (fromCodex)
codex bool
// Only opted-in Claude cache reporting can defer initial keepalives.
// Selection releases it before process startup; expiry keeps the stream alive.
cacheReportUntil time.Time
@@ -2493,6 +2495,18 @@ type keptAlive struct {
// itself, so a second held try, or a group's pause (#1418), went past it.
var agentQuietMost = 4 * time.Minute
// compactsInStream says a refusal of a request too large to be taken —
// past the vendor's byte cap (413) or the model's window (tooLong) — goes
// to the agent in its stream though none was sent yet: Codex compacts on
// response.failed context_length_exceeded alone. Told by status, it takes
// a 413 for an unexpected status and a 400 context_length_exceeded for an
// invalid request, and either ends the turn with nothing compacted, a
// compaction refused the same way failing outright (codex-rs codex-api
// api_bridge.rs). Another client keeps the status.
func (a *keptAlive) compactsInStream(status int, msg string) bool {
return a.codex && a.streams && a.proto == provider.Responses && (status == http.StatusRequestEntityTooLarge || tooLong(status, msg))
}
// tooQuiet says whether a Responses agent that has had no event of its
// reply would go agentQuietMost without one after d more.
func (a *keptAlive) tooQuiet(d time.Duration) bool {
+20
View File
@@ -2706,6 +2706,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
var firstBegan time.Time // when the first try began
streams := streamOf(body)
kept.streams = streams
kept.codex = fromCodex(r.Header) || codexForClaudeCode(r.Header)
if from == provider.Gemini {
streams = strings.Contains(r.URL.Path, "streamGenerateContent")
}
@@ -4039,6 +4040,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
} else if !hw.passing && hw.code() == http.StatusRequestEntityTooLarge {
// No member left took the body; only now add the byte-limit hint.
failTo(w, kept, from, call.Status, call.Error)
} else if !hw.passing && hw.code() >= 400 && kept.compactsInStream(call.Status, call.Error) {
// the vendor said the conversation is past the model's window:
// Codex is told in its stream, the one place it compacts on it
failTo(w, kept, from, call.Status, call.Error)
} else {
hw.release()
if hw.passing {
@@ -8139,6 +8144,10 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
// stream's error once a held stream sent it the stream's headers to keep
// it alive (keepAlive), where a status can no longer be said.
func failTo(w http.ResponseWriter, a *keptAlive, proto provider.Protocol, status int, msg string) int {
if a != nil && !a.sent && a.compactsInStream(status, msg) {
newSSEWriter(w).begin()
a.sent = true
}
if a == nil || !a.sent {
return writeError(w, proto, status, msg)
}
@@ -8171,6 +8180,17 @@ func streamError(w http.ResponseWriter, proto provider.Protocol, model string, s
if byteCap && !ownShape && !alreadySaid {
ev.Text = text + " (request_too_large)"
}
if byteCap && proto == provider.Responses {
// The Responses API has one code that says the input must be
// smaller. Codex reads only the code: server_error had it send
// the same body again five times ("reconnecting 5/5"), refused
// each time, while context_length_exceeded has it stop and
// compact, its compaction trimming the oldest items for as long
// as that is refused too (codex-rs codex-api
// sse/responses_error.rs, core compact.rs; celestial_eagle_99230
// on Discord)
ev.Code = "context_length_exceeded"
}
makeEncoder(proto, sw, &Request{Model: model}).event(ev)
}
@@ -140,8 +140,9 @@ func TestStreamedByteCapSaysRequestTooLargeToPi(t *testing.T) {
}
// Every shape a stream already begun says a 413 in (#2533): the text names
// request_too_large for Chat, Anthropic and Responses, and Chat's and
// Anthropic's type is it; Gemini keeps its own status shape; a 413 that
// request_too_large for Chat, Anthropic and Responses, Chat's and
// Anthropic's type is it, and Responses' code is context_length_exceeded,
// the one Codex compacts on; Gemini keeps its own status shape; a 413 that
// says the context is too long stays context_length_exceeded.
func TestStreamErrorByteCapInEveryShape(t *testing.T) {
const capped = "A: 413 Request Entity Too Large"
@@ -152,7 +153,8 @@ func TestStreamErrorByteCapInEveryShape(t *testing.T) {
}{
{provider.Chat, capped, "request_too_large", `"type":"request_too_large"`},
{provider.Anthropic, capped, "request_too_large", `"type":"request_too_large"`},
{provider.Responses, capped, "request_too_large", `"code":"server_error"`},
// Codex reconnects on server_error and compacts on this alone
{provider.Responses, capped, "request_too_large", `"code":"context_length_exceeded"`},
{provider.Gemini, capped, "", `"status"`},
{provider.Chat, "A: 413 prompt is too long: 300000 tokens > 200000 maximum", "", `"code":"context_length_exceeded"`},
} {