Commit Graph
6 Commits
Author SHA1 Message Date
yetoneandcrayon b68218f43e gateway: a Responses reply to a client that isn't Codex carries only the Responses enum's events (#4482)
Grok Build, reading /v1/responses through async-openai's typed
ResponseStreamEvent, lost whole turns on a ChatGPT account: the backend
speaks part of the Codex protocol (codex.rate_limits,
codex.response.metadata, response.metadata, a keepalive event), and the
client read each as `unknown variant` and ended the turn.

passthrough now runs responsesEnumTidy (responses_enum.go) last in its
chain for a Responses stream to a client that isn't Codex (the
fromCodex / agentOf pair codex_own_v1.go uses): every event whose
`event:` name, or data `type` where it names none, is outside the OpenAI
Responses enum is dropped; a keepalive goes on as an SSE comment so a
quiet upstream still keeps the client's idle timer alive. sniff and
codexLimitsTap read the upstream bytes before it, so failover and the
account's windows are unchanged. Codex itself gets every event as it
came. A plugin's Responses reply goes through the same passthrough, so
it is covered too. The WebSocket route's synthesized header frames
(socketTurnWriter.headerFrames) go to Codex alone too.

The response.failed shape from the report (missing created_at /
sequence_number) was already fixed on main by 29bfd5dc8 (plugins#852);
crayonlu's test for it is kept.

Ported from crayonlu's codex-lead-events branch (917878484, four
commits), with the keepalive comment and OpenAI's audio events added to
the enum.

Run (mote, macOS arm64, Go 1.26.8):
- focused: TestResponsesEventsOutsideTheEnumStayWithCodex,
  TestResponsesEnumAllowed, TestPassthroughResponsesEndsShort,
  TestSocketHeaderFramesOnlyForCodex, TestCodexSocketServed,
  TestResponsesEventsAreClientShaped: ok.
- broken by hand: gateway.go and responses_ws.go back to origin/main
  with the tests kept: both foreign clients red (codex.rate_limits,
  codex.response.metadata, response.metadata, keepalive there=true, no
  keepalive comment) and the socket test red with the leaked frames;
  the Codex cases stay green.
- gofmt -l clean; go vet -tags nogui ./internal/gateway on darwin,
  GOOS=linux and GOOS=windows ok.
- go test -tags nogui -timeout 45m -count=1 ./internal/gateway: ok
  (2186s), at this tree on origin/main c9d253e4a.
- rebased on 44d6dd75d (gateway.go changed upstream): the focused
  tests above with the new cap/group tests (TestCapGroup*,
  TestCodexOneAccountSpent*, TestPluginCapPool*) ok; vet ok.
Not tried: a real ChatGPT account with Grok Build (a second sign-in can
rotate the live refresh token); the full ./... suite (mote at load ~760
with a long suite-lock queue).

Reported-by: crayonlu
Reported-by: Jeo-Meek
Co-authored-by: crayon <hicrayon@outlook.com>
2026-11-09 12:36:18 +08:00
yetone acd789d452 gateway: a finished route drops its tool scan, so socket turn bodies are freed
casyubaji (Discord) saw magpie at ~2.8 GB after 6 hours on v0.1.2909
with Claude Code, Codex and DeepSeek. The cause is Codex's Responses
socket. Each turn is served from a body built in memory (turnBody), the
whole conversation, through a POST whose Body and GetBody keep it. The
trace keeps its last 60 routes. Each turn's route kept its tool scan
(toolScan), which held the request's context. That context holds the
inflight (inflightKey), the inflight holds its unrouted watch
(unroutedHold.r), and the watch holds the request and so the body. So
60 conversations stayed in memory after every socket had closed: with
Codex's 20 MB ones, over 1.2 GB.

The scan is read only for turnFinal, when the route is done. trace.update
now drops r.tools right after that read. The scan itself still lives with
the request's capture writer while the reply goes.

Soak on mote (fake upstream, sandbox HOME, 300 codexws turns, 3 at a
time, conversations of 20000 to 60000 items, then 2 minutes idle, all
sockets closed):
- main 43849d51c: live heap 1418.6 MB idle, rss 2.9 GB. Idle profile:
  turnBody 1263.6 MB.
