Files
magpie/internal/gateway/long_turn_copies_test.go
T
yetone ccc791231f gateway: a long turn sent to a Chat upstream is copied once, not five times
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 <tag> & "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 (<ZEBRA&42>, 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).
2026-10-31 21:39:37 +08:00

94 lines
3.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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": "<b>"}
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{"<k>": "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")
}
}