gateway: a Codex turn of its own reads past 512 MB, to a sixteenth of the machine's memory (dallascao)

dallascao on Discord: generating images in Codex and revising them again
and again, magpie answered 413 "request body is over magpie's gateway
limit of 512 MB (decoded); the provider was not asked" on
127.0.0.1:3425/backend-api/codex/responses, while Codex signed in to
OpenAI directly went on. The count was right: Codex keeps each image it
generated in the conversation (a function_call_output input_image, a
~3 MB PNG as ~4 MB base64; codex-rs ext/image-generation to_response_item,
and history keeps image_generation_call results), and over HTTP sends the
conversation whole every turn, so ~130 images is 512 MB decoded. To
OpenAI directly Codex uses its WebSocket and sends a delta.

- Codex's own path (codexBackend, the Codex relay, the Responses
  WebSocket's read limit, keyLimited on CodexPath) reads to
  codexBodyLimit: a sixteenth of the machine's memory (memLimit, else
  proc.MemTotal), 512 MB at least, 2 GB at most. 16 GB: 1024 MB,
  24 GB: 1536 MB, 32 GB+: 2048 MB, 8 GB or unknown: 512 MB as before.
  It is still the bomb guard: nothing decodes past it, and the zstd
  decoder keeps its window bound.
- A turn for a magpie model ("provider/model") on that path is held to
  the 512 MB of every other route once its model is read: it is
  translated, at several times its size. Its 413 says one of Codex's own
  models takes up to codexBodyLimit; writeError's /compact hint stays.
- provider.codexNamesBad read tools/input/tool_choice with
  GetManyBytes, which copied the whole input (the body's size: 300 MB of
  a 300 MB turn in the alloc profile). It reads in place now.

Cost at the largest input (mote, a relayed gpt-5.5 turn of random
~3 MB images, heap objects sampled every 5ms, load ~350): 300 MB took
4.7s, 600 MB 7.7s, 1000 MB 11.9s, peak heap 1.5 to 2.1 GB past the
body's own bytes. The rest of the cost is io.ReadAll growing the decoded
body and fillJSONIn/exchangeOf; bodyRoom still runs a body bigger than
its room alone.

