: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 writes on a first-commit version race (#79405)
Tom Owers56fcbe95c2ca
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/errors.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/errors.pyindex 511f8e426f96..bd34d9837ef4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/errors.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/errors.py@@ -115,6 +115,20 @@ def is_offset_overflow_compaction_error(error: BaseException) -> bool:return isinstance(error, deltalake.exceptions.DeltaError) and DELTA_OFFSET_OVERFLOW_ERROR_NEEDLE in str(error)+# The optimistic-concurrency conflict checker raises this when the loser of a race to commit the+# very next version can't read back the winner's just-committed log entry (delta-rs+# `kernel/transaction/conflict_checker.rs`'s `WinningCommitSummary::try_new`) — most commonly two+# writers racing to create the very first version of the same brand-new table, where the version in+# the message is 0. Unlike `CommitFailedError` (mapped from `DeltaTableError::Transaction`), this+# variant falls through delta-rs's Python binding as a plain `DeltaError` (see its `python/src/error.rs`+# catch-all), so callers need to recognize it by message to retry it the same way as a commit conflict.+DELTA_INVALID_VERSION_RACE_NEEDLE = "Invalid table version:"+++def is_invalid_version_race(error: BaseException) -> bool:+ return type(error) is deltalake.exceptions.DeltaError and DELTA_INVALID_VERSION_RACE_NEEDLE in str(error)++def is_transient_maintenance_error(error: BaseException) -> bool:"""Infra blips seen during delta maintenance that aren't a maintenance bug.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.pyindex 7c11ee8f0424..277e897d426f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py@@ -8,6 +8,8 @@ import deltalakeimport deltalake.exceptionsfrom structlog.types import FilteringBoundLogger+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import is_invalid_version_race+T = TypeVar("T")@@ -45,16 +47,20 @@ async def execute_with_conflict_retry(operation_name: str,logger: FilteringBoundLogger,) -> T:- """Run a Delta operation that commits (merge, optimize.compact, vacuum, ...), refreshing the- table and re-running it on a commit conflict.+ """Run a Delta operation that commits (merge, overwrite, append, optimize.compact, vacuum, ...),+ 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.+ See DELTA_MERGE_CONFLICT_RETRIES for why this can't rely on delta-rs's own retry budget. Also+ retries `is_invalid_version_race` — the same race surfacing as a plain `DeltaError` rather than+ `CommitFailedError` because delta-rs's Python binding doesn't give that variant its own class."""attempt = 0while True:try:return await asyncio.to_thread(operation_fn)- except deltalake.exceptions.CommitFailedError:+ except deltalake.exceptions.DeltaError as e:+ if not isinstance(e, deltalake.exceptions.CommitFailedError) and not is_invalid_version_race(e):+ raiseif attempt >= DELTA_MERGE_CONFLICT_RETRIES:raiseattempt += 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_delta_errors.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_delta_errors.pyindex d8c40e73d853..3f25975cdf7a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_delta_errors.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_delta_errors.py@@ -6,6 +6,7 @@ from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (TransientObjectStoreError,+ is_invalid_version_race,is_offset_overflow_compaction_error,is_transient_delta_maintenance_error,is_transient_maintenance_error,@@ -157,6 +158,37 @@ class TestIsTransientMaintenanceError:assert is_transient_maintenance_error(error) is expected+class TestIsInvalidVersionRace:+ @parameterized.expand(+ [+ # Two writers racing to commit the very first version of a brand-new table: the loser's+ # conflict check can't read back the winner's just-committed version 0 log entry.+ ("invalid_table_version_zero", deltalake.exceptions.DeltaError("Invalid table version: 0"), True),+ # The same race losing at a later version, not just table creation.+ ("invalid_table_version_nonzero", deltalake.exceptions.DeltaError("Invalid table version: 7"), True),+ # A distinct delta-rs error variant (`VersionDowngrade`, not `InvalidVersion`) with its own+ # message shape and a real bug to surface (a caller requesting an older version than+ # loaded) — must not be swept up by this race classifier.+ (+ "downgrade_error_not_matched",+ deltalake.exceptions.DeltaError("Cannot downgrade from version 5 to 2; use DeltaTable.load_version()"),+ False,+ ),+ ("unrelated_delta_error", deltalake.exceptions.DeltaError("no protocol found in delta log"), False),+ # `CommitFailedError` is a `DeltaError` subclass, but this classifier is deliberately exact-type+ # only — that variant already has its own dedicated handling via `CommitFailedError`.+ (+ "commit_failed_error_not_matched",+ deltalake.exceptions.CommitFailedError("Invalid table version: 0"),+ False,+ ),+ ("wrong_exception_type", RuntimeError("Invalid table version: 0"), False),+ ]+ )+ def test_classifies_invalid_version_race(self, _name: str, error: Exception, expected: bool):+ assert is_invalid_version_race(error) is expected++class TestIsOffsetOverflowCompactionError:@parameterized.expand([diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.pyindex 31ce1126359c..cfa07490210e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py@@ -45,7 +45,8 @@ class TestExecuteWithConflictRetry:commit outright, without spending any of its own internal retry budget (see the comment onDELTA_MERGE_CONFLICT_RETRIES). Regression coverage for the sync dying on the first suchconflict 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."""+ "must be rerun" message calls for. Shared by merges, overwrite/append writes, and+ `compact_table`'s optimize.compact."""@pytest.mark.asyncioasync def test_succeeds_without_retry(self):@@ -74,6 +75,37 @@ class TestExecuteWithConflictRetry:assert operation_fn.call_count == 2table.update_incremental.assert_called_once()+ @pytest.mark.asyncio+ async def test_retries_on_invalid_version_race_then_succeeds(self):+ # Two writers racing to commit the very first version of a brand-new table surface as a+ # plain DeltaError, not CommitFailedError (delta-rs's Python binding only special-cases+ # DeltaTableError::Transaction — see errors.py's is_invalid_version_race). Regression+ # coverage for this race killing the sync instead of retrying like a normal commit conflict.+ table = MagicMock()+ operation_fn = MagicMock(+ side_effect=[+ deltalake.exceptions.DeltaError("Invalid table version: 0"),+ {"num_output_rows": 1},+ ]+ )++ result = await execute_with_conflict_retry(table, operation_fn, "op", make_logger())++ assert result == {"num_output_rows": 1}+ assert operation_fn.call_count == 2+ table.update_incremental.assert_called_once()++ @pytest.mark.asyncio+ async def test_unrelated_delta_error_propagates_without_retry(self):+ table = MagicMock()+ operation_fn = MagicMock(side_effect=deltalake.exceptions.DeltaError("no protocol found in delta log"))++ with pytest.raises(deltalake.exceptions.DeltaError):+ await execute_with_conflict_retry(table, operation_fn, "op", make_logger())++ operation_fn.assert_called_once()+ table.update_incremental.assert_not_called()+@pytest.mark.asyncioasync def test_gives_up_after_exhausting_retries(self):table = MagicMock()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.pyindex a924ff66ada8..f8e694f40596 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py@@ -482,27 +482,35 @@ class DeltaWriter:data = align_incoming_decimals_to_delta(data, delta_table.schema())try:- await asyncio.to_thread(- _write_deltalake,+ await execute_with_conflict_retry(delta_table,- data,- partition_by=PARTITION_KEY if use_partitioning else None,- mode=mode,- schema_mode=schema_mode,- commit_properties=commit_properties,+ lambda: _write_deltalake(+ delta_table,+ data,+ partition_by=PARTITION_KEY if use_partitioning else None,+ mode=mode,+ schema_mode=schema_mode,+ commit_properties=commit_properties,+ ),+ "write: overwrite",+ self._logger,)except deltalake.exceptions.SchemaMismatchError as e:await self._logger.adebug("SchemaMismatchError: attempting to overwrite schema instead", exc_info=e)capture_exception(e)- await asyncio.to_thread(- _write_deltalake,+ await execute_with_conflict_retry(delta_table,- data,- partition_by=None,- mode=mode,- schema_mode="overwrite",- commit_properties=commit_properties,+ lambda: _write_deltalake(+ delta_table,+ data,+ partition_by=None,+ mode=mode,+ schema_mode="overwrite",+ commit_properties=commit_properties,+ ),+ "write: overwrite (schema retry)",+ self._logger,)elif write_type == "append":if delta_table is None:@@ -527,14 +535,18 @@ class DeltaWriter:await self._logger.adebug(f"write: write_type = append")- await asyncio.to_thread(- _write_deltalake,+ await execute_with_conflict_retry(delta_table,- data,- partition_by=PARTITION_KEY if use_partitioning else None,- mode="append",- schema_mode="merge",- commit_properties=commit_properties,+ lambda: _write_deltalake(+ delta_table,+ data,+ partition_by=PARTITION_KEY if use_partitioning else None,+ mode="append",+ schema_mode="merge",+ commit_properties=commit_properties,+ ),+ "write: append",+ self._logger,)delta_table = await self._table.get_delta_table()