-
Notifications
You must be signed in to change notification settings - Fork 588
Support rewrite_manifests table maintenance #3631
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
moomindani
wants to merge
12
commits into
apache:main
Choose a base branch
from
moomindani:moomindani/rewrite-manifests
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
919f598
Support rewrite_manifests table maintenance
moomindani e00c634
Address review: skip the commit when no manifests need merging
moomindani 59d98ff
Rename the interop test to avoid a duplicate module name
moomindani 4b586f7
Fix mypy type narrowing in sequence number preservation test
moomindani d799ef9
Make the target-size grouping test robust to manifest size variation
moomindani dd05200
Use the default Spark catalog in the interop test, matching other int…
moomindani d46350b
Docs: Document rewrite_manifests in the table maintenance section
moomindani 928e59a
feat: add rewrite_if predicate to RewriteManifests
hedger9487 85375d4
fix(table): avoid writing empty manifest for fully-deleted manifests …
hedger9487 a47f58f
Docs: Document the rewrite_if predicate of rewrite_manifests
moomindani 1a7ab16
Rename the rewrite_if predicate field to avoid shadowing _SnapshotPro…
moomindani cadafef
Replan the manifest rewrite on commit retry and align rewrites_needed…
moomindani File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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]: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should check that the manifest rewrites preserve every active file. Java does this. I think this would be the best place to that. In general, we should validate as much as we can. If we write data, we should have some run-time assumptions about how valid the data is. |
||
| if self._computed_manifests is not None: | ||
| return self._computed_manifests | ||
|
|
||
| snapshot = self._transaction.table_metadata.snapshot_by_name(self._target_branch or MAIN_BRANCH) | ||
| if snapshot is None: | ||
| self._computed_manifests = [] | ||
| return self._computed_manifests | ||
|
|
||
| data_manifests_by_spec: defaultdict[int, list[ManifestFile]] = defaultdict(list) | ||
| kept_manifests: list[ManifestFile] = [] | ||
| for manifest in snapshot.manifests(self._io): | ||
| if manifest.content == ManifestContent.DATA and ( | ||
| self._manifest_predicate is None or self._manifest_predicate(manifest) | ||
| ): | ||
| data_manifests_by_spec[manifest.partition_spec_id].append(manifest) | ||
| else: | ||
| kept_manifests.append(manifest) | ||
|
|
||
| new_manifests: list[ManifestFile] = [] | ||
| for spec_id, manifests in data_manifests_by_spec.items(): | ||
| for group in self._group_by_target_size(manifests): | ||
| if len(group) == 1 and self._manifest_predicate is None: | ||
| # nothing to merge and no predicate specified; keep the manifest as-is | ||
| kept_manifests.append(group[0]) | ||
| continue | ||
|
|
||
| entries = (entry for manifest in group for entry in manifest.fetch_manifest_entry(self._io, discard_deleted=True)) | ||
| first_entry = next(entries, None) | ||
| if first_entry is None: | ||
| kept_manifests.extend(group) | ||
| continue | ||
|
|
||
| with self.new_manifest_writer(self.spec(spec_id)) as writer: | ||
| for entry in itertools.chain([first_entry], entries): | ||
| writer.existing(entry) | ||
| self._entries_processed += 1 | ||
|
|
||
| new_manifests.append(writer.to_manifest_file()) | ||
| self._created_count += 1 | ||
| self._rewritten_count += len(group) | ||
|
|
||
| self._kept_count = len(kept_manifests) | ||
| self.snapshot_properties = { | ||
| **self.snapshot_properties, | ||
| "manifests-created": str(self._created_count), | ||
| "manifests-kept": str(self._kept_count), | ||
| "manifests-replaced": str(self._rewritten_count), | ||
| "entries-processed": str(self._entries_processed), | ||
| } | ||
| self._computed_manifests = new_manifests + kept_manifests | ||
| return self._computed_manifests | ||
|
|
||
| def _refresh_for_retry(self) -> None: | ||
| """Reset state for a retry attempt, discarding the plan built from the stale branch head.""" | ||
| super()._refresh_for_retry() | ||
| # The plan and its counters depend on the branch head, which changes on retry. Keeping them | ||
| # would rebuild the replacement snapshot from the manifests of the superseded snapshot, | ||
| # dropping whatever was committed concurrently. | ||
| self._computed_manifests = None | ||
| self._rewritten_count = 0 | ||
| self._created_count = 0 | ||
| self._kept_count = 0 | ||
| self._entries_processed = 0 | ||
|
|
||
| def _commit(self) -> UpdatesAndRequirements: | ||
| self._existing_manifests() | ||
| if self._created_count == 0: | ||
| # nothing was merged; committing would only produce a pointless replace snapshot | ||
| return (), () | ||
| return super()._commit() | ||
|
|
||
| def rewrites_needed(self) -> bool: | ||
| """Return whether committing would rewrite any manifest. | ||
|
|
||
| This mirrors the grouping that `_existing_manifests` performs, so a snapshot whose data | ||
| manifests all end up kept as-is reports False. A predicate that matches only manifests | ||
| holding no live entries still reports True, because deciding that requires reading them. | ||
| """ | ||
| snapshot = self._transaction.table_metadata.snapshot_by_name(self._target_branch or MAIN_BRANCH) | ||
| if snapshot is None: | ||
| return False | ||
|
|
||
| data_manifests_by_spec: defaultdict[int, list[ManifestFile]] = defaultdict(list) | ||
| for manifest in snapshot.manifests(self._io): | ||
| if manifest.content == ManifestContent.DATA and ( | ||
| self._manifest_predicate is None or self._manifest_predicate(manifest) | ||
| ): | ||
| data_manifests_by_spec[manifest.partition_spec_id].append(manifest) | ||
|
|
||
| return any( | ||
| len(group) > 1 or self._manifest_predicate is not None | ||
| for manifests in data_manifests_by_spec.values() | ||
| for group in self._group_by_target_size(manifests) | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| # 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. | ||
| # pylint:disable=redefined-outer-name | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| import pyarrow as pa | ||
| import pytest | ||
|
|
||
| from pyiceberg.catalog import Catalog | ||
| from pyiceberg.exceptions import NoSuchTableError | ||
| from pyiceberg.manifest import ManifestContent | ||
|
|
||
| if TYPE_CHECKING: | ||
| from pyspark.sql import SparkSession | ||
|
|
||
|
|
||
| @pytest.mark.integration | ||
| def test_spark_reads_table_after_rewrite_manifests(session_catalog: Catalog, spark: "SparkSession") -> None: | ||
| identifier = "default.test_rewrite_manifests_interop" | ||
| try: | ||
| session_catalog.drop_table(identifier) | ||
| except NoSuchTableError: | ||
| pass | ||
|
|
||
| table = session_catalog.create_table(identifier, schema=pa.schema([pa.field("id", pa.int64())])) | ||
| for i in range(3): | ||
| table.append(pa.table({"id": pa.array([i * 3 + 1, i * 3 + 2, i * 3 + 3], type=pa.int64())})) | ||
|
|
||
| table = session_catalog.load_table(identifier) | ||
| snapshot = table.current_snapshot() | ||
| assert snapshot is not None | ||
| assert len([m for m in snapshot.manifests(table.io) if m.content == ManifestContent.DATA]) == 3 | ||
|
|
||
| table.maintenance.rewrite_manifests().commit() | ||
|
|
||
| table = session_catalog.load_table(identifier) | ||
| snapshot = table.current_snapshot() | ||
| assert snapshot is not None | ||
| assert len([m for m in snapshot.manifests(table.io) if m.content == ManifestContent.DATA]) == 1 | ||
|
|
||
| # Spark must read the rewritten table with the same data | ||
| spark_rows = spark.table(f"{identifier}").collect() | ||
| assert sorted(row.id for row in spark_rows) == list(range(1, 10)) | ||
|
|
||
| # Spark must see the replace snapshot and the preserved data files | ||
| snapshots = spark.sql(f"SELECT operation FROM {identifier}.snapshots ORDER BY committed_at").collect() | ||
| assert [row.operation for row in snapshots] == ["append", "append", "append", "replace"] | ||
|
|
||
| files = spark.sql(f"SELECT file_path FROM {identifier}.files").collect() | ||
| assert len(files) == 3 | ||
|
|
||
| # Spark sees the same manifest consolidation | ||
| manifests = spark.sql(f"SELECT path FROM {identifier}.manifests").collect() | ||
| assert len(manifests) == 1 | ||
|
|
||
| # time travel to the pre-rewrite snapshot still works from Spark | ||
| previous_snapshot_id = snapshot.parent_snapshot_id | ||
| assert previous_snapshot_id is not None | ||
| previous_rows = spark.sql(f"SELECT id FROM {identifier} VERSION AS OF {previous_snapshot_id}").collect() | ||
| assert sorted(row.id for row in previous_rows) == list(range(1, 10)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've got some concerns around concurrency.
Some of the classes override
SnapshotProducer._validate_concurrencyto remove all validation. I think we want to do the same thing here.