Skip to content

Commit 029834f

Browse files
arpitjain099claude
andauthored
Ingester client: release the gRPC connection when stream setup fails (#7969)
* Ingester client: release the gRPC connection when stream setup fails MakeIngesterClient returned the error from Run without closing the connection or cancelling the stream context, so a discarded client left a connection reconnecting to the ingester address for the lifetime of the process. Nothing could reach it, because ring/client.Pool only records a client once the factory has succeeded. Run also stored the workers' error in a plain variable written by all of them concurrently, which the race detector reports. Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Arpit Jain <arpitjain099@gmail.com> * Shorten the changelog entry and range over SplitSeq in the client test Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Arpit Jain <arpitjain099@gmail.com> --------- Signed-off-by: Arpit Jain <arpitjain099@gmail.com> Co-authored-by: Claude <noreply@anthropic.com>
1 parent e12c48f commit 029834f

3 files changed

Lines changed: 65 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
* [BUGFIX] Ring: Fix `DoBatch` counting a key more than once when more replicas than the quorum succeed, which in rare cases could hide a write error from a key that did not reach quorum. A distributor push now always waits until every series reaches quorum, so it returns the error of a series that misses quorum, and takes as long as its slowest series to reach quorum. #7975
4444
* [BUGFIX] Compactor: Stop downloading the parquet files and the `parquet-converter-mark.json` and `parquet-no-convert-mark.json` markers written by the parquet converter under a block's prefix. Compaction never reads them, so they only used local disk and bandwidth until the compaction job ended. #7972
4545
* [BUGFIX] Ring: Fix shuffle-sharding subrings treating instances with a stale heartbeat as healthy when using the DynamoDB KV store. #7976
46+
* [BUGFIX] Ingester Client: Fix a gRPC connection leak when `-distributor.use-stream-push` is enabled and the push streams to an ingester cannot be opened. #7969
4647

4748
## 1.22.0 2026-11-19
4849

‎pkg/ingester/client/client.go‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,11 @@ func MakeIngesterClient(addr string, cfg Config, useStreamConnection bool) (Heal
168168
streamCtx, streamCancel := context.WithCancel(context.Background())
169169
err = c.Run(make(chan *streamWriteJob, INGESTER_CLIENT_STREAM_WORKER_COUNT), streamCtx, streamCancel)
170170
if err != nil {
171+
// The client is discarded, so nothing will ever call Close() on it. Undo what
172+
// has already been set up: cancelling streamCtx stops the job goroutines of the
173+
// workers that did start, and closing conn stops its reconnect loop.
174+
streamCancel()
175+
_ = conn.Close()
171176
return nil, err
172177
}
173178
}
@@ -210,7 +215,9 @@ func (c *closableHealthAndIngesterClient) Run(streamPushChan chan *streamWriteJo
210215
c.streamCtx = streamCtx
211216
c.streamCancel = streamCancel
212217

213-
var workerErr error
218+
// All the workers below run concurrently, so the error they report has to be
219+
// stored through something that is safe for concurrent writes.
220+
var workerErr atomic.Error
214221
var wg sync.WaitGroup
215222
// Sanitize addr: colons (from host:port) are not allowed in tenant IDs.
216223
sanitizedAddr := strings.ReplaceAll(c.addr, ":", "-")
@@ -220,12 +227,12 @@ func (c *closableHealthAndIngesterClient) Run(streamPushChan chan *streamWriteJo
220227
workerCtx := user.InjectOrgID(streamCtx, workerName)
221228
err := c.worker(workerCtx)
222229
if err != nil {
223-
workerErr = err
230+
workerErr.Store(err)
224231
}
225232
})
226233
}
227234
wg.Wait()
228-
return workerErr
235+
return workerErr.Load()
229236
}
230237

231238
func (c *closableHealthAndIngesterClient) worker(ctx context.Context) error {

‎pkg/ingester/client/client_test.go‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@ package client
33
import (
44
"context"
55
"fmt"
6+
"net"
67
"net/http/httptest"
8+
"runtime"
79
"strconv"
10+
"strings"
811
"testing"
912
"time"
1013

@@ -17,6 +20,7 @@ import (
1720

1821
"github.com/cortexproject/cortex/pkg/cortexpb"
1922
"github.com/cortexproject/cortex/pkg/util"
23+
"github.com/cortexproject/cortex/pkg/util/flagext"
2024
)
2125

2226
// TestMarshall is useful to try out various optimisation on the unmarshalling code.
@@ -393,3 +397,53 @@ func TestClosableHealthAndIngesterClient_ShouldNotPanicWhenClose(t *testing.T) {
393397

394398
time.Sleep(100 * time.Millisecond)
395399
}
400+
401+
// grpcGoroutines counts the running goroutines that have a gRPC frame on their stack.
402+
// A ClientConn that is still open keeps at least its reconnect goroutine around, so
403+
// this is enough to tell a closed connection from a leaked one.
404+
func grpcGoroutines() int {
405+
buf := make([]byte, 1<<20)
406+
for {
407+
n := runtime.Stack(buf, true)
408+
if n < len(buf) {
409+
buf = buf[:n]
410+
break
411+
}
412+
buf = make([]byte, 2*len(buf))
413+
}
414+
415+
count := 0
416+
for stack := range strings.SplitSeq(string(buf), "\n\n") {
417+
if strings.Contains(stack, "google.golang.org/grpc") {
418+
count++
419+
}
420+
}
421+
return count
422+
}
423+
424+
// TestMakeIngesterClient_StreamSetupFailureClosesConnection covers the stream-push
425+
// factory used by the distributor and the querier: when the push streams cannot be
426+
// opened, MakeIngesterClient returns an error and the client is discarded, so nothing
427+
// will ever call Close() on it and it has to clean up after itself.
428+
func TestMakeIngesterClient_StreamSetupFailureClosesConnection(t *testing.T) {
429+
// Reserve a port and release it, so grpc.NewClient still succeeds (it connects
430+
// lazily) while every PushStream worker fails to establish a transport.
431+
l, err := net.Listen("tcp", "127.0.0.1:0")
432+
require.NoError(t, err)
433+
addr := l.Addr().String()
434+
require.NoError(t, l.Close())
435+
436+
var cfg Config
437+
flagext.DefaultValues(&cfg)
438+
439+
baseline := grpcGoroutines()
440+
441+
c, err := MakeIngesterClient(addr, cfg, true)
442+
require.Error(t, err, "opening the push streams should fail against an address that refuses connections")
443+
require.Nil(t, c)
444+
445+
require.Eventually(t, func() bool {
446+
return grpcGoroutines() <= baseline
447+
}, 30*time.Second, 50*time.Millisecond,
448+
"gRPC goroutines stayed above the %d at the start of the test, so the connection of the discarded client was left open", baseline)
449+
}

0 commit comments

Comments
 (0)