: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(data-imports): retry delta merge commit conflicts with a refreshed table (#74648)
Tom Owers397eb2a9cf01
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.pyindex 7f2f5f56af4b..4176f587bcc9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.py@@ -71,6 +71,14 @@ def is_transient_object_store_error(error: BaseException) -> bool:return isinstance(error, OSError) and any(needle in str(error) for needle in TRANSIENT_OBJECT_STORE_ERRORS)+# A merge's conflict checker raises CommitFailedError the moment a concurrent commit added data+# the merge predicate didn't account for — unlike a plain version-bump race, delta-rs does not+# consume max_commit_retries or retry this itself (see delta-rs kernel/transaction/conflict_checker.rs),+# because resolving it safely requires re-reading the table and re-running the merge, which is+# exactly what its "must be rerun" error message asks the caller to do.+DELTA_MERGE_CONFLICT_RETRIES = 3++def _delta_merge_spill_kwargs() -> dict[str, int]:"""delta-rs `merge` kwargs that let DataFusion spill to disk instead of OOMing on large merges.@@ -397,6 +405,27 @@ class DeltaTableHelper:return await asyncio.to_thread(delta_table.file_uris)+ async def _execute_merge_with_conflict_retry(+ self, table: deltalake.DeltaTable, merge_fn: Callable[[], dict]+ ) -> dict:+ """Run a Delta merge, refreshing the table and re-running it on a commit conflict.++ See DELTA_MERGE_CONFLICT_RETRIES for why this can't rely on delta-rs's own retry budget.+ """+ attempt = 0+ while True:+ try:+ return await asyncio.to_thread(merge_fn)+ except deltalake.exceptions.CommitFailedError:+ if attempt >= DELTA_MERGE_CONFLICT_RETRIES:+ raise+ attempt += 1+ await self._logger.awarning(+ f"write_to_deltalake: merge commit conflict, retrying with refreshed table "+ f"(attempt {attempt}/{DELTA_MERGE_CONFLICT_RETRIES})"+ )+ await asyncio.to_thread(table.update_incremental)+async def _dedupe_incremental_batch(self, data: pa.Table, primary_keys: Sequence[Any], use_partitioning: bool) -> pa.Table:@@ -512,11 +541,13 @@ class DeltaTableHelper:merge_commit_properties = commit_properties if i == last_partition_index else None+ # Bind the current loop values as defaults so a conflict retry (which re-calls+ # this closure) can't accidentally pick up a later iteration's values.def _do_merge(- filtered_table: pa.Table,- predicate: str,- merge_commit_properties: deltalake.CommitProperties | None,- ):+ filtered_table: pa.Table = filtered_table,+ predicate: str = predicate,+ merge_commit_properties: deltalake.CommitProperties | None = merge_commit_properties,+ ) -> dict:return (existing_delta_table.merge(source=filtered_table,@@ -532,7 +563,7 @@ class DeltaTableHelper:.execute())- merge_stats = await asyncio.to_thread(_do_merge, filtered_table, predicate, merge_commit_properties)+ merge_stats = await self._execute_merge_with_conflict_retry(existing_delta_table, _do_merge)await self._logger.adebug(f"Delta Merge Stats: {json.dumps(merge_stats)}")@@ -556,7 +587,9 @@ class DeltaTableHelper:.execute())- merge_stats = await asyncio.to_thread(_do_merge_unpartitioned, data, predicate_ops)+ merge_stats = await self._execute_merge_with_conflict_retry(+ existing_delta_table, lambda: _do_merge_unpartitioned(data, predicate_ops)+ )await self._logger.adebug(f"Delta Merge Stats: {json.dumps(merge_stats)}")elif (write_type == "full_refresh"@@ -709,7 +742,9 @@ class DeltaTableHelper:.execute())- close_stats = await asyncio.to_thread(_do_scd2_close, first_per_pk, predicate)+ close_stats = await self._execute_merge_with_conflict_retry(+ existing_delta_table, lambda: _do_scd2_close(first_per_pk, predicate)+ )await self._logger.adebug(f"SCD2 close stats: {json.dumps(close_stats)}")# Step 2: Append all new rowsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.pyindex 6cdbabad9fdc..ed155fae90d2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.py@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper import (+ DELTA_MERGE_CONFLICT_RETRIES,DeltaTableHelper,_delta_merge_spill_kwargs,_first_per_pk_table,@@ -478,6 +479,74 @@ class TestWriteToDeltalakeCommitMetadataPassThrough:assert commit_properties.custom_metadata == expected_custom_metadata+class TestExecuteMergeWithConflictRetry:+ """A merge's CommitFailedError means delta-rs's conflict checker rejected the commit+ outright, without spending any of its own internal retry budget (see the comment on+ DELTA_MERGE_CONFLICT_RETRIES). Regression coverage for the sync dying on the first such+ conflict instead of refreshing the table and re-running the merge, as the error's own+ "must be rerun" message calls for."""++ def _helper(self) -> DeltaTableHelper:+ return DeltaTableHelper(resource_name="t", job=MagicMock(), logger=_make_logger())++ @pytest.mark.asyncio+ async def test_succeeds_without_retry(self):+ helper = self._helper()+ table = MagicMock()+ merge_fn = MagicMock(return_value={"num_output_rows": 1})++ result = await helper._execute_merge_with_conflict_retry(table, merge_fn)++ assert result == {"num_output_rows": 1}+ merge_fn.assert_called_once()+ table.update_incremental.assert_not_called()++ @pytest.mark.asyncio+ async def test_retries_on_conflict_then_succeeds(self):+ helper = self._helper()+ table = MagicMock()+ merge_fn = MagicMock(+ side_effect=[+ deltalake.exceptions.CommitFailedError("Commit failed: a concurrent transactions added new data."),+ {"num_output_rows": 1},+ ]+ )++ result = await helper._execute_merge_with_conflict_retry(table, merge_fn)++ assert result == {"num_output_rows": 1}+ assert merge_fn.call_count == 2+ table.update_incremental.assert_called_once()++ @pytest.mark.asyncio+ async def test_gives_up_after_exhausting_retries(self):+ helper = self._helper()+ table = MagicMock()+ merge_fn = MagicMock(+ side_effect=deltalake.exceptions.CommitFailedError(+ "Commit failed: a concurrent transactions added new data."+ )+ )++ with pytest.raises(deltalake.exceptions.CommitFailedError):+ await helper._execute_merge_with_conflict_retry(table, merge_fn)++ assert merge_fn.call_count == DELTA_MERGE_CONFLICT_RETRIES + 1+ assert table.update_incremental.call_count == DELTA_MERGE_CONFLICT_RETRIES++ @pytest.mark.asyncio+ async def test_other_errors_propagate_without_retry(self):+ helper = self._helper()+ table = MagicMock()+ merge_fn = MagicMock(side_effect=ValueError("not a commit conflict"))++ with pytest.raises(ValueError):+ await helper._execute_merge_with_conflict_retry(table, merge_fn)++ merge_fn.assert_called_once()+ table.update_incremental.assert_not_called()++def _create_legacy_delta_table(path: str, *, partitioned: bool = False) -> deltalake.DeltaTable:"""Seed a Delta table that mimics what the old dlt pipeline created:business columns plus NOT NULL _dlt_id and _dlt_load_id."""