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.