Files
magpie/internal/gateway/responses_ws_mem_test.go
T
yetone a268aadc40 gateway: a stopped unrouted timer lets go of its request (#5250)
TestSocketTurnBodiesFreed kept 1 to 3 of 12 turn bodies in full runs on
mote. A heap dump taken at the failure (debug.WriteHeapDump, walked from
the roots) gave the path: allp -> a P's timer heap -> a stopped runtime
timer whose func was (*unroutedHold).checkUnknown -> the unroutedHold ->
u.r, the turn's *http.Request -> its GetBody closure -> the 256 KB body.

A stopped timer is not gone: the runtime keeps it, and its func, in the
heap of the P that set it until its time comes or that P tidies its heap
(only once a quarter of it is stopped timers), and an idle P never does.
watchUnrouted's three timers took u's method values, so every request it
watches (chat completions, responses, messages, Gemini, a socket's every
turn) could stay reachable, body and context values, up to unroutedMost
(2m) after its handler returned. The timers now reach u through an
atomic handle that unwatch clears after stopping them; a timer firing
then does nothing, as u.over already made it.

The test waits on state: drain returns once the socket's handler has
ended, then one runtime.GC and weak pointers to each body, no 10s poll.
TestUnroutedTimersLetGoOfRequest holds the stopped timers as the runtime
heap does and checks the body is unreachable.

Run on mote (go1.26.8, load ~100 from other sessions):
- Before the fix, test binary at b61c71448: 10 of 360 runs of the old
  test kept a body (12 copies x -count 15 x -cpu 1,4); each heap dump
  showed the path above.
- Broken by hand (unrouted.go reverted, new tests kept): the new unit
  test red 5 of 5; the socket test red 151 of 360, "turn bodies [11] of
  12 still kept".
- With the fix: unit test 20 of 20; socket test 0 of 540 failures
  (12 x 15 x -cpu 1,4,18).
- go vet -tags nogui ./internal/gateway for darwin, linux, windows: ok.
- go test -run 'Unrouted|Socket|ResponsesWS|Held' ./internal/gateway: ok.
- gofmt -l: clean.
Not run: the full suite; two other sessions' full suites were running
on mote, and one runs at a time. It follows and goes on #5250.
2026-11-04 22:18:49 +08:00

102 lines
3.3 KiB
Go

package gateway
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"weak"
"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 mu sync.Mutex
var bodies []weak.Pointer[byte]
socketTurnBody = func(body []byte) {
mu.Lock()
bodies = append(bodies, weak.Make(&body[0]))
mu.Unlock()
}
t.Cleanup(func() { socketTurnBody = nil })
s, 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()
// the socket's handler ends after its client goes (drain waits for
// it); nothing of a turn is kept after, but the trace's routes. Not a
// wait for the collector: a weak pointer is gone at the first
// collection after its body is unreachable (#5250: a stopped timer
// kept the last turn's request for up to unroutedMost).
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
s.sockets.drain(ctx)
if ctx.Err() != nil {
t.Fatal("the socket's handler did not end after its client went")
}
mu.Lock()
defer mu.Unlock()
if len(bodies) != turns {
t.Fatalf("%d turn bodies for %d turns", len(bodies), turns)
}
runtime.GC()
var kept []int
for i, b := range bodies {
if b.Value() != nil {
kept = append(kept, i)
}
}
if len(kept) > 0 {
t.Fatalf("turn bodies %v of %d still kept after the socket's handler ended", kept, turns)
}
}