Commit Graph
1 Commits
Author SHA1 Message Date
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