From acd789d4527d93f6116312e9fc139ea51d637780 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 4 Nov 2026 20:29:32 +0800 Subject: [PATCH] gateway: a finished route drops its tool scan, so socket turn bodies are freed casyubaji (Discord) saw magpie at ~2.8 GB after 6 hours on v0.1.2909 with Claude Code, Codex and DeepSeek. The cause is Codex's Responses socket. Each turn is served from a body built in memory (turnBody), the whole conversation, through a POST whose Body and GetBody keep it. The trace keeps its last 60 routes. Each turn's route kept its tool scan (toolScan), which held the request's context. That context holds the inflight (inflightKey), the inflight holds its unrouted watch (unroutedHold.r), and the watch holds the request and so the body. So 60 conversations stayed in memory after every socket had closed: with Codex's 20 MB ones, over 1.2 GB. The scan is read only for turnFinal, when the route is done. trace.update now drops r.tools right after that read. The scan itself still lives with the request's capture writer while the reply goes. Soak on mote (fake upstream, sandbox HOME, 300 codexws turns, 3 at a time, conversations of 20000 to 60000 items, then 2 minutes idle, all sockets closed): - main 43849d51c: live heap 1418.6 MB idle, rss 2.9 GB. Idle profile: turnBody 1263.6 MB. - this change: live heap 133.0 MB idle, rss 754 MB. Idle profile: turnBody 21.2 MB (one body), readSized 63.7 MB (the bounded prompt bodies, promptBodiesMax 64 MB). HTTP soaks (Claude Code, Codex, chat, sessions polling) stayed flat at ~37 MB on main, since an HTTP request's body is the network's reader. Test: TestSocketTurnBodiesFreed runs 12 socket turns with a 256 KB conversation, closes the socket, and checks through runtime.AddCleanup (the socketTurnBody hook) that every turn body is freed. - Broken by hand: on the old code (without r.tools = nil) it is red, "12 of 12 socket turn bodies still kept after the socket closed". - With the change it is green. Run on mote: go test -tags nogui -count=1 ./internal/gateway ok (788.8s); go vet for darwin, linux and windows on ./internal/gateway; gofmt -l clean. Full suite: after the push, recorded on the tag's run. Not tried: - a real Codex account. The upstream was a fake. - Codex over HTTP with zstd bodies (decoded into memory, so the same chain could keep them). It was not soaked; the fix covers that route too. - the one turn body and its ownItems still live after idle were not traced to their holder. They stay at one and do not grow. --- internal/gateway/responses_ws.go | 7 ++ internal/gateway/responses_ws_mem_test.go | 83 +++++++++++++++++++++++ internal/gateway/trace.go | 5 ++ 3 files changed, 95 insertions(+) create mode 100644 internal/gateway/responses_ws_mem_test.go diff --git a/internal/gateway/responses_ws.go b/internal/gateway/responses_ws.go index 8ffd4ef72..b912228d0 100644 --- a/internal/gateway/responses_ws.go +++ b/internal/gateway/responses_ws.go @@ -498,6 +498,9 @@ func (rs *responsesSocket) turn(ctx context.Context, t *socketTurnRun, frame []b return } rs.sent += int64(len(body)) + if socketTurnBody != nil { + socketTurnBody(body) + } req := rs.request(ctx, body) out := &socketTurnWriter{rs: rs, ctx: ctx, run: t, h: http.Header{}} rs.o.via.ServeHTTP(out, req) @@ -514,6 +517,10 @@ func (rs *responsesSocket) turn(ctx context.Context, t *socketTurnRun, frame []b } } +// socketTurnBody, set by the tests, is handed each body a turn is served +// with, to see that nothing keeps it once the turn is over. +var socketTurnBody func(body []byte) + // 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 diff --git a/internal/gateway/responses_ws_mem_test.go b/internal/gateway/responses_ws_mem_test.go new file mode 100644 index 000000000..2df7e16e6 --- /dev/null +++ b/internal/gateway/responses_ws_mem_test.go @@ -0,0 +1,83 @@ +package gateway + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// A socket turn's body is freed once the turn is over (casyubaji on +// Discord: ~2.8 GB after 6 hours of Codex). Each turn is served from a +// body built in memory, the whole conversation, and the trace keeps its +// last 60 routes: a route that kept the turn's request context (its tool +// scan, for the turn's end) kept the request on it (the inflight's +// unrouted watch), and with it the body, so 60 of Codex's 20 MB +// conversations stayed after every socket had closed. +func TestSocketTurnBodiesFreed(t *testing.T) { + fresh(t) + var served atomic.Int64 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + n := served.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + id := fmt.Sprintf("resp_up%d", n) + item := fmt.Sprintf(`{"type":"message","id":"msg_%d","role":"assistant","status":"completed","content":[{"type":"output_text","text":"answer %d"}]}`, n, n) + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"`+id+`","object":"response","status":"in_progress","output":[]}}`, + `data: {"type":"response.output_item.done","output_index":0,"item":`+item+`}`, + `data: {"type":"response.completed","response":{"id":"`+id+`","object":"response","status":"completed","output":[`+item+`],"usage":{"input_tokens":300,"output_tokens":50,"total_tokens":350}}}`)) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Responses: up.URL + "/v1", Models: []string{"m1"}}); err != nil { + t.Fatal(err) + } + var made, freed atomic.Int64 + socketTurnBody = func(body []byte) { + made.Add(1) + runtime.AddCleanup(&body[0], func(struct{}) { freed.Add(1) }, struct{}{}) + } + t.Cleanup(func() { socketTurnBody = nil }) + + _, ts := sockServer(t) + c, _, err := dialSock(t, ts, "/v1/responses", nil) + if err != nil { + t.Fatal(err) + } + big := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 256<<10) + `"}]}` + const turns = 12 + id := "" + for i := range turns { + in := userMore + if i == 0 { + in = big + } + got := c.turn(create(id, in)) + end := last(got) + if end.Get("type").String() != "response.completed" { + t.Fatalf("turn %d: %v", i, got) + } + id = end.Get("response.id").String() + } + c.c.CloseNow() + if made.Load() != turns { + t.Fatalf("%d turn bodies for %d turns", made.Load(), turns) + } + // the socket's handler ends after its client goes; nothing of a + // turn is kept after, but the trace's routes + deadline := time.Now().Add(10 * time.Second) + for freed.Load() < turns && time.Now().Before(deadline) { + runtime.GC() + time.Sleep(20 * time.Millisecond) + } + if n := freed.Load(); n < turns { + t.Fatalf("%d of %d socket turn bodies still kept after the socket closed", turns-n, turns) + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 3f6f12138..9e579d979 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -851,6 +851,11 @@ func (t *trace) update(r *Route, f func(r *Route)) { t.totals.Errors++ } t.turns.end(r, turnFinal(r), time.Now()) + // read: the scan's context is its request's, which keeps the + // request on it (inflight's unrouted watch) and so its body; a + // socket turn's is the whole conversation, in memory, and 60 + // routes are kept + r.tools = nil if keepsRoutes() { c := *r c.Order = append([]Weighed{}, r.Order...) // [] for none: the GUI reads it as a list