gateway: a context kept after its handler returns no longer reaches the request's body (#5250)

TestSocketTurnBodiesFreed went red on ubuntu CI at a3d2a85dd ("turn
bodies [8] of 12 still kept"), after a268aadc4 had let the unrouted
watch's own timers go. Two more paths kept a turn's request, and with
it the whole conversation it was sent with:

- A context timer. Any WithTimeout under the request's context, stopped
  as its call ended, is kept with its context in the timer heap of the
  P that set it until that P tidies its heap, and an idle P never does.
  Through the context's values it reached the watch twice: the
  unroutedKey value held the watch itself, and inflightOf's value held
  the inflight, whose f.unrouted is the watch. The watch holds the
  request (u.r), and the request's Body and GetBody the bytes.
  The unroutedKey value is now the watch's held pointer, as its timers
  already were (unroutedOf), let go as the handler returns; done clears
  f.unrouted too. Its readers (noteRoute, showRedacting, notDescribed)
  run inside the handler, before done.
- An asynchronous release. holdBody and the body room let go of a body
  in a context.AfterFunc, which runs in a goroutine of its own once the
  turn's context ends, so under load the test's one collection could
  come first. The test now collects until every body is gone, within
  10s: far under unroutedShow (15s) and unroutedMost (2m), the times a
  real holder kept one for.

Run (the Linux box, wsl-run, since mote is out of disk):
- origin/main 4ddc150c6, TestSocketTurnBodiesFreed -race -cpu 1,2:
  1 red in 80. With a probe, the red was a body still held after 10s,
  and in 9 of 300 runs bodies were freed only 30-120ms after the first
  collection (the async release).
- With the context-value half only: 3 red in 200, each held over 10s.
  With holdBody's sharing turned off: still 1 red in 200, so it isn't
  a decoded string sharing the body. A goroutine dump at the red had 7
  goroutines, none of the gateway's: a heap reference, not a runner.
- With both halves and the new test: 300 of 300 green (-race,
  -count=150, -cpu 1,2).
- TestUnroutedContextLetsGoOfRequest, new, holds the request's context
  past its handler: red 5 of 5 on the old code, red 5 of 5 with only
  the context-value half, red 3 of 3 with only the f.unrouted half,
  green with both. TestUnroutedTimersLetGoOfRequest still passes.
- go vet ./internal/gateway on Linux: ok. gofmt -l: clean.
- The whole internal/gateway package runs next on the Linux box; its
  result goes on #5250.

Not tried: macOS and Windows runs (mote is out of disk and refuses
ssh); other context values that might hold a request are not audited.
This commit is contained in:
yetone
2026-11-11 14:24:25 +08:00
parent 69453574d7
commit 032340056e
3 changed files with 75 additions and 21 deletions
+18 -8
View File
@@ -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)
+32 -13
View File
@@ -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
+25
View File
@@ -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)
}