From ed72088125525269a3ecaec06eb2121b43c870b7 Mon Sep 17 00:00:00 2001 From: Anurag Singh Date: Wed, 11 Nov 2026 03:51:16 +0530 Subject: [PATCH 1/2] Retry appends when the catalog hides the starting snapshot --- pyiceberg/table/update/snapshot.py | 22 +++++--- tests/table/test_commit_retry.py | 82 ++++++++++++++++++++++++++++-- 2 files changed, 94 insertions(+), 10 deletions(-) diff --git a/pyiceberg/table/update/snapshot.py b/pyiceberg/table/update/snapshot.py index 5ca3eb7a73..213f4c9a5f 100644 --- a/pyiceberg/table/update/snapshot.py +++ b/pyiceberg/table/update/snapshot.py @@ -29,6 +29,7 @@ from pyiceberg.avro.codecs import AvroCompressionCodec from pyiceberg.exceptions import ( + CommitFailedException, NoSuchSnapshotRefError, NotAncestorError, SnapshotRefTypeError, @@ -109,26 +110,29 @@ class CommitWindow: base: The snapshot when the operation began (exclusive lower bound, fixed across retries). head: The branch HEAD snapshot after metadata refresh (inclusive upper bound). + base_id: The starting snapshot id, also kept when the catalog no longer exposes it. + base_missing: True when the starting snapshot is not in the refreshed metadata, for + example when the catalog only exposes the current snapshot. """ base: Snapshot | None head: Snapshot | None + base_id: int | None = None + base_missing: bool = False @classmethod def resolve(cls, metadata: TableMetadata, base_id: int | None, branch: str | None) -> CommitWindow: """Resolve a CommitWindow from metadata, starting snapshot ID, and target branch.""" head = metadata.snapshot_by_name(branch) base = metadata.snapshot_by_id(base_id) if base_id is not None else None - if base_id is not None and base is None: - raise ValidationException(f"Cannot find starting snapshot {base_id}") - return cls(base=base, head=head) + return cls(base=base, head=head, base_id=base_id, base_missing=base_id is not None and base is None) def is_empty(self) -> bool: """Return True if no concurrent commits occurred (validation can be skipped). - A None base means the operation started on a table with no snapshots. If a head - exists, another writer landed the first snapshot concurrently, so the window is not - empty and validation must run against the whole history. + A None base means the operation started on a table with no snapshots, or that the + catalog did not expose the starting snapshot. If a head exists, another writer landed + a snapshot concurrently, so the window is not empty. """ return self.head is None or (self.base is not None and self.base.snapshot_id == self.head.snapshot_id) @@ -487,6 +491,12 @@ def _validate_concurrency(self) -> None: if self._commit_window is None or self._commit_window.is_empty(): return + if self._commit_window.base_missing: + raise CommitFailedException( + f"Cannot determine history between starting snapshot {self._commit_window.base_id} " + "and the current snapshot; the catalog does not expose the starting snapshot" + ) + catalog_head = self._commit_window.head starting_snapshot = self._commit_window.base diff --git a/tests/table/test_commit_retry.py b/tests/table/test_commit_retry.py index ab95457e23..b93510fae8 100644 --- a/tests/table/test_commit_retry.py +++ b/tests/table/test_commit_retry.py @@ -735,8 +735,8 @@ def test_validate_concurrency_skips_when_commit_window_is_empty(catalog: Catalog producer._validate_concurrency() -def test_validate_concurrency_raises_on_missing_starting_snapshot(catalog: Catalog) -> None: - """CommitWindow.resolve should raise when starting_snapshot_id cannot be resolved.""" +def test_validate_concurrency_marks_missing_starting_snapshot(catalog: Catalog) -> None: + """CommitWindow.resolve should record a starting snapshot the refreshed metadata does not expose.""" catalog.create_namespace("default") schema = _test_schema() table = catalog.create_table("default.missing_starting_test", schema=schema) @@ -747,8 +747,82 @@ def test_validate_concurrency_raises_on_missing_starting_snapshot(catalog: Catal from pyiceberg.table.update.snapshot import CommitWindow - with pytest.raises(ValidationException, match="Cannot find starting snapshot"): - CommitWindow.resolve(table.metadata, base_id=99999999, branch="main") + window = CommitWindow.resolve(table.metadata, base_id=99999999, branch="main") + + assert window.base is None + assert window.base_missing + assert window.head is not None + assert not window.is_empty() + + +def _hiding_starting_snapshot(rebuild: Any) -> Any: + def patched_rebuild(self_tx: Any) -> None: + metadata_cls = type(self_tx._table.metadata) + base_id = self_tx._snapshot_producers[0]._starting_snapshot_id + original_snapshot_by_id = metadata_cls.snapshot_by_id + + def snapshot_by_id(self_md: Any, snapshot_id: int) -> Any: + return None if snapshot_id == base_id else original_snapshot_by_id(self_md, snapshot_id) + + with patch.object(metadata_cls, "snapshot_by_id", snapshot_by_id): + rebuild(self_tx) + + return patched_rebuild + + +def test_append_retry_without_starting_snapshot(catalog: Catalog) -> None: + """An append retries on catalogs that only expose the current snapshot.""" + catalog.create_namespace("default") + schema = _test_schema() + catalog.create_table("default.hidden_history_append_test", schema=schema) + + import pyarrow as pa + + import pyiceberg.table as _table_module + + df = pa.table({"x": [1, 2, 3]}) + table = catalog.load_table("default.hidden_history_append_test") + table.append(df) + + tbl1 = catalog.load_table("default.hidden_history_append_test") + tbl2 = catalog.load_table("default.hidden_history_append_test") + + tbl1.append(df) + + RuntimeTransaction = _table_module.Transaction + original_rebuild = RuntimeTransaction._rebuild_snapshot_updates + + with patch.object(RuntimeTransaction, "_rebuild_snapshot_updates", _hiding_starting_snapshot(original_rebuild)): + tbl2.append(df) + + assert len(catalog.load_table("default.hidden_history_append_test").scan().to_arrow()) == 9 + + +def test_delete_retry_without_starting_snapshot_raises_commit_failed(catalog: Catalog) -> None: + """A delete cannot validate without the starting snapshot and raises CommitFailedException.""" + catalog.create_namespace("default") + schema = _test_schema() + catalog.create_table("default.hidden_history_delete_test", schema=schema) + + import pyarrow as pa + + import pyiceberg.table as _table_module + + df = pa.table({"x": [1, 2, 3]}) + table = catalog.load_table("default.hidden_history_delete_test") + table.append(df) + + tbl1 = catalog.load_table("default.hidden_history_delete_test") + tbl2 = catalog.load_table("default.hidden_history_delete_test") + + tbl1.append(df) + + RuntimeTransaction = _table_module.Transaction + original_rebuild = RuntimeTransaction._rebuild_snapshot_updates + + with patch.object(RuntimeTransaction, "_rebuild_snapshot_updates", _hiding_starting_snapshot(original_rebuild)): + with pytest.raises(CommitFailedException, match="Cannot determine history"): + tbl2.delete("x == 1") def test_mixed_delete_overwrite_retries_successfully(catalog: Catalog) -> None: From d74e66522dcf959c2e0e6a4be9242e3d10f24333 Mon Sep 17 00:00:00 2001 From: Anurag Singh Date: Fri, 27 Nov 2026 22:53:34 +0530 Subject: [PATCH 2/2] Validate the commit window from the starting snapshot id Match Java's MergingSnapshotProducer.validationHistory: walk back from the branch head to the starting snapshot id and only require the snapshots after it. CommitWindow now keeps just the id, so deletes and overwrites can retry on catalogs that no longer expose the starting snapshot, as long as the history still connects to it. A broken chain raises ValidationException with Java's message instead of failing up front. The sequence number lookup falls back to INITIAL_SEQUENCE_NUMBER when the starting snapshot is missing, and the validate helpers use Java's parent/startingSnapshotId naming. --- pyiceberg/table/update/snapshot.py | 38 +++------ pyiceberg/table/update/validate.py | 127 +++++++++++++++-------------- tests/table/test_commit_retry.py | 76 ++++++++++++++--- tests/table/test_validate.py | 58 ++++++------- 4 files changed, 171 insertions(+), 128 deletions(-) diff --git a/pyiceberg/table/update/snapshot.py b/pyiceberg/table/update/snapshot.py index 213f4c9a5f..422e9acde8 100644 --- a/pyiceberg/table/update/snapshot.py +++ b/pyiceberg/table/update/snapshot.py @@ -29,7 +29,6 @@ from pyiceberg.avro.codecs import AvroCompressionCodec from pyiceberg.exceptions import ( - CommitFailedException, NoSuchSnapshotRefError, NotAncestorError, SnapshotRefTypeError, @@ -108,33 +107,26 @@ def _new_manifest_list_file_name(snapshot_id: int, attempt: int, commit_uuid: uu class CommitWindow: """Tracks the commit range to validate against during retry. - base: The snapshot when the operation began (exclusive lower bound, fixed across retries). + base_id: The starting snapshot id (exclusive lower bound, fixed across retries). It is kept + even when the refreshed metadata no longer exposes the snapshot. head: The branch HEAD snapshot after metadata refresh (inclusive upper bound). - base_id: The starting snapshot id, also kept when the catalog no longer exposes it. - base_missing: True when the starting snapshot is not in the refreshed metadata, for - example when the catalog only exposes the current snapshot. """ - base: Snapshot | None head: Snapshot | None base_id: int | None = None - base_missing: bool = False @classmethod def resolve(cls, metadata: TableMetadata, base_id: int | None, branch: str | None) -> CommitWindow: """Resolve a CommitWindow from metadata, starting snapshot ID, and target branch.""" - head = metadata.snapshot_by_name(branch) - base = metadata.snapshot_by_id(base_id) if base_id is not None else None - return cls(base=base, head=head, base_id=base_id, base_missing=base_id is not None and base is None) + return cls(head=metadata.snapshot_by_name(branch), base_id=base_id) def is_empty(self) -> bool: """Return True if no concurrent commits occurred (validation can be skipped). - A None base means the operation started on a table with no snapshots, or that the - catalog did not expose the starting snapshot. If a head exists, another writer landed - a snapshot concurrently, so the window is not empty. + A None base_id means the operation started on a table with no snapshots. If a head + exists, another writer landed a snapshot concurrently, so the window is not empty. """ - return self.head is None or (self.base is not None and self.base.snapshot_id == self.head.snapshot_id) + return self.head is None or (self.base_id is not None and self.base_id == self.head.snapshot_id) class _SnapshotProducer(UpdateTableMetadata[U], Generic[U]): @@ -491,14 +483,8 @@ def _validate_concurrency(self) -> None: if self._commit_window is None or self._commit_window.is_empty(): return - if self._commit_window.base_missing: - raise CommitFailedException( - f"Cannot determine history between starting snapshot {self._commit_window.base_id} " - "and the current snapshot; the catalog does not expose the starting snapshot" - ) - catalog_head = self._commit_window.head - starting_snapshot = self._commit_window.base + starting_snapshot_id = self._commit_window.base_id if catalog_head is None: return @@ -508,19 +494,19 @@ def _validate_concurrency(self) -> None: conflict_detection_filter = self._predicate if self._predicate != AlwaysFalse() else None if isolation_level == IsolationLevel.SERIALIZABLE: - _validate_added_data_files(table, catalog_head, conflict_detection_filter, starting_snapshot) + _validate_added_data_files(table, catalog_head, conflict_detection_filter, starting_snapshot_id) if self._predicate != AlwaysFalse(): # partition_set is None, so any concurrently committed delete file counts as # a conflict even in unrelated partitions. Scope this via partition projection # (as Java does) when delete-file write support lands. - _validate_no_new_delete_files(table, catalog_head, conflict_detection_filter, None, starting_snapshot) - _validate_deleted_data_files(table, catalog_head, conflict_detection_filter, starting_snapshot) + _validate_no_new_delete_files(table, catalog_head, conflict_detection_filter, None, starting_snapshot_id) + _validate_deleted_data_files(table, catalog_head, conflict_detection_filter, starting_snapshot_id) if self._deleted_data_files: - _validate_data_files_exist(table, catalog_head, self._deleted_data_files, starting_snapshot) + _validate_data_files_exist(table, catalog_head, self._deleted_data_files, starting_snapshot_id) _validate_no_new_deletes_for_data_files( - table, catalog_head, conflict_detection_filter, self._deleted_data_files, starting_snapshot + table, catalog_head, conflict_detection_filter, self._deleted_data_files, starting_snapshot_id ) def _build_partition_projection(self, spec_id: int) -> BooleanExpression: diff --git a/pyiceberg/table/update/validate.py b/pyiceberg/table/update/validate.py index 66e3f111ea..bb35b5e2c6 100644 --- a/pyiceberg/table/update/validate.py +++ b/pyiceberg/table/update/validate.py @@ -31,7 +31,7 @@ from pyiceberg.schema import Schema from pyiceberg.table import Table from pyiceberg.table.delete_file_index import DeleteFileIndex -from pyiceberg.table.snapshots import Operation, Snapshot, ancestors_between +from pyiceberg.table.snapshots import Operation, Snapshot, ancestors_between_ids from pyiceberg.typedef import Record VALIDATE_DATA_FILES_EXIST_OPERATIONS: set[Operation] = {Operation.OVERWRITE, Operation.REPLACE, Operation.DELETE} @@ -41,41 +41,42 @@ def _validation_history( table: Table, - from_snapshot: Snapshot | None, + from_snapshot_id: int | None, to_snapshot: Snapshot, matching_operations: set[Operation], manifest_content_filter: ManifestContent, ) -> tuple[list[ManifestFile], set[int]]: """Return newly added manifests and snapshot IDs between the starting snapshot and parent snapshot. - Walks from to_snapshot backwards towards from_snapshot, collecting manifests from - snapshots whose operations match. from_snapshot is excluded from results. A None - from_snapshot walks the entire history of to_snapshot down to the root. + Walks from to_snapshot backwards towards from_snapshot_id, collecting manifests from + snapshots whose operations match. from_snapshot_id is excluded from results. A None + from_snapshot_id walks the entire history of to_snapshot down to the root. + + Only the snapshots after the starting snapshot need to be present, so a catalog that no + longer exposes the starting snapshot can still validate a window that connects to it. Args: table: Table to get the history from - from_snapshot: Snapshot where the walk stops (exclusive), or None to walk the whole history + from_snapshot_id: Snapshot id where the walk stops (exclusive), or None to walk the whole history to_snapshot: Snapshot where the walk starts matching_operations: Operations to match on manifest_content_filter: Manifest content type to filter Raises: - ValidationException: If no matching snapshot is found or only one snapshot is found + ValidationException: If a snapshot in the history has no summary, or if the history + does not connect the last known ancestor to the starting snapshot Returns: List of manifest files and set of snapshots ID's matching conditions """ - if from_snapshot is not None and from_snapshot.snapshot_id == to_snapshot.snapshot_id: + if from_snapshot_id is not None and from_snapshot_id == to_snapshot.snapshot_id: return [], set() manifests_files: list[ManifestFile] = [] snapshots: set[int] = set() last_snapshot = None - for snapshot in ancestors_between(from_snapshot, to_snapshot, table.metadata): - if from_snapshot is not None and snapshot.snapshot_id == from_snapshot.snapshot_id: - last_snapshot = snapshot - break + for snapshot in ancestors_between_ids(from_snapshot_id, to_snapshot.snapshot_id, table.metadata): last_snapshot = snapshot summary = snapshot.summary if summary is None: @@ -92,8 +93,11 @@ def _validation_history( ] ) - if from_snapshot is not None and (last_snapshot is None or last_snapshot.snapshot_id != from_snapshot.snapshot_id): - raise ValidationException("No matching snapshot found.") + if last_snapshot is not None and last_snapshot.parent_snapshot_id != from_snapshot_id: + raise ValidationException( + f"Cannot determine history between starting snapshot {from_snapshot_id} " + f"and the last known ancestor {last_snapshot.snapshot_id}" + ) return manifests_files, snapshots @@ -141,19 +145,19 @@ def _filter_manifest_entries( def _deleted_data_files( table: Table, - starting_snapshot: Snapshot, + parent_snapshot: Snapshot, data_filter: BooleanExpression | None, partition_set: dict[int, set[Record]] | None, - parent_snapshot: Snapshot | None, + starting_snapshot_id: int | None, ) -> Iterator[ManifestEntry]: """Find deleted data files matching a filter since a starting snapshot. Args: table: Table to validate - starting_snapshot: Snapshot current at the start of the operation + parent_snapshot: Ending snapshot on the branch being validated data_filter: Expression used to find deleted data files partition_set: dict of {spec_id: set[partition]} to filter on - parent_snapshot: Ending snapshot on the branch being validated + starting_snapshot_id: Snapshot id current at the start of the operation, excluded from the scan Returns: List of conflicting manifest-entries @@ -161,8 +165,8 @@ def _deleted_data_files( # if there is no current table state, no files have been deleted manifests, snapshot_ids = _validation_history( table, + starting_snapshot_id, parent_snapshot, - starting_snapshot, VALIDATE_DATA_FILES_EXIST_OPERATIONS, ManifestContent.DATA, ) @@ -177,20 +181,20 @@ def _deleted_data_files( def _validate_deleted_data_files( table: Table, - starting_snapshot: Snapshot, + parent_snapshot: Snapshot, data_filter: BooleanExpression | None, - parent_snapshot: Snapshot | None, + starting_snapshot_id: int | None, ) -> None: """Validate that no files matching a filter have been deleted from the table since a starting snapshot. Args: table: Table to validate - starting_snapshot: Snapshot current at the start of the operation - data_filter: Expression used to find deleted data files parent_snapshot: Ending snapshot on the branch being validated + data_filter: Expression used to find deleted data files + starting_snapshot_id: Snapshot id current at the start of the operation """ - conflicting_entries = _deleted_data_files(table, starting_snapshot, data_filter, None, parent_snapshot) + conflicting_entries = _deleted_data_files(table, parent_snapshot, data_filter, None, starting_snapshot_id) if any(conflicting_entries): conflicting_snapshots = {entry.snapshot_id for entry in conflicting_entries} raise ValidationException(f"Deleted data files were found matching the filter for snapshots {conflicting_snapshots}!") @@ -198,17 +202,17 @@ def _validate_deleted_data_files( def _validate_data_files_exist( table: Table, - starting_snapshot: Snapshot, + parent_snapshot: Snapshot, data_files: set[DataFile], - parent_snapshot: Snapshot | None, + starting_snapshot_id: int | None, ) -> None: """Validate that explicitly replaced data files have not been concurrently deleted. Args: table: Table to validate - starting_snapshot: Snapshot at the end of the validation window + parent_snapshot: Ending snapshot on the branch being validated data_files: Data files that must still exist - parent_snapshot: Snapshot at the start of the validation window, excluded from the scan + starting_snapshot_id: Snapshot id current at the start of the operation, excluded from the scan """ partition_set: dict[int, set[Record]] = defaultdict(set) for data_file in data_files: @@ -216,7 +220,7 @@ def _validate_data_files_exist( conflicting_paths = { entry.data_file.file_path - for entry in _deleted_data_files(table, starting_snapshot, None, partition_set, parent_snapshot) + for entry in _deleted_data_files(table, parent_snapshot, None, partition_set, starting_snapshot_id) if entry.data_file in data_files } if conflicting_paths: @@ -225,27 +229,27 @@ def _validate_data_files_exist( def _added_data_files( table: Table, - starting_snapshot: Snapshot, + parent_snapshot: Snapshot, data_filter: BooleanExpression | None, partition_set: dict[int, set[Record]] | None, - parent_snapshot: Snapshot | None, + starting_snapshot_id: int | None, ) -> Iterator[ManifestEntry]: """Return manifest entries for data files added between the starting snapshot and parent snapshot. Args: table: Table to get the history from - starting_snapshot: Starting snapshot to get the history from + parent_snapshot: Ending snapshot on the branch being validated data_filter: Optional filter to match data files partition_set: Optional set of partitions to match data files - parent_snapshot: Parent snapshot to get the history from + starting_snapshot_id: Snapshot id current at the start of the operation, excluded from the scan Returns: Iterator of manifest entries for added data files matching the conditions """ manifests, snapshot_ids = _validation_history( table, + starting_snapshot_id, parent_snapshot, - starting_snapshot, VALIDATE_ADDED_DATA_FILES_OPERATIONS, ManifestContent.DATA, ) @@ -258,19 +262,19 @@ def _added_data_files( def _added_delete_files( table: Table, - starting_snapshot: Snapshot, + parent_snapshot: Snapshot, data_filter: BooleanExpression | None, partition_set: dict[int, set[Record]] | None, - parent_snapshot: Snapshot | None, + starting_snapshot_id: int | None, ) -> DeleteFileIndex: """Return matching delete files that have been added to the table since a starting snapshot. Args: table: Table to get the history from - starting_snapshot: Starting snapshot to get the history from + parent_snapshot: Ending snapshot on the branch being validated data_filter: Optional filter to match data files partition_set: Optional set of partitions to match data files - parent_snapshot: Parent snapshot to get the history from + starting_snapshot_id: Snapshot id current at the start of the operation, excluded from the scan Returns: DeleteFileIndex @@ -279,7 +283,7 @@ def _added_delete_files( return DeleteFileIndex() manifests, snapshot_ids = _validation_history( - table, parent_snapshot, starting_snapshot, VALIDATE_ADDED_DELETE_FILES_OPERATIONS, ManifestContent.DELETES + table, starting_snapshot_id, parent_snapshot, VALIDATE_ADDED_DELETE_FILES_OPERATIONS, ManifestContent.DELETES ) dfi = DeleteFileIndex() @@ -294,38 +298,39 @@ def _added_delete_files( return dfi -def _starting_sequence_number(table: Table, starting_snapshot: Snapshot) -> int: - """Find the starting sequence number from a snapshot. +def _starting_sequence_number(table: Table, starting_snapshot_id: int | None) -> int: + """Find the starting sequence number from a snapshot id. Args: table: Table to find snapshot from - starting_snapshot: Snapshot from where to start looking + starting_snapshot_id: Snapshot id from where to start looking Returns: Sequence number as int """ - if starting_snapshot is not None: - if seq := starting_snapshot.sequence_number: - return seq + if starting_snapshot_id is not None: + starting_snapshot = table.metadata.snapshot_by_id(starting_snapshot_id) + if starting_snapshot is not None and starting_snapshot.sequence_number is not None: + return starting_snapshot.sequence_number return INITIAL_SEQUENCE_NUMBER def _validate_added_data_files( table: Table, - starting_snapshot: Snapshot, + parent_snapshot: Snapshot, data_filter: BooleanExpression | None, - parent_snapshot: Snapshot | None, + starting_snapshot_id: int | None, ) -> None: """Validate that no files matching a filter have been added to the table since a starting snapshot. Args: table: Table to validate - starting_snapshot: Snapshot current at the start of the operation - data_filter: Expression used to find added data files parent_snapshot: Ending snapshot on the branch being validated + data_filter: Expression used to find added data files + starting_snapshot_id: Snapshot id current at the start of the operation """ - conflicting_entries = _added_data_files(table, starting_snapshot, data_filter, None, parent_snapshot) + conflicting_entries = _added_data_files(table, parent_snapshot, data_filter, None, starting_snapshot_id) if any(conflicting_entries): conflicting_snapshots = {entry.snapshot_id for entry in conflicting_entries if entry.snapshot_id is not None} raise ValidationException(f"Added data files were found matching the filter for snapshots {conflicting_snapshots}!") @@ -333,21 +338,21 @@ def _validate_added_data_files( def _validate_no_new_delete_files( table: Table, - starting_snapshot: Snapshot, + parent_snapshot: Snapshot, data_filter: BooleanExpression | None, partition_set: dict[int, set[Record]] | None, - parent_snapshot: Snapshot | None, + starting_snapshot_id: int | None, ) -> None: """Validate no new delete files matching a filter have been added to the table since starting a snapshot. Args: table: Table to validate - starting_snapshot: Snapshot current at the start of the operation + parent_snapshot: Ending snapshot on the branch being validated data_filter: Expression used to find added data files partition_set: Dictionary of partition spec to set of partition records - parent_snapshot: Ending snapshot on the branch being validated + starting_snapshot_id: Snapshot id current at the start of the operation """ - deletes = _added_delete_files(table, starting_snapshot, data_filter, partition_set, parent_snapshot) + deletes = _added_delete_files(table, parent_snapshot, data_filter, partition_set, starting_snapshot_id) if deletes.is_empty(): return @@ -360,26 +365,26 @@ def _validate_no_new_delete_files( def _validate_no_new_deletes_for_data_files( table: Table, - starting_snapshot: Snapshot, + parent_snapshot: Snapshot, data_filter: BooleanExpression | None, data_files: set[DataFile], - parent_snapshot: Snapshot | None, + starting_snapshot_id: int | None, ) -> None: """Validate no new delete files must be applied for data files that have been added to the table since a starting snapshot. Args: table: Table to validate - starting_snapshot: Snapshot current at the start of the operation + parent_snapshot: Ending snapshot on the branch being validated data_filter: Expression used to find added data files data_files: data files to validate have no new deletes - parent_snapshot: Ending snapshot on the branch being validated + starting_snapshot_id: Snapshot id current at the start of the operation """ # If there is no current state, or no files has been added if table.format_version < 2: return - deletes = _added_delete_files(table, starting_snapshot, data_filter, None, parent_snapshot) - seq_num = _starting_sequence_number(table, starting_snapshot) + deletes = _added_delete_files(table, parent_snapshot, data_filter, None, starting_snapshot_id) + seq_num = _starting_sequence_number(table, starting_snapshot_id) # Fail to any delete file found that applies to files written in or before the starting snapshot for data_file in data_files: diff --git a/tests/table/test_commit_retry.py b/tests/table/test_commit_retry.py index b93510fae8..71793892d8 100644 --- a/tests/table/test_commit_retry.py +++ b/tests/table/test_commit_retry.py @@ -15,6 +15,7 @@ # specific language governing permissions and limitations # under the License. import uuid +from collections.abc import Callable from typing import Any from unittest.mock import patch @@ -729,7 +730,8 @@ def test_validate_concurrency_skips_when_commit_window_is_empty(catalog: Catalog # CommitWindow where base == head means no concurrent commits occurred assert table.metadata.current_snapshot_id is not None current = table.metadata.snapshot_by_id(table.metadata.current_snapshot_id) - producer._commit_window = CommitWindow(base=current, head=current) + assert current is not None + producer._commit_window = CommitWindow(head=current, base_id=current.snapshot_id) # Should not raise (validation is skipped) producer._validate_concurrency() @@ -749,20 +751,19 @@ def test_validate_concurrency_marks_missing_starting_snapshot(catalog: Catalog) window = CommitWindow.resolve(table.metadata, base_id=99999999, branch="main") - assert window.base is None - assert window.base_missing + assert window.base_id == 99999999 assert window.head is not None assert not window.is_empty() -def _hiding_starting_snapshot(rebuild: Any) -> Any: +def _hiding_snapshots(rebuild: Any, hidden_ids: Callable[[Any], set[int]]) -> Any: def patched_rebuild(self_tx: Any) -> None: metadata_cls = type(self_tx._table.metadata) - base_id = self_tx._snapshot_producers[0]._starting_snapshot_id original_snapshot_by_id = metadata_cls.snapshot_by_id + hidden = hidden_ids(self_tx) def snapshot_by_id(self_md: Any, snapshot_id: int) -> Any: - return None if snapshot_id == base_id else original_snapshot_by_id(self_md, snapshot_id) + return None if snapshot_id in hidden else original_snapshot_by_id(self_md, snapshot_id) with patch.object(metadata_cls, "snapshot_by_id", snapshot_by_id): rebuild(self_tx) @@ -770,6 +771,25 @@ def snapshot_by_id(self_md: Any, snapshot_id: int) -> Any: return patched_rebuild +def _hiding_starting_snapshot(rebuild: Any) -> Any: + """Hide only the starting snapshot, as a catalog that keeps older history but drops the base would.""" + + def hidden_ids(self_tx: Any) -> set[int]: + return {self_tx._snapshot_producers[0]._starting_snapshot_id} + + return _hiding_snapshots(rebuild, hidden_ids) + + +def _hiding_all_but_head(rebuild: Any) -> Any: + """Expose only the current snapshot, as a catalog with no reachable history would.""" + + def hidden_ids(self_tx: Any) -> set[int]: + metadata = self_tx._table.metadata + return {snapshot.snapshot_id for snapshot in metadata.snapshots if snapshot.snapshot_id != metadata.current_snapshot_id} + + return _hiding_snapshots(rebuild, hidden_ids) + + def test_append_retry_without_starting_snapshot(catalog: Catalog) -> None: """An append retries on catalogs that only expose the current snapshot.""" catalog.create_namespace("default") @@ -792,14 +812,14 @@ def test_append_retry_without_starting_snapshot(catalog: Catalog) -> None: RuntimeTransaction = _table_module.Transaction original_rebuild = RuntimeTransaction._rebuild_snapshot_updates - with patch.object(RuntimeTransaction, "_rebuild_snapshot_updates", _hiding_starting_snapshot(original_rebuild)): + with patch.object(RuntimeTransaction, "_rebuild_snapshot_updates", _hiding_all_but_head(original_rebuild)): tbl2.append(df) assert len(catalog.load_table("default.hidden_history_append_test").scan().to_arrow()) == 9 -def test_delete_retry_without_starting_snapshot_raises_commit_failed(catalog: Catalog) -> None: - """A delete cannot validate without the starting snapshot and raises CommitFailedException.""" +def test_delete_retry_without_starting_snapshot_succeeds(catalog: Catalog) -> None: + """A delete retries when the history between the starting snapshot and the head is still reachable.""" catalog.create_namespace("default") schema = _test_schema() catalog.create_table("default.hidden_history_delete_test", schema=schema) @@ -809,20 +829,52 @@ def test_delete_retry_without_starting_snapshot_raises_commit_failed(catalog: Ca import pyiceberg.table as _table_module df = pa.table({"x": [1, 2, 3]}) + other_df = pa.table({"x": [10, 20, 30]}) table = catalog.load_table("default.hidden_history_delete_test") table.append(df) tbl1 = catalog.load_table("default.hidden_history_delete_test") tbl2 = catalog.load_table("default.hidden_history_delete_test") - tbl1.append(df) + tbl1.append(other_df) RuntimeTransaction = _table_module.Transaction original_rebuild = RuntimeTransaction._rebuild_snapshot_updates with patch.object(RuntimeTransaction, "_rebuild_snapshot_updates", _hiding_starting_snapshot(original_rebuild)): - with pytest.raises(CommitFailedException, match="Cannot determine history"): - tbl2.delete("x == 1") + tbl2.delete("x == 1") + + result = catalog.load_table("default.hidden_history_delete_test").scan().to_arrow() + assert sorted(result.column("x").to_pylist()) == [2, 3, 10, 20, 30] + + +def test_delete_retry_without_history_raises_validation_exception(catalog: Catalog) -> None: + """A delete cannot validate when two concurrent commits leave the history unresolvable.""" + catalog.create_namespace("default") + schema = _test_schema() + catalog.create_table("default.hidden_history_delete_unresolvable_test", schema=schema) + + import pyarrow as pa + + import pyiceberg.table as _table_module + + df = pa.table({"x": [1, 2, 3]}) + table = catalog.load_table("default.hidden_history_delete_unresolvable_test") + table.append(df) + + tbl1 = catalog.load_table("default.hidden_history_delete_unresolvable_test") + tbl2 = catalog.load_table("default.hidden_history_delete_unresolvable_test") + tbl3 = catalog.load_table("default.hidden_history_delete_unresolvable_test") + + tbl1.append(df) + tbl2.append(df) + + RuntimeTransaction = _table_module.Transaction + original_rebuild = RuntimeTransaction._rebuild_snapshot_updates + + with patch.object(RuntimeTransaction, "_rebuild_snapshot_updates", _hiding_all_but_head(original_rebuild)): + with pytest.raises(ValidationException, match="Cannot determine history between starting snapshot"): + tbl3.delete("x == 1") def test_mixed_delete_overwrite_retries_successfully(catalog: Catalog) -> None: diff --git a/tests/table/test_validate.py b/tests/table/test_validate.py index f44de3089a..dd761e6ae6 100644 --- a/tests/table/test_validate.py +++ b/tests/table/test_validate.py @@ -89,7 +89,7 @@ def mock_read_manifest_side_effect(self: Snapshot, io: FileIO) -> list[ManifestF with patch("pyiceberg.table.snapshots.Snapshot.manifests", new=mock_read_manifest_side_effect): manifests, snapshots = _validation_history( table, - oldest_snapshot, + oldest_snapshot.snapshot_id, newest_snapshot, {Operation.APPEND}, ManifestContent.DATA, @@ -115,21 +115,21 @@ def test_validation_history_fails_on_snapshot_with_no_summary( summary=None, manifest_list="foo/bar", ) - with patch("pyiceberg.table.update.validate.ancestors_between", return_value=[snapshot_with_no_summary]): + with patch("pyiceberg.table.update.validate.ancestors_between_ids", return_value=[snapshot_with_no_summary]): with pytest.raises(ValidationException): _validation_history( table, - oldest_snapshot, + oldest_snapshot.snapshot_id, newest_snapshot, {Operation.APPEND}, ManifestContent.DATA, ) -def test_validation_history_fails_on_from_snapshot_not_matching_last_snapshot( +def test_validation_history_fails_when_history_does_not_reach_starting_snapshot( table_v2_with_extensive_snapshots_and_manifests: tuple[Table, dict[int, list[ManifestFile]]], ) -> None: - """Test the validation history function fails when from_snapshot doesn't match last_snapshot.""" + """Test the validation history function fails when the chain does not connect to the starting snapshot.""" table, mock_manifests = table_v2_with_extensive_snapshots_and_manifests oldest_snapshot = table.snapshots()[0] @@ -145,11 +145,11 @@ def mock_read_manifest_side_effect(self: Snapshot, io: FileIO) -> list[ManifestF missing_oldest_snapshot = table.snapshots()[1:] with patch("pyiceberg.table.snapshots.Snapshot.manifests", new=mock_read_manifest_side_effect): - with patch("pyiceberg.table.update.validate.ancestors_between", return_value=missing_oldest_snapshot): + with patch("pyiceberg.table.update.validate.ancestors_between_ids", return_value=missing_oldest_snapshot): with pytest.raises(ValidationException): _validation_history( table, - oldest_snapshot, + oldest_snapshot.snapshot_id, newest_snapshot, {Operation.APPEND}, ManifestContent.DATA, @@ -176,9 +176,9 @@ def mock_read_manifest_side_effect(self: Snapshot, io: FileIO) -> list[ManifestF result = list( _deleted_data_files( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_filter=None, - parent_snapshot=oldest_snapshot, + starting_snapshot_id=oldest_snapshot.snapshot_id, partition_set=None, ) ) @@ -207,9 +207,9 @@ def mock_read_manifest_side_effect(self: Snapshot, io: FileIO) -> list[ManifestF result = list( _deleted_data_files( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_filter=None, - parent_snapshot=oldest_snapshot, + starting_snapshot_id=oldest_snapshot.snapshot_id, partition_set=None, ) ) @@ -231,9 +231,9 @@ class DummyEntry: with pytest.raises(ValidationException): _validate_deleted_data_files( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_filter=None, - parent_snapshot=oldest_snapshot, + starting_snapshot_id=oldest_snapshot.snapshot_id, ) @@ -262,9 +262,9 @@ def data_file() -> DataFile: with pytest.raises(ValidationException, match="Data files were concurrently deleted"): _validate_data_files_exist( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_files={data_file()}, - parent_snapshot=oldest_snapshot, + starting_snapshot_id=oldest_snapshot.snapshot_id, ) @@ -312,9 +312,9 @@ def mock_fetch_manifest_entry(self: ManifestFile, io: FileIO, discard_deleted: b result = list( _added_data_files( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_filter=None, - parent_snapshot=boundary_snapshot, + starting_snapshot_id=boundary_snapshot.snapshot_id, partition_set=None, ) ) @@ -366,9 +366,9 @@ def mock_fetch_manifest_entry(self: ManifestFile, io: FileIO, discard_deleted: b result = list( _added_data_files( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_filter=None, - parent_snapshot=oldest_snapshot, + starting_snapshot_id=oldest_snapshot.snapshot_id, partition_set=None, ) ) @@ -390,9 +390,9 @@ class DummyEntry: with pytest.raises(ValidationException): _validate_added_data_files( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_filter=None, - parent_snapshot=oldest_snapshot, + starting_snapshot_id=oldest_snapshot.snapshot_id, ) @@ -437,9 +437,9 @@ def mock_fetch_manifest_entry(self: ManifestFile, io: FileIO, discard_deleted: b ): dfi = _added_delete_files( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_filter=None, - parent_snapshot=oldest_snapshot, + starting_snapshot_id=oldest_snapshot.snapshot_id, partition_set=None, ) @@ -498,9 +498,9 @@ def mock_fetch_manifest_entry(self: ManifestFile, io: FileIO, discard_deleted: b ): dfi = _added_delete_files( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_filter=None, - parent_snapshot=oldest_snapshot, + starting_snapshot_id=oldest_snapshot.snapshot_id, partition_set=None, ) @@ -519,10 +519,10 @@ def test_validate_no_new_delete_files_raises_on_conflict( with pytest.raises(ValidationException): _validate_no_new_delete_files( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_filter=None, partition_set=None, - parent_snapshot=oldest_snapshot, + starting_snapshot_id=oldest_snapshot.snapshot_id, ) @@ -539,8 +539,8 @@ def test_validate_no_new_delete_files_for_data_files_raises_on_conflict( with pytest.raises(ValidationException): _validate_no_new_deletes_for_data_files( table=table, - starting_snapshot=newest_snapshot, + parent_snapshot=newest_snapshot, data_filter=None, data_files={mocked_data_file}, - parent_snapshot=oldest_snapshot, + starting_snapshot_id=oldest_snapshot.snapshot_id, )