This is an automated email from the ASF dual-hosted git repository. XiaoHongbo-Hope pushed a commit to branch release-2.1 in repository https://gitbox.apache.org/repos/asf/paimon.git
commit c86035326b55e0f37951dae0328d15e0a107f14b Author: Jingsong Lee <[email protected]> AuthorDate: Mon Nov 9 22:04:27 2026 +0800 [python] Align table rollback with Java (#11049) --- .../pypaimon/changelog/changelog_manager.py | 39 +++++---- .../pypaimon/snapshot/snapshot_manager.py | 18 +++-- paimon-python/pypaimon/table/file_store_table.py | 72 +++++------------ paimon-python/pypaimon/table/rollback_helper.py | 93 +++++++++------------- .../pypaimon/tests/rest/rollback_protocol_test.py | 9 ++- .../pypaimon/tests/table/simple_table_test.py | 45 ++++++++++- 6 files changed, 143 insertions(+), 133 deletions(-) diff --git a/paimon-python/pypaimon/changelog/changelog_manager.py b/paimon-python/pypaimon/changelog/changelog_manager.py index 7f717828e2..f0851a2740 100644 --- a/paimon-python/pypaimon/changelog/changelog_manager.py +++ b/paimon-python/pypaimon/changelog/changelog_manager.py @@ -55,7 +55,12 @@ class ChangelogManager: The latest changelog ID, or None if not found """ try: - return self._find_latest_hint_id(self.changelog_directory()) + latest = self._find_latest_hint_id(self.changelog_directory()) + if (latest is not None and latest > 0 + and self.long_lived_changelog_exists(latest) + and not self.long_lived_changelog_exists(latest + 1)): + return latest + return max(self.list_changelog_ids(), default=None) except Exception as e: raise RuntimeError("Failed to find latest changelog id") from e @@ -66,7 +71,10 @@ class ChangelogManager: The earliest changelog ID, or None if not found """ try: - return self._find_earliest_hint_id(self.changelog_directory()) + earliest = self._find_earliest_hint_id(self.changelog_directory()) + if earliest is not None and self.long_lived_changelog_exists(earliest): + return earliest + return min(self.list_changelog_ids(), default=None) except Exception as e: raise RuntimeError("Failed to find earliest changelog id") from e @@ -174,7 +182,7 @@ class ChangelogManager: Yields: Changelog instances in ascending order of ID """ - for snapshot_id in self._list_changelog_ids(): + for snapshot_id in self.list_changelog_ids(): yield self.changelog(snapshot_id) def safely_get_all_changelogs(self) -> List[Changelog]: @@ -186,7 +194,12 @@ class ChangelogManager: Returns: List of Changelog instances (may include None for failed reads) """ - paths = [self.long_lived_changelog_path(sid) for sid in self._list_changelog_ids()] + try: + changelog_ids = self.list_changelog_ids() + except Exception as e: + logger.warning(f"Failed to list changelog files: {e}") + return [] + paths = [self.long_lived_changelog_path(sid) for sid in changelog_ids] changelogs: List[Optional[Changelog]] = [None] * len(paths) def read_changelog(index: int, path: str): @@ -233,7 +246,7 @@ class ChangelogManager: """ return BranchManager.branch_path(self.table_path, self.branch) - def _list_changelog_ids(self) -> List[int]: + def list_changelog_ids(self) -> List[int]: """List all changelog IDs in the changelog directory. Returns: @@ -244,16 +257,14 @@ class ChangelogManager: try: file_infos = self.file_io.list_status(self.changelog_directory()) - for file_info in file_infos: - filename = file_info.path.split('/')[-1] - match = pattern.match(filename) - if match: - changelog_id = int(match.group(1)) - changelog_ids.append(changelog_id) - except Exception as e: - logger.warning(f"Failed to list changelog files: {e}") + except FileNotFoundError: return [] + for file_info in file_infos: + filename = file_info.path.split('/')[-1] + match = pattern.match(filename) + if match: + changelog_ids.append(int(match.group(1))) return sorted(changelog_ids) def _find_latest_hint_id(self, directory: str) -> Optional[int]: @@ -308,7 +319,7 @@ class ChangelogManager: directory: Directory to write hint file """ latest_file = f"{directory}/LATEST" - self.file_io.write_file(latest_file, str(snapshot_id), False) + self.file_io.overwrite_file_utf8(latest_file, str(snapshot_id)) def _commit_earliest_hint(self, snapshot_id: int, directory: str) -> None: """Commit the earliest hint file. diff --git a/paimon-python/pypaimon/snapshot/snapshot_manager.py b/paimon-python/pypaimon/snapshot/snapshot_manager.py index 2fc1438f56..76992b3384 100644 --- a/paimon-python/pypaimon/snapshot/snapshot_manager.py +++ b/paimon-python/pypaimon/snapshot/snapshot_manager.py @@ -297,6 +297,15 @@ class SnapshotManager: cleaned them) are skipped silently, so the result reflects only snapshots that can still be inspected. """ + snapshots: List[Snapshot] = [] + for snapshot_id in self.list_snapshot_ids(): + snapshot = self.get_snapshot_by_id(snapshot_id) + if snapshot is not None: + snapshots.append(snapshot) + return snapshots + + def list_snapshot_ids(self) -> List[int]: + """List persisted snapshot IDs in ascending order.""" import re if not self.file_io.exists(self.snapshot_dir): @@ -313,14 +322,7 @@ class SnapshotManager: match = pattern.match(name) if match: ids.append(int(match.group(1))) - ids.sort() - - snapshots: List[Snapshot] = [] - for snapshot_id in ids: - snapshot = self.get_snapshot_by_id(snapshot_id) - if snapshot is not None: - snapshots.append(snapshot) - return snapshots + return sorted(ids) def later_or_equal_watermark(self, watermark: int) -> Optional[Snapshot]: """ diff --git a/paimon-python/pypaimon/table/file_store_table.py b/paimon-python/pypaimon/table/file_store_table.py index 76f2d019a1..c7507b1971 100644 --- a/paimon-python/pypaimon/table/file_store_table.py +++ b/paimon-python/pypaimon/table/file_store_table.py @@ -223,8 +223,8 @@ class FileStoreTable(Table): - int: rollback to the snapshot with that ID - str: rollback to the tag with that name - First tries catalog-based rollback (e.g., REST). If catalog rollback - is not available, falls back to local file cleanup. + Catalogs that provide rollback handle the entire operation. Tables + without catalog rollback clean up their filesystem metadata directly. Args: target: Snapshot ID (int) or tag name (str). @@ -232,35 +232,25 @@ class FileStoreTable(Table): Raises: ValueError: If the target doesn't exist or type is unsupported. """ - if isinstance(target, int): - self._rollback_to_snapshot(target) - elif isinstance(target, str): - self._rollback_to_tag(target) - else: - raise ValueError("Unsupported rollback target type: {}".format(type(target))) - - def _rollback_to_snapshot(self, snapshot_id): - """Rollback to a snapshot by ID. - - First tries catalog-based rollback. If not available, falls back to - local file cleanup. If the snapshot file has been expired, tries to - recover from a tag with the same snapshot ID. - - Args: - snapshot_id: The snapshot ID to rollback to. - - Raises: - ValueError: If the snapshot doesn't exist. - """ from pypaimon.table.instant import Instant + if not isinstance(target, (int, str)): + raise ValueError("Unsupported rollback target type: {}".format(type(target))) + table_rollback = self.catalog_environment.catalog_table_rollback() if table_rollback is not None: - table_rollback.rollback_to(Instant.snapshot(snapshot_id)) + instant = Instant.snapshot(target) if isinstance(target, int) else Instant.tag(target) + table_rollback.rollback_to(instant) return - snapshot_mgr = self.snapshot_manager() - snapshot = snapshot_mgr.get_snapshot_by_id(snapshot_id) + if isinstance(target, int): + self._rollback_to_snapshot(target) + else: + tag = self.tag_manager().get_or_throw(target) + self._rollback_to_tagged_snapshot(tag.trim_to_snapshot()) + + def _rollback_to_snapshot(self, snapshot_id): + snapshot = self.snapshot_manager().get_snapshot_by_id(snapshot_id) if snapshot is not None: self.rollback_helper().clean_larger_than(snapshot) return @@ -268,36 +258,14 @@ class FileStoreTable(Table): tag_mgr = self.tag_manager() for tag_name in tag_mgr.list_tags(): tag = tag_mgr.get(tag_name) - if tag is not None: - tag_snapshot = tag.trim_to_snapshot() - if tag_snapshot.id == snapshot_id: - self.rollback_to(tag_name) - return + if tag is not None and tag.id == snapshot_id: + self._rollback_to_tagged_snapshot(tag.trim_to_snapshot()) + return raise ValueError( "Rollback snapshot '{}' doesn't exist.".format(snapshot_id)) - def _rollback_to_tag(self, tag_name): - """Rollback to a tag by name. - - First tries catalog-based rollback. If not available, falls back to - local file cleanup and recreates the snapshot file if needed. - - Args: - tag_name: The tag name to rollback to. - - Raises: - ValueError: If the tag doesn't exist. - """ - from pypaimon.table.instant import Instant - - table_rollback = self.catalog_environment.catalog_table_rollback() - if table_rollback is not None: - table_rollback.rollback_to(Instant.tag(tag_name)) - return - - tag_mgr = self.tag_manager() - tagged_snapshot = tag_mgr.get_or_throw(tag_name).trim_to_snapshot() + def _rollback_to_tagged_snapshot(self, tagged_snapshot): helper = self.rollback_helper() helper.clean_larger_than(tagged_snapshot) helper.create_snapshot_file_if_needed(tagged_snapshot) @@ -306,7 +274,7 @@ class FileStoreTable(Table): """Create a RollbackHelper instance for this table.""" from pypaimon.table.rollback_helper import RollbackHelper return RollbackHelper( - self.snapshot_manager(), self.tag_manager(), self.file_io) + self.snapshot_manager(), self.changelog_manager(), self.tag_manager(), self.file_io) def rollback_to_timestamp(self, timestamp_millis: int) -> None: """Rollback table to the latest snapshot with commit time <= the given timestamp. diff --git a/paimon-python/pypaimon/table/rollback_helper.py b/paimon-python/pypaimon/table/rollback_helper.py index 889bc991e5..a36baa32ae 100644 --- a/paimon-python/pypaimon/table/rollback_helper.py +++ b/paimon-python/pypaimon/table/rollback_helper.py @@ -15,68 +15,56 @@ # specific language governing permissions and limitations # under the License. -import logging +from bisect import bisect_right from pypaimon.common.json_util import JSON -logger = logging.getLogger(__name__) - class RollbackHelper: - """Helper class for table rollback including utils to clean snapshots. - """ - - def __init__(self, snapshot_manager, tag_manager, file_io): - """Initialize RollbackHelper. + """Clean filesystem metadata during table rollback.""" - Args: - snapshot_manager: The SnapshotManager instance. - tag_manager: The TagManager instance. - file_io: The FileIO instance for file operations. - """ + def __init__(self, snapshot_manager, changelog_manager, tag_manager, file_io): self._snapshot_manager = snapshot_manager + self._changelog_manager = changelog_manager self._tag_manager = tag_manager self._file_io = file_io def clean_larger_than(self, retained_snapshot): - """Clean snapshots and tags whose id is larger than the retained snapshot. - - Updates the LATEST hint and removes snapshot files and tag files - for snapshots newer than the retained one. - - Args: - retained_snapshot: The snapshot to retain; everything newer is removed. - """ - latest = self._snapshot_manager.get_latest_snapshot() - if latest is None: - return - - latest_id = latest.id + """Remove snapshot, long-lived changelog, and tag files above the target ID.""" retained_id = retained_snapshot.id + self._clean_snapshots(retained_id) + self._clean_long_lived_changelogs(retained_id) + self._clean_tags(retained_id) + + def _clean_snapshots(self, retained_id): + manager = self._snapshot_manager + # A previous attempt can leave LATEST at the target while newer files + # still exist. List actual IDs so a gap cannot hide those files. + snapshot_ids = manager.list_snapshot_ids() + self._file_io.overwrite_file_utf8(manager.latest_file, str(retained_id)) + for snapshot_id in reversed(snapshot_ids): + if snapshot_id <= retained_id: + break + path = manager.get_snapshot_path(snapshot_id) + if not self._file_io.delete(path) and self._file_io.exists(path): + raise OSError(f"Failed to delete snapshot file {path}") + + def _clean_long_lived_changelogs(self, retained_id): + manager = self._changelog_manager + changelog_ids = manager.list_changelog_ids() + first_removed = bisect_right(changelog_ids, retained_id) + if first_removed == len(changelog_ids): + return + latest = changelog_ids[first_removed - 1] if first_removed else -1 + manager.commit_long_lived_changelog_latest_hint(latest) + for changelog_id in reversed(changelog_ids[first_removed:]): + self._file_io.delete_quietly(manager.long_lived_changelog_path(changelog_id)) - # Update LATEST hint - try: - # Try atomic write first - success = self._file_io.try_to_write_atomic(self._snapshot_manager.latest_file, str(retained_id)) - if not success: - # Fallback to regular write - self._file_io.write_file(self._snapshot_manager.latest_file, str(retained_id), overwrite=True) - except Exception as e: - logger.warning("Failed to update LATEST hint: %s", e) - - # Delete snapshot files larger than retained - for snapshot_id in range(retained_id + 1, latest_id + 1): - snapshot_path = self._snapshot_manager.get_snapshot_path(snapshot_id) - if self._file_io.exists(snapshot_path): - self._file_io.delete(snapshot_path) - - # Clean tags whose snapshot id is larger than retained + def _clean_tags(self, retained_id): for tag_name in self._tag_manager.list_tags(): tag = self._tag_manager.get(tag_name) - if tag is not None: - tag_snapshot = tag.trim_to_snapshot() - if tag_snapshot.id > retained_id: - self._tag_manager.delete_tag(tag_name) + if tag is not None and tag.id > retained_id: + self._file_io.delete_quietly(self._tag_manager.tag_path(tag_name)) def create_snapshot_file_if_needed(self, tagged_snapshot): """Create a snapshot file from a tag if the snapshot file doesn't exist. @@ -89,12 +77,9 @@ class RollbackHelper: """ snapshot_path = self._snapshot_manager.get_snapshot_path(tagged_snapshot.id) if not self._file_io.exists(snapshot_path): + # Update EARLIEST before creating the file so a failed hint write + # leaves the missing snapshot available to restore on retry. + earliest_file = f"{self._snapshot_manager.snapshot_dir}/EARLIEST" + self._file_io.overwrite_file_utf8(earliest_file, str(tagged_snapshot.id)) self._file_io.write_file( snapshot_path, JSON.to_json(tagged_snapshot), overwrite=False) - # The snapshot file is missing because it was expired, so EARLIEST - # still points past it. Move the hint back to the restored snapshot, - # as the Java RollbackHelper does: otherwise, once new commits reach - # the old EARLIEST id, readers treat that id as the earliest snapshot - # and skip the restored snapshot and the commits after it. - earliest_file = "{}/EARLIEST".format(self._snapshot_manager.snapshot_dir) - self._file_io.overwrite_file_utf8(earliest_file, str(tagged_snapshot.id)) diff --git a/paimon-python/pypaimon/tests/rest/rollback_protocol_test.py b/paimon-python/pypaimon/tests/rest/rollback_protocol_test.py index 085d251515..33dddc989d 100644 --- a/paimon-python/pypaimon/tests/rest/rollback_protocol_test.py +++ b/paimon-python/pypaimon/tests/rest/rollback_protocol_test.py @@ -107,7 +107,14 @@ def test_legacy_request_constructor(): (1, {'type': 'snapshot', 'snapshotId': 1}), ('v1', {'type': 'tag', 'tagName': 'v1'}), ]) -def test_table_rollback_transmits_loaded_uuid(table, transport, target, instant): +def test_table_rollback_transmits_loaded_uuid(table, transport, target, instant, monkeypatch): + def unexpected_local_access(): + pytest.fail('REST rollback must not access local snapshot or tag metadata') + + monkeypatch.setattr(table, 'rollback_helper', unexpected_local_access) + monkeypatch.setattr(table, 'tag_manager', unexpected_local_access) + monkeypatch.setattr(table, 'snapshot_manager', unexpected_local_access) + table.rollback_to(target) assert len(transport.requests) == 1 diff --git a/paimon-python/pypaimon/tests/table/simple_table_test.py b/paimon-python/pypaimon/tests/table/simple_table_test.py index 856c4f183c..2270e169dc 100644 --- a/paimon-python/pypaimon/tests/table/simple_table_test.py +++ b/paimon-python/pypaimon/tests/table/simple_table_test.py @@ -19,6 +19,7 @@ import os import shutil import tempfile import unittest +from unittest.mock import patch import pyarrow as pa @@ -625,12 +626,26 @@ class SimpleTableTest(unittest.TestCase): snapshot_mgr = table.snapshot_manager() self.assertEqual(snapshot_mgr.get_latest_snapshot().id, 5) - # Rollback to snapshot 3 + changelog_mgr = table.changelog_manager() + for snapshot_id in (2, 5): + table.file_io.copy_file(snapshot_mgr.get_snapshot_path(snapshot_id), + changelog_mgr.long_lived_changelog_path(snapshot_id)) + changelog_mgr.commit_long_lived_changelog_earliest_hint(2) + changelog_mgr.commit_long_lived_changelog_latest_hint(5) + + # Retry a rollback after LATEST was advanced and a newer snapshot is missing. + table.file_io.overwrite_file_utf8(snapshot_mgr.latest_file, "3") + table.file_io.delete(snapshot_mgr.get_snapshot_path(4)) table.rollback_to(3) self.assertEqual(snapshot_mgr.get_latest_snapshot().id, 3) self.assertIsNone(snapshot_mgr.get_snapshot_by_id(4)) self.assertIsNone(snapshot_mgr.get_snapshot_by_id(5)) + self.assertTrue(changelog_mgr.long_lived_changelog_exists(2)) + self.assertFalse(changelog_mgr.long_lived_changelog_exists(5)) + self.assertEqual(changelog_mgr.latest_long_lived_changelog_id(), 2) + self.assertEqual(table.file_io.read_file_utf8( + f"{changelog_mgr.changelog_directory()}/LATEST"), "2") def test_table_rollback_to_tag(self): """Test table-level rollback to a specific tag.""" @@ -665,14 +680,15 @@ class SimpleTableTest(unittest.TestCase): self.assertEqual(snapshot_mgr.get_latest_snapshot().id, 5) # Rollback to tag v3 - table.rollback_to("v3") + with patch.object(type(tag_mgr), "delete_tag", side_effect=AssertionError( + "Rollback must delete tag files directly")): + table.rollback_to("v3") self.assertEqual(snapshot_mgr.get_latest_snapshot().id, 3) # Tags with snapshot > 3 should be cleaned self.assertFalse(tag_mgr.tag_exists("v4")) self.assertFalse(tag_mgr.tag_exists("v5")) - # Tag v3 should still exist - self.assertTrue(tag_mgr.tag_exists("v3")) + self.assertEqual(sorted(tag_mgr.list_tags()), ["v1", "v2", "v3"]) def test_table_rollback_to_tag_after_snapshot_expired(self): """Rolling back to a tag whose snapshot expired must move EARLIEST back to it.""" @@ -703,12 +719,33 @@ class SimpleTableTest(unittest.TestCase): # directory: their files are gone and EARLIEST points at snapshot 5. # The tag keeps the metadata and data files of snapshot 2. snapshot_mgr = table.snapshot_manager() + changelog_mgr = table.changelog_manager() + for snapshot_id in (3, 4): + table.file_io.copy_file(snapshot_mgr.get_snapshot_path(snapshot_id), + changelog_mgr.long_lived_changelog_path(snapshot_id)) + changelog_mgr.commit_long_lived_changelog_earliest_hint(3) for snapshot_id in range(1, 5): table.file_io.delete(snapshot_mgr.get_snapshot_path(snapshot_id)) earliest_file = "{}/EARLIEST".format(snapshot_mgr.snapshot_dir) table.file_io.overwrite_file_utf8(earliest_file, "5") + overwrite_hint = table.file_io.overwrite_file_utf8 + + def fail_earliest_hint(path, content): + if path == earliest_file: + raise OSError("EARLIEST write failed") + overwrite_hint(path, content) + + with patch.object(table.file_io, "overwrite_file_utf8", side_effect=fail_earliest_hint): + with self.assertRaisesRegex(OSError, "EARLIEST write failed"): + table.rollback_to(2) + table.rollback_to("v2") + self.assertEqual(list(changelog_mgr.changelogs()), []) + self.assertIsNone(changelog_mgr.earliest_long_lived_changelog_id()) + self.assertIsNone(changelog_mgr.latest_long_lived_changelog_id()) + self.assertEqual(table.file_io.read_file_utf8( + f"{changelog_mgr.changelog_directory()}/LATEST"), "-1") for k in range(6, 9): write(k)
