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).
This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -461,13 +462,7 @@ func (rs *responsesSocket) turn(ctx context.Context, t *socketTurnRun, frame []b
|
||||
delete(q, "type")
|
||||
delete(q, "previous_response_id")
|
||||
delete(q, "generate")
|
||||
in, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
rs.writeError(ctx, http.StatusBadRequest, "invalid_request_error", "invalid_value", err.Error(), "input")
|
||||
return
|
||||
}
|
||||
q["input"] = in
|
||||
body, err := json.Marshal(q)
|
||||
body, err := turnBody(q, input)
|
||||
if err != nil {
|
||||
rs.writeError(ctx, http.StatusBadRequest, "invalid_request_error", "invalid_json", err.Error(), "")
|
||||
return
|
||||
@@ -489,6 +484,78 @@ func (rs *responsesSocket) turn(ctx context.Context, t *socketTurnRun, frame []b
|
||||
}
|
||||
}
|
||||
|
||||
// turnBody is json.Marshal(q) with input, as json.Marshal writes it, for
|
||||
// q's input, written once into a slice of about its size. A turn wrote
|
||||
// its conversation with json.Marshal twice, the list and then q around
|
||||
// it, through encoding/json's scanner a byte at a time and a buffer that
|
||||
// doubles and is copied out: about five copies of a long conversation on
|
||||
// every turn, the garbage that sets the peak (marshalRaw has the rest).
|
||||
func turnBody(q map[string]json.RawMessage, input []json.RawMessage) ([]byte, error) {
|
||||
q["input"] = nil
|
||||
n := 2
|
||||
keys := make([]string, 0, len(q))
|
||||
for k, raw := range q {
|
||||
n += len(k) + escapedSize(raw) + 4
|
||||
keys = append(keys, k)
|
||||
}
|
||||
for _, raw := range input {
|
||||
n += escapedSize(raw) + 1
|
||||
}
|
||||
slices.Sort(keys)
|
||||
dst := make([]byte, 0, n)
|
||||
dst = append(dst, '{')
|
||||
ok := true
|
||||
for i, k := range keys {
|
||||
if i > 0 {
|
||||
dst = append(dst, ',')
|
||||
}
|
||||
if dst, ok = appendJSONKey(dst, k, true); !ok {
|
||||
break
|
||||
}
|
||||
dst = append(dst, ':')
|
||||
if k != "input" {
|
||||
if dst, ok = appendRawJSON(dst, q[k], true); !ok {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
if input == nil {
|
||||
dst = append(dst, "null"...)
|
||||
continue
|
||||
}
|
||||
dst = append(dst, '[')
|
||||
for j, raw := range input {
|
||||
if j > 0 {
|
||||
dst = append(dst, ',')
|
||||
}
|
||||
if dst, ok = appendRawJSON(dst, raw, true); !ok {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
dst = append(dst, ']')
|
||||
}
|
||||
if ok {
|
||||
return append(dst, '}'), nil
|
||||
}
|
||||
// a value encoding/json refuses: it says why
|
||||
in, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q["input"] = in
|
||||
return json.Marshal(q)
|
||||
}
|
||||
|
||||
// escapedSize is about what appendRawJSON writes of raw: its length, and
|
||||
// the five bytes each <, > and & grows by as \u003c and the like. Code
|
||||
// is full of them, and a slice that grows doubles.
|
||||
func escapedSize(raw []byte) int {
|
||||
return len(raw) + 5*(bytes.Count(raw, []byte("<"))+bytes.Count(raw, []byte(">"))+bytes.Count(raw, []byte("&")))
|
||||
}
|
||||
|
||||
// request is the POST a turn stands for: the upgrade's own request, its
|
||||
// URL, Host, address and headers, with the turn as its body.
|
||||
func (rs *responsesSocket) request(ctx context.Context, body []byte) *http.Request {
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
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) }))
|
||||
}
|
||||
Reference in New Issue
Block a user