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) +}