oresttokovenko commented on code in PR #4496:
URL: https://github.com/apache/iceberg-python/pull/4496#discussion_r4722845754


##########
pyiceberg/table/__init__.py:
##########
@@ -1364,6 +1374,128 @@ def commit_transaction(self) -> Table:
         return self._table
 
 
+class ReplaceTableTransaction(Transaction):
+    """A transaction that atomically replaces the definition and data of an 
existing table.
+
+    Mirrors Java's TableMetadata.buildReplacement: the UUID, snapshots and 
history are kept, the main
+    branch is removed, field IDs are reused by name, and properties are merged 
into the existing ones.
+    """
+
+    def __init__(
+        self,
+        table: Table,
+        schema: Schema,
+        location: str | None = None,
+        partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
+        sort_order: SortOrder = UNSORTED_SORT_ORDER,
+        properties: Properties = EMPTY_DICT,
+    ):
+        super().__init__(table, autocommit=False)
+        base = table.metadata
+        properties = dict(properties)
+        format_version = int(properties.pop(TableProperties.FORMAT_VERSION, 
base.format_version))
+        if format_version < base.format_version:
+            raise ValueError(f"Cannot downgrade v{base.format_version} table 
to v{format_version}")
+        if format_version == 1 and not (base.spec().is_unpartitioned() and 
partition_spec.is_unpartitioned()):
+            # TODO: support Java's carry-forward of the current v1 partition 
fields as void transforms
+            raise ValueError("Replacing a partitioned v1 table is not 
supported, set format-version to 2 or higher")
+        schema.check_format_version_compatibility(format_version)
+
+        fresh_schema = assign_fresh_schema_ids_for_replace(schema, 
base.schema(), base.last_column_id)
+        fresh_spec = assign_fresh_partition_spec_ids(partition_spec, schema, 
fresh_schema)
+        fresh_sort_order = assign_fresh_sort_order_ids(sort_order, schema, 
fresh_schema)
+
+        if format_version > base.format_version:
+            self._updates += 
(UpgradeFormatVersionUpdate(format_version=format_version),)
+        if MAIN_BRANCH in base.refs:
+            self._updates += (RemoveSnapshotRefUpdate(ref_name=MAIN_BRANCH),)
+
+        # Reuse partition field IDs by (source, transform) across all specs, 
new fields get IDs above last_partition_id
+        existing_fields = sorted((f for s in base.partition_specs for f in 
s.fields), key=lambda f: f.field_id)
+        field_ids = {(f.source_id, str(f.transform)): f.field_id for f in 
existing_fields}  # highest ID wins, like Java
+        next_field_id = itertools.count((base.last_partition_id or 
PARTITION_FIELD_ID_START - 1) + 1)
+        fresh_spec = PartitionSpec(
+            *[
+                PartitionField(
+                    source_id=f.source_id,
+                    field_id=field_ids.get((f.source_id, str(f.transform))) or 
next(next_field_id),
+                    transform=f.transform,
+                    name=f.name,
+                )
+                for f in fresh_spec.fields
+            ]
+        )
+
+        # Reuse an existing schema, spec or sort order when identical, 
otherwise add it and make it the default
+        if (schema_id := next((s.schema_id for s in base.schemas if s == 
fresh_schema), None)) is not None:
+            self._updates += (SetCurrentSchemaUpdate(schema_id=schema_id),)
+        else:
+            new_schema_id = max(s.schema_id for s in base.schemas) + 1
+            self._updates += (
+                
AddSchemaUpdate(schema_=fresh_schema.model_copy(update={"schema_id": 
new_schema_id})),
+                SetCurrentSchemaUpdate(schema_id=-1),
+            )
+
+        if (spec_id := next((s.spec_id for s in base.partition_specs if 
s.fields == fresh_spec.fields), None)) is not None:
+            self._updates += (SetDefaultSpecUpdate(spec_id=spec_id),)
+        else:
+            new_spec_id = max(s.spec_id for s in base.partition_specs) + 1
+            self._updates += (
+                AddPartitionSpecUpdate(spec=PartitionSpec(*fresh_spec.fields, 
spec_id=new_spec_id)),
+                SetDefaultSpecUpdate(spec_id=-1),
+            )
+
+        if (order_id := next((o.order_id for o in base.sort_orders if o.fields 
== fresh_sort_order.fields), None)) is not None:
+            self._updates += 
(SetDefaultSortOrderUpdate(sort_order_id=order_id),)
+        elif fresh_sort_order.is_unsorted:
+            # The unsorted order always has ID 0
+            self._updates += 
(AddSortOrderUpdate(sort_order=UNSORTED_SORT_ORDER), 
SetDefaultSortOrderUpdate(sort_order_id=0))
+        else:
+            new_order_id = max(o.order_id for o in base.sort_orders) + 1
+            self._updates += (
+                
AddSortOrderUpdate(sort_order=SortOrder(*fresh_sort_order.fields, 
order_id=new_order_id)),
+                SetDefaultSortOrderUpdate(sort_order_id=-1),
+            )
+
+        if location and location.rstrip("/") != base.location:
+            self._updates += 
(SetLocationUpdate(location=location.rstrip("/")),)
+        if properties:
+            self._updates += (SetPropertiesUpdate(updates=properties),)
+
+    def commit_transaction(self) -> Table:
+        """Commit the replacement to the catalog.
+
+        Like Java's UpdateRequirements.forReplaceTable, the main branch and 
current IDs are overwritten
+        regardless of concurrent changes; only the table identity and ID 
assignment are asserted.
+
+        Unlike Java, the current schema, spec or sort order is also asserted 
when a new one is added: the
+        catalogs in PyIceberg keep the IDs assigned by the client, so a 
concurrent addition would reuse the ID.
+
+        Returns:
+            The table with the updates applied.
+        """
+        if len(self._updates) > 0:
+            base = self._table.metadata
+            requirements: tuple[TableRequirement, ...] = (
+                AssertTableUUID(uuid=base.table_uuid),
+                
AssertLastAssignedFieldId(last_assigned_field_id=base.last_column_id),
+                
AssertLastAssignedPartitionId(last_assigned_partition_id=base.last_partition_id),
+            )
+            update_types = {type(update) for update in self._updates}
+            if AddSchemaUpdate in update_types:
+                requirements += 
(AssertCurrentSchemaId(current_schema_id=base.current_schema_id),)
+            if AddPartitionSpecUpdate in update_types:
+                requirements += 
(AssertDefaultSpecId(default_spec_id=base.default_spec_id),)
+            if AddSortOrderUpdate in update_types:
+                requirements += 
(AssertDefaultSortOrderId(default_sort_order_id=base.default_sort_order_id),)
+            self._table._do_commit(updates=self._updates, 
requirements=requirements)  # pylint: disable=W0212

Review Comment:
    Unlike `Transaction.commit_transaction`, this `skips _attempt_landed()` and 
`_clean_all_uncommitted()` on `CommitFailedException` or `ValidationException`, 
so failed replaces leave orphaned manifests in storage. It also never sets or 
checks `self._failed` (leaving a failed transaction reusable) and never clears 
`self._snapshot_producers` on success.
   
   
   here's a visualization of the failure model:
   ```mermaid
   flowchart TD
       subgraph PR["Current"]
           P_Open(["Open"]) -->|"commit()"| P_Commit(["Committing"])
           P_Commit -->|"ok"| P_Done(["Committed"]):::ok
           P_Commit -->|"any error (leaks manifests,<br/>stays Open)"| P_Open
       end
   
       subgraph Expected["Expected"]
           E_Open(["Open"]) -->|"commit()"| E_Commit(["Committing"])
           E_Commit -->|"ok"| E_Done(["Committed"]):::ok
           E_Commit -->|"CommitFailed / ValidationError"| 
E_Clean["_attempt_landed()<br/>+ _clean_all_uncommitted()"]
           E_Clean --> E_Fail(["Failed (_failed = True)"]):::fail
           E_Commit -->|"other error (keep files)"| E_Fail
       end
   
       classDef ok fill:#eaf7ee,stroke:#227a3e,color:#111
       classDef fail fill:#fdecec,stroke:#b3261e,color:#111
       linkStyle 2 stroke:#b3261e,stroke-width:2px
   ```
   To be fair, this is a structural issue with the code, right now, nothing 
enforces or documents the commit lifecycle for Transaction subclasses, so it's 
pretty much tribal knowledge. Once Transactions is refactored it will simplify 
the code and we can pull these methods out



##########
pyiceberg/table/__init__.py:
##########
@@ -1364,6 +1374,128 @@ def commit_transaction(self) -> Table:
         return self._table
 
 
+class ReplaceTableTransaction(Transaction):
+    """A transaction that atomically replaces the definition and data of an 
existing table.
+
+    Mirrors Java's TableMetadata.buildReplacement: the UUID, snapshots and 
history are kept, the main
+    branch is removed, field IDs are reused by name, and properties are merged 
into the existing ones.
+    """
+
+    def __init__(
+        self,
+        table: Table,
+        schema: Schema,
+        location: str | None = None,
+        partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
+        sort_order: SortOrder = UNSORTED_SORT_ORDER,
+        properties: Properties = EMPTY_DICT,
+    ):
+        super().__init__(table, autocommit=False)
+        base = table.metadata
+        properties = dict(properties)
+        format_version = int(properties.pop(TableProperties.FORMAT_VERSION, 
base.format_version))

Review Comment:
    This checks for downgrades, but misses the upper bound (`format_version > 
SUPPORTED_TABLE_FORMAT_VERSION`) and 
`_check_properties_format_version_compatibility(properties, format_version)` 
that `new_table_metadata` runs. An unsupported version like format-version=99 
or v3 only properties
   like `encryption.key-id` on a v2 table will pass here and either fail late 
or get sent straight to a REST server.
   



##########
pyiceberg/catalog/__init__.py:
##########
@@ -493,6 +494,93 @@ def create_table_if_not_exists(
         except TableAlreadyExistsError:
             return self.load_table(identifier)
 
+    def replace_table_transaction(
+        self,
+        identifier: str | Identifier,
+        schema: Schema | pa.Schema,
+        location: str | None = None,
+        partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
+        sort_order: SortOrder = UNSORTED_SORT_ORDER,
+        properties: Properties = EMPTY_DICT,
+    ) -> ReplaceTableTransaction:
+        """Create a ReplaceTableTransaction that atomically replaces an 
existing table.
+
+        The table keeps its UUID and history, but the main branch is removed 
until new data is
+        written in the transaction. Field IDs are reused by name, and the 
given properties are
+        merged into the existing ones.
+
+        Args:
+            identifier (str | Identifier): Table identifier.
+            schema (Schema): Table's new schema.
+            location (str | None): New location for the table. Defaults to the 
current location.
+            partition_spec (PartitionSpec): New PartitionSpec for the table.
+            sort_order (SortOrder): New SortOrder for the table.
+            properties (Properties): Table properties to set on the table.
+
+        Returns:
+            ReplaceTableTransaction: the transaction to stage changes in and 
commit.
+
+        Raises:
+            NoSuchTableError: If a table with the name does not exist.
+        """
+        table = self.load_table(identifier)
+        format_version = int(properties.get(TableProperties.FORMAT_VERSION, 
table.metadata.format_version))
+        iceberg_schema = self._convert_schema_if_needed(schema, 
format_version)  # type: ignore
+        return ReplaceTableTransaction(table, iceberg_schema, location, 
partition_spec, sort_order, properties)
+
+    def create_or_replace_table_transaction(
+        self,
+        identifier: str | Identifier,
+        schema: Schema | pa.Schema,
+        location: str | None = None,
+        partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
+        sort_order: SortOrder = UNSORTED_SORT_ORDER,
+        properties: Properties = EMPTY_DICT,
+    ) -> CreateTableTransaction | ReplaceTableTransaction:
+        """Create a transaction that creates the table, or atomically replaces 
it if it already exists.
+
+        Args:
+            identifier (str | Identifier): Table identifier.
+            schema (Schema): Table's schema.
+            location (str | None): Location for the table. Optional Argument.
+            partition_spec (PartitionSpec): PartitionSpec for the table.
+            sort_order (SortOrder): SortOrder for the table.
+            properties (Properties): Table properties that can be a string 
based dictionary.
+
+        Returns:
+            CreateTableTransaction | ReplaceTableTransaction: the transaction 
to stage changes in and commit.
+        """
+        try:
+            return self.replace_table_transaction(identifier, schema, 
location, partition_spec, sort_order, properties)
+        except NoSuchTableError:
+            return self.create_table_transaction(identifier, schema, location, 
partition_spec, sort_order, properties)
+
+    def create_or_replace_table(

Review Comment:
   this function seems redundant? it's just a 1 line wrapper around 
`create_or_replace_table_transaction(...).commit_transaction()`, which could 
just be called directly



##########
pyiceberg/table/__init__.py:
##########
@@ -1364,6 +1374,128 @@ def commit_transaction(self) -> Table:
         return self._table
 
 
+class ReplaceTableTransaction(Transaction):
+    """A transaction that atomically replaces the definition and data of an 
existing table.
+
+    Mirrors Java's TableMetadata.buildReplacement: the UUID, snapshots and 
history are kept, the main
+    branch is removed, field IDs are reused by name, and properties are merged 
into the existing ones.
+    """
+
+    def __init__(
+        self,
+        table: Table,
+        schema: Schema,
+        location: str | None = None,
+        partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
+        sort_order: SortOrder = UNSORTED_SORT_ORDER,
+        properties: Properties = EMPTY_DICT,
+    ):
+        super().__init__(table, autocommit=False)
+        base = table.metadata
+        properties = dict(properties)
+        format_version = int(properties.pop(TableProperties.FORMAT_VERSION, 
base.format_version))
+        if format_version < base.format_version:
+            raise ValueError(f"Cannot downgrade v{base.format_version} table 
to v{format_version}")
+        if format_version == 1 and not (base.spec().is_unpartitioned() and 
partition_spec.is_unpartitioned()):
+            # TODO: support Java's carry-forward of the current v1 partition 
fields as void transforms
+            raise ValueError("Replacing a partitioned v1 table is not 
supported, set format-version to 2 or higher")
+        schema.check_format_version_compatibility(format_version)
+
+        fresh_schema = assign_fresh_schema_ids_for_replace(schema, 
base.schema(), base.last_column_id)
+        fresh_spec = assign_fresh_partition_spec_ids(partition_spec, schema, 
fresh_schema)
+        fresh_sort_order = assign_fresh_sort_order_ids(sort_order, schema, 
fresh_schema)
+
+        if format_version > base.format_version:
+            self._updates += 
(UpgradeFormatVersionUpdate(format_version=format_version),)
+        if MAIN_BRANCH in base.refs:
+            self._updates += (RemoveSnapshotRefUpdate(ref_name=MAIN_BRANCH),)
+
+        # Reuse partition field IDs by (source, transform) across all specs, 
new fields get IDs above last_partition_id
+        existing_fields = sorted((f for s in base.partition_specs for f in 
s.fields), key=lambda f: f.field_id)
+        field_ids = {(f.source_id, str(f.transform)): f.field_id for f in 
existing_fields}  # highest ID wins, like Java
+        next_field_id = itertools.count((base.last_partition_id or 
PARTITION_FIELD_ID_START - 1) + 1)
+        fresh_spec = PartitionSpec(
+            *[
+                PartitionField(
+                    source_id=f.source_id,
+                    field_id=field_ids.get((f.source_id, str(f.transform))) or 
next(next_field_id),
+                    transform=f.transform,
+                    name=f.name,
+                )
+                for f in fresh_spec.fields
+            ]
+        )
+
+        # Reuse an existing schema, spec or sort order when identical, 
otherwise add it and make it the default
+        if (schema_id := next((s.schema_id for s in base.schemas if s == 
fresh_schema), None)) is not None:
+            self._updates += (SetCurrentSchemaUpdate(schema_id=schema_id),)
+        else:
+            new_schema_id = max(s.schema_id for s in base.schemas) + 1
+            self._updates += (
+                
AddSchemaUpdate(schema_=fresh_schema.model_copy(update={"schema_id": 
new_schema_id})),
+                SetCurrentSchemaUpdate(schema_id=-1),
+            )
+
+        if (spec_id := next((s.spec_id for s in base.partition_specs if 
s.fields == fresh_spec.fields), None)) is not None:
+            self._updates += (SetDefaultSpecUpdate(spec_id=spec_id),)
+        else:
+            new_spec_id = max(s.spec_id for s in base.partition_specs) + 1
+            self._updates += (
+                AddPartitionSpecUpdate(spec=PartitionSpec(*fresh_spec.fields, 
spec_id=new_spec_id)),
+                SetDefaultSpecUpdate(spec_id=-1),
+            )
+
+        if (order_id := next((o.order_id for o in base.sort_orders if o.fields 
== fresh_sort_order.fields), None)) is not None:
+            self._updates += 
(SetDefaultSortOrderUpdate(sort_order_id=order_id),)
+        elif fresh_sort_order.is_unsorted:
+            # The unsorted order always has ID 0
+            self._updates += 
(AddSortOrderUpdate(sort_order=UNSORTED_SORT_ORDER), 
SetDefaultSortOrderUpdate(sort_order_id=0))
+        else:
+            new_order_id = max(o.order_id for o in base.sort_orders) + 1
+            self._updates += (
+                
AddSortOrderUpdate(sort_order=SortOrder(*fresh_sort_order.fields, 
order_id=new_order_id)),
+                SetDefaultSortOrderUpdate(sort_order_id=-1),
+            )
+
+        if location and location.rstrip("/") != base.location:

Review Comment:
   If a replace sets a new location (or `write.metadata.path`) and appends 
data, data files write to the new path via `self.table_metadata`, while 
`_SnapshotProducer` in `pyiceberg/table/update/snapshot.py` calls 
`self._transaction._table.location_provider()`, which still points to the old 
metadata. That splits data files and manifests across the old and new locations.



-- 
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