This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-4446-ee86b4beffd0a40a0fedf1e045302be8cfeca7eb in repository https://gitbox.apache.org/repos/asf/iceberg-python.git
commit 4f24f48d985c4963b99fff5b90953a154e17933a Author: GayathriSrividya <[email protected]> AuthorDate: Sun Nov 22 21:27:22 2026 +0000 Fix duplicate file checks after commit retry (#4446) * Fix duplicate file checks after commit retry Revalidate add_files duplicate paths against the refreshed branch snapshot before rebuilding a retried snapshot. Co-authored-by: Copilot <[email protected]> * Merge retry validation into concurrency checks * Use validation exceptions for retried duplicate files Raise ValidationException when a duplicate is discovered during a commit retry so cleanup only runs for validation failures known to be safe. Keep ValueError for the initial duplicate check. --------- Co-authored-by: Gayathri Srividya Rajavarapu <[email protected]> Co-authored-by: Copilot <[email protected]> --- pyiceberg/table/__init__.py | 17 ++++++++++++++--- pyiceberg/table/update/snapshot.py | 15 +++++++++++++-- tests/table/test_commit_retry.py | 24 ++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 5 deletions(-) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 4ee15ab58..a8fcdb16e 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -1032,9 +1032,9 @@ class Transaction: return UpsertResult(rows_updated=update_row_cnt, rows_inserted=insert_row_cnt) - def _find_referenced_data_files(self, file_paths: list[str]) -> list[str]: + def _find_referenced_data_files(self, file_paths: list[str], branch: str | None = MAIN_BRANCH) -> list[str]: """Return file_paths already referenced by data files in the current snapshot.""" - snapshot = self.table_metadata.current_snapshot() + snapshot = self.table_metadata.snapshot_by_name(branch) if snapshot is None: return [] @@ -1071,12 +1071,13 @@ class Transaction: FileNotFoundError: If the file does not exist. ValueError: Raises a ValueError given file_paths contains duplicate files ValueError: Raises a ValueError given file_paths already referenced by table + ValidationException: Raises a ValidationException if a file becomes referenced during a commit retry """ if len(file_paths) != len(set(file_paths)): raise ValueError("File paths must be unique") if check_duplicate_files: - referenced_files = self._find_referenced_data_files(file_paths) + referenced_files = self._find_referenced_data_files(file_paths, branch) if referenced_files: raise ValueError(f"Cannot add files that are already referenced by table, files: {', '.join(referenced_files)}") @@ -1085,6 +1086,16 @@ class Transaction: **{TableProperties.DEFAULT_NAME_MAPPING: self.table_metadata.schema().name_mapping.model_dump_json()} ) with self._append_snapshot_producer(snapshot_properties, branch=branch) as append_files: + if check_duplicate_files: + + def validate_duplicate_files() -> None: + referenced_files = self._find_referenced_data_files(file_paths, branch) + if referenced_files: + raise ValidationException( + f"Cannot add files that are already referenced by table, files: {', '.join(referenced_files)}" + ) + + append_files._set_retry_validator(validate_duplicate_files) data_files = _parquet_files_to_data_files( table_metadata=self.table_metadata, file_paths=file_paths, io=self._table.io ) diff --git a/pyiceberg/table/update/snapshot.py b/pyiceberg/table/update/snapshot.py index 0c9831450..7a37b7628 100644 --- a/pyiceberg/table/update/snapshot.py +++ b/pyiceberg/table/update/snapshot.py @@ -152,6 +152,7 @@ class _SnapshotProducer(UpdateTableMetadata[U], Generic[U]): _uncommitted_manifests: list[str] _written_manifest_lists: list[str] _isolation_operation: Operation + _retry_validator: Callable[[], None] | None def __init__( self, @@ -186,6 +187,16 @@ class _SnapshotProducer(UpdateTableMetadata[U], Generic[U]): self._case_sensitive = True self._commit_window = None self._isolation_operation: Operation = Operation.DELETE + self._retry_validator = None + + def _set_retry_validator(self, validator: Callable[[], None]) -> None: + self._retry_validator = validator + + def _validate_concurrency(self) -> None: + """Validate retry-specific invariants and conflicts with concurrent changes.""" + if self._retry_validator is not None: + self._retry_validator() + self._validate_concurrent_changes() def _validate_target_branch(self, branch: str | None) -> str | None: # if branch is none, write will be written into a staging snapshot @@ -468,7 +479,7 @@ class _SnapshotProducer(UpdateTableMetadata[U], Generic[U]): self._manifest_num_counter = itertools.count(0) self.commit_uuid = uuid.uuid4() - def _validate_concurrency(self) -> None: + def _validate_concurrent_changes(self) -> None: """Validate that concurrent changes do not conflict with this operation. Uses the CommitWindow to determine which catalog commits to validate against. @@ -690,7 +701,7 @@ class _DeleteFiles(_SnapshotProducer["_DeleteFiles"]): class _FastAppendFiles(_SnapshotProducer["_FastAppendFiles"]): - def _validate_concurrency(self) -> None: + def _validate_concurrent_changes(self) -> None: """Skip validation; appends do not conflict with other operations.""" def _existing_manifests(self) -> list[ManifestFile]: diff --git a/tests/table/test_commit_retry.py b/tests/table/test_commit_retry.py index 99fcc826f..22f743c1c 100644 --- a/tests/table/test_commit_retry.py +++ b/tests/table/test_commit_retry.py @@ -15,9 +15,11 @@ # specific language governing permissions and limitations # under the License. import uuid +from pathlib import Path from typing import Any from unittest.mock import patch +import pyarrow.parquet as pq import pytest from pyiceberg.catalog import Catalog @@ -97,6 +99,28 @@ def test_commit_retry_on_commit_failed(catalog: Catalog) -> None: assert len(result) == 6 +def test_concurrent_add_files_retry_rechecks_duplicate_paths(catalog: Catalog, tmp_path: Path) -> None: + """A retried add_files call rejects a file committed concurrently.""" + catalog.create_namespace("default") + catalog.create_table("default.add_files_retry_test", schema=_test_schema()) + + import pyarrow as pa + + data_file = tmp_path / "data.parquet" + pq.write_table(pa.table({"x": [1, 2]}), data_file) + + tbl1 = catalog.load_table("default.add_files_retry_test") + tbl2 = catalog.load_table("default.add_files_retry_test") + + tbl1.add_files([str(data_file)]) + + with pytest.raises(ValidationException, match="Cannot add files that are already referenced by table"): + tbl2.add_files([str(data_file)]) + + refreshed = catalog.load_table("default.add_files_retry_test") + assert refreshed.scan().to_arrow()["x"].to_pylist() == [1, 2] + + def test_no_retry_without_snapshot_producers(catalog: Catalog) -> None: """Verify that a transaction with no snapshot producers has an empty producer list.""" catalog.create_namespace("default")
