: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(warehouse-sources): probe the merge key on clickhouse incremental syncs (#107863)
posthog[bot]6f027f2c69fb
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 ed35d3e731ca..940c5adf552d 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@@ -36,6 +36,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.erris_transient_egress_proxy_error,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _require_loopback+from products.warehouse_sources.backend.temporal.data_imports.sources.common.primary_keys import (+ resolve_merge_keys,+ should_probe_for_duplicates,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (Column,Table,@@ -1046,8 +1050,9 @@ def get_primary_keys_for_schemas(DUPLICATE_PK_CHECK_ROW_BUDGET = 10_000_000# Settings for the duplicate-PK probe.-# - optimize_aggregation_in_order streams the GROUP BY along the sorting-# key without building a hash table (bounded memory).+# - optimize_aggregation_in_order streams the GROUP BY without a hash table+# when the merge key is a prefix of the sorting key. Any other key is a+# hash aggregation, which max_memory_usage bounds.# - max_rows_to_read + read_overflow_mode='break' cap the scan at# DUPLICATE_PK_CHECK_ROW_BUDGET and *silently stop* instead of throwing.# - max_execution_time and max_memory_usage are belt-and-braces bounds.@@ -1060,18 +1065,19 @@ _DUPLICATE_PK_CHECK_SETTINGS: dict[str, Any] = {}# Substrings of probe errors that are expected environment limits or designed-# fallbacks rather than bugs on our side. In every case we fall back to append-# mode, so capturing them only adds error-tracking noise:+# fallbacks rather than bugs on our side. In every case the probe compared no+# rows, so the key stays unverified and the sync continues. Capturing them only+# adds error-tracking noise:# - "is unknown or readonly": clickhouse-connect validates session settings# client-side and refuses any the server reports as readonly or unknown# ("Setting <x> is unknown or readonly"), routine on managed offerings# (ClickHouse Cloud) and readonly user profiles.# - MEMORY_LIMIT_EXCEEDED / TIMEOUT_EXCEEDED: the bounded probe exhausted one# of its own budgets (`max_memory_usage` / `max_execution_time`).-# `optimize_aggregation_in_order` keeps the GROUP BY streaming, but on-# large/slow (e.g. S3-backed) source tables the scan can still hit these-# caps before `read_overflow_mode='break'` truncates on rows — the probe-# behaving exactly as designed. Some managed servers also enforce a memory+# A merge key that is not a sorting-key prefix needs a hash table, and on+# large/slow (e.g. S3-backed) source tables even a streamed scan can hit+# these caps before `read_overflow_mode='break'` truncates on rows — the+# probe behaving exactly as designed. Some managed servers also enforce a memory# cap below our `max_memory_usage`, surfacing the same way.# - "Read timed out": the probe's `max_execution_time` only bounds server-side# execution, not ClickHouse Cloud's cold-resume wake-up latency or a scan@@ -1096,15 +1102,15 @@ def _has_duplicate_primary_keys(table_name: str,primary_keys: list[str] | None,logger: FilteringBoundLogger,-) -> bool:- """Check whether the sorting key has obvious duplicate combinations.+) -> bool | None:+ """Check whether the merge key has obvious duplicate combinations.- ClickHouse sorting keys are *not* enforced unique. For incremental syncs- we need a unique-ish key to do safe merges into Delta. We probe a+ ClickHouse enforces uniqueness on nothing, so the key an incremental merge+ matches rows on is unproven until this probes it. We probe abounded prefix of the table (DUPLICATE_PK_CHECK_ROW_BUDGET rows) ratherthan scanning the whole thing, because:- 1. A user who chose a non-unique sort key will virtually always show+ 1. A user who chose a non-unique key will virtually always showduplicates inside any reasonably sized prefix.2. A full-table GROUP BY every incremental sync is prohibitivelyexpensive on the tables this source is designed for.@@ -1113,7 +1119,8 @@ def _has_duplicate_primary_keys(Returns:True if duplicates are detected in the probed prefix, or if theprobe failed in an unexpected way. False when the probe completed- within budget without finding duplicates.+ within budget without finding duplicates. None when the probe never+ got to compare any rows, so it proves nothing either way."""if not primary_keys:return False@@ -1125,20 +1132,20 @@ def _has_duplicate_primary_keys(result = client.query(query, settings=_DUPLICATE_PK_CHECK_SETTINGS)return len(result.result_rows) > 0except ClickHouseError as e:- # Any server error is treated as "assume duplicates" — safer to force- # append mode than to merge against a key we couldn't verify. (We don't- # hit max_rows_to_read here because read_overflow_mode='break' turns- # that into a silent truncation.)+ # An exhausted budget or a rejected setting compared no rows, so it says nothing about+ # the key. Reporting it as a duplicate would stop a table that can still merge. (We+ # don't hit max_rows_to_read here because read_overflow_mode='break' turns that into a+ # silent truncation.)+ if _is_expected_probe_failure(str(e)):+ logger.warning(+ f"_has_duplicate_primary_keys: probe did not complete for {database}.{table_name}, "+ f"leaving the key unverified: {e}"+ )+ return Nonelogger.warning(f"_has_duplicate_primary_keys: assuming duplicates exist (probe failed for {database}.{table_name}): {e}")- # Only report genuinely unexpected probe failures. Exhausting the- # probe's own memory/time budget is the designed fallback on large- # source tables, and managed/readonly ClickHouse servers routinely- # reject our tuning settings — expected outcomes the append-mode- # fallback already handles, so capturing them only adds noise.- if not _is_expected_probe_failure(str(e)):- capture_exception(e)+ capture_exception(e)return True@@ -1619,6 +1626,7 @@ def clickhouse_source(incremental_field_type: Optional[IncrementalFieldType] = None,row_filters: Optional[list[ValidatedRowFilter]] = None,enabled_columns: Optional[list[str]] = None,+ stored_primary_keys: Optional[list[str]] = None,bypass_env_proxy: BypassEnvProxy = None,server_hostname: str | None = None,) -> SourceResponse:@@ -1708,11 +1716,18 @@ def clickhouse_source(_get_partition_settings(client, database, table_name, logger) if should_use_incremental_field else None)+ # The merge matches rows on the stored key when one exists (`resolve_primary_keys`),+ # so the probe must check that key and not the sorting key.+ merge_keys = resolve_merge_keys(+ stored_primary_keys, primary_keys, [column.name for column in table.columns]+ )has_duplicate_primary_keys = False- if should_use_incremental_field and primary_keys:- has_duplicate_primary_keys = _has_duplicate_primary_keys(- client, database, table_name, primary_keys, logger- )+ if should_use_incremental_field and should_probe_for_duplicates(+ merge_keys, primary_keys, constraints_enforced=False+ ):+ probed = _has_duplicate_primary_keys(client, database, table_name, merge_keys, logger)+ # Only a probe that ran proves anything.+ has_duplicate_primary_keys = probed is Truefinally:client.close()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.pyindex b49667a4bc2e..54dd4c5c945d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py@@ -636,6 +636,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valchunk_size_override=schema.chunk_size_override,row_filters=inputs.row_filters,enabled_columns=inputs.enabled_columns,+ stored_primary_keys=inputs.primary_keys,bypass_env_proxy=self._bypass_env_proxy(config, inputs.team_id),server_hostname=config.host,)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 befb1f9f6d28..d5536107bdfd 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@@ -1325,10 +1325,9 @@ class TestHasDuplicatePrimaryKeys:client.query.side_effect = ClickHouseError(error_msg)with patch.object(ch_module, "capture_exception") as mock_capture:- # Still assumes duplicates (safe append mode), but the probe hitting- # its own memory/time budget is the designed fallback — not error- # tracking noise.- assert _has_duplicate_primary_keys(client, "db", "t", ["id"], self._logger()) is True+ # The probe hitting its own memory/time budget compared no rows, so it+ # proves nothing about the key and must not read as duplicates.+ assert _has_duplicate_primary_keys(client, "db", "t", ["id"], self._logger()) is Nonemock_capture.assert_not_called()@@ -1372,8 +1371,8 @@ class TestHasDuplicatePrimaryKeys:with patch("products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse.clickhouse.capture_exception") as mock_capture:- # Still fails safe to True (force append mode), just without noise.- assert _has_duplicate_primary_keys(client, "db", "t", ["id"], self._logger()) is True+ # An environment limit is not evidence about the key, so it stays unverified.+ assert _has_duplicate_primary_keys(client, "db", "t", ["id"], self._logger()) is Nonemock_capture.assert_not_called()@@ -1389,6 +1388,105 @@ class TestHasDuplicatePrimaryKeys:mock_capture.assert_called_once()+class TestDuplicateProbeTargetsMergeKey:+ _MEMORY_LIMIT = ClickHouseError("Code: 241. DB::Exception: Query memory limit exceeded. (MEMORY_LIMIT_EXCEEDED)")++ def _run(self, *, stored_primary_keys, sorting_key, probe_outcome):+ probe_queries: list[str] = []++ def fake_query(query, **_kwargs):+ result = MagicMock()+ if "is_in_sorting_key" in query:+ result.result_rows = [(name,) for name in sorting_key]+ elif "HAVING count() > 1" in query:+ probe_queries.append(query)+ if isinstance(probe_outcome, Exception):+ raise probe_outcome+ result.result_rows = probe_outcome+ else:+ result.result_rows = []+ return result++ client = MagicMock()+ client.query.side_effect = fake_query++ mock_table = MagicMock()+ mock_table.columns = [+ ClickHouseColumn(name=n, data_type="String", nullable=False) for n in ("region", "created_at", "id")+ ]+ mock_table.to_arrow_schema.return_value = pa.schema([pa.field("id", pa.string())])++ @contextmanager+ def fake_tunnel():+ yield ("localhost", 8443)++ with (+ patch.object(ch_module, "_get_client", return_value=client),+ patch.object(ch_module, "_get_table", return_value=mock_table),+ patch.object(ch_module, "_get_partition_settings", return_value=None),+ patch.object(ch_module, "get_clickhouse_row_count", return_value={}),+ ):+ response = ch_module.clickhouse_source(+ tunnel=fake_tunnel,+ user="u",+ password="p",+ database="db",+ secure=True,+ verify=True,+ table_names=["events"],+ should_use_incremental_field=True,+ incremental_field="created_at",+ incremental_field_type=IncrementalFieldType.Timestamp,+ logger=MagicMock(),+ db_incremental_field_last_value=None,+ stored_primary_keys=stored_primary_keys,+ )+ return response, probe_queries++ @pytest.mark.parametrize(+ "stored_primary_keys,sorting_key,probe_outcome,expected_group_by,expected_blocked",+ [+ (["id"], ["created_at", "id", "region"], [], "GROUP BY `id` HAVING", False),+ (None, ["region", "id"], [], "GROUP BY `region`, `id` HAVING", False),+ (["id"], ["region", "id"], [(1,)], "GROUP BY `id` HAVING", True),+ (["id"], ["region", "id"], _MEMORY_LIMIT, "GROUP BY `id` HAVING", False),+ ],+ ids=[+ "stored_key_wins",+ "sorting_key_when_nothing_stored",+ "duplicates_block",+ "exhausted_budget_does_not_block",+ ],+ )+ def test_probe_checks_the_merge_key(+ self, stored_primary_keys, sorting_key, probe_outcome, expected_group_by, expected_blocked+ ):+ response, probe_queries = self._run(+ stored_primary_keys=stored_primary_keys, sorting_key=sorting_key, probe_outcome=probe_outcome+ )++ assert len(probe_queries) == 1+ assert expected_group_by in probe_queries[0]+ assert response.has_duplicate_primary_keys is expected_blocked++ def test_source_for_pipeline_passes_the_schema_key_to_the_probe(self):+ from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse import source as source_module++ source = ClickHouseSource()+ inputs = MagicMock()+ inputs.primary_keys = ["id"]++ with (+ patch.object(ExternalDataSchema, "objects"),+ patch.object(source, "make_ssh_tunnel_func"),+ patch.object(source, "_bypass_env_proxy", return_value=None),+ patch.object(source_module, "clickhouse_source") as mock_clickhouse_source,+ ):+ source.source_for_pipeline(MagicMock(), inputs)++ assert mock_clickhouse_source.call_args.kwargs["stored_primary_keys"] == ["id"]++class TestGetIncrementalRowCount:def _logger(self):return MagicMock()