Files
magpie/internal/gateway/fastjson_held_test.go
T
yetone 68133754a3 gateway: a request's body is read in place, not copied by every reader (yg6888 on X: ~1 GB)
yg6888 on X: "magpie 占用内存有点高 随时1个g", with a group of 29
accounts and three agents sending at once.

Cause: each reader of a request decodes its turns into json.RawMessage
values (the images walk, the conversation id, the prompt, the edits, the
chat parse), and decodeJSON copied each value it filled, as
encoding/json does. A 1.5 MB conversation allocated ~42.8 MB on its way
through a group. Three agents at once kept the heap in the hundreds of
MB, and the GC ran behind it.

Fix:
- readRequestBody holds the body (holdBody) until the request's context
  ends. A RawMessage decodeJSON fills from inside a held body shares the
  body's bytes, capped so an append can't write into it. The body must
  be at most 16x the value (heldShareMost), so a small value kept past
  its request (a cache entry, a signature) never pins a whole body.
  Anything not held is still copied: a stream's buffer, a scanner line,
  a body built and changed in place. The list is bounded at 64 bodies
  (heldBodiesMost) and each leaves it through context.AfterFunc.
- The ratio leaves a long conversation's many small turns copied, so
  the two readers that run on every request take them in place:
  - conversationID takes the turns with elementsOf, slices of the
    body.
  - walkImages, which runs several times a request, first scans the
    turns without decoding (anyImageBlock/anyImageIn) and returns at
    once when there is no image. Keys and kinds are compared with
    jsonStringIs, so an escaped "type", a duplicate key, a tool
    result, a Responses function_call_output and Gemini's inlineData,
    fileData and functionResponse still count.

Numbers: sandbox gateway, fresh process each run, 150 requests of a
1.5 MB conversation, 3 at once through a group, machine load ~250:

                    peak RSS  HeapSys  GCs  allocated   bytes.Clone
  before            273 MB    222 MB   117  6416 MB     3635 MB
  held bodies       233 MB    186 MB    74  3379 MB     1480 MB
  + id/image scan   223 MB    174 MB    64  2853 MB      927 MB

That is ~42.8 MB allocated per request before and ~19 MB after. What is
still copied comes from the translators (stringOrText, editMessages,
parseChat, responsesContent), unquoteJSON (~670 MB), io.ReadAll
(~480 MB) and rewriteModel (~225 MB). None of these is changed here.

Tests:
- TestRequestBodyRawValuesShareIt, TestDecodeJSONCopiesWhatIsNotHeld and
  TestHeldBodiesBounded (fastjson_held_test.go).
- TestImageWalkReadsTextOnlyTurnsInPlace: a 938 KB text-only
  conversation allocates under len/8 per walk plus id, and eight image
  shapes are still found.

Broken by hand, each red:
- no share cap
- no ratio
- no bound
- no release
- pre-scan removed (8,780,204 B per iteration)
- tool_result skipped (case not found)
- id decoding each turn (1,044,859 B over the 117,265 limit)
- kind compared as raw bytes (the escaped case is not found)

No subsystem page covers decodeJSON.

