diff --git a/CHANGELOG.md b/CHANGELOG.md index 61c6092f8bf..472bc314211 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ * [BUGFIX] Querier: Increment `cortex_query_evictions_total` and deregister the victim before cancelling it in the query evictor, fixing double-counted evictions of still-unwinding queries. #7616 * [BUGFIX] Ring: Ignore READONLY ingesters when assigning tokens so the active series remain balanced. #7946 * [BUGFIX] Distributor: Fix a `panic: send on closed channel` crash during shutdown when `-distributor.num-push-workers` or `-distributor.num-query-workers` is greater than 0. #7964 +* [BUGFIX] Ingester Client: Fix a gRPC connection leak when `-distributor.use-stream-push` is enabled. A client whose push streams could not be opened was discarded without closing its connection or cancelling its stream context, and because the client pool only records a client once the factory has succeeded, nothing could close it afterwards. Each failure left a connection reconnecting to the ingester address for the lifetime of the process, and the failures cluster while an address is still in the ring but already unreachable. The error the stream workers report is also no longer written to a plain variable from all of them concurrently. #7969 ## 1.22.0 2026-11-19 diff --git a/pkg/ingester/client/client.go b/pkg/ingester/client/client.go index 0604b0de7f7..f522a224a87 100644 --- a/pkg/ingester/client/client.go +++ b/pkg/ingester/client/client.go @@ -168,6 +168,11 @@ func MakeIngesterClient(addr string, cfg Config, useStreamConnection bool) (Heal streamCtx, streamCancel := context.WithCancel(context.Background()) err = c.Run(make(chan *streamWriteJob, INGESTER_CLIENT_STREAM_WORKER_COUNT), streamCtx, streamCancel) if err != nil { + // The client is discarded, so nothing will ever call Close() on it. Undo what + // has already been set up: cancelling streamCtx stops the job goroutines of the + // workers that did start, and closing conn stops its reconnect loop. + streamCancel() + _ = conn.Close() return nil, err } } @@ -210,7 +215,9 @@ func (c *closableHealthAndIngesterClient) Run(streamPushChan chan *streamWriteJo c.streamCtx = streamCtx c.streamCancel = streamCancel - var workerErr error + // All the workers below run concurrently, so the error they report has to be + // stored through something that is safe for concurrent writes. + var workerErr atomic.Error var wg sync.WaitGroup // Sanitize addr: colons (from host:port) are not allowed in tenant IDs. sanitizedAddr := strings.ReplaceAll(c.addr, ":", "-") @@ -220,12 +227,12 @@ func (c *closableHealthAndIngesterClient) Run(streamPushChan chan *streamWriteJo workerCtx := user.InjectOrgID(streamCtx, workerName) err := c.worker(workerCtx) if err != nil { - workerErr = err + workerErr.Store(err) } }) } wg.Wait() - return workerErr + return workerErr.Load() } func (c *closableHealthAndIngesterClient) worker(ctx context.Context) error { diff --git a/pkg/ingester/client/client_test.go b/pkg/ingester/client/client_test.go index 65b46d6ca24..7ca01b68a52 100644 --- a/pkg/ingester/client/client_test.go +++ b/pkg/ingester/client/client_test.go @@ -3,8 +3,11 @@ package client import ( "context" "fmt" + "net" "net/http/httptest" + "runtime" "strconv" + "strings" "testing" "time" @@ -17,6 +20,7 @@ import ( "github.com/cortexproject/cortex/pkg/cortexpb" "github.com/cortexproject/cortex/pkg/util" + "github.com/cortexproject/cortex/pkg/util/flagext" ) // TestMarshall is useful to try out various optimisation on the unmarshalling code. @@ -393,3 +397,53 @@ func TestClosableHealthAndIngesterClient_ShouldNotPanicWhenClose(t *testing.T) { time.Sleep(100 * time.Millisecond) } + +// grpcGoroutines counts the running goroutines that have a gRPC frame on their stack. +// A ClientConn that is still open keeps at least its reconnect goroutine around, so +// this is enough to tell a closed connection from a leaked one. +func grpcGoroutines() int { + buf := make([]byte, 1<<20) + for { + n := runtime.Stack(buf, true) + if n < len(buf) { + buf = buf[:n] + break + } + buf = make([]byte, 2*len(buf)) + } + + count := 0 + for _, stack := range strings.Split(string(buf), "\n\n") { + if strings.Contains(stack, "google.golang.org/grpc") { + count++ + } + } + return count +} + +// TestMakeIngesterClient_StreamSetupFailureClosesConnection covers the stream-push +// factory used by the distributor and the querier: when the push streams cannot be +// opened, MakeIngesterClient returns an error and the client is discarded, so nothing +// will ever call Close() on it and it has to clean up after itself. +func TestMakeIngesterClient_StreamSetupFailureClosesConnection(t *testing.T) { + // Reserve a port and release it, so grpc.NewClient still succeeds (it connects + // lazily) while every PushStream worker fails to establish a transport. + l, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + addr := l.Addr().String() + require.NoError(t, l.Close()) + + var cfg Config + flagext.DefaultValues(&cfg) + + baseline := grpcGoroutines() + + c, err := MakeIngesterClient(addr, cfg, true) + require.Error(t, err, "opening the push streams should fail against an address that refuses connections") + require.Nil(t, c) + + require.Eventually(t, func() bool { + return grpcGoroutines() <= baseline + }, 30*time.Second, 50*time.Millisecond, + "gRPC goroutines stayed above the %d at the start of the test, so the connection of the discarded client was left open", baseline) +}