Files
magpie/internal/gateway/codex_relay.go
T
yetone 694f4a6d65 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.
2026-11-03 16:05:53 +08:00

136 lines
5.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gateway
import (
"bytes"
"net/http"
"strings"
"github.com/yetone/magpie/internal/masking"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// CodexRelay is what serves Codex's own ChatGPT sign-in at the gateway's
// address once magpie has quit, for the Codex threads still open then
// (codexrelay). magpie takes the failover base URL out of Codex's config
// at quit (agent.EndCodexFailover), but a thread open in the Codex app,
// and the app-server holding it, keep the URL they started with: every
// turn after went to a port nobody listened on, and a system proxy in
// between answered 503 "Unknown error" until magpie was opened again
// (idkatbro on X). The relay passes those turns on to the ChatGPT backend
// as the gateway does a turn on one of Codex's own models, signed by the
// caller's own Authorization; it adds no credential of its own. What only
// the running magpie could do is refused with a reason Codex shows: a
// magpie model, a turn on one of magpie's accounts, masking (Settings ›
// Privacy) that would have masked it. Its answer at "/" never says it is
// magpie (ServedBy), so the next magpie starting asks it to leave.
func CodexRelay() http.Handler {
client := &http.Client{Transport: upstreamTransport()}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !loopbackHost(r.Host) || r.Header.Get("Origin") != "" {
// as the gateway's corsGuard: a rebound or foreign page, or
// a frame's null, never reaches the sign-in Codex sends
relayError(w, http.StatusForbidden, "magpie's Codex relay serves Codex on this computer only")
return
}
if !strings.HasPrefix(r.URL.Path, CodexPath+"/") {
relayError(w, http.StatusServiceUnavailable, relayGone)
return
}
if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
http.Error(w, "magpie speaks HTTP", http.StatusUpgradeRequired)
return
}
rest := strings.TrimPrefix(r.URL.Path, CodexPath)
body, status, err := readBoundedRequestBody(w, r, requestLimits{body: codexBodyLimit()})
if err != nil {
relayError(w, status, err.Error())
return
}
if r.Method == http.MethodPost && (rest == "/responses" || rest == "/responses/compact") {
if msg := relayRefuses(r, body); msg != "" {
// 400, not 503: Codex retries a 5xx five times over for
// a refusal that a retry doesn't change (seen with codex
// 0.162.1), and shows a 4xx's message at once
relayError(w, http.StatusBadRequest, msg)
return
}
// as codexBackend sends a turn of Codex's own to its sign-in
body = plainItemIDs(boundCallIDs(callItemIDs(body)))
body, _ = codexInput(body, false)
}
body = withoutClaudeSeals(body)
base := provider.CodexBase
if apiKey(r.Header) && rest != "/models" {
base = codexAPIBase
}
if r.Method == http.MethodPost && rest == "/responses" && base == provider.CodexBase {
body = provider.DeclareSearch(body, strings.EqualFold(r.Header.Get("X-OpenAI-Internal-Codex-Responses-Lite"), "true"))
}
u := base + rest
if r.URL.RawQuery != "" {
u += "?" + r.URL.RawQuery
}
req, err := http.NewRequestWithContext(provider.ViaSignedIn(r.Context(), "codex"), r.Method, u, bytes.NewReader(body))
if err != nil {
relayError(w, http.StatusBadGateway, err.Error())
return
}
copyHeaders(req.Header, r.Header)
req.Header.Del("Accept-Encoding")
provider.CodexCompressed(req, body)
res, err := client.Do(req)
if err != nil {
relayError(w, http.StatusBadGateway, "OpenAI can't be reached ("+err.Error()+"). magpie isn't running, so this thread goes to OpenAI on Codex's own sign-in.")
return
}
defer res.Body.Close()
for k, vs := range res.Header {
if !hopHeader(k) {
w.Header()[k] = vs
}
}
w.WriteHeader(res.StatusCode)
flush := http.NewResponseController(w)
buf := make([]byte, 32<<10)
for {
n, err := res.Body.Read(buf)
if n > 0 {
if _, werr := w.Write(buf[:n]); werr != nil {
return
}
flush.Flush()
}
if err != nil {
return
}
}
})
}
// relayGone is the relay's answer to anything but Codex's own turns.
const relayGone = "magpie isn't running: only Codex threads open when it quit are passed on, on Codex's own ChatGPT sign-in. Open magpie for everything else."
// relayRefuses says why a turn can't be passed on with magpie gone, ""
// when it can: what only the running gateway serves, and a turn masking
// would have masked, which never goes unmasked.
func relayRefuses(r *http.Request, body []byte) string {
model := modelOf(body)
if strings.Contains(model, "/") {
return model + " is one of magpie's models, and magpie isn't running. Open magpie to go on with this thread, or pick one of Codex's own models."
}
if r.Header.Get(AccountHeader) != "" {
return AccountHeader + " names one of magpie's Codex accounts, and magpie isn't running. Open magpie to go on with this thread."
}
if masking.Wanted(settings.Load()) {
return "magpie isn't running, and Settings › Privacy masks what is sent: this turn is not sent unmasked. Open magpie to go on with this thread."
}
return ""
}
// relayError answers as the ChatGPT backend words an error, so Codex
// shows the message (an empty body reads "Unknown error").
func relayError(w http.ResponseWriter, status int, msg string) {
writeError(w, provider.Responses, status, msg)
}