Skip to content

feat: validation_history and ancestors_between #1935

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

Merged
merged 29 commits into from
May 1, 2025
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
beff92b
feat: validation history
jayceslesar Apr 18, 2025
c369720
format
jayceslesar Apr 18, 2025
41bb8a4
almost a working test
jayceslesar Apr 18, 2025
763e9f4
allow content_filter in snapshot.manifests
jayceslesar Apr 18, 2025
f200beb
simplify order of arguments to validation_history
jayceslesar Apr 18, 2025
7f6bf9d
simplify return in snapshot.manifests
jayceslesar Apr 18, 2025
c63cc55
tests passing
jayceslesar Apr 19, 2025
f2f3a88
correct ancestors_between
jayceslesar Apr 19, 2025
74d5569
fix to/from logic and allow optional `to_snapshot` arg in `validation…
jayceslesar Apr 19, 2025
167f9e4
remove a level of nesting with smarter clause
jayceslesar Apr 19, 2025
efe50b4
fix bad accessor
jayceslesar Apr 19, 2025
0793713
fix docstring
jayceslesar Apr 19, 2025
b10a0bf
Merge branch 'main' into feat/validation-history
jayceslesar Apr 19, 2025
d57133e
move `ValidationException` to `exceptions.py`, make `to_snapshot` req…
jayceslesar Apr 22, 2025
6ef1aa2
default to `Operation.OVERWRITE` in `validation_history` if summary i…
jayceslesar Apr 22, 2025
fce608f
preserve order of snapshots by changing response to a list instead of…
jayceslesar Apr 22, 2025
a6624d9
validation_history and from_ancestor argument alignment
jayceslesar Apr 23, 2025
0763056
raise error on summary operation being none in validation_history
jayceslesar Apr 23, 2025
cd0146f
Merge branch 'main' into feat/validation-history
jayceslesar Apr 23, 2025
d7c7088
Merge branch 'main' into feat/validation-history
jayceslesar Apr 24, 2025
fe8d103
Update pyiceberg/table/update/validate.py
jayceslesar Apr 24, 2025
f8c5fee
Update pyiceberg/table/update/validate.py
jayceslesar Apr 24, 2025
d95e6ed
formatting
jayceslesar Apr 24, 2025
87ee601
remove emoji (lol)
jayceslesar Apr 27, 2025
c16a3e6
vix validation exception check
jayceslesar Apr 27, 2025
e272b26
fix bug in ancestors_between
jayceslesar Apr 27, 2025
727845b
break into separate test
jayceslesar Apr 27, 2025
e2bba3f
Merge branch 'main' into feat/validation-history
jayceslesar Apr 27, 2025
a74d7a9
add test that ensures we raise an error
jayceslesar Apr 30, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions pyiceberg/table/snapshots.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,3 +435,16 @@ def ancestors_of(current_snapshot: Optional[Snapshot], table_metadata: TableMeta
if snapshot.parent_snapshot_id is None:
break
snapshot = table_metadata.snapshot_by_id(snapshot.parent_snapshot_id)


def ancestors_between(
to_snapshot: Snapshot, from_snapshot: Optional[Snapshot], table_metadata: TableMetadata
) -> Iterable[Snapshot]:
"""Get the ancestors of and including the given snapshot between the to and from snapshots."""
if from_snapshot is not None:
for snapshot in ancestors_of(to_snapshot, table_metadata):
if snapshot == from_snapshot:
break
yield snapshot
else:
yield from ancestors_of(to_snapshot, table_metadata)
72 changes: 72 additions & 0 deletions pyiceberg/table/update/validate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# 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 Optional

from pyiceberg.manifest import ManifestContent, ManifestFile
from pyiceberg.table import Table
from pyiceberg.table.snapshots import Operation, Snapshot, ancestors_between


class ValidationException(Exception):
"""Raised when validation fails."""


def validation_history(
table: Table,
from_snapshot: Snapshot,
to_snapshot: Optional[Snapshot],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think of making the API a bit more strict and simplify code along the way. I don't think this needs to be Optional:

Suggested change
to_snapshot: Optional[Snapshot],
to_snapshot: Snapshot,

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Fokko I think the existing behavior of the Spark/Java API is for to check all snapshots if the from_snapshot is Optional.

https://github.com/apache/iceberg/blob/main/spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/SparkWriteConf.java#L443-L448

Should we mirror that behavior in PyIceberg, or just require that the validate_from_snapshot_id be specified if isolation_level is not None?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

matching_operations: set[Operation],
manifest_content_filter: ManifestContent,
) -> tuple[list[ManifestFile], set[Snapshot]]:
"""Return newly added manifests and snapshot IDs between the starting snapshot and parent snapshot.

Args:
table: Table to get the history from
from_snapshot: Parent snapshot to get the history from
to_snapshot: Starting snapshot
matching_operations: Operations to match on
manifest_content_filter: Manifest content type to filter

Raises:
ValidationException: If no matching snapshot is found or only one snapshot is found

Returns:
List of manifest files and set of snapshots matching conditions
"""
manifests_files: list[ManifestFile] = []
snapshots: set[Snapshot] = set()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Java just returns ints, we can return Snapshot's as well, but with the set we lose the order.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great, I am happy to remove this being a set, I was just attempting to copy what made sense from java

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now returns a unique list, happy to modify that to allow duplicates if wanted

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, or return Set[int], similar to Java :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__hash__ dunder on Snapshot ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nah, will just return the Set[int]

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__hash__ dunder on Snapshot ?

I like that as well, but let's do that in a separate PR 👍

Now we're back at a set, we can remove the in check below:

        if snapshot not in snapshots:
            snapshots.add(snapshot.snapshot_id)


last_snapshot = None
for snapshot in ancestors_between(from_snapshot, to_snapshot, table.metadata):
last_snapshot = snapshot
summary = snapshot.summary
if summary is None or summary.operation not in matching_operations:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks dangerous to me, I don't think we want to skip over this if the summary is None

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the right thing here is to assume that it is an Overwrite operation

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is a case where summary would ever be None? I can't seem to find any checks against that in the codebase except for https://github.com/apache/iceberg-python/blob/main/pyiceberg/table/snapshots.py#L367 which seems to be checking against an empty dict (well mapping) and should also be checking the or is None case imo

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It now defaults to Operation.OVERWRITE if summary is determined to be None, but still wondering about above

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

summary can be None if the Table format version is v1 according to the Iceberg Spec: https://iceberg.apache.org/spec/#snapshots

Instead of setting it as Operation.OVERWRITE I think an alternative approach is to just throw an exception if summary field is None with a helpful error message that explains that validation_history cannot be generated in the absence of summary fields. Wdyt @Fokko @jayceslesar ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sungwy That would also work for me. We can always see if there are ways to make it work for V1 tables later, however, I'm not sure how big the problem is because most implementations also produce an operation for V1 tables. So, I think we're good with the approach that @sungwy suggests 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good to me, implemented and added to the existing test to assure that we raise an error when that happens. Planning on cleaning up tests in the next MR when I will likely need to make some fixtures & parameterize

continue

snapshots.add(snapshot)
manifests_files.extend(
[
manifest
for manifest in snapshot.manifests(table.io)
if manifest.added_snapshot_id == snapshot.snapshot_id and manifest.content == manifest_content_filter
]
)

if last_snapshot is None or last_snapshot.snapshot_id == from_snapshot.snapshot_id:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if last_snapshot is None or last_snapshot.snapshot_id == from_snapshot.snapshot_id:
if last_snapshot is not None and last_snapshot.snapshot_id != from_snapshot.snapshot_id:
`if not (last_snapshot is not None and last_snapshot.snapshot_id != from_snapshot.snapshot_id):`

The ValidationCheck in java throws an Exception with the provided error message if the boolean condition in doesn't hold. So we'd actually be throwing in the inverse of this condition.

https://github.com/apache/iceberg/blob/22d194f5d685fdf5bec17c6bcc92a69db4ae4957/api/src/main/java/org/apache/iceberg/exceptions/ValidationException.java#L47-L50

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Made this change

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome, changing this to be correct also caught an issue with ancestors_between that is not fixed!

raise ValidationException("No matching snapshot found.")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can leave it like this for now, but it seems odd to throw here, since there is no history to validate, which in turn is valid.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has been fixed!


return manifests_files, snapshots
39 changes: 0 additions & 39 deletions tests/table/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@
Snapshot,
SnapshotLogEntry,
Summary,
ancestors_of,
)
from pyiceberg.table.sorting import (
NullOrder,
Expand Down Expand Up @@ -225,44 +224,6 @@ def test_snapshot_by_timestamp(table_v2: Table) -> None:
assert table_v2.snapshot_as_of_timestamp(1515100955770, inclusive=False) is None


def test_ancestors_of(table_v2: Table) -> None:
assert list(ancestors_of(table_v2.current_snapshot(), table_v2.metadata)) == [
Snapshot(
snapshot_id=3055729675574597004,
parent_snapshot_id=3051729675574597004,
sequence_number=1,
timestamp_ms=1555100955770,
manifest_list="s3://a/b/2.avro",
summary=Summary(Operation.APPEND),
schema_id=1,
),
Snapshot(
snapshot_id=3051729675574597004,
parent_snapshot_id=None,
sequence_number=0,
timestamp_ms=1515100955770,
manifest_list="s3://a/b/1.avro",
summary=Summary(Operation.APPEND),
schema_id=None,
),
]


def test_ancestors_of_recursive_error(table_v2_with_extensive_snapshots: Table) -> None:
# Test RecursionError: maximum recursion depth exceeded
assert (
len(
list(
ancestors_of(
table_v2_with_extensive_snapshots.current_snapshot(),
table_v2_with_extensive_snapshots.metadata,
)
)
)
== 2000
)


def test_snapshot_by_id_does_not_exist(table_v2: Table) -> None:
assert table_v2.snapshot_by_id(-1) is None

Expand Down
68 changes: 67 additions & 1 deletion tests/table/test_snapshots.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,23 @@
# specific language governing permissions and limitations
# under the License.
# pylint:disable=redefined-outer-name,eval-used
from typing import cast

import pytest

from pyiceberg.manifest import DataFile, DataFileContent, ManifestContent, ManifestFile
from pyiceberg.partitioning import PartitionField, PartitionSpec
from pyiceberg.schema import Schema
from pyiceberg.table.snapshots import Operation, Snapshot, SnapshotSummaryCollector, Summary, update_snapshot_summaries
from pyiceberg.table import Table
from pyiceberg.table.snapshots import (
Operation,
Snapshot,
SnapshotSummaryCollector,
Summary,
ancestors_between,
ancestors_of,
update_snapshot_summaries,
)
from pyiceberg.transforms import IdentityTransform
from pyiceberg.typedef import Record
from pyiceberg.types import (
Expand Down Expand Up @@ -333,3 +344,58 @@ def test_invalid_type() -> None:
)

assert "Could not parse summary property total-data-files to an int: abc" in str(e.value)


def test_ancestors_of(table_v2: Table) -> None:
assert list(ancestors_of(table_v2.current_snapshot(), table_v2.metadata)) == [
Snapshot(
snapshot_id=3055729675574597004,
parent_snapshot_id=3051729675574597004,
sequence_number=1,
timestamp_ms=1555100955770,
manifest_list="s3://a/b/2.avro",
summary=Summary(Operation.APPEND),
schema_id=1,
),
Snapshot(
snapshot_id=3051729675574597004,
parent_snapshot_id=None,
sequence_number=0,
timestamp_ms=1515100955770,
manifest_list="s3://a/b/1.avro",
summary=Summary(Operation.APPEND),
schema_id=None,
),
]


def test_ancestors_of_recursive_error(table_v2_with_extensive_snapshots: Table) -> None:
# Test RecursionError: maximum recursion depth exceeded
assert (
len(
list(
ancestors_of(
table_v2_with_extensive_snapshots.current_snapshot(),
table_v2_with_extensive_snapshots.metadata,
)
)
)
== 2000
)


def test_ancestors_between(table_v2_with_extensive_snapshots: Table) -> None:
oldest_snapshot = table_v2_with_extensive_snapshots.snapshots()[0]
current_snapshot = cast(Snapshot, table_v2_with_extensive_snapshots.current_snapshot())
assert (
len(
list(
ancestors_between(
current_snapshot,
oldest_snapshot,
table_v2_with_extensive_snapshots.metadata,
)
)
)
== 1999
)
67 changes: 67 additions & 0 deletions tests/table/test_validate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# 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,eval-used
from typing import cast
from unittest.mock import patch

from pyiceberg.io import FileIO
from pyiceberg.manifest import ManifestContent, ManifestFile
from pyiceberg.table import Table
from pyiceberg.table.snapshots import Operation, Snapshot
from pyiceberg.table.update.validate import validation_history


def test_validation_history(table_v2_with_extensive_snapshots: Table) -> None:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add another test which tests the expected failure when from_snapshot value doesn't match a snapshot in the history of the table?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added!

"""Test the validation history function."""
mock_manifests = {}

for i, snapshot in enumerate(table_v2_with_extensive_snapshots.snapshots()):
mock_manifest = ManifestFile(
manifest_path=f"foo/bar/{i}",
manifest_length=1,
partition_spec_id=1,
content=ManifestContent.DATA if i % 2 == 0 else ManifestContent.DELETES,
sequence_number=1,
min_sequence_number=1,
added_snapshot_id=snapshot.snapshot_id,
)

# Store the manifest for this specific snapshot
mock_manifests[snapshot.snapshot_id] = [mock_manifest]

expected_manifest_data_counts = len([m for m in mock_manifests.values() if m[0].content == ManifestContent.DATA]) - 1

oldest_snapshot = table_v2_with_extensive_snapshots.snapshots()[0]
newest_snapshot = cast(Snapshot, table_v2_with_extensive_snapshots.current_snapshot())

def mock_read_manifest_side_effect(self: Snapshot, io: FileIO) -> list[ManifestFile]:
"""Mock the manifests method to use the snapshot_id for lookup."""
snapshot_id = self.snapshot_id
if snapshot_id in mock_manifests:
return mock_manifests[snapshot_id]
return []

with patch("pyiceberg.table.snapshots.Snapshot.manifests", new=mock_read_manifest_side_effect):
manifests, snapshots = validation_history(
table_v2_with_extensive_snapshots,
newest_snapshot,
oldest_snapshot,
{Operation.APPEND},
ManifestContent.DATA,
)

assert len(manifests) == expected_manifest_data_counts