- this change: live heap 133.0 MB idle, rss 754 MB. Idle profile:
  turnBody 21.2 MB (one body), readSized 63.7 MB (the bounded prompt
  bodies, promptBodiesMax 64 MB).
HTTP soaks (Claude Code, Codex, chat, sessions polling) stayed flat at
~37 MB on main, since an HTTP request's body is the network's reader.

Test: TestSocketTurnBodiesFreed runs 12 socket turns with a 256 KB
conversation, closes the socket, and checks through runtime.AddCleanup
(the socketTurnBody hook) that every turn body is freed.
- Broken by hand: on the old code (without r.tools = nil) it is red,
  "12 of 12 socket turn bodies still kept after the socket closed".
- With the change it is green.

Run on mote: go test -tags nogui -count=1 ./internal/gateway ok (788.8s);
go vet for darwin, linux and windows on ./internal/gateway; gofmt -l
clean. Full suite: after the push, recorded on the tag's run.

Not tried:
- a real Codex account. The upstream was a fake.
- Codex over HTTP with zstd bodies (decoded into memory, so the same
  chain could keep them). It was not soaked; the fix covers that route too.
- the one turn body and its ownItems still live after idle were not
  traced to their holder. They stay at one and do not grow.
2026-11-04 20:29:35 +08:00
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
yetone ec0a11d47f gateway: a Codex socket's held reply keeps its input, not the frame it came in
A held turn's fresh input items were views into the response.create frame
they were decoded from, so each held reply kept that whole frame alive:
Codex's tools and instructions with it, for as long as the socket held
the reply (~39 MB of a long session's live heap). keep now copies the
fresh items into one buffer of their own; the conversation held before
is already owned, and the reply's items were already copied.

Run on mote: go vet ./internal/gateway; go test -run
'TestHeldTurnOwnsItsInput|TestResponsesSocket|TestCodexSocket'
./internal/gateway ok. Broken by hand (keep appends fresh as views):
TestHeldTurnOwnsItsInput fails, held items read back as the overwritten
frame.
Not run: the full gateway package before the push, and a real Codex
session over the socket.
2026-11-01 12:11:05 +08:00
yetone a51776f9c3 gateway: a socket's turn writes its conversation once, not through json.Marshal twice
Codex sends each turn on its Responses WebSocket with only what came
after the reply before it, and the gateway put the conversation back
together and wrote the body the HTTP route would have had: json.Marshal
of the list, then json.Marshal of the body around it. encoding/json
writes a json.RawMessage through its scanner a byte at a time into a
buffer that doubles and is then copied out, so a 3.2 MB conversation
allocated 9.6 MB on every turn. marshalRaw (#1532) had fixed this for
the HTTP routes' rewrites; the socket's turn was left on json.Marshal.

turnBody writes the same bytes, keys sorted, each value checked by
jsonCheck and compacted with <, > and & and U+2028/2029 escaped, into
one slice sized for them: its length plus the five bytes each <, > and
& grows by, counted with bytes.Count, since code is full of them. A
value encoding/json would refuse still goes to json.Marshal, which says
why. Live heap on the owner's running app had 8.8 MB under this
json.Marshal between collections.

Run on mote (M5 Pro), at this tree:
- TestTurnBodyIsJSONMarshal: byte for byte json.Marshal's for 0, 1 and
  40 pretty-printed items with literal <, >, &, U+2028, U+2029, tabs
  and CJK; nil input is null; a broken item is refused.
- TestTurnBodyWrittenOnce: a 3,225,123-byte turn allocates 3,252,336
  bytes (1.01x); json.Marshal twice, 9,605,256.
  Broken by hand in the mote copy, each red: the escape count dropped
  (2.9x, the slice grew twice); values written without HTML escaping
  (bytes differ for all three sizes); json.Marshal back inside
  turnBody (3.0x).
- TestResponsesSocket* and TestCodexSocket*: ok.
- go vet ./internal/gateway/ for darwin, linux and windows; gofmt clean.
- The whole internal/gateway package at the parent, v0.1.2406: ok (772s).

Real use: this build (go build -tags nogui) in a sandbox HOME with the
owner's DeepSeek key only, magpie serve on 127.0.0.1:3581, and Node 22's
WebSocket on /v1/responses: a 30 KB first turn of 400 lines with
<ZEBRA&n> and code, asked for the last one, answered <ZEBRA&399>; the
second turn, previous_response_id and one new message, asked for the
first, answered <ZEBRA&0>. The log: 2 turns, 1 continued, 88003 bytes
sent on as whole requests.

Not tried: a real Codex CLI session on the socket (the client here
sends what Codex sends: response.create, previous_response_id, input).
2026-10-31 21:58:06 +08:00
yetone ffa07395eb gateway: Codex talks Responses to magpie over a WebSocket, turns after the first as a delta (#4058)
Codex names previous_response_id and sends only the new input on its
WebSocket path alone; magpie answered the upgrade 426 (a87dc1ff2), so
Codex fell back to HTTP and re-sent the whole conversation, images
included, every turn (kevinzhow and neighbads on X).

/v1/responses, /responses and /backend-api/codex/responses now accept the
socket (responses_ws.go), with Codex's protocol (codex-rs 2f1e4f9,
responses_websocket.rs):
- each response.create frame is replayed as the POST it stands for through
  the outermost handler the upgrade came in on (socketEntry wraps Front and
  Handler), so the allow list, rebound Host check, key, corsGuard,
  keyLimited, routing, failover, usage and log judge every turn;
- previous_response_id resolves to the socket's own last two replies
  (input + output items); the provider gets the whole conversation, so a
  switch of account or provider mid-chain loses nothing. An id the socket
  doesn't hold is previous_response_not_found (Codex reconnects with
  everything);
- generate:false (warmup) is answered locally; response.interrupt cancels
  the turn (accepted + incomplete/interrupted, or failed); errors are
  Codex's error frame with status and the headers it acts on;
  response.metadata, codex.response.metadata (x-models-etag, magpie's tag)
  and codex.rate_limits are sent as the backend does;
- shutdown drains sockets with 1001 and refuses new ones 503.
Codex needs no config change: magpie's wiring points the built-in openai
provider at /backend-api/codex, which Codex already speaks WS to. Other
Codex backend paths still answer 426. Docs: gateway-routing (new section
"A Responses WebSocket"), providers-accounts, reference.

Run at the pushed head (rebased on origin/main 430005726), on mote:
gofmt -l clean; go vet ./internal/gateway for darwin, linux, windows;
go test -timeout 45m ./internal/gateway: ok (480s).

Real Codex (codex-cli 0.165.0, sandbox HOME/CODEX_HOME with a copy of the
owner's ChatGPT auth, sandbox magpie on 127.0.0.1:3481, gpt-5.6-luna, a
task with three tool calls). At the pushed head, built on mote: exit 0,
right answer, 5 turns on one socket, 4 continued, 75480 B received vs
278210 B sent on as whole requests, no fallback to HTTP. Before the
rebase, with a temporary per-turn log: exit 0, right answer. 5 turns on one socket,
4 continued with previous_response_id; frames 58073 B (first), then 4465,
3051, 3093 B, against 58.7-66.6 KB had each been a whole request. 70185 B
received over the socket vs 255379 B sent on as whole requests.

Broken by hand:
- serveResponsesSocket returning false (the old 426): 9 of the new tests
  red.
- turns sent straight to the Responses handler with the upgrade's
  post-guard context: TestResponsesSocketGuards red (a key turned off
  still served; a 700-token limit not held).

Not tried: images in a real run; Codex on Windows/Linux. Not done: the
leg magpie -> vendor still sends the whole conversation each turn (for
ChatGPT, keeping an upstream socket per client socket would save that);
the saving is Codex's upload to magpie. A socket's conversation does not
survive the socket or a restart (Codex then resends everything).
2026-10-30 08:51:03 +08:00