moomindani commented on code in PR #3631:
URL: https://github.com/apache/iceberg-python/pull/3631#discussion_r4350527080


##########
tests/table/test_rewrite_manifests.py:
##########
@@ -0,0 +1,305 @@
+# 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 pathlib import Path
+
+import pyarrow as pa
+import pytest
+
+from pyiceberg.catalog import Catalog
+from pyiceberg.catalog.memory import InMemoryCatalog
+from pyiceberg.manifest import ManifestContent, ManifestFile
+from pyiceberg.table import Table
+from pyiceberg.table.snapshots import Operation
+
+
[email protected]
+def catalog(tmp_path: Path) -> Catalog:
+    catalog = InMemoryCatalog("test.rewrite_manifests", 
warehouse=f"file://{tmp_path}")
+    catalog.create_namespace("default")
+    return catalog
+
+
+def _arrow_table(offset: int = 0) -> pa.Table:
+    return pa.table({"id": pa.array([offset + 1, offset + 2, offset + 3], 
type=pa.int64())})
+
+
+def _create_table_with_appends(catalog: Catalog, appends: int = 3) -> Table:
+    table = catalog.create_table("default.test_rewrite", 
schema=pa.schema([pa.field("id", pa.int64())]))
+    for i in range(appends):
+        table.append(_arrow_table(offset=i * 3))
+    return table
+
+
+def _data_manifests(table: Table) -> list[ManifestFile]:
+    snapshot = table.current_snapshot()
+    assert snapshot is not None
+    return [m for m in snapshot.manifests(table.io) if m.content == 
ManifestContent.DATA]
+
+
+def test_rewrite_manifests_merges_data_manifests(catalog: Catalog) -> None:

Review Comment:
   Added as `test_rewrite_manifests_replans_after_concurrent_append`, thanks 
for writing it. I adapted it to this file's helpers; it fails on the previous 
head with the error above and passes now.
   



##########
pyiceberg/table/update/snapshot.py:
##########
@@ -1312,3 +1312,185 @@ def older_than(self, dt: datetime) -> ExpireSnapshots:
             if snapshot.timestamp_ms < expire_from and snapshot.snapshot_id 
not in protected_ids:
                 self._snapshot_ids_to_expire.add(snapshot.snapshot_id)
         return self
+
+
+class RewriteManifests(_SnapshotProducer["RewriteManifests"]):
+    """Rewrite the current snapshot's data manifests without changing data.
+
+    Live entries from the rewritten data manifests are regrouped into new
+    manifests sized by `commit.manifest.target-size-bytes`, written as EXISTING
+    entries that keep their sequence numbers. Entries with status DELETED are
+    dropped, matching the reference implementation, which rewrites live entries
+    only. Delete manifests are kept as-is. The result is committed as a
+    `replace` snapshot; if no manifests need merging, no snapshot is committed.
+    """
+
+    _computed_manifests: list[ManifestFile] | None
+    _manifest_predicate: Callable[[ManifestFile], bool] | None
+
+    _rewritten_count: int
+    _created_count: int
+    _kept_count: int
+    _entries_processed: int
+
+    def __init__(
+        self,
+        transaction: Transaction,
+        io: FileIO,
+        commit_uuid: uuid.UUID | None = None,
+        snapshot_properties: dict[str, str] = EMPTY_DICT,
+        branch: str | None = MAIN_BRANCH,
+    ) -> None:
+        super().__init__(Operation.REPLACE, transaction, io, commit_uuid, 
snapshot_properties, branch)
+        if transaction.table_metadata.format_version >= 3:
+            raise NotImplementedError(
+                "Rewriting manifests is not yet supported for V3 tables: "
+                "the first-row-id of rewritten manifests must be preserved, "
+                "see: https://github.com/apache/iceberg-python/issues/3621";
+            )
+        self._manifest_predicate = None
+        self._rewritten_count = 0
+        self._created_count = 0
+        self._kept_count = 0
+        self._entries_processed = 0
+        self._computed_manifests = None
+
+    def rewrite_if(self, predicate: Callable[[ManifestFile], bool]) -> 
RewriteManifests:
+        """Filter which manifests should be rewritten.
+
+        Passing a predicate also disables the optimization that keeps 
single-manifest
+        groups as-is, allowing single manifests to be rewritten when they 
match the predicate.
+
+        Args:
+            predicate: A function that takes a ManifestFile and returns True 
if it should be rewritten.
+
+        Returns:
+            This RewriteManifests instance for method chaining.
+        """
+        self._manifest_predicate = predicate
+        return self
+
+    def _deleted_entries(self) -> list[ManifestEntry]:
+        return []
+
+    def _target_size_bytes(self) -> int:
+        from pyiceberg.table import TableProperties
+
+        return property_as_int(  # type: ignore
+            self._transaction.table_metadata.properties,
+            TableProperties.MANIFEST_TARGET_SIZE_BYTES,
+            TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT,
+        )
+
+    def _group_by_target_size(self, manifests: list[ManifestFile]) -> 
list[list[ManifestFile]]:
+        """Pack manifests into groups whose source sizes add up to roughly the 
target size."""
+        target_size = self._target_size_bytes()
+        groups: list[list[ManifestFile]] = []
+        current_group: list[ManifestFile] = []
+        current_size = 0
+        for manifest in manifests:
+            if current_group and current_size + manifest.manifest_length > 
target_size:
+                groups.append(current_group)
+                current_group = []
+                current_size = 0
+            current_group.append(manifest)
+            current_size += manifest.manifest_length
+        if current_group:
+            groups.append(current_group)
+        return groups
+
+    def _existing_manifests(self) -> list[ManifestFile]:

Review Comment:
   Added in 631b53d7. The created manifests must hold the same number of active 
files (added + existing) as the manifests they replace, or the commit raises 
`ValidationException` with the same message as Java's `validateFilesCounts`. As 
in Java, a manifest with missing counts is rejected. 
`test_rewrite_manifests_rejects_rewrite_that_drops_files` covers it by losing 
one manifest's entries mid-rewrite.
   



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