Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(clickhouse): retry transient connection drops on connect (#64650)

Tom Owers1d7e250261bd
diff --git a/posthog/temporal/data_imports/sources/clickhouse/clickhouse.py b/posthog/temporal/data_imports/sources/clickhouse/clickhouse.py
index be885760107b..8cb14021b44a 100644
--- a/posthog/temporal/data_imports/sources/clickhouse/clickhouse.py
+++ b/posthog/temporal/data_imports/sources/clickhouse/clickhouse.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import re
import ssl
import math
+import time
import collections
from collections.abc import Callable, Iterator
from contextlib import _GeneratorContextManager
@@ -73,6 +74,27 @@ def _qualified_table(database: str, table_name: str) -> str:
return f"{_quote_identifier(database)}.{_quote_identifier(table_name)}"
+# Number of times we re-open the client before giving up on a transient drop during connect.
+_MAX_CONNECT_ATTEMPTS = 3
+
+# Substrings of a connect-time failure that denote the connection being dropped before/during the
+# TLS read (ClickHouse Cloud cold-resume hanging up the first request, a proxy/LB idle cull, a
+# network blip) rather than a deterministic config error. A fresh attempt recovers. The TLS config
+# failures we never retry (`certificate verify failed`, `SSL: WRONG_VERSION_NUMBER`) don't contain
+# any of these, so the allowlist can't catch them.
+_TRANSIENT_CONNECT_DROP_SUBSTRINGS = (
+ # OpenSSL 3.x and 1.x wordings for the peer closing the socket without a clean TLS close_notify.
+ "UNEXPECTED_EOF_WHILE_READING",
+ "EOF occurred in violation of protocol",
+ "Connection reset by peer",
+ "Connection aborted",
+)
+
+
+def _is_transient_connect_drop(error_message: str) -> bool:
+ return any(substring in error_message for substring in _TRANSIENT_CONNECT_DROP_SUBSTRINGS)
+
+
def _get_client(
*,
host: str,
@@ -92,28 +114,41 @@ def _get_client(
reader that we use to read very large tables without buffering them in
memory.
"""
- try:
- return get_client(
- host=host,
- port=port,
- database=database,
- username=user,
- # clickhouse-connect expects str; passwordless auth is empty string.
- password=password or "",
- secure=secure,
- verify=verify,
- connect_timeout=CONNECT_TIMEOUT_SECONDS,
- send_receive_timeout=query_timeout,
- query_limit=0, # we manage limits ourselves
- settings=settings or {},
- compress=True,
- )
- except (ClickHouseError, OSError, ssl.SSLError) as e:
- # OSError covers socket.gaierror, ConnectionRefusedError, TimeoutError,
- # and httpx-raised network errors that subclass OSError. ssl.SSLError
- # covers TLS handshake failures that happen before ClickHouse sees
- # the request.
- raise ClickHouseConnectionError(str(e)) from e
+ attempt = 0
+ while True:
+ try:
+ return get_client(
+ host=host,
+ port=port,
+ database=database,
+ username=user,
+ # clickhouse-connect expects str; passwordless auth is empty string.
+ password=password or "",
+ secure=secure,
+ verify=verify,
+ connect_timeout=CONNECT_TIMEOUT_SECONDS,
+ send_receive_timeout=query_timeout,
+ query_limit=0, # we manage limits ourselves
+ settings=settings or {},
+ compress=True,
+ )
+ except (ClickHouseError, OSError, ssl.SSLError) as e:
+ # OSError covers socket.gaierror, ConnectionRefusedError, TimeoutError,
+ # and httpx-raised network errors that subclass OSError. ssl.SSLError
+ # covers TLS handshake failures that happen before ClickHouse sees
+ # the request.
+ attempt += 1
+ message = str(e)
+ if attempt < _MAX_CONNECT_ATTEMPTS and _is_transient_connect_drop(message):
+ structlog.get_logger().warning(
+ "Transient ClickHouse connection drop during connect; retrying",
+ attempt=attempt,
+ max_attempts=_MAX_CONNECT_ATTEMPTS,
+ exc_info=e,
+ )
+ time.sleep(attempt)
+ continue
+ raise ClickHouseConnectionError(message) from e
def _strip_type_modifiers(type_name: str) -> tuple[str, bool]:
diff --git a/posthog/temporal/data_imports/sources/clickhouse/test_clickhouse.py b/posthog/temporal/data_imports/sources/clickhouse/test_clickhouse.py
index cd0af949a01b..23c8c6262405 100644
--- a/posthog/temporal/data_imports/sources/clickhouse/test_clickhouse.py
+++ b/posthog/temporal/data_imports/sources/clickhouse/test_clickhouse.py
@@ -6,12 +6,17 @@ from unittest.mock import MagicMock, patch
import pyarrow as pa
from clickhouse_connect.driver.exceptions import ClickHouseError
+from posthog.temporal.data_imports.sources.clickhouse import clickhouse as ch_module
from posthog.temporal.data_imports.sources.clickhouse.clickhouse import (
+ _MAX_CONNECT_ATTEMPTS,
YIELD_TARGET_ROWS,
ClickHouseColumn,
+ ClickHouseConnectionError,
_build_query,
+ _get_client,
_get_incremental_row_count,
_has_duplicate_primary_keys,
+ _is_transient_connect_drop,
_parse_mv_target,
_quote_identifier,
_strip_type_modifiers,
@@ -559,6 +564,75 @@ class TestClickHouseSourceNonRetryableErrors:
assert not is_non_retryable, f"Transient error should be retryable: {error_msg}"
+class TestIsTransientConnectDrop:
+ @pytest.mark.parametrize(
+ "message",
+ [
+ # The exact wrapped message that reached error tracking from ClickHouse Cloud.
+ "Error HTTPSConnectionPool(host='h', port=8443): Max retries exceeded with url: /? "
+ "(Caused by SSLError(SSLEOFError(8, '[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred "
+ "in violation of protocol (_ssl.c:1032)'))) executing HTTP request attempt 1",
+ "EOF occurred in violation of protocol",
+ "Connection reset by peer",
+ "('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))",
+ ],
+ )
+ def test_matches_transient_drops(self, message):
+ assert _is_transient_connect_drop(message)
+
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "certificate verify failed",
+ "[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:2657)",
+ "Code: 516. DB::Exception: Authentication failed",
+ "HTTPDriver for https://host:8443 returned response code 404",
+ ],
+ )
+ def test_does_not_match_deterministic_failures(self, message):
+ assert not _is_transient_connect_drop(message)
+
+
+class TestGetClientTransientRetry:
+ """`_get_client` retries a transient connection drop during connect in-process."""
+
+ def _connect(self):
+ return _get_client(
+ host="h", port=8443, database="default", user="default", password=None, secure=True, verify=True
+ )
+
+ def test_retries_transient_drop_then_succeeds(self):
+ client = MagicMock()
+ ssl_eof = ClickHouseError("[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol")
+ with (
+ patch.object(ch_module.time, "sleep"),
+ patch.object(ch_module, "get_client", side_effect=[ssl_eof, client]) as mock_get_client,
+ ):
+ assert self._connect() is client
+ assert mock_get_client.call_count == 2
+
+ def test_gives_up_after_max_attempts(self):
+ ssl_eof = ClickHouseError("[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol")
+ with (
+ patch.object(ch_module.time, "sleep"),
+ patch.object(ch_module, "get_client", side_effect=ssl_eof) as mock_get_client,
+ ):
+ with pytest.raises(ClickHouseConnectionError):
+ self._connect()
+ assert mock_get_client.call_count == _MAX_CONNECT_ATTEMPTS
+
+ def test_does_not_retry_deterministic_failure(self):
+ cert_error = ClickHouseError("certificate verify failed")
+ with (
+ patch.object(ch_module.time, "sleep") as mock_sleep,
+ patch.object(ch_module, "get_client", side_effect=cert_error) as mock_get_client,
+ ):
+ with pytest.raises(ClickHouseConnectionError):
+ self._connect()
+ assert mock_get_client.call_count == 1
+ mock_sleep.assert_not_called()
+
+
class TestTranslateError:
def test_matches_substring_inside_long_error(self):
msg = "Code: 516. DB::Exception: Authentication failed for user 'default'"