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).
82 lines
2.8 KiB
Go
82 lines
2.8 KiB
Go
package gateway
|
||
|
||
import (
|
||
"bytes"
|
||
"encoding/json"
|
||
"strconv"
|
||
"strings"
|
||
"testing"
|
||
)
|
||
|
||
// oldTurnBody is what a socket's turn wrote before turnBody.
|
||
func oldTurnBody(q map[string]json.RawMessage, input []json.RawMessage) ([]byte, error) {
|
||
in, err := json.Marshal(input)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
q["input"] = in
|
||
return json.Marshal(q)
|
||
}
|
||
|
||
func longSocketTurn(items int) (map[string]json.RawMessage, []json.RawMessage) {
|
||
frame := `{"type":"response.create","model":"fake/m1","stream":true,"instructions":"be <brief> & kind` + "\u2028\u2029" + `","input":[` +
|
||
`{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}],` +
|
||
`"tools":[ {"type": "function", "name": "a<b", "parameters": {"type":"object"}} ],"prompt_cache_key":null}`
|
||
var q map[string]json.RawMessage
|
||
if err := decodeJSONView([]byte(frame), &q); err != nil {
|
||
panic(err)
|
||
}
|
||
line := strings.Repeat("读这个文件 if a < b && c > d { return \"x\\ty\" }\n", 20)
|
||
var input []json.RawMessage
|
||
for i := range items {
|
||
// <, > and & as Codex sends them: as they are
|
||
var b bytes.Buffer
|
||
e := json.NewEncoder(&b)
|
||
e.SetEscapeHTML(false)
|
||
e.Encode(line + strconv.Itoa(i) + "\u2028\u2029")
|
||
text := bytes.TrimSpace(b.Bytes())
|
||
// pretty-printed, as a reply's item may be
|
||
input = append(input, json.RawMessage(`{ "type": "message",`+"\n\t"+`"role": "user", "content": [ {"type":"input_text", "text": `+string(text)+`} ] }`))
|
||
}
|
||
return q, input
|
||
}
|
||
|
||
// A socket's turn is written as json.Marshal wrote it, byte for byte:
|
||
// keys sorted, values compacted, <, >, & and U+2028, U+2029 escaped.
|
||
func TestTurnBodyIsJSONMarshal(t *testing.T) {
|
||
for _, items := range []int{0, 1, 40} {
|
||
q, input := longSocketTurn(items)
|
||
want, err := oldTurnBody(q, input)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
q, input = longSocketTurn(items)
|
||
got, err := turnBody(q, input)
|
||
if err != nil || !bytes.Equal(got, want) {
|
||
t.Errorf("%d items: %v\n got %.300s\nwant %.300s", items, err, got, want)
|
||
}
|
||
}
|
||
q, _ := longSocketTurn(0)
|
||
if got, err := turnBody(q, nil); err != nil || !bytes.Contains(got, []byte(`"input":null`)) {
|
||
t.Errorf("nil input: %s %v", got, err)
|
||
}
|
||
q, input := longSocketTurn(2)
|
||
input[1] = json.RawMessage(`{"bad"`)
|
||
if _, err := turnBody(q, input); err == nil {
|
||
t.Error("a broken item went upstream")
|
||
}
|
||
}
|
||
|
||
// A long conversation on a socket is written once a turn: json.Marshal
|
||
// of the list and then of the body around it allocated ~5 copies.
|
||
func TestTurnBodyWrittenOnce(t *testing.T) {
|
||
q, input := longSocketTurn(2000)
|
||
body, _ := turnBody(q, input)
|
||
size := uint64(len(body))
|
||
got := allocatedEach(func() { turnBody(q, input) })
|
||
if got > size*5/4 {
|
||
t.Errorf("a %d-byte turn allocated %d bytes (%.1f×)", size, got, float64(got)/float64(size))
|
||
}
|
||
t.Logf("body %d: turnBody %d, json.Marshal %d", size, got, allocatedEach(func() { oldTurnBody(q, input) }))
|
||
}
|