From a268aadc40615e39ee1e4ef60bb334ce2f10cc79 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 4 Nov 2026 22:15:17 +0800 Subject: [PATCH] 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. --- internal/gateway/responses_ws_mem_test.go | 46 ++++++++++++++++------- internal/gateway/unrouted.go | 23 ++++++++++-- internal/gateway/unrouted_test.go | 30 +++++++++++++++ 3 files changed, 82 insertions(+), 17 deletions(-) diff --git a/internal/gateway/responses_ws_mem_test.go b/internal/gateway/responses_ws_mem_test.go index 2df7e16e6..0f2e76ddf 100644 --- a/internal/gateway/responses_ws_mem_test.go +++ b/internal/gateway/responses_ws_mem_test.go @@ -1,15 +1,18 @@ 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" ) @@ -39,14 +42,16 @@ func TestSocketTurnBodiesFreed(t *testing.T) { 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 + var mu sync.Mutex + var bodies []weak.Pointer[byte] socketTurnBody = func(body []byte) { - made.Add(1) - runtime.AddCleanup(&body[0], func(struct{}) { freed.Add(1) }, struct{}{}) + mu.Lock() + bodies = append(bodies, weak.Make(&body[0])) + mu.Unlock() } t.Cleanup(func() { socketTurnBody = nil }) - _, ts := sockServer(t) + s, ts := sockServer(t) c, _, err := dialSock(t, ts, "/v1/responses", nil) if err != nil { t.Fatal(err) @@ -67,17 +72,30 @@ func TestSocketTurnBodiesFreed(t *testing.T) { 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 (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") } - // 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) + mu.Lock() + defer mu.Unlock() + if len(bodies) != turns { + t.Fatalf("%d turn bodies for %d turns", len(bodies), turns) } - if n := freed.Load(); n < turns { - t.Fatalf("%d of %d socket turn bodies still kept after the socket closed", turns-n, 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) } } diff --git a/internal/gateway/unrouted.go b/internal/gateway/unrouted.go index af20223e3..2ffa7fe9a 100644 --- a/internal/gateway/unrouted.go +++ b/internal/gateway/unrouted.go @@ -595,17 +595,34 @@ func (s *Server) watchUnrouted(w http.ResponseWriter, r *http.Request, f *inflig f.mu.Lock() f.unrouted = u f.mu.Unlock() + // The timers reach u through held alone, let go as the handler + // returns. A stopped timer is not gone: the runtime keeps it, and its + // func, in the timer heap of the P that set it until its time comes + // or that P next tidies its heap, and an idle P never does. Through u + // a stopped timer kept the request, its body and its context's values + // up to unroutedMost after the handler returned (#5250: a socket's + // last 256 KB turn body was kept that way). + held := new(atomic.Pointer[unroutedHold]) + held.Store(u) + via := func(m func(*unroutedHold)) func() { + return func() { + if u := held.Load(); u != nil { + m(u) + } + } + } u.wmu.Lock() - u.unknown = time.AfterFunc(unroutedUnknown, u.checkUnknown) - u.most = time.AfterFunc(unroutedMost, u.checkMost) + u.unknown = time.AfterFunc(unroutedUnknown, via((*unroutedHold).checkUnknown)) + u.most = time.AfterFunc(unroutedMost, via((*unroutedHold).checkMost)) u.wmu.Unlock() - show := time.AfterFunc(unroutedShow, u.show) + show := time.AfterFunc(unroutedShow, via((*unroutedHold).show)) return u.w, r, func() { show.Stop() u.wmu.Lock() u.unknown.Stop() u.most.Stop() u.wmu.Unlock() + held.Store(nil) f.mu.Lock() // a timer that fired as the handler returned does nothing now u.over = true diff --git a/internal/gateway/unrouted_test.go b/internal/gateway/unrouted_test.go index d5c2bbfed..4f30c8265 100644 --- a/internal/gateway/unrouted_test.go +++ b/internal/gateway/unrouted_test.go @@ -1,14 +1,17 @@ package gateway import ( + "bytes" "context" "io" "net/http" "net/http/httptest" + "runtime" "strings" "sync" "testing" "time" + "weak" "github.com/yetone/magpie/internal/gwmw" "github.com/yetone/magpie/internal/settings" @@ -591,3 +594,30 @@ func TestUnroutedCodexPathShowsItsModel(t *testing.T) { t.Fatal("never answered once masked") } } + +// TestUnroutedTimersLetGoOfRequest: a stopped timer is not gone. The +// runtime keeps it, and its func, in the timer heap of the P that set it +// until its time comes or that P tidies its heap, so a timer that reached +// the request kept its body up to unroutedMost after the handler returned +// (#5250). The test holds the stopped timers as that heap does. +func TestUnroutedTimersLetGoOfRequest(t *testing.T) { + body := make([]byte, 64<<10) + gone := weak.Make(&body[0]) + f := &inflight{} + r := httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + body = nil + _, r, unwatch := (&Server{}).watchUnrouted(httptest.NewRecorder(), r, f) + f.mu.Lock() + u := f.unrouted + f.mu.Unlock() + u.wmu.Lock() + timers := []*time.Timer{u.unknown, u.most} + u.wmu.Unlock() + unwatch() + u, r, f = nil, nil, nil + runtime.GC() + if gone.Value() != nil { + t.Fatal("a stopped unrouted timer still reaches its request's body") + } + runtime.KeepAlive(timers) +}