From ccc791231fc4b05dc3095ec9d6ce6e8bf73a2847 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 21:38:20 +0800 Subject: [PATCH] gateway: a long turn sent to a Chat upstream is copied once, not five times MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 3.2 MB Codex /v1/responses request served by a Chat provider allocated about 70 MB in the gateway, and that garbage, at GOGC 100 over the app's live heap, set the peak footprint. Four copies went: - unquoteJSON built an escaped string (any text with a newline) in a buffer and then copied it into a string; the buffer is the string now (unsafe.String, nothing writes to it again), with a copy only when \u escapes left more than a quarter of it unused. - turnIn joined every user text of the conversation (userSaid) only to see whether any was there; saysAnything stops at the first. - buildChat's user message grew a strings.Builder part by part across a merged turn; joinTexts sizes it once and takes a lone part as it is. - marshalItems ran json.Marshal, whose buffer doubles and is then copied out, over one message that holds the whole turn. marshalSized sizes the maps, lists, strings, bools and ints a body is made of first and writes them into one slice of that size, as encoding/json writes them (HTML escaped, � for bad UTF-8, U+2028/2029); any other value is json.Marshal's own. A []any item, reached by its address, is a *any, which went to json.Marshal twice (to size, then to write) until it was dereferenced; TestMarshalBodyAllocatesTwoBodies caught that at 154 MiB for a 47 MiB body, now 52. Run on mote (M5 Pro), at this tree: - TestLongTurnCopiedFewTimes, a 2.0 MB 300-turn Responses body with CJK and newlines: read 6.72 MB -> 4.76 MB (3.4x -> 2.4x), turnIn 1.93 MB -> 10 KB, buildChat 27.3 MB -> 6.06 MB (13.7x -> 3.0x). Broken by hand one at a time in the mote copy, each red on its own bound: unquote back to string(b) 3.4x; userSaid back in turnIn 1.9 MB; the Builder back 7.4x; json.Marshal back 6.2x. - TestMarshalSizedIsJSONMarshal: byte for byte against json.Marshal over all 256 bytes, bad UTF-8, a lone surrogate, U+2028/2029, HTML characters, keys needing escapes, nil maps and lists, floats, RawMessage, pointers, and a func json.Marshal refuses. - go test -count=1 -timeout 45m ./internal/gateway/: ok (582.9s). - go vet ./internal/gateway/ for darwin, linux and windows; gofmt clean. - Gateway bench (120 requests of a 3.2 MB Responses body, 4 at a time, through a fake Chat provider, 200 MB ballast held live), 3 runs each, old/new: TotalAlloc 8368-8403 MB -> 5889-5891 MB (-30%), GCs 26-27 -> 18-19, phys_footprint_peak 795/806/807 MB -> 763/762/749 MB, CPU 7.89-7.92 s -> 8.01-8.17 s (the size pass costs about what the copies saved). 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. A 180 KB /v1/responses request (a long CJK turn with & "quotes" \ tabs, a function_call and its output holding U+2028, then a question) to deepseek/deepseek-flash, served through buildChat: answered with both code words as sent (, MANGO), non-streamed and streamed. Not tried: an Anthropic-in, Chat-out request, and the live app's own peak (the bench stands in for it). --- internal/gateway/affinity.go | 2 +- internal/gateway/chat.go | 25 +- internal/gateway/fastjson.go | 333 ++++++++++++++++++++-- internal/gateway/long_turn_copies_test.go | 93 ++++++ internal/gateway/prompt.go | 6 + 5 files changed, 432 insertions(+), 27 deletions(-) create mode 100644 internal/gateway/long_turn_copies_test.go diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index 3eca4c5ef..e981215c4 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -378,7 +378,7 @@ func turnIn(req *Request) (turn int, within bool) { if m.Role != "user" { continue } - said, result := userSaid(m) != "", false + said, result := saysAnything(m), false for _, p := range m.Parts { switch p.Kind { case Image, File: diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 83c5180ab..251943942 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -320,6 +320,25 @@ func chatReplaysReasoning(host, model string) bool { return strings.Contains(host, "deepseek") || strings.Contains(strings.ToLower(model), "deepseek") || host == provider.CommandCodePlanID || host == "qoder" || host == "qoder-cn" } +// joinTexts joins text parts once, at their joined size: a long turn +// is many parts, and a Builder grown part by part copied the turn +// several times over on every request +func joinTexts(content []map[string]any) string { + if len(content) == 1 { + return content[0]["text"].(string) + } + n := 0 + for _, c := range content { + n += len(c["text"].(string)) + } + var b strings.Builder + b.Grow(n) + for _, c := range content { + b.WriteString(c["text"].(string)) + } + return b.String() +} + func buildChat(r *Request, model, host string, rejectTemp bool) []byte { r = responseInstructions(r) var msgs []map[string]any @@ -454,11 +473,7 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte { seen = nil } if plain { - var b strings.Builder - for _, c := range content { - b.WriteString(c["text"].(string)) - } - msgs = append(msgs, map[string]any{"role": "user", "content": b.String()}) + msgs = append(msgs, map[string]any{"role": "user", "content": joinTexts(content)}) } else { msgs = append(msgs, map[string]any{"role": "user", "content": content}) } diff --git a/internal/gateway/fastjson.go b/internal/gateway/fastjson.go index 35f64a9eb..64ade9d2a 100644 --- a/internal/gateway/fastjson.go +++ b/internal/gateway/fastjson.go @@ -10,6 +10,7 @@ import ( "hash/maphash" "reflect" "slices" + "strconv" "sync" "sync/atomic" "unicode" @@ -754,7 +755,15 @@ func unquoteJSON(q []byte) (string, bool) { b = utf8.AppendRune(b, rr) } } - return string(b), true + if cap(b)-len(b) > len(b)/4 { + // \u escapes came to much less than they were: a copy of its + // own size, so a string kept long holds no room it doesn't use + return string(b), true + } + // b is this string's own and nothing writes to it again: the string + // is b, not a second copy of a long text (a turn's text has escapes, + // its newlines at least, and was copied twice on every request) + return unsafe.String(unsafe.SliceData(b), len(b)), true } // hex4 is encoding/json's getu4: the rune of the \uXXXX at s, or -1. @@ -1509,11 +1518,10 @@ func marshalBody(out map[string]any, spent string) ([]byte, error) { continue } // measured only: written now, straight into the body - w := appendWriter{dst} - if err := json.NewEncoder(&w).Encode(list.Index(j).Addr().Interface()); err != nil { + var err error + if dst, err = appendJSONValue(dst, list.Index(j).Addr().Interface()); err != nil { return nil, err } - dst = w.b[:len(w.b)-1] // Encode's newline if k == spent { list.Index(j).SetZero() } @@ -1541,28 +1549,26 @@ func isSplitList(v any) bool { // kept to its zero value. func marshalItems(v any, spend bool, kept *int) ([]json.RawMessage, int, bool) { if !isSplitList(v) { - b, err := json.Marshal(v) + b, err := marshalSized(v) *kept -= len(b) return []json.RawMessage{b}, len(b), err == nil } rv := reflect.ValueOf(v) items := make([]json.RawMessage, rv.Len()) - var count countWriter - measure := json.NewEncoder(&count) size := 0 for i := range items { // by its address, as json.Marshal reaches a slice's items: a // MarshalJSON on the pointer is called it := rv.Index(i).Addr().Interface() if *kept <= 0 { - before := count.n - if measure.Encode(it) != nil { + n, ok := jsonSize(it) + if !ok { return nil, 0, false } - size += count.n - before - 1 // Encode's newline + size += n continue } - b, err := json.Marshal(it) + b, err := marshalSized(it) if err != nil { return nil, 0, false } @@ -1576,16 +1582,301 @@ func marshalItems(v any, spend bool, kept *int) ([]json.RawMessage, int, bool) { return items, size, true } +// marshalSized is json.Marshal(v), written into one slice of its size. +// json.Marshal grows its buffer by doubling and then copies it out, so a +// long turn's text cost three to four times its size again on every +// request to a Chat upstream. The maps, lists, strings, bools and ints a +// body is built of are written here as encoding/json writes them; any +// other value is json.Marshal's own. +func marshalSized(v any) ([]byte, error) { + n, ok := jsonSize(v) + if !ok { + return json.Marshal(v) + } + return appendJSONValue(make([]byte, 0, n), v) +} + +// jsonSize is how long json.Marshal(v) is; false when it fails. +func jsonSize(v any) (int, bool) { + switch v := v.(type) { + case nil: + return 4, true + case string: + return jsonStringSize(v), true + case bool: + if v { + return 4, true + } + return 5, true + case int: + var b [20]byte + return len(strconv.AppendInt(b[:0], int64(v), 10)), true + case int64: + var b [20]byte + return len(strconv.AppendInt(b[:0], v, 10)), true + case *any: + // a []any's item, by its address + if v == nil { + return 4, true + } + return jsonSize(*v) + case *map[string]any: + if v == nil { + return 4, true + } + return jsonSize(*v) + case map[string]any: + if v == nil { + return 4, true + } + n := 2 + max(len(v)-1, 0) + for k, x := range v { + if !plainJSONKey(k) { + return 0, false + } + m, ok := jsonSize(x) + if !ok { + return 0, false + } + n += len(k) + 3 + m + } + return n, true + case *[]map[string]any: + if v == nil { + return 4, true + } + return jsonSize(*v) + case []map[string]any: + if v == nil { + return 4, true + } + n := 2 + max(len(v)-1, 0) + for _, x := range v { + m, ok := jsonSize(x) + if !ok { + return 0, false + } + n += m + } + return n, true + case *[]any: + if v == nil { + return 4, true + } + return jsonSize(*v) + case []any: + if v == nil { + return 4, true + } + n := 2 + max(len(v)-1, 0) + for _, x := range v { + m, ok := jsonSize(x) + if !ok { + return 0, false + } + n += m + } + return n, true + } + b, err := json.Marshal(v) + return len(b), err == nil +} + +// appendJSONValue appends json.Marshal(v) to dst (jsonSize's values). +func appendJSONValue(dst []byte, v any) ([]byte, error) { + switch v := v.(type) { + case nil: + return append(dst, "null"...), nil + case string: + return appendJSONString(dst, v), nil + case bool: + return strconv.AppendBool(dst, v), nil + case int: + return strconv.AppendInt(dst, int64(v), 10), nil + case int64: + return strconv.AppendInt(dst, v, 10), nil + case *any: + if v == nil { + return append(dst, "null"...), nil + } + return appendJSONValue(dst, *v) + case *map[string]any: + if v == nil { + return append(dst, "null"...), nil + } + return appendJSONValue(dst, *v) + case map[string]any: + if v == nil { + return append(dst, "null"...), nil + } + keys := make([]string, 0, len(v)) + for k := range v { + if !plainJSONKey(k) { + return appendMarshalled(dst, v) + } + keys = append(keys, k) + } + slices.Sort(keys) + dst = append(dst, '{') + for i, k := range keys { + if i > 0 { + dst = append(dst, ',') + } + dst = append(dst, '"') + dst = append(dst, k...) + dst = append(dst, '"', ':') + var err error + if dst, err = appendJSONValue(dst, v[k]); err != nil { + return dst, err + } + } + return append(dst, '}'), nil + case *[]map[string]any: + if v == nil { + return append(dst, "null"...), nil + } + return appendJSONValue(dst, *v) + case []map[string]any: + if v == nil { + return append(dst, "null"...), nil + } + dst = append(dst, '[') + for i, x := range v { + if i > 0 { + dst = append(dst, ',') + } + var err error + if dst, err = appendJSONValue(dst, x); err != nil { + return dst, err + } + } + return append(dst, ']'), nil + case *[]any: + if v == nil { + return append(dst, "null"...), nil + } + return appendJSONValue(dst, *v) + case []any: + if v == nil { + return append(dst, "null"...), nil + } + dst = append(dst, '[') + for i, x := range v { + if i > 0 { + dst = append(dst, ',') + } + var err error + if dst, err = appendJSONValue(dst, x); err != nil { + return dst, err + } + } + return append(dst, ']'), nil + } + return appendMarshalled(dst, v) +} + +func appendMarshalled(dst []byte, v any) ([]byte, error) { + b, err := json.Marshal(v) + if err != nil { + return dst, err + } + return append(dst, b...), nil +} + +// plainJSONKey is a key json.Marshal writes as it is, between quotes. +func plainJSONKey(k string) bool { + for i := 0; i < len(k); i++ { + if c := k[i]; c < 0x20 || c >= 0x7f || c == '"' || c == '\\' || c == '<' || c == '>' || c == '&' { + return false + } + } + return true +} + +// jsonStringSize is how long json.Marshal(s) is. +func jsonStringSize(s string) int { + n := 2 + for i := 0; i < len(s); { + c := s[i] + if c < utf8.RuneSelf { + switch { + case c == '"', c == '\\', c == '\b', c == '\f', c == '\n', c == '\r', c == '\t': + n += 2 + case c < 0x20, c == '<', c == '>', c == '&': + n += 6 + default: + n++ + } + i++ + continue + } + r, size := utf8.DecodeRuneInString(s[i:]) + if r == utf8.RuneError && size == 1 || r == '\u2028' || r == '\u2029' { + n += 6 + } else { + n += size + } + i += size + } + return n +} + +// appendJSONString appends s as encoding/json writes a string, its HTML +// characters escaped: invalid UTF-8 as \ufffd, and U+2028 and U+2029 +// escaped. +func appendJSONString(dst []byte, s string) []byte { + const hex = "0123456789abcdef" + dst = append(dst, '"') + start := 0 + for i := 0; i < len(s); { + c := s[i] + if c < utf8.RuneSelf { + if c >= 0x20 && c != '"' && c != '\\' && c != '<' && c != '>' && c != '&' { + i++ + continue + } + dst = append(dst, s[start:i]...) + switch c { + case '"', '\\': + dst = append(dst, '\\', c) + case '\b': + dst = append(dst, '\\', 'b') + case '\f': + dst = append(dst, '\\', 'f') + case '\n': + dst = append(dst, '\\', 'n') + case '\r': + dst = append(dst, '\\', 'r') + case '\t': + dst = append(dst, '\\', 't') + default: + dst = append(dst, '\\', 'u', '0', '0', hex[c>>4], hex[c&0xF]) + } + i++ + start = i + continue + } + r, size := utf8.DecodeRuneInString(s[i:]) + if r == utf8.RuneError && size == 1 { + dst = append(dst, s[start:i]...) + dst = append(dst, `\ufffd`...) + i += size + start = i + continue + } + if r == '\u2028' || r == '\u2029' { + dst = append(dst, s[start:i]...) + dst = append(dst, '\\', 'u', '2', '0', '2', hex[r&0xF]) + i += size + start = i + continue + } + i += size + } + dst = append(dst, s[start:]...) + return append(dst, '"') +} + // bodyKept is how many bytes of a body's written items marshalBody keeps // to put in the body; past it they are measured and written again. var bodyKept = 4 << 20 - -// countWriter counts what is written to it. -type countWriter struct{ n int } - -func (w *countWriter) Write(b []byte) (int, error) { w.n += len(b); return len(b), nil } - -// appendWriter appends what is written to it to b. -type appendWriter struct{ b []byte } - -func (w *appendWriter) Write(p []byte) (int, error) { w.b = append(w.b, p...); return len(p), nil } diff --git a/internal/gateway/long_turn_copies_test.go b/internal/gateway/long_turn_copies_test.go new file mode 100644 index 000000000..67567b9d2 --- /dev/null +++ b/internal/gateway/long_turn_copies_test.go @@ -0,0 +1,93 @@ +package gateway + +import ( + "context" + "encoding/json" + "strings" + "testing" +) + +// allocatedEach is what f allocates a run, over a few runs. +func allocatedEach(f func()) uint64 { + f() + const n = 4 + return allocated(func() { + for range n { + f() + } + }) / n +} + +// A long Responses turn sent to a Chat upstream is copied as few times +// as it must be. A 3.2 MB Codex request allocated ~70 MB in the gateway, +// and that garbage, not what is kept, set the app's peak footprint: its +// text was unquoted into a buffer and copied again into a string, the +// user's words were joined only to see they were there, and the Chat +// message's text was built part by part, growing and copying. +func TestLongTurnCopiedFewTimes(t *testing.T) { + var items []string + for i := range 300 { + text := strings.Repeat("读这个文件 read this file\n", 200) + strings.Repeat("x", i) + q, _ := json.Marshal(text) + items = append(items, `{"type":"message","role":"user","content":[{"type":"input_text","text":`+string(q)+`}]}`) + } + body := []byte(`{"model":"m","stream":true,"input":[` + strings.Join(items, ",") + `]}`) + ctx, done := context.WithCancel(context.Background()) + defer done() + holdBody(ctx, body) // as readRequestBody holds a request's + r, err := readResponsesFor(body, false, false) + if err != nil { + t.Fatal(err) + } + size := uint64(len(body)) + + if got := allocatedEach(func() { readResponsesFor(body, false, false) }); got > size*3 { + t.Errorf("reading a %d-byte request allocated %d bytes (%.1f×)", size, got, float64(got)/float64(size)) + } + if got := allocatedEach(func() { turnIn(r) }); got > size/16 { + t.Errorf("finding a %d-byte request's turn allocated %d bytes", size, got) + } + // the text once for the merged turn, once in the marshalled body + if got := allocatedEach(func() { buildChat(r, "m", "api.example.com", false) }); got > size*7/2 { + t.Errorf("building a Chat body from a %d-byte request allocated %d bytes (%.1f×)", size, got, float64(got)/float64(size)) + } + t.Logf("body %d: read %d, turn %d, chat %d", size, + allocatedEach(func() { readResponsesFor(body, false, false) }), allocatedEach(func() { turnIn(r) }), + allocatedEach(func() { buildChat(r, "m", "api.example.com", false) })) +} + +// marshalSized writes what json.Marshal writes, byte for byte: every +// byte, invalid UTF-8, the HTML characters, U+2028 and U+2029, and the +// values it leaves to json.Marshal. +func TestMarshalSizedIsJSONMarshal(t *testing.T) { + var all []byte + for c := range 256 { + all = append(all, byte(c)) + } + temp := 0.7 + m := map[string]any{"a": 1} + list := []map[string]any{{"x": "y"}} + var values0 any = map[string]any{"role": "tool", "content": ""} + values := []any{ + nil, "", string(all), "a
b
c<>&\"\\\x7f\xed\xa0\x80é😀\xff", "读这个文件\n", + true, false, 0, -42, int64(1) << 62, 1.5, &temp, []string{"a", "<"}, + map[string]any{"z": 1, "a": []any{nil, "x", 2, map[string]any{}}, "m": map[string]any(nil)}, + map[string]any{"": "v", "é": 1, "q\"": 2}, + map[string]any{"raw": json.RawMessage(` {"a" : [1, 2]} `), "s": map[string]string{"b": "<"}}, + []map[string]any{{"role": "user", "content": "hi\tthere"}, nil}, []map[string]any(nil), + []any(nil), []any{}, &m, &list, (*map[string]any)(nil), &values0, (*any)(nil), + } + for _, v := range values { + want, werr := json.Marshal(v) + got, gerr := marshalSized(v) + if (werr == nil) != (gerr == nil) || string(got) != string(want) { + t.Errorf("%#v: wrote %s (%v), json.Marshal %s (%v)", v, got, gerr, want, werr) + } + if n, ok := jsonSize(v); ok && n != len(want) { + t.Errorf("%#v: sized %d, json.Marshal wrote %d", v, n, len(want)) + } + } + if _, err := marshalSized(map[string]any{"bad": func() {}}); err == nil { + t.Error("a value json.Marshal refuses was written") + } +} diff --git a/internal/gateway/prompt.go b/internal/gateway/prompt.go index 1a205623e..9134a1aa3 100644 --- a/internal/gateway/prompt.go +++ b/internal/gateway/prompt.go @@ -763,6 +763,12 @@ func userWords(text string) string { return t } +// saysAnything is whether userSaid has anything, without joining the +// words of a long turn only to see they are there +func saysAnything(m Message) bool { + return slices.ContainsFunc(m.Parts, func(p Part) bool { return p.Kind == Text && userSays(p.Text) }) +} + // userSaid is what the user said in a message: the words of its texts. func userSaid(m Message) string { var said []string