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-4397-710d15e8f437f59dc1684dfb9cb49168e505697b
in repository https://gitbox.apache.org/repos/asf/iceberg-python.git

commit e1fc90e122f13cd6a4e89fecc541e16e04b541e1
Author: Rahul Shivu Mahadev <[email protected]>
AuthorDate: Wed Nov 18 13:02:58 2026 +0000

    Add update_partition_statistics() to Table and Transaction (#4397)
    
    * Add update_partition_statistics() to Table and Transaction
    
    Add an UpdatePartitionStatistics builder with set_partition_statistics() and
    remove_partition_statistics(), so callers no longer build update objects by
    hand. Sets apply before removals and absent removals are no-ops, as in Java.
    The RemovePartitionStatisticsUpdate handler therefore no longer raises.
    
    Co-authored-by: Isaac <[email protected]>
    
    * Take partition statistics fields instead of the file object
    
    Review feedback: set_partition_statistics takes snapshot_id, statistics_path
    and file_size_in_bytes and builds the PartitionStatisticsFile, so the model
    can evolve separately from the API. Add docstrings to both public methods.
    
    Co-authored-by: Isaac <[email protected]>
    
    ---------
    
    Co-authored-by: Isaac <[email protected]>
---
 mkdocs/docs/api.md                             |  24 +++++
 pyiceberg/table/__init__.py                    |  27 +++++
 pyiceberg/table/update/__init__.py             |   3 +-
 pyiceberg/table/update/partition_statistics.py |  95 +++++++++++++++++
 tests/table/test_init.py                       |  21 ++--
 tests/table/test_statistics.py                 | 137 +++++++++++++++++++++++++
 6 files changed, 296 insertions(+), 11 deletions(-)

diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md
index a732d2c0a..078157dc8 100644
--- a/mkdocs/docs/api.md
+++ b/mkdocs/docs/api.md
@@ -1788,6 +1788,30 @@ with table.update_statistics() as update:
     update.remove_statistics(snapshot_id2)
 ```
 
+## Table Partition Statistics Management
+
+Manage partition statistics files with operations through the `Table` API:
+
+```python
+# Setting a file for a snapshot replaces the file already set for that snapshot
+table.update_partition_statistics().set_partition_statistics(
+    snapshot_id=snapshot_id, 
statistics_path="s3://bucket/partition-stats.parquet", file_size_in_bytes=1024
+).commit()
+table.update_partition_statistics().remove_partition_statistics(snapshot_id).commit()
+```
+
+You can also use context managers to make more changes:
+
+```python
+with table.update_partition_statistics() as update:
+    update.set_partition_statistics(
+        snapshot_id=snapshot_id, 
statistics_path="s3://bucket/partition-stats.parquet", file_size_in_bytes=1024
+    )
+    update.remove_partition_statistics(snapshot_id)
+```
+
+Within one update, sets are applied before removals, as in Java, so a removal 
wins over a set for the same snapshot regardless of the order of the calls. 
Removing partition statistics for a snapshot that has no file is a no-op.
+
 ## Query the data
 
 To query a table, a table scan is needed. A table scan accepts a filter, 
columns, optionally a limit and a snapshot ID:
diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py
index 39a3f7a7b..84925fd02 100644
--- a/pyiceberg/table/__init__.py
+++ b/pyiceberg/table/__init__.py
@@ -97,6 +97,7 @@ from pyiceberg.table.update import (
     UpgradeFormatVersionUpdate,
     update_table_metadata,
 )
+from pyiceberg.table.update.partition_statistics import 
UpdatePartitionStatistics
 from pyiceberg.table.update.schema import UpdateSchema
 from pyiceberg.table.update.snapshot import ManageSnapshots, UpdateSnapshot, 
_FastAppendFiles
 from pyiceberg.table.update.sorting import UpdateSortOrder
@@ -510,6 +511,15 @@ class Transaction:
         """
         return UpdateStatistics(transaction=self)
 
+    def update_partition_statistics(self) -> UpdatePartitionStatistics:
+        """
+        Create a new UpdatePartitionStatistics to update the partition 
statistics of the table.
+
+        Returns:
+            A new UpdatePartitionStatistics
+        """
+        return UpdatePartitionStatistics(transaction=self)
+
     def append(
         self,
         df: pa.Table | pa.RecordBatchReader,
@@ -1704,6 +1714,23 @@ class Table:
         """
         return UpdateStatistics(transaction=Transaction(self, autocommit=True))
 
+    def update_partition_statistics(self) -> UpdatePartitionStatistics:
+        """
+        Shorthand to run partition statistics management operations like set 
and remove partition statistics.
+
+        Use table.update_partition_statistics().<operation>().commit() to run 
a specific operation.
+        Use 
table.update_partition_statistics().<operation-one>().<operation-two>().commit()
 to run multiple operations.
+
+        Pending changes are applied on commit.
+
+        We can also use context managers to make more changes. For example:
+
+        with table.update_partition_statistics() as update:
+            
update.set_partition_statistics(partition_statistics_file=partition_statistics_file)
+            update.remove_partition_statistics(snapshot_id=2)
+        """
+        return UpdatePartitionStatistics(transaction=Transaction(self, 
autocommit=True))
+
     def update_schema(self, allow_incompatible_changes: bool = False, 
case_sensitive: bool = True) -> UpdateSchema:
         """Create a new UpdateSchema to alter the columns of this table.
 
diff --git a/pyiceberg/table/update/__init__.py 
b/pyiceberg/table/update/__init__.py
index fc1d2347d..ae637eeaa 100644
--- a/pyiceberg/table/update/__init__.py
+++ b/pyiceberg/table/update/__init__.py
@@ -692,8 +692,9 @@ def _(update: SetPartitionStatisticsUpdate, base_metadata: 
TableMetadata, contex
 def _(
     update: RemovePartitionStatisticsUpdate, base_metadata: TableMetadata, 
context: _TableMetadataUpdateContext
 ) -> TableMetadata:
+    # Removing an absent entry is a no-op, so the metadata is not changed
     if not any(part_stat.snapshot_id == update.snapshot_id for part_stat in 
base_metadata.partition_statistics):
-        raise ValueError(f"Partition Statistics with snapshot id 
{update.snapshot_id} does not exist")
+        return base_metadata
 
     statistics = 
filter_statistics_by_snapshot_id(base_metadata.partition_statistics, 
update.snapshot_id)
     context.add_update(update)
diff --git a/pyiceberg/table/update/partition_statistics.py 
b/pyiceberg/table/update/partition_statistics.py
new file mode 100644
index 000000000..c6f453476
--- /dev/null
+++ b/pyiceberg/table/update/partition_statistics.py
@@ -0,0 +1,95 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from typing import TYPE_CHECKING
+
+from pyiceberg.table.statistics import PartitionStatisticsFile
+from pyiceberg.table.update import (
+    RemovePartitionStatisticsUpdate,
+    SetPartitionStatisticsUpdate,
+    TableUpdate,
+    UpdatesAndRequirements,
+    UpdateTableMetadata,
+)
+
+if TYPE_CHECKING:
+    from pyiceberg.table import Transaction
+
+
+class 
UpdatePartitionStatistics(UpdateTableMetadata["UpdatePartitionStatistics"]):
+    """
+    Run partition statistics management operations using APIs.
+
+    APIs include set_partition_statistics and remove_partition_statistics 
operations.
+
+    Use table.update_partition_statistics().<operation>().commit() to run a 
specific operation.
+    Use 
table.update_partition_statistics().<operation-one>().<operation-two>().commit()
 to run multiple operations.
+
+    Pending changes are applied on commit. Sets are applied before removals, 
so a removal wins over a set
+    for the same snapshot, regardless of the order of the calls.
+
+    We can also use context managers to make more changes. For example:
+
+    with table.update_partition_statistics() as update:
+        update.set_partition_statistics(snapshot_id=1, 
statistics_path="s3://bucket/stats.parquet", file_size_in_bytes=124)
+        update.remove_partition_statistics(snapshot_id=2)
+    """
+
+    _sets: dict[int, SetPartitionStatisticsUpdate]
+    _removals: dict[int, RemovePartitionStatisticsUpdate]
+
+    def __init__(self, transaction: "Transaction") -> None:
+        super().__init__(transaction)
+        self._sets = {}
+        self._removals = {}
+
+    def set_partition_statistics(
+        self, snapshot_id: int, statistics_path: str, file_size_in_bytes: int
+    ) -> "UpdatePartitionStatistics":
+        """Set the partition statistics file of a snapshot, replacing the file 
already set for that snapshot.
+
+        Args:
+            snapshot_id: The ID of the snapshot that the statistics file 
describes.
+            statistics_path: The location of the partition statistics file.
+            file_size_in_bytes: The size of the partition statistics file in 
bytes.
+
+        Returns:
+            This for method chaining.
+        """
+        partition_statistics_file = PartitionStatisticsFile(
+            snapshot_id=snapshot_id, statistics_path=statistics_path, 
file_size_in_bytes=file_size_in_bytes
+        )
+        self._sets[snapshot_id] = 
SetPartitionStatisticsUpdate(partition_statistics=partition_statistics_file)
+
+        return self
+
+    def remove_partition_statistics(self, snapshot_id: int) -> 
"UpdatePartitionStatistics":
+        """Remove the partition statistics file of a snapshot. Removing a 
snapshot that has no file is a no-op.
+
+        Args:
+            snapshot_id: The ID of the snapshot whose partition statistics 
file is removed.
+
+        Returns:
+            This for method chaining.
+        """
+        self._removals[snapshot_id] = 
RemovePartitionStatisticsUpdate(snapshot_id=snapshot_id)
+
+        return self
+
+    def _commit(self) -> UpdatesAndRequirements:
+        # Sets come before removals, as in Java's SetPartitionStatistics, so a 
removal wins over a set
+        updates: tuple[TableUpdate, ...] = (*self._sets.values(), 
*self._removals.values())
+        return updates, ()
diff --git a/tests/table/test_init.py b/tests/table/test_init.py
index e053ee95b..3e47d3fee 100644
--- a/tests/table/test_init.py
+++ b/tests/table/test_init.py
@@ -2215,16 +2215,17 @@ def 
test_remove_partition_statistics_update(table_v2_with_statistics: Table) ->
     assert len(remove_metadata.partition_statistics) == 0
 
 
-def 
test_remove_partition_statistics_update_with_invalid_snapshot_id(table_v2_with_statistics:
 Table) -> None:
-    # Remove the same partition statistics file.
-    with pytest.raises(
-        ValueError,
-        match="Partition Statistics with snapshot id 123456789 does not exist",
-    ):
-        update_table_metadata(
-            table_v2_with_statistics.metadata,
-            (RemovePartitionStatisticsUpdate(snapshot_id=123456789),),
-        )
+def 
test_remove_partition_statistics_update_without_file_is_noop(table_v2_with_statistics:
 Table) -> None:
+    # Removing a partition statistics file that does not exist leaves the 
metadata unchanged, also when repeated
+    new_metadata = update_table_metadata(
+        table_v2_with_statistics.metadata,
+        (
+            RemovePartitionStatisticsUpdate(snapshot_id=123456789),
+            RemovePartitionStatisticsUpdate(snapshot_id=123456789),
+        ),
+    )
+
+    assert new_metadata == table_v2_with_statistics.metadata
 
 
 def test_add_encryption_key_update(table_v3: Table) -> None:
diff --git a/tests/table/test_statistics.py b/tests/table/test_statistics.py
index 6c91990ea..4161c4472 100644
--- a/tests/table/test_statistics.py
+++ b/tests/table/test_statistics.py
@@ -14,6 +14,11 @@
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
 # under the License.
+import pyarrow as pa
+import pytest
+
+from pyiceberg.catalog import Catalog
+from pyiceberg.table import Table
 from pyiceberg.table.statistics import BlobMetadata, PartitionStatisticsFile, 
StatisticsFile
 
 
@@ -52,3 +57,135 @@ def test_statistics_file() -> None:
     )
 
     assert statistics_file.model_dump_json() == statistics_file_json
+
+
+def _create_table_with_two_snapshots(catalog: Catalog) -> tuple[Table, int, 
int]:
+    arrow_table = pa.table({"id": [1, 2, 3]})
+    catalog.create_namespace("default")
+    table = catalog.create_table("default.test_partition_statistics", 
schema=arrow_table.schema)
+    table.append(arrow_table)
+    table.append(arrow_table)
+    snapshot_id_1, snapshot_id_2 = [snapshot.snapshot_id for snapshot in 
table.snapshots()]
+    return table, snapshot_id_1, snapshot_id_2
+
+
+def _partition_statistics_file(snapshot_id: int, statistics_path: str) -> 
PartitionStatisticsFile:
+    return PartitionStatisticsFile(snapshot_id=snapshot_id, 
statistics_path=statistics_path, file_size_in_bytes=124)
+
+
+def test_update_partition_statistics(catalog: Catalog) -> None:
+    table, snapshot_id_1, snapshot_id_2 = 
_create_table_with_two_snapshots(catalog)
+    stats_1 = _partition_statistics_file(snapshot_id_1, 
"s3://bucket/partition-stats-1.parquet")
+    stats_1_replaced = _partition_statistics_file(snapshot_id_1, 
"s3://bucket/partition-stats-1-v2.parquet")
+    stats_2 = _partition_statistics_file(snapshot_id_2, 
"s3://bucket/partition-stats-2.parquet")
+
+    
table.update_partition_statistics().set_partition_statistics(**stats_1.model_dump(by_alias=False)).commit()
+    assert table.metadata.partition_statistics == [stats_1]
+
+    # A file set for a snapshot that already has one replaces it
+    
table.update_partition_statistics().set_partition_statistics(**stats_1_replaced.model_dump(by_alias=False)).commit()
+    assert table.metadata.partition_statistics == [stats_1_replaced]
+
+    with table.update_partition_statistics() as update:
+        update.set_partition_statistics(**stats_2.model_dump(by_alias=False))
+    assert table.metadata.partition_statistics == [stats_1_replaced, stats_2]
+
+    
table.update_partition_statistics().remove_partition_statistics(snapshot_id_1).commit()
+    assert table.metadata.partition_statistics == [stats_2]
+    assert catalog.load_table(table.name()).metadata.partition_statistics == 
[stats_2]
+
+
+def test_update_partition_statistics_set_and_remove_in_one_update(catalog: 
Catalog) -> None:
+    table, snapshot_id_1, snapshot_id_2 = 
_create_table_with_two_snapshots(catalog)
+    stats_1 = _partition_statistics_file(snapshot_id_1, 
"s3://bucket/partition-stats-1.parquet")
+    stats_1_replaced = _partition_statistics_file(snapshot_id_1, 
"s3://bucket/partition-stats-1-v2.parquet")
+    stats_2 = _partition_statistics_file(snapshot_id_2, 
"s3://bucket/partition-stats-2.parquet")
+
+    # Operations on different snapshots are both applied, in either call order
+    
table.update_partition_statistics().set_partition_statistics(**stats_1.model_dump(by_alias=False)).commit()
+    table.update_partition_statistics().set_partition_statistics(
+        **stats_2.model_dump(by_alias=False)
+    ).remove_partition_statistics(snapshot_id_1).commit()
+    assert table.metadata.partition_statistics == [stats_2]
+
+    with table.update_partition_statistics() as update:
+        update.set_partition_statistics(**stats_1.model_dump(by_alias=False))
+        update.remove_partition_statistics(snapshot_id_2)
+    assert table.metadata.partition_statistics == [stats_1]
+
+    # On the same snapshot, the removal wins in either call order, with or 
without an existing file
+    for has_existing_file in (False, True):
+        for remove_first in (False, True):
+            if has_existing_file:
+                
table.update_partition_statistics().set_partition_statistics(**stats_1.model_dump(by_alias=False)).commit()
+            else:
+                
table.update_partition_statistics().remove_partition_statistics(snapshot_id_1).commit()
+            with table.update_partition_statistics() as update:
+                if remove_first:
+                    
update.remove_partition_statistics(snapshot_id_1).set_partition_statistics(
+                        **stats_1_replaced.model_dump(by_alias=False)
+                    )
+                else:
+                    
update.set_partition_statistics(**stats_1_replaced.model_dump(by_alias=False)).remove_partition_statistics(
+                        snapshot_id_1
+                    )
+            assert table.metadata.partition_statistics == []
+
+    # Repeated operations: the last file set wins, and repeated removals are 
no-ops
+    with table.update_partition_statistics() as update:
+        
update.set_partition_statistics(**stats_1.model_dump(by_alias=False)).set_partition_statistics(
+            **stats_1_replaced.model_dump(by_alias=False)
+        )
+    assert table.metadata.partition_statistics == [stats_1_replaced]
+
+    with table.update_partition_statistics() as update:
+        update.remove_partition_statistics(snapshot_id_1)
+        update.remove_partition_statistics(snapshot_id_1)
+    assert table.metadata.partition_statistics == []
+
+
+def test_update_partition_statistics_in_transaction(catalog: Catalog) -> None:
+    table, snapshot_id_1, snapshot_id_2 = 
_create_table_with_two_snapshots(catalog)
+    stats_1 = _partition_statistics_file(snapshot_id_1, 
"s3://bucket/partition-stats-1.parquet")
+    stats_2 = _partition_statistics_file(snapshot_id_2, 
"s3://bucket/partition-stats-2.parquet")
+
+    with table.transaction() as transaction:
+        
transaction.update_partition_statistics().set_partition_statistics(**stats_1.model_dump(by_alias=False)).commit()
+        with transaction.update_partition_statistics() as update:
+            
update.set_partition_statistics(**stats_2.model_dump(by_alias=False))
+
+        # The pending changes are visible in the transaction only, until it 
commits
+        assert transaction.table_metadata.partition_statistics == [stats_1, 
stats_2]
+        assert table.metadata.partition_statistics == []
+        assert catalog.load_table(table.name()).metadata.partition_statistics 
== []
+
+    assert table.metadata.partition_statistics == [stats_1, stats_2]
+    assert catalog.load_table(table.name()).metadata.partition_statistics == 
[stats_1, stats_2]
+
+    # An exception raised inside the transaction rolls back its pending changes
+    def abort_transaction() -> None:
+        with table.transaction() as transaction:
+            
transaction.update_partition_statistics().remove_partition_statistics(snapshot_id_1).commit()
+            raise RuntimeError("abort")
+
+    with pytest.raises(RuntimeError, match="abort"):
+        abort_transaction()
+
+    assert table.metadata.partition_statistics == [stats_1, stats_2]
+    assert catalog.load_table(table.name()).metadata.partition_statistics == 
[stats_1, stats_2]
+
+
+def test_remove_partition_statistics_without_file_is_noop(catalog: Catalog) -> 
None:
+    table, snapshot_id_1, snapshot_id_2 = 
_create_table_with_two_snapshots(catalog)
+    stats_2 = _partition_statistics_file(snapshot_id_2, 
"s3://bucket/partition-stats-2.parquet")
+    
table.update_partition_statistics().set_partition_statistics(**stats_2.model_dump(by_alias=False)).commit()
+    metadata_before = table.metadata
+
+    # Removing a snapshot without a file commits without error, once or 
repeated, and leaves the metadata unchanged
+    
table.update_partition_statistics().remove_partition_statistics(snapshot_id_1).commit()
+    with table.update_partition_statistics() as update:
+        update.remove_partition_statistics(snapshot_id_1)
+        update.remove_partition_statistics(snapshot_id_1)
+
+    assert table.metadata == metadata_before
+    assert catalog.load_table(table.name()).metadata.partition_statistics == 
[stats_2]

Reply via email to