diff --git a/internal/gateway/responses_ws.go b/internal/gateway/responses_ws.go index 6c91065ae..e7556456a 100644 --- a/internal/gateway/responses_ws.go +++ b/internal/gateway/responses_ws.go @@ -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 { diff --git a/internal/gateway/socket_turn_body_test.go b/internal/gateway/socket_turn_body_test.go new file mode 100644 index 000000000..6172d0db7 --- /dev/null +++ b/internal/gateway/socket_turn_body_test.go @@ -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 & kind` + "\u2028\u2029" + `","input":[` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}],` + + `"tools":[ {"type": "function", "name": "a 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) })) +}