Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 0 additions & 3 deletions pyiceberg/table/update/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -515,9 +515,6 @@ def _validate_concurrent_changes(self) -> None:
_validate_added_data_files(table, catalog_head, conflict_detection_filter, starting_snapshot, self._case_sensitive)

if self._predicate != AlwaysFalse():
# partition_set is None, so any concurrently committed delete file counts as
# a conflict even in unrelated partitions. Scope this via partition projection
# (as Java does) when delete-file write support lands.
_validate_no_new_delete_files(
table, catalog_head, conflict_detection_filter, None, starting_snapshot, self._case_sensitive
)
Expand Down
27 changes: 24 additions & 3 deletions pyiceberg/table/update/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@
# specific language governing permissions and limitations
# under the License.
from collections import defaultdict
from collections.abc import Iterator
from collections.abc import Callable, Iterator

from pyiceberg.exceptions import ValidationException
from pyiceberg.expressions import BooleanExpression
from pyiceberg.expressions.visitors import ROWS_CANNOT_MATCH, _InclusiveMetricsEvaluator
from pyiceberg.expressions.visitors import (
ROWS_CANNOT_MATCH,
_InclusiveMetricsEvaluator,
expression_evaluator,
inclusive_projection,
)
from pyiceberg.manifest import (
INITIAL_SEQUENCE_NUMBER,
DataFile,
Expand All @@ -32,7 +37,7 @@
from pyiceberg.table import Table
from pyiceberg.table.delete_file_index import DeleteFileIndex
from pyiceberg.table.snapshots import Operation, Snapshot, ancestors_between
from pyiceberg.typedef import Record
from pyiceberg.typedef import KeyDefaultDict, Record

VALIDATE_DATA_FILES_EXIST_OPERATIONS: set[Operation] = {Operation.OVERWRITE, Operation.REPLACE, Operation.DELETE}
VALIDATE_ADDED_DATA_FILES_OPERATIONS: set[Operation] = {Operation.APPEND, Operation.OVERWRITE}
Expand Down Expand Up @@ -294,8 +299,24 @@ def _added_delete_files(

dfi = DeleteFileIndex()

# Delete files have no stats on the data columns, so only the partition can rule them out:
# project the data filter onto each spec, as Java's DeleteFileIndex does.
partition_evaluators: KeyDefaultDict[int, Callable[[Record], bool]] | None = None
if data_filter is not None:
row_filter = data_filter

def _partition_evaluator(spec_id: int) -> Callable[[Record], bool]:
spec = table.specs()[spec_id]
partition_schema = Schema(*spec.partition_type(table.schema()).fields)
projected = inclusive_projection(table.schema(), spec, case_sensitive)(row_filter)
return expression_evaluator(partition_schema, projected, case_sensitive)

partition_evaluators = KeyDefaultDict(_partition_evaluator)

for manifest in manifests:
for entry in manifest.fetch_manifest_entry(table.io, discard_deleted=True):
if partition_evaluators is not None and not partition_evaluators[entry.data_file.spec_id](entry.data_file.partition):
continue
if _filter_manifest_entries(
entry, snapshot_ids, data_filter, partition_set, ManifestEntryStatus.ADDED, table.schema(), case_sensitive
):
Expand Down
45 changes: 45 additions & 0 deletions tests/table/test_commit_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,51 @@ def test_partial_delete_validates_concurrent_delete_outside_the_filter(catalog:
assert catalog.load_table(identifier).scan().to_arrow()["k"].to_pylist() == [1, 3]


def test_partition_filtered_write_validates_concurrent_position_delete_by_partition(catalog: Catalog) -> None:
"""A retried write filtered to one partition must only conflict with a concurrent delete file in that partition."""
import pyarrow as pa

from pyiceberg.partitioning import PartitionField, PartitionSpec
from pyiceberg.transforms import IdentityTransform

catalog.create_namespace("default")
schema = Schema(
NestedField(1, "category", StringType(), required=False),
NestedField(2, "value", LongType(), required=False),
)
spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="category"))

for operation in ("delete", "overwrite"):
for delete_partition, expect_conflict in (("a", True), ("b", False)):
identifier = f"default.concurrent_position_delete_{operation}_{delete_partition}"
table = catalog.create_table(identifier, schema=schema, partition_spec=spec, properties={"format-version": "2"})
table.append(pa.table({"category": ["a", "a", "b", "b"], "value": [1, 2, 3, 4]}))
target_file = next(task.file for task in table.scan().plan_files() if task.file.partition[0] == delete_partition)

writing_table = catalog.load_table(identifier)

# Another engine commits a merge-on-read delete of the first row of the file in `delete_partition`.
commit_partition_position_delete(table, Record(delete_partition), target_file.file_path, pos=0)

if expect_conflict:
with pytest.raises(ValidationException, match="Found new conflicting delete files"):
_write_partition_a(writing_table, operation)
continue

_write_partition_a(writing_table, operation)
expected = [4] if operation == "delete" else [4, 10]
assert sorted(catalog.load_table(identifier).scan().to_arrow()["value"].to_pylist()) == expected, operation


def _write_partition_a(table: Table, operation: str) -> None:
import pyarrow as pa

if operation == "delete":
table.delete("category == 'a'")
else:
table.overwrite(pa.table({"category": ["a"], "value": [10]}), overwrite_filter="category == 'a'")


def test_concurrent_overwrite_append_retries_successfully(catalog: Catalog) -> None:
"""Append after a concurrent overwrite should succeed via retry."""
catalog.create_namespace("default")
Expand Down
1 change: 1 addition & 0 deletions tests/table/test_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,7 @@ def test_added_delete_files_case_insensitive_filter(
content=DataFileContent.POSITION_DELETES,
file_path="s3://dummy/path",
record_count=1,
partition=Record(1),
)
mock_delete_file.spec_id = 0

Expand Down