abnobdoss commented on code in PR #3320:
URL: https://github.com/apache/iceberg-python/pull/3320#discussion_r3610876958
##########
pyiceberg/table/update/snapshot.py:
##########
@@ -353,11 +405,103 @@ 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 = self._current_branch_head_id()
+ # The snapshot id is kept stable across attempts so it acts as an
idempotency key: if a
+ # previous attempt actually landed but its response was lost, the id
can be found in the
+ # refreshed metadata and the commit is not repeated.
+ 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.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:
+ return
+
+ table = self._transaction._table
+ isolation_level =
table.metadata.isolation_level(self._isolation_operation)
+ 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 self._predicate != AlwaysFalse():
+ _validate_no_new_delete_files(table, catalog_head,
conflict_detection_filter, None, starting_snapshot)
Review Comment:
Is the `None` here intentional? It's the `partition_set`, and for delete
files it's the only filter that can actually work. The other way
`_filter_manifest_entries` clears a candidate is by checking the row filter
against the file's column stats, but a delete file's stats don't describe the
table's data columns (a position delete only has bounds for `file_path`), so
that check can never rule one out. With the partition set also absent, any
delete file committed concurrently, in any partition, counts as a conflict.
pyiceberg can't write delete files itself yet, but tables shared with Spark
or Flink merge-on-read writers have them, and I confirmed with a hand-built
delete manifest that a plain `delete()` on partition `a` gets rejected when a
position delete lands in partition `b` (happy to share the script). Java avoids
this by projecting the conflict filter onto the partition spec.
To be clear, I don't see this as blocking; it's more of a
good-to-be-aware-of, since it may be some time before pyiceberg supports MoR
deletes itself. A code comment noting the limitation might suffice for now,
with the projection wired up when delete-file support arrives.
##########
pyiceberg/table/__init__.py:
##########
@@ -1042,18 +1084,111 @@ def commit_transaction(self) -> Table:
Returns:
The table with the updates applied.
"""
+ if self._failed:
+ raise RuntimeError("This transaction failed to commit and cannot
be reused; create a new transaction.")
if len(self._updates) > 0:
Review Comment:
I can see one edge case here that predates this PR but sidesteps the delete
fix you just made: that fix freezes the planned file set and leans on
commit-time validation to catch staleness, but a delete whose plan is empty
never reaches that validation. It contributes an empty update
(`_DeleteFiles._commit` returns `(), ()`), so `_updates` stays empty and
`commit_transaction` returns here before the ref check, retry loop, or
`_validate_concurrency` run. If a row matching the writer's own predicate lands
between staging and commit, the writer still gets a success:
```python
import pyarrow as pa
import pytest
from pyiceberg.catalog.memory import InMemoryCatalog
from pyiceberg.exceptions import ValidationException
from pyiceberg.schema import Schema
from pyiceberg.types import LongType, NestedField
def test_delete_that_matched_nothing_at_staging_still_validates(tmp_path):
catalog = InMemoryCatalog("test", warehouse=tmp_path.as_uri())
catalog.create_namespace("default")
catalog.create_table(
"default.t",
schema=Schema(NestedField(1, "x", LongType(), required=False)),
properties={"commit.retry.min-wait-ms": "1",
"commit.retry.max-wait-ms": "2"},
)
tx = catalog.load_table("default.t").transaction()
with pytest.warns(UserWarning): # the delete matches nothing at staging
time
tx.delete("x > 45")
# A row matching the writer's own predicate lands concurrently.
catalog.load_table("default.t").append(pa.table({"x": [50]}))
with pytest.raises(ValidationException):
tx.commit_transaction()
```
Fails because nothing is raised and the matching row survives. The existing
empty-table test misses this because `overwrite` also stages an append, keeping
`_updates` non-empty; a delete-only transaction has no backstop. One direction:
enter the commit path whenever `_snapshot_producers` is non-empty, so
validation still runs even when the staged output is empty.
##########
pyiceberg/table/__init__.py:
##########
@@ -1042,18 +1084,111 @@ def commit_transaction(self) -> Table:
Returns:
The table with the updates applied.
"""
+ if self._failed:
+ raise RuntimeError("This transaction failed to commit and cannot
be reused; create a new transaction.")
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 = max(
Review Comment:
Thank you for sorting this one out and clamping the retries! minor: could we
also clamp `min_wait_ms`, `max_wait_ms`, and `total_timeout_ms` the same way? A
negative wait currently raises `ValueError` from `time.sleep` mid-retry, which
masks the real `CommitFailedException`.
--
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]