diff --git a/internal/gateway/responses_ws_mem_test.go b/internal/gateway/responses_ws_mem_test.go index 0f2e76ddf..c6edd9b2e 100644 --- a/internal/gateway/responses_ws_mem_test.go +++ b/internal/gateway/responses_ws_mem_test.go @@ -73,10 +73,13 @@ func TestSocketTurnBodiesFreed(t *testing.T) { } 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). + // it); nothing of a turn is kept after, but the trace's routes. A + // held body is let go by a context.AfterFunc (holdBody, body room), + // which runs in a goroutine of its own once the turn's context ends, + // so under load a collection can come before it: collect until each + // is gone, within a bar far under what a real holder keeps one for + // (#5250: a stopped timer kept the last turn's request for up to + // unroutedMost, 2m; unroutedShow is 15s). ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() s.sockets.drain(ctx) @@ -88,12 +91,19 @@ func TestSocketTurnBodiesFreed(t *testing.T) { 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) + for bar := time.Now().Add(10 * time.Second); ; { + runtime.GC() + kept = kept[:0] + for i, b := range bodies { + if b.Value() != nil { + kept = append(kept, i) + } } + if len(kept) == 0 || time.Now().After(bar) { + break + } + time.Sleep(20 * time.Millisecond) } 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 737cb019e..0e253280d 100644 --- a/internal/gateway/unrouted.go +++ b/internal/gateway/unrouted.go @@ -270,10 +270,21 @@ type unroutedHold struct { type unroutedKey struct{} +// unroutedOf is ctx's watch while its handler runs, and nil after: the +// context's value reaches it through the watch's held, as its timers do, +// since a stopped context timer (a WithTimeout under the request's) keeps +// its context, and so this value, as a stopped timer of its own would. +func unroutedOf(ctx context.Context) *unroutedHold { + if held, _ := ctx.Value(unroutedKey{}).(*atomic.Pointer[unroutedHold]); held != nil { + return held.Load() + } + return nil +} + // noteAsked tells ctx's watch the model its request asked for, for the // route that shows it. func noteAsked(ctx context.Context, model string) { - if u, _ := ctx.Value(unroutedKey{}).(*unroutedHold); u != nil { + if u := unroutedOf(ctx); u != nil { u.asked.Store(model) } } @@ -282,7 +293,7 @@ func noteAsked(ctx context.Context, model string) { // func it answers is called: a wait it knows of, whose time counts // toward neither unroutedUnknown nor unroutedMost. func noteMasking(ctx context.Context) func() { - u, _ := ctx.Value(unroutedKey{}).(*unroutedHold) + u := unroutedOf(ctx) if u == nil { return func() {} } @@ -378,7 +389,7 @@ func unroutedRecheck() time.Duration { return min(time.Second, unroutedMost/8) } // kind names the wait in the report of a request held too long // (heldReport): "body", "body room", "hooks" and the rest. func noteWait(ctx context.Context, kind string) (done func()) { - u, _ := ctx.Value(unroutedKey{}).(*unroutedHold) + u := unroutedOf(ctx) if u == nil { return func() {} } @@ -604,7 +615,19 @@ func (s *Server) watchUnrouted(w http.ResponseWriter, r *http.Request, f *inflig } ctx, cancel := context.WithCancelCause(r.Context()) u := &unroutedHold{s: s, f: f, w: newHeldWriter(w), cancel: cancel, agent: callerFrom(r).agent, saved: make(chan struct{})} - r = r.WithContext(context.WithValue(ctx, unroutedKey{}, u)) + // The timers and the context 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), and a + // stopped context timer under the request's (a WithTimeout's) kept + // it through the context's values, this one and the inflight's, for + // as long (#5250 again). + held := new(atomic.Pointer[unroutedHold]) + held.Store(u) + r = r.WithContext(context.WithValue(ctx, unroutedKey{}, held)) if r.Body != nil && r.Body != http.NoBody { r.Body = waitedBody{r.Body, u} } @@ -612,15 +635,6 @@ 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 { @@ -643,6 +657,11 @@ func (s *Server) watchUnrouted(w http.ResponseWriter, r *http.Request, f *inflig f.mu.Lock() // a timer that fired as the handler returned does nothing now u.over = true + // nor does the request in flight reach u: its context's value + // (inflightOf) is kept by a stopped context timer as u's own is + if f.unrouted == u { + f.unrouted = nil + } shown := u.shown if !u.ended { u.shown = nil diff --git a/internal/gateway/unrouted_test.go b/internal/gateway/unrouted_test.go index 9a4308389..d591f86b8 100644 --- a/internal/gateway/unrouted_test.go +++ b/internal/gateway/unrouted_test.go @@ -659,3 +659,28 @@ func TestUnroutedTimersLetGoOfRequest(t *testing.T) { } runtime.KeepAlive(timers) } + +// TestUnroutedContextLetsGoOfRequest: the same for a context timer. A +// WithTimeout under the request's context, stopped as its call ended, +// keeps that context, and its values, in the timer heap as long, and +// through the watch's value or the inflight's one kept the request's +// body (#5250 again: a socket's turn bodies on ubuntu CI). The test +// holds the context as that heap does. +func TestUnroutedContextLetsGoOfRequest(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 = r.WithContext(context.WithValue(r.Context(), inflightKey{}, f)) + _, r, unwatch := (&Server{}).watchUnrouted(httptest.NewRecorder(), r, f) + ctx, cancel := context.WithTimeout(r.Context(), time.Hour) + cancel() + unwatch() + r, f = nil, nil + runtime.GC() + if gone.Value() != nil { + t.Fatal("a context kept after its handler returned still reaches its request's body") + } + runtime.KeepAlive(ctx) +}