Fokko commented on code in PR #3320:
URL: https://github.com/apache/iceberg-python/pull/3320#discussion_r3600324981


##########
pyiceberg/table/update/snapshot.py:
##########
@@ -353,11 +397,116 @@ def new_manifest_output(self) -> OutputFile:
         location_provider = self._transaction._table.location_provider()
         file_name = 
_new_manifest_file_name(num=next(self._manifest_num_counter), 
commit_uuid=self.commit_uuid)
         file_path = location_provider.new_metadata_location(file_name)
+        self._written_manifests.append(file_path)
         return self._io.new_output(file_path)
 
     def fetch_manifest_entry(self, manifest: ManifestFile, discard_deleted: 
bool = True) -> list[ManifestEntry]:
         return manifest.fetch_manifest_entry(io=self._io, 
discard_deleted=discard_deleted)
 
+    def commit(self) -> None:
+        self._transaction._register_snapshot_producer(self)
+        super().commit()
+
+    def _cleanup_uncommitted(self) -> None:
+        """Delete manifest files and manifest lists from failed retry 
attempts."""
+        for path in self._uncommitted_manifests:
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest: %s", 
path, exc_info=True)
+        self._uncommitted_manifests.clear()
+        # Delete all manifest lists except the last one (which the committed 
snapshot references)
+        if len(self._written_manifest_lists) > 1:
+            for path in self._written_manifest_lists[:-1]:
+                try:
+                    self._io.delete(path)
+                except Exception:
+                    logger.warning("Failed to delete uncommitted manifest 
list: %s", path, exc_info=True)
+            self._written_manifest_lists = self._written_manifest_lists[-1:]
+
+    def _clean_all_uncommitted(self) -> None:
+        """Clean up all manifests and manifest lists on abort."""
+        for path in itertools.chain(self._uncommitted_manifests, 
self._written_manifests):
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest: %s", 
path, exc_info=True)
+        for path in self._written_manifest_lists:
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest list: 
%s", path, exc_info=True)
+        self._uncommitted_manifests.clear()
+        self._written_manifests.clear()
+        self._written_manifest_lists.clear()
+
+    def _refresh_for_retry(self) -> None:
+        """Reset state for a retry attempt with refreshed metadata."""
+        self._uncommitted_manifests.extend(self._written_manifests)
+        self._written_manifests.clear()
+        self._parent_snapshot_id = (
+            snapshot.snapshot_id if (snapshot := 
self._transaction.table_metadata.snapshot_by_name(self._target_branch)) else 
None
+        )

Review Comment:
   nit, should we make a helper for getting the latest head of a branch? This 
is not the easiest to read, and I believe we use this more than once