Run at the pushed head (mote): gofmt -l clean; GOOS=linux and
GOOS=windows go vet ./internal/gateway ./internal/provider ok;
go test -timeout 45m ./internal/provider ok, ./internal/gateway ok but
TestCompactionOverByteCapEveryTime, red in the full package run only
(#4862, filed before this; passes alone 3 of 3 here).
TestRequestBodyTooLarge/codex now sends codexBodyLimit+1.
- TestCodexGeneratedImagesPastOldLimit (16 GB machine fixture, a 516 MB
  turn of generated images in Codex's shape): reaches the fake ChatGPT
  backend whole in ~6s; the same turn for x/gpt-5 is 413 naming
  "one of Codex's own models takes up to 1024 MB".
- TestCodexBodyLimitFromMemory: 2/8/16/24/64 GiB and unknown memory.
Broken by hand: codexBackend reading with limit 0 (the old code) makes
TestCodexGeneratedImagesPastOldLimit red with the reporter's 413; the
magpie-model check turned off makes it red (404 from routing, not 413).

Not tried: the reporter's own session or a real Codex image-generation
run through magpie; a turn past 1 GB on a 16 GB machine; the WebSocket's
raised read limit has no test of its own.
This commit is contained in:
yetone
2026-11-03 16:05:53 +08:00
parent bc10a61985
commit 694f4a6d65
9 changed files with 205 additions and 8 deletions
File diff suppressed because one or more lines are too long
+117
View File
@@ -3,11 +3,19 @@ package gateway
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/klauspost/compress/zstd"
"github.com/yetone/magpie/internal/provider"
)
// NeoPengZhile's Codex session had read many images; Codex sends the
@@ -77,3 +85,112 @@ func TestOverLimitSaysWhoseAndWhatToDo(t *testing.T) {
}
}
}
// codexMemory has this test's machine memTotal bytes of memory, as
// codexBodyLimit and bodyRoomSize read it.
func codexMemory(t *testing.T, memTotal int64) {
t.Helper()
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "proc"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "proc/meminfo"), []byte(fmt.Sprintf("MemTotal: %d kB\n", memTotal>>10)), 0o644); err != nil {
t.Fatal(err)
}
wasGOOS, wasRoot := memGOOS, memRoot
memGOOS, memRoot = "linux", root
t.Cleanup(func() { memGOOS, memRoot = wasGOOS, wasRoot })
}
// A turn's limit on Codex's own path is a sixteenth of the machine's
// memory, never under the gateway's 512 MB nor over 2 GB.
func TestCodexBodyLimitFromMemory(t *testing.T) {
for _, c := range []struct{ mem, want int64 }{
{2 << 30, defaultBodyLimit},
{8 << 30, defaultBodyLimit},
{16 << 30, 1 << 30},
{24 << 30, 1536 << 20},
{64 << 30, codexBodyMost},
} {
codexMemory(t, c.mem)
if got := codexBodyLimit(); got != c.want {
t.Errorf("%d GiB: %d MiB, want %d MiB", c.mem>>30, got>>20, c.want>>20)
}
}
// memory not known is not a small machine, nor a large one
memGOOS, memRoot = "linux", t.TempDir()
if got := codexBodyLimit(); got != defaultBodyLimit {
t.Errorf("unknown: %d MiB", got>>20)
}
}
// dallascao on Discord: Codex generating images and revising them again
// and again, until magpie answered 413 "over magpie's gateway limit of
// 512 MB (decoded)" on /backend-api/codex/responses, while Codex signed
// in to OpenAI went on. Codex keeps each generated image in the
// conversation as a function_call_output's input_image, and over HTTP
// sends it whole every turn. On a 16 GB machine such a turn of a little
// over 512 MB, on one of Codex's own models, now reaches the ChatGPT
// backend whole; the same turn for a magpie model is still refused, as a
// magpie model's turn is translated at several times its size, and the
// 413 says Codex's own models take more.
func TestCodexGeneratedImagesPastOldLimit(t *testing.T) {
if testing.Short() {
t.Skip("allocates a few GB")
}
codexMemory(t, 16<<30)
setup(t, provider.Chat, &fake{t: t})
var got atomic.Int64
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
n, _ := io.Copy(io.Discard, r.Body)
got.Store(n)
w.Header()["Content-Type"] = nil
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1"}}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9,"output_tokens":2}}}`))
})
// a generated 1536x1024 PNG of ~3 MB, ~4 MB as base64
img := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{0x89, 'P', 'N', 'G', 5, 6, 7, 8}, 3<<17))
var turn bytes.Buffer
turn.Grow(defaultBodyLimit + 16<<20)
turn.WriteString(`{"model":"gpt-5.5","stream":true,"store":false,"input":[`)
for i := 0; turn.Len() <= defaultBodyLimit+4<<20; i++ {
if i > 0 {
turn.WriteByte(',')
}
fmt.Fprintf(&turn, `{"type":"message","role":"user","content":[{"type":"input_text","text":"bluer, take %d"}]},`, i)
fmt.Fprintf(&turn, `{"type":"function_call","name":"imagegen","namespace":"image_gen","arguments":"{\"prompt\":\"a cat, take %d\"}","call_id":"call_%d"},`, i, i)
fmt.Fprintf(&turn, `{"type":"function_call_output","call_id":"call_%d","output":[{"type":"input_image","image_url":"data:image/png;base64,%s","detail":"high"}]}`, i, img)
}
turn.WriteString(`]}`)
body := turn.Bytes()
post := func() *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
New().Handler().ServeHTTP(rec, req)
return rec
}
start := time.Now()
rec := post()
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"input_tokens":9`) {
t.Fatalf("a %d MB turn of generated images: %d %.300s", len(body)>>20, rec.Code, rec.Body.String())
}
if got.Load() < int64(len(body))-1<<20 {
t.Fatalf("the backend got %d bytes of %d", got.Load(), len(body))
}
t.Logf("a %d MB turn went on in %s", len(body)>>20, time.Since(start))
got.Store(0)
copy(body[len(`{"model":"`):], "x/gpt-5") // a magpie model, as long as gpt-5.5
rec = post()
if rec.Code != 413 || got.Load() != 0 {
t.Fatalf("a magpie model's %d MB turn: %d, backend got %d", len(body)>>20, rec.Code, got.Load())
}
for _, want := range []string{"magpie's gateway limit of 512 MB", "the provider was not asked", "one of Codex's own models takes up to 1024 MB", "/compact"} {
if !strings.Contains(rec.Body.String(), want) {
t.Errorf("413 %s doesn't say %q", rec.Body.String(), want)
}
}
}
+8 -1
View File
@@ -80,7 +80,9 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
// newer: the backend serves a model only to a client that knows it
provider.SawCodexClient(r.Header)
rest := strings.TrimPrefix(r.URL.Path, CodexPath)
body, ok := s.readRequestBody(w, r, provider.Responses, 0)
// a turn of Codex's own is read to codexBodyLimit, one for a magpie
// model held to the limit of every other route once it is named
body, ok := s.readRequestBody(w, r, provider.Responses, s.codexLimitOf())
if !ok {
return
}
@@ -180,6 +182,11 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
// The namespace owns the route even if a model is not in the catalog.
// Unknown providers/groups must fail locally, never fall through to OpenAI.
if strings.Contains(model, "/") {
if most := s.bodyLimitOf(); int64(len(body)) > most {
writeError(w, provider.Responses, http.StatusRequestEntityTooLarge, overLimit(most).Error()+
"; this limit is for a magpie model, and one of Codex's own models takes up to "+sizeWord(s.codexLimitOf()))
return
}
if rest == "/responses/compact" {
writeError(w, provider.Responses, 400, "/responses/compact is not supported for Magpie models; use a compaction_trigger on /responses")
return
+1 -1
View File
@@ -42,7 +42,7 @@ func CodexRelay() http.Handler {
return
}
rest := strings.TrimPrefix(r.URL.Path, CodexPath)
body, status, err := readBoundedRequestBody(w, r, requestLimits{})
body, status, err := readBoundedRequestBody(w, r, requestLimits{body: codexBodyLimit()})
if err != nil {
relayError(w, status, err.Error())
return
+6 -1
View File
@@ -48,7 +48,12 @@ func keyLimited(next http.Handler) http.Handler {
// a compressed body (#1223) is reserved at its decoded size and model
costCap := slices.ContainsFunc(limits, func(l *access.Limit) bool { return l.Cost > 0 })
if enc := r.Header.Get("Content-Encoding"); costCap || size < 0 || (enc != "" && !strings.EqualFold(enc, "identity")) {
b, status, err := readBoundedRequestBody(w, r, requestLimits{})
// a turn on Codex's own path reads to its own limit (codexBackend)
var most int64
if strings.HasPrefix(r.URL.Path, CodexPath+"/") {
most = codexBodyLimit()
}
b, status, err := readBoundedRequestBody(w, r, requestLimits{body: most})
if err != nil {
writeError(w, protoOfPath(r.URL.Path), status, err.Error())
return
+57
View File
@@ -7,11 +7,13 @@ import (
"io"
"net"
"net/http"
"runtime"
"strings"
"sync"
"time"
"github.com/klauspost/compress/zstd"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/provider"
)
@@ -30,6 +32,61 @@ const (
defaultBodyTimeout = 60 * time.Second
)
// codexBodyMost bounds codexBodyLimit on any machine.
const codexBodyMost = 2 << 30
// codexBodyLimit is the decoded limit of a turn on Codex's own backend
// path (CodexPath, the relay, its WebSocket): a sixteenth of what
// magpie's processes may use (bodyRoomSize's memory), defaultBodyLimit at
// least and codexBodyMost at most. Codex keeps every image it generated
// in the conversation, a ~3 MB PNG as ~4 MB of base64 each, and over
// HTTP sends the conversation whole every turn: a session that generated
// and revised images for a while went past 512 MB and got magpie's 413,
// while Codex signed in to OpenAI directly kept going (dallascao on
// Discord). One of Codex's own models is sent on to its sign-in as it
// came, at about four times the body's size in Go heap at its peak; a
// turn for a magpie model is translated, at several times that, and keeps
// defaultBodyLimit (codexBackend). The bound still holds a zstd bomb: no
// body decodes past it.
func codexBodyLimit() int64 {
codexLimit.Lock()
defer codexLimit.Unlock()
if codexLimit.goos != memGOOS || codexLimit.root != memRoot || codexLimit.n == 0 {
limit, _ := memLimit(memGOOS, memRoot)
if limit <= 0 && memGOOS == runtime.GOOS {
limit = proc.MemTotal()
}
codexLimit.goos, codexLimit.root = memGOOS, memRoot
codexLimit.n = min(max(limit/16, defaultBodyLimit), codexBodyMost)
}
return codexLimit.n
}
// codexLimit is codexBodyLimit as last read, for the memory it was read
// from (memGOOS and memRoot change only in tests).
var codexLimit struct {
sync.Mutex
goos, root string
n int64
}
// codexLimitOf is the decoded limit of a request on Codex's own path to
// s: its requestLimits' when set (a test's), else codexBodyLimit.
func (s *Server) codexLimitOf() int64 {
if s.requestLimits.body > 0 {
return s.requestLimits.body
}
return codexBodyLimit()
}
// bodyLimitOf is s's decoded limit for every other request.
func (s *Server) bodyLimitOf() int64 {
if s.requestLimits.body > 0 {
return s.requestLimits.body
}
return defaultBodyLimit
}
type requestLimits struct {
body int64
readTimeout time.Duration
+3
View File
@@ -24,6 +24,9 @@ func TestRequestBodyTooLarge(t *testing.T) {
s := New()
r := httptest.NewRequest("POST", "/", strings.NewReader("{}"))
r.ContentLength = defaultBodyLimit + 1
if api == "codex" { // Codex's own turns are read to more
r.ContentLength = codexBodyLimit() + 1
}
w := httptest.NewRecorder()
switch api {
case "chat":
+6 -1
View File
@@ -199,7 +199,12 @@ func (s *Server) serveResponsesSocket(w http.ResponseWriter, r *http.Request) bo
log.Printf("responses socket from %s: %v", r.RemoteAddr, err)
return true
}
c.SetReadLimit(defaultBodyLimit)
// a turn on a new socket is the conversation whole (codexBodyLimit)
most := int64(defaultBodyLimit)
if strings.HasPrefix(r.URL.Path, CodexPath+"/") {
most = s.codexLimitOf()
}
c.SetReadLimit(most)
sock := &responsesSocket{s: s, o: o, path: r.URL.Path, c: c, ctx: o.ctx}
if !s.sockets.add(sock) {
c.Close(websocket.StatusGoingAway, "magpie is restarting")
+4 -1
View File
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"regexp"
"unsafe"
"github.com/tidwall/gjson"
)
@@ -109,7 +110,9 @@ func codexNamesBad(body []byte) bool {
return !bad
})
}
top := gjson.GetManyBytes(body, "tools", "input", "tool_choice")
// read in place: GetManyBytes copies each value it finds, the input
// whole, which is the body's size (hundreds of MB with Codex's images)
top := gjson.GetMany(unsafe.String(unsafe.SliceData(body), len(body)), "tools", "input", "tool_choice")
tools(top[0])
top[1].ForEach(func(_, it gjson.Result) bool {
switch it.Get("type").String() {