diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 73107945f..87bc3f150 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -689,6 +689,11 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st // a web page or nothing at all, served 200, is the 502 it stands // for (#1012) res = notAnAPIReply(res, "OpenAI: ") + if base != codexAPIBase { + // dropped by ChatGPT for its size: Codex is told it's too + // large rather than sending it again (ylorn on Discord) + res = codexDropped(res, len(body)) + } } defer res.Body.Close() if base == codexAPIBase && res.StatusCode == http.StatusUnauthorized { diff --git a/internal/gateway/codex_dropped.go b/internal/gateway/codex_dropped.go new file mode 100644 index 000000000..fd586904a --- /dev/null +++ b/internal/gateway/codex_dropped.go @@ -0,0 +1,57 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "regexp" +) + +// edgeReset is the 503 ChatGPT's front (Cloudflare, then Envoy) answers, +// as text, when the backend behind it closed the connection before any +// reply. +var edgeReset = regexp.MustCompile(`(?i)upstream connect error or disconnect/reset before headers`) + +// codexDropBody is the request size from which that 503 is taken to be +// about the request. ylorn (Discord, v0.1.1179) got it for every Codex +// turn a PNG screenshot took past about 1 MiB, also without magpie, and +// never once the same image was a smaller JPEG. It isn't the backend's +// limit for everyone: bodies of 1 to 20 MiB were answered from here. +const codexDropBody = 1 << 20 + +// codexDropped is the 413 a ChatGPT Codex reply stands for when the +// backend dropped a request of size bytes this large. Sent again — to +// the same account or another one — the same bytes are dropped the same +// way, so it isn't a 503 to retry, and no account is at fault for it. A +// smaller request dropped the same way is the backend's own trouble and +// stays the 503 it is. +func codexDropped(res *http.Response, size int) *http.Response { + if res == nil || res.StatusCode != http.StatusServiceUnavailable || size < codexDropBody { + return res + } + head, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10)) + if !edgeReset.Match(head) { + res.Body = struct { + io.Reader + io.Closer + }{io.MultiReader(bytes.NewReader(head), res.Body), res.Body} + return res + } + res.Body.Close() + msg := fmt.Sprintf("ChatGPT's Codex backend dropped this %.1f MiB request before answering (503: %s). "+ + "It does this to requests this large, most often from images, on any account, so magpie didn't retry it or rest the account. "+ + "Run /compact, or remove or shrink the images (a JPEG in place of a large PNG screenshot), then try again.", + float64(size)/(1<<20), bytes.TrimSpace(head)) + b, _ := json.Marshal(map[string]any{"error": map[string]any{"message": msg, "type": "request_too_large", "code": "request_too_large"}}) + h := res.Header.Clone() + for _, k := range []string{"Content-Type", "Content-Length", "Content-Encoding", "Transfer-Encoding"} { + h.Del(k) + } + h.Set("Content-Type", "application/json") + out := *res + out.StatusCode, out.Status = http.StatusRequestEntityTooLarge, "413 Request Entity Too Large" + out.Header, out.Body, out.ContentLength = h, io.NopCloser(bytes.NewReader(b)), int64(len(b)) + return &out +} diff --git a/internal/gateway/codex_dropped_test.go b/internal/gateway/codex_dropped_test.go new file mode 100644 index 000000000..3066643c4 --- /dev/null +++ b/internal/gateway/codex_dropped_test.go @@ -0,0 +1,131 @@ +package gateway + +import ( + "crypto/rand" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// edgeDropped is what ylorn's ChatGPT backend answered to a request whose +// screenshot took it past about 1 MiB (Discord, v0.1.1179): Envoy's own +// 503 behind Cloudflare, as text, before any reply. +const edgeDropped = "upstream connect error or disconnect/reset before headers. reset reason: remote connection failure" + +// dropsBig stands in for that ChatGPT backend: a body past 1 MiB is +// answered with edgeDropped, as ylorn's was, and a smaller one is served. +// It notes the account asked each time. +func dropsBig(t *testing.T, tried *[]string) { + t.Helper() + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + *tried = append(*tried, r.Header.Get("chatgpt-account-id")) + if len(b) > 1<<20 { + w.Header().Set("Content-Type", "text/plain") + w.Header().Set("Server", "cloudflare") + w.WriteHeader(http.StatusServiceUnavailable) + io.WriteString(w, edgeDropped) + return + } + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`, + `data: {"type":"response.output_text.delta","delta":"pong"}`, + `data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`)) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) +} + +// screenshotTurn is a Responses turn with a PNG screenshot of about n +// bytes inline, base64 as an agent sends it. Its bytes aren't an image +// any decoder reads, so nothing on the way makes it smaller. +func screenshotTurn(t *testing.T, n int) string { + t.Helper() + raw := make([]byte, n*3/4) + rand.Read(raw) + b, _ := json.Marshal(map[string]any{"model": "gpt-5.5", "stream": true, "input": []any{ + map[string]any{"type": "message", "role": "user", "content": []any{ + map[string]any{"type": "input_text", "text": "what does this screenshot show?"}, + map[string]any{"type": "input_image", "image_url": "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw)}, + }}}}) + return string(b) +} + +// With two ChatGPT accounts on, a turn the backend drops for its size is +// asked of one account once: the other would be dropped the same, a retry +// sends the same bytes again, and neither account is at fault, so nobody +// rests. The agent is told the request is too large, at a status it +// doesn't retry, and what to do about it. A small turn after it goes to +// the first account as before. +func TestCodexDroppedBigBodyIsTheRequests(t *testing.T) { + codexSignedIn(t, "spare@example.com") + var tried []string + dropsBig(t, &tried) + + code, body := codexPost(t, screenshotTurn(t, 1200<<10)) + if code != http.StatusRequestEntityTooLarge { + t.Fatalf("status %d, want 413: %s", code, body) + } + for _, want := range []string{"MiB", "compact", "image"} { + if !strings.Contains(body, want) { + t.Errorf("the agent isn't told %q: %s", want, body) + } + } + if strings.Join(tried, ",") != "acct-1" { + t.Errorf("asked %v, want acct-1 once", tried) + } + if r := restingNow(t); len(r) != 0 { + t.Errorf("rest over the request's size: %v", r) + } + + tried = nil + code, body = codexPost(t, `{"model":"gpt-5.5","stream":true,"input":"ping"}`) + if code != 200 || !strings.Contains(body, "pong") || strings.Join(tried, ",") != "acct-1" { + t.Fatalf("small turn after: %d %s tried %v", code, body, tried) + } +} + +// With Codex's own sign-in alone, relayed as it came: Codex is answered +// the same 413 and words, not the 503 it would send the same bytes again +// for, five times over. +func TestCodexDroppedBigBodyRelayed(t *testing.T) { + codexSignedIn(t) + var tried []string + dropsBig(t, &tried) + + code, body := codexPost(t, screenshotTurn(t, 1200<<10)) + if code != http.StatusRequestEntityTooLarge || !strings.Contains(body, "compact") { + t.Fatalf("status %d: %s", code, body) + } + if strings.Join(tried, ",") != "acct-1" { + t.Errorf("asked %v, want acct-1 once", tried) + } +} + +// The same 503 to a small request is the backend's trouble, as it is in +// an outage: it is relayed as the 503 it is, for the client to try again. +func TestCodexEdgeResetSmallBodyStays503(t *testing.T) { + codexSignedIn(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + w.WriteHeader(http.StatusServiceUnavailable) + io.WriteString(w, edgeDropped) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + + code, body := codexPost(t, `{"model":"gpt-5.5","stream":true,"input":"ping"}`) + if code != http.StatusServiceUnavailable || !strings.Contains(body, "reset reason") { + t.Fatalf("status %d: %s", code, body) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index e3513cf8a..a518ca0ca 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3134,6 +3134,11 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid // Cline's whole replies come in {success, data}; a web page or // nothing at all, served 200, is the 502 it stands for (#1012) res = notAnAPIReply(clineUnwrapped(p, res), "") + if p.Account != nil && p.Account.Agent == "codex" { + // a request ChatGPT drops for its size is the request's, not a + // 503 to ask every account again for (ylorn on Discord) + res = codexDropped(res, len(body)) + } // what a Codex account's reply says it has used, for its cap (#1295) heardCodexLimits(p, res) return res, nil