##########
pyiceberg/table/update/snapshot.py:
##########
@@ -91,19 +97,50 @@ def _new_manifest_list_file_name(snapshot_id: int, attempt: 
int, commit_uuid: uu
     return f"snap-{snapshot_id}-{attempt}-{commit_uuid}.avro"
 
 
+@dataclass(frozen=True)
+class CommitWindow:
+    """Tracks the commit range to validate against during retry.
+
+    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: Snapshot | None
+    head: Snapshot | None
+
+    @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}")

Review Comment:
   This is dead code because `snapshot_by_id` will throw a `StopIteration` 
before it gets here.
   
   
https://github.com/apache/iceberg-python/blob/48e710d20ceeeaa637d5aeae7746b787410859f8/pyiceberg/table/metadata.py#L239-L241



##########
pyiceberg/table/update/snapshot.py:
##########
@@ -353,11 +397,116 @@ def new_manifest_output(self) -> OutputFile:
         location_provider = self._transaction._table.location_provider()
         file_name = 
_new_manifest_file_name(num=next(self._manifest_num_counter), 
commit_uuid=self.commit_uuid)
         file_path = location_provider.new_metadata_location(file_name)
+        self._written_manifests.append(file_path)
         return self._io.new_output(file_path)
 
     def fetch_manifest_entry(self, manifest: ManifestFile, discard_deleted: 
bool = True) -> list[ManifestEntry]:
         return manifest.fetch_manifest_entry(io=self._io, 
discard_deleted=discard_deleted)
 
+    def commit(self) -> None:
+        self._transaction._register_snapshot_producer(self)
+        super().commit()
+
+    def _cleanup_uncommitted(self) -> None:
+        """Delete manifest files and manifest lists from failed retry 
attempts."""
+        for path in self._uncommitted_manifests:
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest: %s", 
path, exc_info=True)
+        self._uncommitted_manifests.clear()
+        # Delete all manifest lists except the last one (which the committed 
snapshot references)
+        if len(self._written_manifest_lists) > 1:
+            for path in self._written_manifest_lists[:-1]:
+                try:
+                    self._io.delete(path)
+                except Exception:
+                    logger.warning("Failed to delete uncommitted manifest 
list: %s", path, exc_info=True)
+            self._written_manifest_lists = self._written_manifest_lists[-1:]
+
+    def _clean_all_uncommitted(self) -> None:
+        """Clean up all manifests and manifest lists on abort."""
+        for path in itertools.chain(self._uncommitted_manifests, 
self._written_manifests):
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest: %s", 
path, exc_info=True)
+        for path in self._written_manifest_lists:
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest list: 
%s", path, exc_info=True)
+        self._uncommitted_manifests.clear()
+        self._written_manifests.clear()
+        self._written_manifest_lists.clear()
+
+    def _refresh_for_retry(self) -> None:
+        """Reset state for a retry attempt with refreshed metadata."""
+        self._uncommitted_manifests.extend(self._written_manifests)
+        self._written_manifests.clear()
+        self._parent_snapshot_id = (
+            snapshot.snapshot_id if (snapshot := 
self._transaction.table_metadata.snapshot_by_name(self._target_branch)) else 
None
+        )
+        self._snapshot_id = self._transaction.table_metadata.new_snapshot_id()
+        self._manifest_num_counter = itertools.count(0)
+        self.commit_uuid = uuid.uuid4()
+
+    def _validate_concurrency(self) -> None:
+        """Validate that concurrent changes do not conflict with this 
operation.
+
+        Uses the CommitWindow to determine which catalog commits to validate 
against.
+        The window spans from base (when the operation began) to head (latest 
branch
+        HEAD), covering all external concurrent commits.
+
+        Subclasses that do not require validation (e.g. fast append) should 
override
+        with a no-op.
+        """
+        from pyiceberg.table import TableProperties
+        from pyiceberg.table.snapshots import IsolationLevel
+        from pyiceberg.table.update.validate import (
+            _validate_added_data_files,
+            _validate_deleted_data_files,
+            _validate_no_new_delete_files,
+            _validate_no_new_deletes_for_data_files,
+        )
+
+        if self._commit_window is None or self._commit_window.is_empty():
+            return
+
+        catalog_head = self._commit_window.head
+        starting_snapshot = self._commit_window.base
+
+        if catalog_head is None or starting_snapshot is None:
+            return
+
+        table = self._transaction._table
+        isolation_level_str = table.metadata.properties.get(
+            self._isolation_level_property, 
TableProperties.WRITE_ISOLATION_LEVEL_DEFAULT
+        )
+        isolation_level = IsolationLevel(isolation_level_str)

Review Comment:
   How about moving this to a property on `TableMetadata`? So we can do:
   
   
   ```suggestion
           isolation_level = table.metadata.isolation_level(Operation)
   ```



##########
pyiceberg/table/update/snapshot.py:
##########
@@ -353,11 +397,116 @@ def new_manifest_output(self) -> OutputFile:
         location_provider = self._transaction._table.location_provider()
         file_name = 
_new_manifest_file_name(num=next(self._manifest_num_counter), 
commit_uuid=self.commit_uuid)
         file_path = location_provider.new_metadata_location(file_name)
+        self._written_manifests.append(file_path)
         return self._io.new_output(file_path)
 
     def fetch_manifest_entry(self, manifest: ManifestFile, discard_deleted: 
bool = True) -> list[ManifestEntry]:
         return manifest.fetch_manifest_entry(io=self._io, 
discard_deleted=discard_deleted)
 
+    def commit(self) -> None:
+        self._transaction._register_snapshot_producer(self)
+        super().commit()
+
+    def _cleanup_uncommitted(self) -> None:
+        """Delete manifest files and manifest lists from failed retry 
attempts."""
+        for path in self._uncommitted_manifests:
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest: %s", 
path, exc_info=True)
+        self._uncommitted_manifests.clear()
+        # Delete all manifest lists except the last one (which the committed 
snapshot references)
+        if len(self._written_manifest_lists) > 1:
+            for path in self._written_manifest_lists[:-1]:
+                try:
+                    self._io.delete(path)
+                except Exception:
+                    logger.warning("Failed to delete uncommitted manifest 
list: %s", path, exc_info=True)
+            self._written_manifest_lists = self._written_manifest_lists[-1:]
+
+    def _clean_all_uncommitted(self) -> None:
+        """Clean up all manifests and manifest lists on abort."""
+        for path in itertools.chain(self._uncommitted_manifests, 
self._written_manifests):
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest: %s", 
path, exc_info=True)
+        for path in self._written_manifest_lists:
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest list: 
%s", path, exc_info=True)
+        self._uncommitted_manifests.clear()
+        self._written_manifests.clear()
+        self._written_manifest_lists.clear()
+
+    def _refresh_for_retry(self) -> None:
+        """Reset state for a retry attempt with refreshed metadata."""
+        self._uncommitted_manifests.extend(self._written_manifests)
+        self._written_manifests.clear()
+        self._parent_snapshot_id = (
+            snapshot.snapshot_id if (snapshot := 
self._transaction.table_metadata.snapshot_by_name(self._target_branch)) else 
None
+        )
+        self._snapshot_id = self._transaction.table_metadata.new_snapshot_id()
+        self._manifest_num_counter = itertools.count(0)
+        self.commit_uuid = uuid.uuid4()
+
+    def _validate_concurrency(self) -> None:
+        """Validate that concurrent changes do not conflict with this 
operation.
+
+        Uses the CommitWindow to determine which catalog commits to validate 
against.
+        The window spans from base (when the operation began) to head (latest 
branch
+        HEAD), covering all external concurrent commits.
+
+        Subclasses that do not require validation (e.g. fast append) should 
override
+        with a no-op.
+        """
+        from pyiceberg.table import TableProperties
+        from pyiceberg.table.snapshots import IsolationLevel
+        from pyiceberg.table.update.validate import (
+            _validate_added_data_files,
+            _validate_deleted_data_files,
+            _validate_no_new_delete_files,
+            _validate_no_new_deletes_for_data_files,
+        )
+
+        if self._commit_window is None or self._commit_window.is_empty():
+            return
+
+        catalog_head = self._commit_window.head
+        starting_snapshot = self._commit_window.base
+
+        if catalog_head is None or starting_snapshot is None:
+            return
+
+        table = self._transaction._table
+        isolation_level_str = table.metadata.properties.get(
+            self._isolation_level_property, 
TableProperties.WRITE_ISOLATION_LEVEL_DEFAULT
+        )
+        isolation_level = IsolationLevel(isolation_level_str)
+        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)
+
+        if conflict_detection_filter is not None:

Review Comment:
   Why not simplify this by avoiding `conflict_detection_filter`:
   
   ```suggestion
           if self._predicate != AlwaysFalse():
   ```
   
   Makes it easier to read



##########
pyiceberg/table/__init__.py:
##########
@@ -1036,17 +1074,76 @@ def commit_transaction(self) -> Table:
             The table with the updates applied.
         """
         if len(self._updates) > 0:
-            self._requirements += 
(AssertTableUUID(uuid=self.table_metadata.table_uuid),)
-            self._table._do_commit(  # pylint: disable=W0212
-                updates=self._updates,
-                requirements=self._requirements,
+            properties = self._table.metadata.properties
+            num_retries: int = property_as_int(  # type: ignore  # The default 
is set with non-None value.
+                properties, TableProperties.COMMIT_NUM_RETRIES, 
TableProperties.COMMIT_NUM_RETRIES_DEFAULT
+            )
+            min_wait_ms: int = property_as_int(  # type: ignore  # The default 
is set with non-None value.
+                properties, TableProperties.COMMIT_MIN_RETRY_WAIT_MS, 
TableProperties.COMMIT_MIN_RETRY_WAIT_MS_DEFAULT
+            )
+            max_wait_ms: int = property_as_int(  # type: ignore  # The default 
is set with non-None value.
+                properties, TableProperties.COMMIT_MAX_RETRY_WAIT_MS, 
TableProperties.COMMIT_MAX_RETRY_WAIT_MS_DEFAULT
             )
+            total_timeout_ms: int = property_as_int(  # type: ignore  # The 
default is set with non-None value.
+                properties, TableProperties.COMMIT_TOTAL_RETRY_TIME_MS, 
TableProperties.COMMIT_TOTAL_RETRY_TIME_MS_DEFAULT
+            )
+            start_time = time.monotonic()
+            self._requirements += 
(AssertTableUUID(uuid=self.table_metadata.table_uuid),)
+
+            try:
+                for attempt in range(num_retries + 1):
+                    try:
+                        self._table._do_commit(  # pylint: disable=W0212
+                            updates=self._updates,
+                            requirements=self._requirements,
+                        )
+                        self._cleanup_uncommitted_manifests()
+                        break
+                    except CommitFailedException:
+                        elapsed_ms = (time.monotonic() - start_time) * 1000

Review Comment:
   Should we emit a WARN here? So the user knows that the commit is being 
retried? Otherwise the user might not know why it is taking its time.



##########
pyiceberg/table/update/snapshot.py:
##########
@@ -353,11 +397,116 @@ def new_manifest_output(self) -> OutputFile:
         location_provider = self._transaction._table.location_provider()
         file_name = 
_new_manifest_file_name(num=next(self._manifest_num_counter), 
commit_uuid=self.commit_uuid)
         file_path = location_provider.new_metadata_location(file_name)
+        self._written_manifests.append(file_path)
         return self._io.new_output(file_path)
 
     def fetch_manifest_entry(self, manifest: ManifestFile, discard_deleted: 
bool = True) -> list[ManifestEntry]:
         return manifest.fetch_manifest_entry(io=self._io, 
discard_deleted=discard_deleted)
 
+    def commit(self) -> None:
+        self._transaction._register_snapshot_producer(self)
+        super().commit()
+
+    def _cleanup_uncommitted(self) -> None:
+        """Delete manifest files and manifest lists from failed retry 
attempts."""
+        for path in self._uncommitted_manifests:
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest: %s", 
path, exc_info=True)
+        self._uncommitted_manifests.clear()
+        # Delete all manifest lists except the last one (which the committed 
snapshot references)
+        if len(self._written_manifest_lists) > 1:
+            for path in self._written_manifest_lists[:-1]:
+                try:
+                    self._io.delete(path)
+                except Exception:
+                    logger.warning("Failed to delete uncommitted manifest 
list: %s", path, exc_info=True)
+            self._written_manifest_lists = self._written_manifest_lists[-1:]
+
+    def _clean_all_uncommitted(self) -> None:
+        """Clean up all manifests and manifest lists on abort."""
+        for path in itertools.chain(self._uncommitted_manifests, 
self._written_manifests):
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest: %s", 
path, exc_info=True)
+        for path in self._written_manifest_lists:
+            try:
+                self._io.delete(path)
+            except Exception:
+                logger.warning("Failed to delete uncommitted manifest list: 
%s", path, exc_info=True)
+        self._uncommitted_manifests.clear()
+        self._written_manifests.clear()
+        self._written_manifest_lists.clear()
+
+    def _refresh_for_retry(self) -> None:
+        """Reset state for a retry attempt with refreshed metadata."""
+        self._uncommitted_manifests.extend(self._written_manifests)
+        self._written_manifests.clear()
+        self._parent_snapshot_id = (
+            snapshot.snapshot_id if (snapshot := 
self._transaction.table_metadata.snapshot_by_name(self._target_branch)) else 
None
+        )
+        self._snapshot_id = self._transaction.table_metadata.new_snapshot_id()
+        self._manifest_num_counter = itertools.count(0)
+        self.commit_uuid = uuid.uuid4()
+
+    def _validate_concurrency(self) -> None:
+        """Validate that concurrent changes do not conflict with this 
operation.
+
+        Uses the CommitWindow to determine which catalog commits to validate 
against.
+        The window spans from base (when the operation began) to head (latest 
branch
+        HEAD), covering all external concurrent commits.
+
+        Subclasses that do not require validation (e.g. fast append) should 
override
+        with a no-op.
+        """
+        from pyiceberg.table import TableProperties
+        from pyiceberg.table.snapshots import IsolationLevel
+        from pyiceberg.table.update.validate import (
+            _validate_added_data_files,
+            _validate_deleted_data_files,
+            _validate_no_new_delete_files,
+            _validate_no_new_deletes_for_data_files,
+        )
+
+        if self._commit_window is None or self._commit_window.is_empty():
+            return
+
+        catalog_head = self._commit_window.head
+        starting_snapshot = self._commit_window.base
+
+        if catalog_head is None or starting_snapshot is None:
+            return
+
+        table = self._transaction._table
+        isolation_level_str = table.metadata.properties.get(
+            self._isolation_level_property, 
TableProperties.WRITE_ISOLATION_LEVEL_DEFAULT
+        )
+        isolation_level = IsolationLevel(isolation_level_str)
+        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)
+
+        if conflict_detection_filter is not None:
+            _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)
+
+        if self._deleted_data_files:
+            _validate_no_new_deletes_for_data_files(
+                table, catalog_head, conflict_detection_filter, 
self._deleted_data_files, starting_snapshot
+            )
+
+    def _resolve_parent_snapshot(self) -> Snapshot | None:

Review Comment:
   This method seems unused? Less is more 🚀 



##########
pyiceberg/table/update/snapshot.py:
##########
@@ -132,8 +172,11 @@ def __init__(
         self._parent_snapshot_id = (
             snapshot.snapshot_id if (snapshot := 
self._transaction.table_metadata.snapshot_by_name(self._target_branch)) else 
None
         )
+        self._starting_snapshot_id = self._parent_snapshot_id
         self._predicate = AlwaysFalse()
         self._case_sensitive = True
+        self._commit_window = None
+        self._isolation_level_property: str = 
TableProperties.WRITE_DELETE_ISOLATION_LEVEL

Review Comment:
   I really dislike that we have to pass this in and around everywhere, it 
really clutters up the code. Earlier I suggested to adding 
`metadata.isolation_level(Operation)`, I think this would solve this and we can 
just resolve it from the table.
   
   Also, this will also take the latest properties into account. So, if in the 
conflict, the isolation level has been updated, this will be taken into account 
since the underlying properties will be refreshed 😄 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to