Run record, the three commits on origin/main d9c6a60d8 (machine load
~270-480, with other sessions' GUI suites running):
- gofmt -l: clean. go vet ./... on darwin, GOOS=windows and
  GOOS=linux -tags nogui: exit 0.
- go test ./... -count=1 -timeout 45m (sandbox HOME, 11:02-11:34): 64
  ok, 1 FAIL: internal/gui TestCoreScriptBudget, app.js 155 bytes over
  from the first ledNum. ledNum was made smaller (1,268,907 of
  1,269,000 bytes), then internal/gui -count=1 alone: ok (329 s).
- Before the rebase (723f40778 on 9588501c0): internal/gateway ok
  (2064 s), internal/agent ok at -timeout 120m (it timed out at 45m
  at load ~700, #2869), internal/gui red only in
  TestSetAnswersWhileDevinAndProvidersHang (#1375).
- GUI suite, all 140 files, Chromium and WebKit, every language, at
  load 400-840 on 723f40778. Every red was run alone against
  9588501c0, and none comes from this change: routing-bodies
  (#2559/#2658), routing-keys-fold and routing-model-rest (#2658),
  routing-mode-goes WebKit (#2151, head 2/20 vs base 3/20),
  routing-request-metrics (#2571), routing-wb-restricted (#1905),
  usage-agents-hide (#2276/#2399), usage-fold (#2399), usage-checkin
  WebKit Qoder (#2549), usage-refresh (#2184). 5 s first waits under
  load were added to #2900. The usage-ledger route-callback race at
  page close was filed as #3001.
- After the rebase, each alone in both engines: routing-busy-frames,
  routing-intent-entry, routing-key-windows, routing-pause and
  usage-ledger were green.
- After the smaller ledNum, each alone, both engines, all languages:
  routing-busy-frames 6/0 (one later run lost Chromium's launch at
  180 s twice; Chromium alone right after: 3/3), usage-ledger
  Chromium 16/16 and WebKit 17/0. usage-ledger-leave and
  routing-request-metrics were red in browser launch and 5 s waits on
  this head and on d9c6a60d8 alike (#2900, #2571). Added to #2900:
  a WebKit zh usage-ledger run hung after a 5 s timeout.
2026-10-20 13:26:05 +08:00

136 lines
4.6 KiB
Go

package gateway
import (
"bytes"
"context"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"time"
"unsafe"
"github.com/yetone/magpie/internal/provider"
)
// sharesBody says whether part's bytes lie inside whole's.
func sharesBody(part, whole []byte) bool {
p, s := uintptr(unsafe.Pointer(unsafe.SliceData(part))), uintptr(unsafe.Pointer(unsafe.SliceData(whole)))
return len(part) > 0 && p >= s && p+uintptr(len(part)) <= s+uintptr(len(whole))
}
// heldCount is how many bodies heldBodies lists now.
func heldCount() int {
if l := heldBodies.list.Load(); l != nil {
return len(*l)
}
return 0
}
// A request's messages decoded as raw values, as each of its readers
// decodes them (the images, the conversation's id, the prompt, the edits),
// are the body's own bytes while it is served, not a copy each: a 1.5 MB
// body allocated ~60 MB on its way through a group, and three agents
// sending such bodies held the heap at ~310 MB. Once the request is done,
// a decode copies again, and an append to a shared value never writes into
// the body.
func TestRequestBodyRawValuesShareIt(t *testing.T) {
before := heldCount()
sent := memoBody(t.Name())
ctx, done := context.WithCancel(context.Background())
r := httptest.NewRequest("POST", "/v1/chat/completions", bytes.NewReader(sent)).WithContext(ctx)
body, ok := (&Server{}).readRequestBody(httptest.NewRecorder(), r, provider.Chat, 0)
if !ok {
t.Fatal("body not read")
}
var q struct {
Messages []json.RawMessage `json:"messages"`
}
if err := decodeJSON(body, &q); err != nil || len(q.Messages) != 1 {
t.Fatalf("decode: %v, %d messages", err, len(q.Messages))
}
if !sharesBody(q.Messages[0], body) {
t.Fatal("a message decoded from the request's body while it is served is a copy of it")
}
var m map[string]json.RawMessage
if err := decodeJSON(q.Messages[0], &m); err != nil || !sharesBody(m["content"], body) {
t.Fatalf("a value decoded from a shared one is a copy (%v)", err)
}
var small struct {
Model json.RawMessage `json:"model"`
}
if err := decodeJSON(body, &small); err != nil || sharesBody(small.Model, body) {
t.Fatalf("a small value shares the body, which it would keep alive if kept (%v)", err)
}
// the body whole, shared twice: an append to one never shows in the
// other, through the room past the body's end
var w1, w2 json.RawMessage
if decodeJSON(body, &w1) != nil || decodeJSON(body, &w2) != nil || !sharesBody(w1, body) {
t.Fatal("the body decoded whole is not shared")
}
a1, a2 := append(w1, 'x'), append(w2, 'y')
if a1[len(body)] != 'x' || a2[len(body)] != 'y' {
t.Fatal("two appends to the shared body wrote over each other")
}
kept := bytes.Clone(body)
_ = append(m["content"], `,"x"`...)
if !bytes.Equal(body, kept) {
t.Fatal("an append to a shared value wrote into the body")
}
done()
for deadline := time.Now().Add(5 * time.Second); heldCount() > before; {
if time.Now().After(deadline) {
t.Fatal("the body is still held after its request ended")
}
time.Sleep(time.Millisecond)
}
q.Messages = nil
if err := decodeJSON(body, &q); err != nil || sharesBody(q.Messages[0], body) {
t.Fatalf("a body whose request ended is still shared (%v)", err)
}
}
// Only a request's own body is shared: bytes decodeJSON is handed from
// anywhere else — a buffer a stream fills again — are copied, so a raw
// value outlives what is written over them.
func TestDecodeJSONCopiesWhatIsNotHeld(t *testing.T) {
buf := []byte(`{"messages":[{"role":"user","content":"` + strings.Repeat("x", validMemoMin) + `"}]}`)
var q struct {
Messages []json.RawMessage `json:"messages"`
}
if err := decodeJSON(buf, &q); err != nil {
t.Fatal(err)
}
want := string(q.Messages[0])
copy(buf, bytes.Repeat([]byte("y"), len(buf)))
if string(q.Messages[0]) != want {
t.Fatal("a raw value decoded from bytes not held changed with them")
}
}
// heldBodies is bounded: requests whose context never ends, or more than
// heldBodiesMost at once, go without sharing rather than growing the list.
func TestHeldBodiesBounded(t *testing.T) {
before := heldCount()
holdBody(context.Background(), memoBody(t.Name()))
if heldCount() != before {
t.Fatal("a body whose context never ends was held")
}
ctx, done := context.WithCancel(context.Background())
defer done()
for i := range heldBodiesMost + 10 {
holdBody(ctx, memoBody(t.Name()+string(rune('a'+i%26))))
}
if n := heldCount(); n > heldBodiesMost {
t.Fatalf("%d bodies held, past %d", n, heldBodiesMost)
}
done()
for deadline := time.Now().Add(5 * time.Second); heldCount() > before; {
if time.Now().After(deadline) {
t.Fatalf("%d bodies still held after their requests ended", heldCount()-before)
}
time.Sleep(time.Millisecond)
}
}