: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): retry data query when server caps max_execution_time below ours (#114787)
Tom Owersc012c8d64cb3
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 bbb12f56dcbe..b68e35d86e98 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@@ -1532,6 +1532,21 @@ def _is_query_limit_exceeded(message: str) -> bool:return any(substring in message for substring in _QUERY_LIMIT_EXCEEDED_SUBSTRINGS)+# SETTING_CONSTRAINT_VIOLATION (code 452) — a settings profile caps `max_execution_time` below the+# value `_query_settings` requests (ClickHouse Cloud plans commonly set this). The cap isn't visible+# at connect time: `_apply_session_settings` only catches settings the server reports as+# unconditionally readonly, not ones that are writable but range-constrained. So instead of the+# server just enforcing its own lower value, it rejects the first data query outright. The error+# names its own ceiling, so we retry once with that value — still the safety net the setting exists+# for, just shorter than we asked for.+_MAX_EXECUTION_TIME_CONSTRAINT_RE = re.compile(r"Setting max_execution_time shouldn't be greater than (\d+)")+++def _max_execution_time_ceiling(message: str) -> int | None:+ match = _MAX_EXECUTION_TIME_CONSTRAINT_RE.search(message)+ return int(match.group(1)) if match else None++_TIMESTAMP_UNIT_DIGITS: dict[str, int] = {"s": 0, "ms": 3, "us": 6, "ns": 9}@@ -1777,6 +1792,9 @@ def clickhouse_source("""page_rows: int | None = Nonelower: list[str] | None = None+ # Set once a capped retry has fired, so a host that keeps rejecting (a+ # misconfigured or adversarial endpoint) can't spin this loop forever.+ retried_max_execution_time = Falsewhile True:read_any = Falsetry:@@ -1818,7 +1836,20 @@ def clickhouse_source(read_any = read_any or batch.num_rows > 0yield batchexcept ClickHouseError as e:- if read_any or page_key is None or not _is_query_limit_exceeded(str(e)):+ message = str(e)+ if (+ not read_any+ and not retried_max_execution_time+ and (ceiling := _max_execution_time_ceiling(message)) is not None+ ):+ retried_max_execution_time = True+ stream_client.set_client_setting("max_execution_time", ceiling)+ logger.warning(+ f"ClickHouse capped max_execution_time at {ceiling}s for this source; "+ "retrying with that limit"+ )+ continue+ if read_any or page_key is None or not _is_query_limit_exceeded(message):raiseif page_rows is not None and page_rows // 2 < PAGED_READ_MIN_ROWS:raisediff --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 bb62651db9ad..0d2e88294234 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@@ -947,6 +947,36 @@ class TestGetRowsBatching:stream_client.query_column_block_stream.assert_not_called()+ def test_retries_with_the_servers_max_execution_time_ceiling(self):+ constraint_error = ClickHouseError(+ "Received ClickHouse exception, code: 452, server response: Code: 452. DB::Exception: "+ "Setting max_execution_time shouldn't be greater than 600. (SETTING_CONSTRAINT_VIOLATION)"+ )+ stream_client = MagicMock()+ stream_client.query_arrow_stream.side_effect = [constraint_error, self._stream_context([self._block(5)])]++ yielded = self._run_get_rows([], stream_client=stream_client)++ assert len(yielded) == 1+ assert yielded[0].num_rows == 5+ stream_client.set_client_setting.assert_called_once_with("max_execution_time", 600)+ assert stream_client.query_arrow_stream.call_count == 2++ def test_gives_up_after_one_max_execution_time_retry(self):+ # A host that keeps rejecting every value we set must not spin the sync forever.+ constraint_error = ClickHouseError(+ "Received ClickHouse exception, code: 452, server response: Code: 452. DB::Exception: "+ "Setting max_execution_time shouldn't be greater than 600. (SETTING_CONSTRAINT_VIOLATION)"+ )+ stream_client = MagicMock()+ stream_client.query_arrow_stream.side_effect = [constraint_error, constraint_error]++ with pytest.raises(ClickHouseError, match="SETTING_CONSTRAINT_VIOLATION"):+ self._run_get_rows([], stream_client=stream_client)++ stream_client.set_client_setting.assert_called_once_with("max_execution_time", 600)+ assert stream_client.query_arrow_stream.call_count == 2+def test_limit_error_after_rows_were_read_does_not_fall_back_to_pages(self):def blocks_then_limit_error():yield self._block(10)