From 945426127c20a85f1920f9f62501181c6df3cb89 Mon Sep 17 00:00:00 2001 From: Dmitrii Tunikov Date: Fri, 20 Nov 2026 10:49:36 +0100 Subject: [PATCH 1/6] Retry ClickHouse ping with backoff on connect Transient connection resets during the initial ping fail PeerCreate for ClickPipes multiple times a day. Retry transient errors up to 5 times, but return non-retryable server exceptions (e.g. auth failures) immediately. Co-Authored-By: Claude Opus 5.5 --- flow/connectors/clickhouse/clickhouse.go | 2 +- flow/pkg/clickhouse/query_retry.go | 25 +++++++++++++++++ flow/pkg/clickhouse/query_retry_test.go | 34 ++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) diff --git a/flow/connectors/clickhouse/clickhouse.go b/flow/connectors/clickhouse/clickhouse.go index 60cadec5d..6d2e952bc 100644 --- a/flow/connectors/clickhouse/clickhouse.go +++ b/flow/connectors/clickhouse/clickhouse.go @@ -304,7 +304,7 @@ func Connect(ctx context.Context, env map[string]string, config *protos.Clickhou return nil, fmt.Errorf("failed to connect to ClickHouse peer: %w", err) } - if err := conn.Ping(ctx); err != nil { + if err := peerdb_clickhouse.Ping(ctx, internal.LoggerFromCtx(ctx), conn); err != nil { conn.Close() return nil, fmt.Errorf("failed to ping to ClickHouse peer: %w", err) } diff --git a/flow/pkg/clickhouse/query_retry.go b/flow/pkg/clickhouse/query_retry.go index 06d96f41c..279430123 100644 --- a/flow/pkg/clickhouse/query_retry.go +++ b/flow/pkg/clickhouse/query_retry.go @@ -148,3 +148,28 @@ func QueryRow(ctx context.Context, logger log.Logger, } return row } + +// Ping retries transient failures (network errors, retryable exceptions) with backoff. +// Non-retryable server exceptions such as auth failures are returned immediately. +func Ping(ctx context.Context, logger log.Logger, conn clickhouse.Conn) error { + const attempts = 5 + var err error + for i := range attempts { + err = conn.Ping(ctx) + if err == nil || ctx.Err() != nil { + return err + } + if ex, ok := errors.AsType[*clickhouse.Exception](err); ok && !isRetryableException(ex) { + return err + } + logger.Info("[ping] retryable error", slog.Any("error", err), slog.Int64("retry", int64(i))) + if i < attempts-1 { + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(time.Second * time.Duration(i*5+1)): + } + } + } + return err +} diff --git a/flow/pkg/clickhouse/query_retry_test.go b/flow/pkg/clickhouse/query_retry_test.go index 269124e16..5a6e34b9b 100644 --- a/flow/pkg/clickhouse/query_retry_test.go +++ b/flow/pkg/clickhouse/query_retry_test.go @@ -3,6 +3,9 @@ package clickhouse import ( "context" "errors" + "net" + "os" + "syscall" "testing" "time" @@ -135,3 +138,34 @@ func TestExecErrorTraits(t *testing.T) { }) } } + +// pingConn fails Ping with errs in order, then succeeds. +type pingConn struct { + driver.Conn + errs []error + calls int +} + +func (c *pingConn) Ping(context.Context) error { + c.calls++ + if c.calls <= len(c.errs) { + return c.errs[c.calls-1] + } + return nil +} + +func TestPingRetriesConnectionReset(t *testing.T) { + connReset := &net.OpError{Op: "read", Net: "tcp", Err: os.NewSyscallError("read", syscall.ECONNRESET)} + conn := &pingConn{errs: []error{connReset}} + + require.NoError(t, Ping(t.Context(), nopLogger{}, conn)) + require.Equal(t, 2, conn.calls) +} + +func TestPingDoesNotRetryAuthFailure(t *testing.T) { + authErr := &clickhouse.Exception{Code: int32(chproto.ErrAuthenticationFailed)} + conn := &pingConn{errs: []error{authErr}} + + require.ErrorIs(t, Ping(t.Context(), nopLogger{}, conn), authErr) + require.Equal(t, 1, conn.calls) +} From 1abf7b2bb7568879d6427c7c726b173a6b9d0576 Mon Sep 17 00:00:00 2001 From: Dmitrii Tunikov Date: Fri, 20 Nov 2026 10:50:59 +0100 Subject: [PATCH 2/6] Log ClickHouse ping retries at warn level Co-Authored-By: Claude Opus 5.5 --- flow/pkg/clickhouse/query_retry.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flow/pkg/clickhouse/query_retry.go b/flow/pkg/clickhouse/query_retry.go index 279430123..7fad712ce 100644 --- a/flow/pkg/clickhouse/query_retry.go +++ b/flow/pkg/clickhouse/query_retry.go @@ -162,7 +162,7 @@ func Ping(ctx context.Context, logger log.Logger, conn clickhouse.Conn) error { if ex, ok := errors.AsType[*clickhouse.Exception](err); ok && !isRetryableException(ex) { return err } - logger.Info("[ping] retryable error", slog.Any("error", err), slog.Int64("retry", int64(i))) + logger.Warn("[ping] retryable error", slog.Any("error", err), slog.Int64("retry", int64(i))) if i < attempts-1 { select { case <-ctx.Done(): From 766be25178085472af31f0cc85ffbb077104b91c Mon Sep 17 00:00:00 2001 From: Dmitrii Tunikov Date: Fri, 20 Nov 2026 10:54:34 +0100 Subject: [PATCH 3/6] Share retry loop across ClickHouse Exec/Query/QueryRow/Ping Co-Authored-By: Claude Opus 5.5 --- flow/pkg/clickhouse/query_retry.go | 99 ++++++++++++------------------ 1 file changed, 38 insertions(+), 61 deletions(-) diff --git a/flow/pkg/clickhouse/query_retry.go b/flow/pkg/clickhouse/query_retry.go index 7fad712ce..d27bfa62d 100644 --- a/flow/pkg/clickhouse/query_retry.go +++ b/flow/pkg/clickhouse/query_retry.go @@ -73,24 +73,37 @@ func isRetryableException(err error) bool { return errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, syscall.ECONNRESET) } -func Exec(ctx context.Context, logger log.Logger, - conn clickhouse.Conn, query string, args ...any, -) error { +// withRetry runs fn up to 5 times with backoff while shouldRetry returns true for its error. +// On context cancellation during backoff it returns the last result along with ctx.Err(). +func withRetry[T any](ctx context.Context, logger log.Logger, op string, + shouldRetry func(error) bool, fn func() (T, error), +) (T, error) { + const attempts = 5 + var res T var err error - for i := range 5 { - err = conn.Exec(ctx, query, args...) - if !isRetryableException(err) { - break + for i := range attempts { + res, err = fn() + if err == nil || !shouldRetry(err) { + return res, err } - logger.Info("[exec] retryable error", slog.Any("error", err), slog.Int64("retry", int64(i))) - if i < 4 { + logger.Warn("["+op+"] retryable error", slog.Any("error", err), slog.Int64("retry", int64(i))) + if i < attempts-1 { select { case <-ctx.Done(): - return ctx.Err() + return res, ctx.Err() case <-time.After(time.Second * time.Duration(i*5+1)): } } } + return res, err +} + +func Exec(ctx context.Context, logger log.Logger, + conn clickhouse.Conn, query string, args ...any, +) error { + _, err := withRetry(ctx, logger, "exec", isRetryableException, func() (struct{}, error) { + return struct{}{}, conn.Exec(ctx, query, args...) + }) if ex, ok := errors.AsType[*clickhouse.Exception](err); ok { traits := ExecTraits{ View: strings.Contains(ex.Message, "while pushing to view"), @@ -108,68 +121,32 @@ func Exec(ctx context.Context, logger log.Logger, func Query(ctx context.Context, logger log.Logger, conn clickhouse.Conn, query string, args ...any, ) (driver.Rows, error) { - var rows driver.Rows - var err error - for i := range 5 { - rows, err = conn.Query(ctx, query, args...) - if !isRetryableException(err) { - break - } - logger.Info("[query] retryable error", slog.Any("error", err), slog.Int64("retry", int64(i))) - if i < 4 { - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-time.After(time.Second * time.Duration(i*5+1)): - } - } - } - return rows, err + return withRetry(ctx, logger, "query", isRetryableException, func() (driver.Rows, error) { + return conn.Query(ctx, query, args...) + }) } func QueryRow(ctx context.Context, logger log.Logger, conn clickhouse.Conn, query string, args ...any, ) driver.Row { - var row driver.Row - for i := range 5 { - row = conn.QueryRow(ctx, query, args...) - err := row.Err() - if !isRetryableException(err) { - break - } - logger.Info("[queryRow] retryable error", slog.Any("error", err), slog.Int64("retry", int64(i))) - if i < 4 { - select { - case <-ctx.Done(): - return row - case <-time.After(time.Second * time.Duration(i*5+1)): - } - } - } + row, _ := withRetry(ctx, logger, "queryRow", isRetryableException, func() (driver.Row, error) { + row := conn.QueryRow(ctx, query, args...) + return row, row.Err() + }) return row } // Ping retries transient failures (network errors, retryable exceptions) with backoff. // Non-retryable server exceptions such as auth failures are returned immediately. func Ping(ctx context.Context, logger log.Logger, conn clickhouse.Conn) error { - const attempts = 5 - var err error - for i := range attempts { - err = conn.Ping(ctx) - if err == nil || ctx.Err() != nil { - return err - } - if ex, ok := errors.AsType[*clickhouse.Exception](err); ok && !isRetryableException(ex) { - return err - } - logger.Warn("[ping] retryable error", slog.Any("error", err), slog.Int64("retry", int64(i))) - if i < attempts-1 { - select { - case <-ctx.Done(): - return ctx.Err() - case <-time.After(time.Second * time.Duration(i*5+1)): - } + _, err := withRetry(ctx, logger, "ping", func(err error) bool { + if ctx.Err() != nil { + return false } - } + ex, ok := errors.AsType[*clickhouse.Exception](err) + return !ok || isRetryableException(ex) + }, func() (struct{}, error) { + return struct{}{}, conn.Ping(ctx) + }) return err } From e46e8d5e3690659d7f6008b2eb197eb2a01d2c10 Mon Sep 17 00:00:00 2001 From: Dmitrii Tunikov Date: Fri, 20 Nov 2026 11:00:38 +0100 Subject: [PATCH 4/6] Add retry unit tests for ClickHouse Exec/Query/QueryRow Co-Authored-By: Claude Opus 5.5 --- flow/pkg/clickhouse/query_retry_test.go | 85 +++++++++++++++++++++++-- 1 file changed, 79 insertions(+), 6 deletions(-) diff --git a/flow/pkg/clickhouse/query_retry_test.go b/flow/pkg/clickhouse/query_retry_test.go index 5a6e34b9b..d6f9f463b 100644 --- a/flow/pkg/clickhouse/query_retry_test.go +++ b/flow/pkg/clickhouse/query_retry_test.go @@ -139,14 +139,14 @@ func TestExecErrorTraits(t *testing.T) { } } -// pingConn fails Ping with errs in order, then succeeds. -type pingConn struct { +// scriptedConn fails each call with errs in order, then succeeds. +type scriptedConn struct { driver.Conn errs []error calls int } -func (c *pingConn) Ping(context.Context) error { +func (c *scriptedConn) next() error { c.calls++ if c.calls <= len(c.errs) { return c.errs[c.calls-1] @@ -154,17 +154,90 @@ func (c *pingConn) Ping(context.Context) error { return nil } +func (c *scriptedConn) Ping(context.Context) error { + return c.next() +} + +func (c *scriptedConn) Exec(context.Context, string, ...any) error { + return c.next() +} + +func (c *scriptedConn) Query(context.Context, string, ...any) (driver.Rows, error) { + return nil, c.next() +} + +func (c *scriptedConn) QueryRow(context.Context, string, ...any) driver.Row { + return errRow{err: c.next()} +} + +type errRow struct { + driver.Row + err error +} + +func (r errRow) Err() error { + return r.err +} + +var ( + tooManyPartsErr = &clickhouse.Exception{Code: int32(chproto.ErrTooManyParts)} + authErr = &clickhouse.Exception{Code: int32(chproto.ErrAuthenticationFailed)} +) + +func TestExecRetriesRetryableException(t *testing.T) { + conn := &scriptedConn{errs: []error{tooManyPartsErr}} + + require.NoError(t, Exec(t.Context(), nopLogger{}, conn, "INSERT INTO t VALUES (1)")) + require.Equal(t, 2, conn.calls) +} + +func TestExecDoesNotRetryNonRetryableException(t *testing.T) { + conn := &scriptedConn{errs: []error{authErr}} + + require.ErrorIs(t, Exec(t.Context(), nopLogger{}, conn, "INSERT INTO t VALUES (1)"), authErr) + require.Equal(t, 1, conn.calls) +} + +func TestQueryRetriesRetryableException(t *testing.T) { + conn := &scriptedConn{errs: []error{tooManyPartsErr}} + + _, err := Query(t.Context(), nopLogger{}, conn, "SELECT 1") + require.NoError(t, err) + require.Equal(t, 2, conn.calls) +} + +func TestQueryDoesNotRetryNonRetryableException(t *testing.T) { + conn := &scriptedConn{errs: []error{authErr}} + + _, err := Query(t.Context(), nopLogger{}, conn, "SELECT 1") + require.ErrorIs(t, err, authErr) + require.Equal(t, 1, conn.calls) +} + +func TestQueryRowRetriesRetryableException(t *testing.T) { + conn := &scriptedConn{errs: []error{tooManyPartsErr}} + + require.NoError(t, QueryRow(t.Context(), nopLogger{}, conn, "SELECT 1").Err()) + require.Equal(t, 2, conn.calls) +} + +func TestQueryRowDoesNotRetryNonRetryableException(t *testing.T) { + conn := &scriptedConn{errs: []error{authErr}} + + require.ErrorIs(t, QueryRow(t.Context(), nopLogger{}, conn, "SELECT 1").Err(), authErr) + require.Equal(t, 1, conn.calls) +} + func TestPingRetriesConnectionReset(t *testing.T) { connReset := &net.OpError{Op: "read", Net: "tcp", Err: os.NewSyscallError("read", syscall.ECONNRESET)} - conn := &pingConn{errs: []error{connReset}} + conn := &scriptedConn{errs: []error{connReset}} require.NoError(t, Ping(t.Context(), nopLogger{}, conn)) require.Equal(t, 2, conn.calls) } func TestPingDoesNotRetryAuthFailure(t *testing.T) { - authErr := &clickhouse.Exception{Code: int32(chproto.ErrAuthenticationFailed)} - conn := &pingConn{errs: []error{authErr}} + conn := &scriptedConn{errs: []error{authErr}} require.ErrorIs(t, Ping(t.Context(), nopLogger{}, conn), authErr) require.Equal(t, 1, conn.calls) From c399c791c226da8c4f4222d7721550a2d1c3c8c7 Mon Sep 17 00:00:00 2001 From: Dmitrii Tunikov Date: Fri, 20 Nov 2026 11:24:04 +0100 Subject: [PATCH 5/6] Rename test sentinel errors for errname lint Co-Authored-By: Claude Opus 5.5 --- flow/pkg/clickhouse/query_retry_test.go | 26 ++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/flow/pkg/clickhouse/query_retry_test.go b/flow/pkg/clickhouse/query_retry_test.go index d6f9f463b..57a9c1e83 100644 --- a/flow/pkg/clickhouse/query_retry_test.go +++ b/flow/pkg/clickhouse/query_retry_test.go @@ -180,26 +180,26 @@ func (r errRow) Err() error { } var ( - tooManyPartsErr = &clickhouse.Exception{Code: int32(chproto.ErrTooManyParts)} - authErr = &clickhouse.Exception{Code: int32(chproto.ErrAuthenticationFailed)} + errTooManyParts = &clickhouse.Exception{Code: int32(chproto.ErrTooManyParts)} + errAuth = &clickhouse.Exception{Code: int32(chproto.ErrAuthenticationFailed)} ) func TestExecRetriesRetryableException(t *testing.T) { - conn := &scriptedConn{errs: []error{tooManyPartsErr}} + conn := &scriptedConn{errs: []error{errTooManyParts}} require.NoError(t, Exec(t.Context(), nopLogger{}, conn, "INSERT INTO t VALUES (1)")) require.Equal(t, 2, conn.calls) } func TestExecDoesNotRetryNonRetryableException(t *testing.T) { - conn := &scriptedConn{errs: []error{authErr}} + conn := &scriptedConn{errs: []error{errAuth}} - require.ErrorIs(t, Exec(t.Context(), nopLogger{}, conn, "INSERT INTO t VALUES (1)"), authErr) + require.ErrorIs(t, Exec(t.Context(), nopLogger{}, conn, "INSERT INTO t VALUES (1)"), errAuth) require.Equal(t, 1, conn.calls) } func TestQueryRetriesRetryableException(t *testing.T) { - conn := &scriptedConn{errs: []error{tooManyPartsErr}} + conn := &scriptedConn{errs: []error{errTooManyParts}} _, err := Query(t.Context(), nopLogger{}, conn, "SELECT 1") require.NoError(t, err) @@ -207,24 +207,24 @@ func TestQueryRetriesRetryableException(t *testing.T) { } func TestQueryDoesNotRetryNonRetryableException(t *testing.T) { - conn := &scriptedConn{errs: []error{authErr}} + conn := &scriptedConn{errs: []error{errAuth}} _, err := Query(t.Context(), nopLogger{}, conn, "SELECT 1") - require.ErrorIs(t, err, authErr) + require.ErrorIs(t, err, errAuth) require.Equal(t, 1, conn.calls) } func TestQueryRowRetriesRetryableException(t *testing.T) { - conn := &scriptedConn{errs: []error{tooManyPartsErr}} + conn := &scriptedConn{errs: []error{errTooManyParts}} require.NoError(t, QueryRow(t.Context(), nopLogger{}, conn, "SELECT 1").Err()) require.Equal(t, 2, conn.calls) } func TestQueryRowDoesNotRetryNonRetryableException(t *testing.T) { - conn := &scriptedConn{errs: []error{authErr}} + conn := &scriptedConn{errs: []error{errAuth}} - require.ErrorIs(t, QueryRow(t.Context(), nopLogger{}, conn, "SELECT 1").Err(), authErr) + require.ErrorIs(t, QueryRow(t.Context(), nopLogger{}, conn, "SELECT 1").Err(), errAuth) require.Equal(t, 1, conn.calls) } @@ -237,8 +237,8 @@ func TestPingRetriesConnectionReset(t *testing.T) { } func TestPingDoesNotRetryAuthFailure(t *testing.T) { - conn := &scriptedConn{errs: []error{authErr}} + conn := &scriptedConn{errs: []error{errAuth}} - require.ErrorIs(t, Ping(t.Context(), nopLogger{}, conn), authErr) + require.ErrorIs(t, Ping(t.Context(), nopLogger{}, conn), errAuth) require.Equal(t, 1, conn.calls) } From 89d6159932787e661f7b3b6e2f3942e445ca2dbf Mon Sep 17 00:00:00 2001 From: Dmitrii Tunikov Date: Mon, 23 Nov 2026 09:09:19 +0100 Subject: [PATCH 6/6] clickhouse: add Ping context cancellation tests, drop withRetry comment Co-Authored-By: Claude Opus 5.5 --- flow/pkg/clickhouse/query_retry.go | 2 -- flow/pkg/clickhouse/query_retry_test.go | 27 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/flow/pkg/clickhouse/query_retry.go b/flow/pkg/clickhouse/query_retry.go index d27bfa62d..90995ff72 100644 --- a/flow/pkg/clickhouse/query_retry.go +++ b/flow/pkg/clickhouse/query_retry.go @@ -73,8 +73,6 @@ func isRetryableException(err error) bool { return errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, syscall.ECONNRESET) } -// withRetry runs fn up to 5 times with backoff while shouldRetry returns true for its error. -// On context cancellation during backoff it returns the last result along with ctx.Err(). func withRetry[T any](ctx context.Context, logger log.Logger, op string, shouldRetry func(error) bool, fn func() (T, error), ) (T, error) { diff --git a/flow/pkg/clickhouse/query_retry_test.go b/flow/pkg/clickhouse/query_retry_test.go index 57a9c1e83..9b2c0b798 100644 --- a/flow/pkg/clickhouse/query_retry_test.go +++ b/flow/pkg/clickhouse/query_retry_test.go @@ -242,3 +242,30 @@ func TestPingDoesNotRetryAuthFailure(t *testing.T) { require.ErrorIs(t, Ping(t.Context(), nopLogger{}, conn), errAuth) require.Equal(t, 1, conn.calls) } + +func TestPingRetryBackoffPreemptedByContextCancel(t *testing.T) { + connReset := &net.OpError{Op: "read", Net: "tcp", Err: os.NewSyscallError("read", syscall.ECONNRESET)} + conn := &scriptedConn{errs: []error{connReset, connReset, connReset, connReset, connReset}} + ctx, cancel := context.WithCancel(t.Context()) + go func() { + time.Sleep(100 * time.Millisecond) + cancel() + }() + + start := time.Now() + err := Ping(ctx, nopLogger{}, conn) + elapsed := time.Since(start) + + require.ErrorIs(t, err, context.Canceled) + require.Less(t, elapsed, time.Second, "cancellation should preempt the retry backoff") + require.Equal(t, 1, conn.calls) +} + +func TestPingDoesNotRetryAfterContextCanceled(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + conn := &scriptedConn{errs: []error{ctx.Err()}} + + require.ErrorIs(t, Ping(ctx, nopLogger{}, conn), context.Canceled) + require.Equal(t, 1, conn.calls) +}