: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(clickhouse): tolerate readonly source profiles rejecting settings (#71741)
Tom Owersb582bf2a5d79
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.pyindex 47c9a23c2109..80843482b08f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py@@ -13,7 +13,7 @@ import pyarrow as paimport structlogfrom clickhouse_connect import get_clientfrom clickhouse_connect.driver.client import Client as ClickHouseClient-from clickhouse_connect.driver.exceptions import ClickHouseError+from clickhouse_connect.driver.exceptions import ClickHouseError, ProgrammingErrorfrom dlt.common.normalizers.naming.snake_case import NamingConventionfrom structlog.types import FilteringBoundLogger@@ -143,6 +143,28 @@ def _is_retryable_connect_error(error_message: str) -> bool:return _is_transient_connect_drop(error_message) or _TRANSIENT_RATE_LIMIT_SUBSTRING in error_message+def _apply_session_settings(client: ClickHouseClient, settings: dict[str, Any]) -> None:+ """Apply session settings, tolerating a server that reports one as readonly.++ Our settings are performance and Arrow-output tuning hints. A readonly user+ profile (common on managed ClickHouse) reports every setting as readonly, and+ clickhouse-connect refuses to send those — raising ProgrammingError ("Setting+ <x> is unknown or readonly"). Passing them at client construction turns that+ into a fatal connect error that fails the whole sync. Applying them one by one+ lets us keep the settings the server accepts and fall back to the server+ default for the rest.+ """+ for key, value in settings.items():+ try:+ client.set_client_setting(key, value)+ except ProgrammingError as e:+ structlog.get_logger().warning(+ "ClickHouse rejected session setting; falling back to server default",+ setting=key,+ exc_info=e,+ )++def _get_client(*,host: str,@@ -165,7 +187,7 @@ def _get_client(attempt = 0while True:try:- return get_client(+ client = get_client(host=host,port=port,database=database,@@ -177,7 +199,6 @@ def _get_client(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:@@ -198,6 +219,12 @@ def _get_client(continueraise ClickHouseConnectionError(message) from e+ # Apply tuning settings after connect, not at construction, so a readonly+ # source profile that rejects one degrades to the server default instead+ # of failing the whole connection.+ _apply_session_settings(client, settings or {})+ return client+def _strip_type_modifiers(type_name: str) -> tuple[str, bool]:"""Strip Nullable(...) and LowCardinality(...) wrappers.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.pyindex d31d6edd6531..4f4f6c56fd6a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py@@ -5,7 +5,7 @@ from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchimport pyarrow as pa-from clickhouse_connect.driver.exceptions import ClickHouseError, OperationalError+from clickhouse_connect.driver.exceptions import ClickHouseError, OperationalError, ProgrammingErrorfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -778,6 +778,46 @@ class TestGetClientTransientRetry:mock_sleep.assert_not_called()+class TestGetClientSessionSettings:+ """`_get_client` applies tuning settings after connect, tolerating a+ readonly source profile that rejects them instead of failing the sync."""++ def _connect(self, settings):+ return _get_client(+ host="h",+ port=8443,+ database="default",+ user="default",+ password=None,+ secure=True,+ verify=True,+ settings=settings,+ )++ def test_readonly_setting_does_not_fail_connection(self):+ client = MagicMock()++ def set_setting(key, _value):+ if key == "max_block_size":+ raise ProgrammingError("Setting max_block_size is unknown or readonly")++ client.set_client_setting.side_effect = set_setting+ with patch.object(ch_module, "get_client", return_value=client):+ result = self._connect({"max_block_size": 20000, "optimize_read_in_order": 1})++ assert result is client+ # The rejected setting is skipped; the accepted one is still applied.+ client.set_client_setting.assert_any_call("optimize_read_in_order", 1)++ def test_settings_applied_after_connect_not_at_construction(self):+ client = MagicMock()+ with patch.object(ch_module, "get_client", return_value=client) as mock_get_client:+ self._connect({"max_block_size": 20000})++ assert "settings" not in mock_get_client.call_args.kwargs+ client.set_client_setting.assert_called_once_with("max_block_size", 20000)++class TestTranslateError:def test_matches_substring_inside_long_error(self):msg = "Code: 516. DB::Exception: Authentication failed for user 'default'"