rambleraptor commented on code in PR #3361:
URL: https://github.com/apache/iceberg-python/pull/3361#discussion_r3929834093


##########
pyiceberg/table/maintenance/orphan_files.py:
##########
@@ -0,0 +1,414 @@
+# 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.
+"""Action that removes files from storage that are not reachable from table 
metadata.
+
+Lists the table's storage location, computes the set of files referenced by 
any valid
+snapshot or metadata file, and deletes the difference.
+
+Only acts on files older than 3 days by default.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from collections.abc import Callable, Iterable
+from concurrent.futures import as_completed
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta, timezone
+from enum import Enum
+from typing import TYPE_CHECKING
+from urllib.parse import urlparse
+
+from pyiceberg.utils.concurrent import ExecutorFactory
+from pyiceberg.utils.properties import property_as_bool
+
+if TYPE_CHECKING:
+    from pyiceberg.io import FileEntry
+    from pyiceberg.table import Table
+
+logger = logging.getLogger(__name__)
+
+
+class PrefixMismatchMode(str, Enum):
+    """How to treat listed files whose URI scheme or authority differs from 
the referenced file.
+
+    Files may match a referenced path component-for-component but be served 
through a different
+    scheme (s3 vs s3a) or endpoint authority. Use ``equal_schemes`` / 
``equal_authorities`` to
+    declare equivalences; this mode chooses what to do with anything that 
remains ambiguous.
+    """
+
+    ERROR = "ERROR"
+    IGNORE = "IGNORE"
+    DELETE = "DELETE"
+
+
+@dataclass(frozen=True)
+class RemoveOrphanFilesResult:
+    """Outcome of a RemoveOrphanFiles execution."""
+
+    orphan_file_locations: list[str] = field(default_factory=list)
+    deleted_files: list[str] = field(default_factory=list)
+    failed_to_delete: list[str] = field(default_factory=list)
+    total_bytes: int = 0
+
+
+_DEFAULT_OLDER_THAN = timedelta(days=3)
+_DEFAULT_EQUAL_SCHEMES = {"s3a": "s3", "s3n": "s3"}
+
+
+class RemoveOrphanFiles:
+    r"""Builder for the remove-orphan-files action.
+
+    Usage::
+
+        result = table.maintenance.remove_orphan_files() \
+            .older_than(datetime.now(tz=timezone.utc) - timedelta(days=7)) \
+            .execute()
+    """
+
+    _table: Table
+    _location: str | None
+    _older_than_ms: int
+    _dry_run: bool
+    _delete_with: Callable[[str], None] | None
+    _max_concurrency: int | None
+    _prefix_mismatch_mode: PrefixMismatchMode
+    _equal_schemes: dict[str, str]
+    _equal_authorities: dict[str, str]
+    _compare_to_file_list: Iterable[tuple[str, datetime]] | None
+
+    def __init__(self, table: Table) -> None:
+        self._table = table
+        self._location = None
+        self._older_than_ms = _now_ms() - 
int(_DEFAULT_OLDER_THAN.total_seconds() * 1000)
+        self._dry_run = False
+        self._delete_with = None
+        self._max_concurrency = None
+        self._prefix_mismatch_mode = PrefixMismatchMode.ERROR
+        self._equal_schemes = dict(_DEFAULT_EQUAL_SCHEMES)
+        self._equal_authorities = {}
+        self._compare_to_file_list = None
+
+    def location(self, location: str) -> RemoveOrphanFiles:
+        """Restrict the scan to a specific location. Defaults to the table's 
root location."""
+        self._location = location
+        return self
+
+    def older_than(self, value: datetime | timedelta) -> RemoveOrphanFiles:
+        """Only consider files modified strictly before this point.
+
+        Accepts either an absolute datetime or a timedelta interpreted as 
"files older
+        than this much" relative to now. Defaults to 3 days ago.
+        """
+        if isinstance(value, timedelta):
+            self._older_than_ms = _now_ms() - int(value.total_seconds() * 1000)
+        else:
+            if value.tzinfo is None:
+                value = value.replace(tzinfo=timezone.utc)
+            self._older_than_ms = int(value.timestamp() * 1000)
+        return self
+
+    def dry_run(self, enabled: bool = True) -> RemoveOrphanFiles:
+        """When enabled, identify orphans but do not delete them."""
+        self._dry_run = enabled
+        return self
+
+    def delete_with(self, delete_func: Callable[[str], None]) -> 
RemoveOrphanFiles:
+        """Use a custom deleter instead of FileIO.delete.
+
+        Useful for dry runs that collect orphans, or for routing deletes 
through a
+        different sink.
+        """
+        self._delete_with = delete_func
+        return self
+
+    def max_concurrency(self, max_workers: int) -> RemoveOrphanFiles:

Review Comment:
   Yep, great call. Fixed!



##########
pyiceberg/table/maintenance/orphan_files.py:
##########
@@ -0,0 +1,414 @@
+# 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.
+"""Action that removes files from storage that are not reachable from table 
metadata.
+
+Lists the table's storage location, computes the set of files referenced by 
any valid
+snapshot or metadata file, and deletes the difference.
+
+Only acts on files older than 3 days by default.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from collections.abc import Callable, Iterable
+from concurrent.futures import as_completed
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta, timezone
+from enum import Enum
+from typing import TYPE_CHECKING
+from urllib.parse import urlparse
+
+from pyiceberg.utils.concurrent import ExecutorFactory
+from pyiceberg.utils.properties import property_as_bool
+
+if TYPE_CHECKING:
+    from pyiceberg.io import FileEntry
+    from pyiceberg.table import Table
+
+logger = logging.getLogger(__name__)
+
+
+class PrefixMismatchMode(str, Enum):
+    """How to treat listed files whose URI scheme or authority differs from 
the referenced file.
+
+    Files may match a referenced path component-for-component but be served 
through a different
+    scheme (s3 vs s3a) or endpoint authority. Use ``equal_schemes`` / 
``equal_authorities`` to
+    declare equivalences; this mode chooses what to do with anything that 
remains ambiguous.
+    """
+
+    ERROR = "ERROR"
+    IGNORE = "IGNORE"
+    DELETE = "DELETE"
+
+
+@dataclass(frozen=True)
+class RemoveOrphanFilesResult:
+    """Outcome of a RemoveOrphanFiles execution."""
+
+    orphan_file_locations: list[str] = field(default_factory=list)
+    deleted_files: list[str] = field(default_factory=list)
+    failed_to_delete: list[str] = field(default_factory=list)
+    total_bytes: int = 0
+
+
+_DEFAULT_OLDER_THAN = timedelta(days=3)
+_DEFAULT_EQUAL_SCHEMES = {"s3a": "s3", "s3n": "s3"}
+
+
+class RemoveOrphanFiles:
+    r"""Builder for the remove-orphan-files action.
+
+    Usage::
+
+        result = table.maintenance.remove_orphan_files() \
+            .older_than(datetime.now(tz=timezone.utc) - timedelta(days=7)) \
+            .execute()
+    """
+
+    _table: Table
+    _location: str | None
+    _older_than_ms: int
+    _dry_run: bool
+    _delete_with: Callable[[str], None] | None
+    _max_concurrency: int | None
+    _prefix_mismatch_mode: PrefixMismatchMode
+    _equal_schemes: dict[str, str]
+    _equal_authorities: dict[str, str]
+    _compare_to_file_list: Iterable[tuple[str, datetime]] | None
+
+    def __init__(self, table: Table) -> None:
+        self._table = table
+        self._location = None
+        self._older_than_ms = _now_ms() - 
int(_DEFAULT_OLDER_THAN.total_seconds() * 1000)
+        self._dry_run = False
+        self._delete_with = None
+        self._max_concurrency = None
+        self._prefix_mismatch_mode = PrefixMismatchMode.ERROR
+        self._equal_schemes = dict(_DEFAULT_EQUAL_SCHEMES)
+        self._equal_authorities = {}
+        self._compare_to_file_list = None
+
+    def location(self, location: str) -> RemoveOrphanFiles:
+        """Restrict the scan to a specific location. Defaults to the table's 
root location."""
+        self._location = location
+        return self
+
+    def older_than(self, value: datetime | timedelta) -> RemoveOrphanFiles:
+        """Only consider files modified strictly before this point.
+
+        Accepts either an absolute datetime or a timedelta interpreted as 
"files older
+        than this much" relative to now. Defaults to 3 days ago.
+        """
+        if isinstance(value, timedelta):
+            self._older_than_ms = _now_ms() - int(value.total_seconds() * 1000)
+        else:
+            if value.tzinfo is None:
+                value = value.replace(tzinfo=timezone.utc)
+            self._older_than_ms = int(value.timestamp() * 1000)
+        return self
+
+    def dry_run(self, enabled: bool = True) -> RemoveOrphanFiles:
+        """When enabled, identify orphans but do not delete them."""
+        self._dry_run = enabled
+        return self
+
+    def delete_with(self, delete_func: Callable[[str], None]) -> 
RemoveOrphanFiles:
+        """Use a custom deleter instead of FileIO.delete.
+
+        Useful for dry runs that collect orphans, or for routing deletes 
through a
+        different sink.
+        """
+        self._delete_with = delete_func
+        return self
+
+    def max_concurrency(self, max_workers: int) -> RemoveOrphanFiles:
+        """Override the worker count for manifest reads and deletes."""
+        if max_workers <= 0:
+            raise ValueError(f"max_concurrency must be positive, got 
{max_workers}")
+        self._max_concurrency = max_workers
+        return self
+
+    def prefix_mismatch_mode(self, mode: PrefixMismatchMode) -> 
RemoveOrphanFiles:
+        """Set how to handle scheme/authority mismatches between listed and 
referenced files."""
+        self._prefix_mismatch_mode = mode
+        return self
+
+    def equal_schemes(self, schemes: dict[str, str]) -> RemoveOrphanFiles:
+        """Declare schemes that should be considered equivalent.
+
+        Keys may be comma-separated lists of schemes that map to the canonical 
value, e.g.
+        ``{"s3a,s3n": "s3"}``. Extends (not replaces) the default mapping.
+        """
+        self._equal_schemes = dict(_DEFAULT_EQUAL_SCHEMES)
+        self._equal_schemes.update(_flatten_mapping(schemes))
+        return self
+
+    def equal_authorities(self, authorities: dict[str, str]) -> 
RemoveOrphanFiles:
+        """Declare authorities (host[:port]) that should be considered 
equivalent.
+
+        Keys may be comma-separated lists.
+        """
+        self._equal_authorities = _flatten_mapping(authorities)
+        return self
+
+    def compare_to_file_list(self, files: Iterable[tuple[str, datetime]]) -> 
RemoveOrphanFiles:
+        """Skip the storage listing step and use the provided ``(path, 
last_modified)`` pairs.
+
+        Useful when a caller has already enumerated storage (e.g. from an 
external inventory).
+        The same ``location`` and ``older_than`` filters still apply.
+        """
+        self._compare_to_file_list = files
+        return self
+
+    def execute(self) -> RemoveOrphanFilesResult:
+        """Run the action and return the result."""
+        properties = self._table.metadata.properties
+        if not property_as_bool(properties, "gc.enabled", True):
+            raise ValueError(
+                "Cannot remove orphan files: gc.enabled is false on this table 
"
+                "(deleting files may corrupt other tables that reference them)"
+            )
+
+        scan_location = self._location or self._table.metadata.location
+
+        referenced = self._collect_referenced_files()
+
+        candidates = self._collect_candidate_files(scan_location)
+        orphans, conflicts = _find_orphans(
+            candidates,
+            referenced,
+            self._equal_schemes,
+            self._equal_authorities,
+            self._prefix_mismatch_mode,
+        )
+
+        if conflicts and self._prefix_mismatch_mode == 
PrefixMismatchMode.ERROR:
+            raise ValueError(
+                "Unable to determine whether certain files are orphan. 
Metadata references "
+                "files that match listed files except for authority/scheme. 
Resolve by passing "
+                "equal_schemes() / equal_authorities(), or set 
prefix_mismatch_mode to IGNORE or "
+                f"DELETE. Conflicting prefixes: {sorted(conflicts)}"
+            )
+
+        total_bytes = sum(size for _, size in orphans)
+        orphan_locations = [path for path, _ in orphans]
+
+        if self._dry_run:
+            return RemoveOrphanFilesResult(
+                orphan_file_locations=orphan_locations,
+                deleted_files=[],
+                failed_to_delete=[],
+                total_bytes=total_bytes,
+            )
+
+        deleted, failed = self._delete_files(orphan_locations)
+        return RemoveOrphanFilesResult(
+            orphan_file_locations=orphan_locations,
+            deleted_files=deleted,
+            failed_to_delete=failed,
+            total_bytes=total_bytes,
+        )
+
+    def _collect_referenced_files(self) -> set[str]:
+        """Build the full set of file paths reachable from the table's current 
metadata."""

Review Comment:
   Yeah, we can do that. It's much cleaner. Fixed.



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