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(data-imports): retry compact_table on delta commit conflicts (#74723)

Tom Owers8335cbd86f93
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.py
index 4176f587bcc9..44a913eee24a 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,11 +71,12 @@ 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's conflict checker raises CommitFailedError the moment a concurrent commit invalidates what
+# a committing operation read — a merge predicate, or optimize.compact's file-rewrite plan — 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 operation, which is exactly what its "must be rerun" error message
+# asks the caller to do.
DELTA_MERGE_CONFLICT_RETRIES = 3
@@ -405,23 +406,24 @@ 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]
+ async def _execute_with_conflict_retry(
+ self, table: deltalake.DeltaTable, operation_fn: Callable[[], dict], operation_name: str
) -> dict:
- """Run a Delta merge, refreshing the table and re-running it on a commit conflict.
+ """Run a Delta operation that commits (merge, optimize.compact, ...), 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)
+ return await asyncio.to_thread(operation_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"{operation_name}: commit conflict, retrying with refreshed table "
f"(attempt {attempt}/{DELTA_MERGE_CONFLICT_RETRIES})"
)
await asyncio.to_thread(table.update_incremental)
@@ -563,7 +565,9 @@ class DeltaTableHelper:
.execute()
)
- merge_stats = await self._execute_merge_with_conflict_retry(existing_delta_table, _do_merge)
+ merge_stats = await self._execute_with_conflict_retry(
+ existing_delta_table, _do_merge, "write_to_deltalake: merge"
+ )
await self._logger.adebug(f"Delta Merge Stats: {json.dumps(merge_stats)}")
@@ -587,8 +591,10 @@ class DeltaTableHelper:
.execute()
)
- merge_stats = await self._execute_merge_with_conflict_retry(
- existing_delta_table, lambda: _do_merge_unpartitioned(data, predicate_ops)
+ merge_stats = await self._execute_with_conflict_retry(
+ existing_delta_table,
+ lambda: _do_merge_unpartitioned(data, predicate_ops),
+ "write_to_deltalake: merge",
)
await self._logger.adebug(f"Delta Merge Stats: {json.dumps(merge_stats)}")
elif (
@@ -742,8 +748,10 @@ class DeltaTableHelper:
.execute()
)
- close_stats = await self._execute_merge_with_conflict_retry(
- existing_delta_table, lambda: _do_scd2_close(first_per_pk, predicate)
+ close_stats = await self._execute_with_conflict_retry(
+ existing_delta_table,
+ lambda: _do_scd2_close(first_per_pk, predicate),
+ "write_scd2_to_deltalake: close merge",
)
await self._logger.adebug(f"SCD2 close stats: {json.dumps(close_stats)}")
@@ -847,7 +855,9 @@ class DeltaTableHelper:
raise Exception("Deltatable not found")
await self._logger.adebug("Compacting table...")
- compact_stats = await asyncio.to_thread(table.optimize.compact)
+ compact_stats = await self._execute_with_conflict_retry(
+ table, lambda: table.optimize.compact(), "compact_table"
+ )
await self._logger.adebug(json.dumps(compact_stats))
await self.vacuum_table()
diff --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.py
index ed155fae90d2..b3797807aa1d 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
@@ -479,12 +479,12 @@ 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
+class TestExecuteWithConflictRetry:
+ """A committing operation'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."""
+ conflict instead of refreshing the table and re-running the operation, as the error's own
+ "must be rerun" message calls for. Shared by merges and `compact_table`'s optimize.compact."""
def _helper(self) -> DeltaTableHelper:
return DeltaTableHelper(resource_name="t", job=MagicMock(), logger=_make_logger())
@@ -493,60 +493,86 @@ class TestExecuteMergeWithConflictRetry:
async def test_succeeds_without_retry(self):
helper = self._helper()
table = MagicMock()
- merge_fn = MagicMock(return_value={"num_output_rows": 1})
+ operation_fn = MagicMock(return_value={"num_output_rows": 1})
- result = await helper._execute_merge_with_conflict_retry(table, merge_fn)
+ result = await helper._execute_with_conflict_retry(table, operation_fn, "op")
assert result == {"num_output_rows": 1}
- merge_fn.assert_called_once()
+ operation_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(
+ operation_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)
+ result = await helper._execute_with_conflict_retry(table, operation_fn, "op")
assert result == {"num_output_rows": 1}
- assert merge_fn.call_count == 2
+ assert operation_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(
+ operation_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)
+ await helper._execute_with_conflict_retry(table, operation_fn, "op")
- assert merge_fn.call_count == DELTA_MERGE_CONFLICT_RETRIES + 1
+ assert operation_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"))
+ operation_fn = MagicMock(side_effect=ValueError("not a commit conflict"))
with pytest.raises(ValueError):
- await helper._execute_merge_with_conflict_retry(table, merge_fn)
+ await helper._execute_with_conflict_retry(table, operation_fn, "op")
- merge_fn.assert_called_once()
+ operation_fn.assert_called_once()
table.update_incremental.assert_not_called()
+class TestCompactTableConflictRetry:
+ """compact_table's optimize.compact() commits a REMOVE+ADD when rewriting fragmented files —
+ the same commit-conflict shape as a merge (see TestExecuteWithConflictRetry). Regression
+ coverage for a CommitFailedError propagating straight out of compact_table on the first
+ conflict instead of retrying with a refreshed table, like write_to_deltalake's merges do."""
+
+ @pytest.mark.asyncio
+ async def test_retries_compact_on_commit_conflict_then_succeeds(self, helper: DeltaTableHelper):
+ mock_delta = MagicMock()
+ mock_delta.optimize.compact = MagicMock(
+ side_effect=[
+ deltalake.exceptions.CommitFailedError(
+ "Commit failed: a concurrent transaction deleted data this operation read."
+ ),
+ {"numFilesAdded": 1},
+ ]
+ )
+ mock_delta.vacuum = MagicMock(return_value=[])
+
+ with patch.object(helper, "get_delta_table", AsyncMock(return_value=mock_delta)):
+ await helper.compact_table()
+
+ assert mock_delta.optimize.compact.call_count == 2
+ mock_delta.update_incremental.assert_called_once()
+
+
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."""