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

# Position deletes and deletion vectors usually have no stats on the data columns, so also prune by partition:
# 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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nothing covers a delete file written under an older spec: with table.spec() here, tests/table still passes. A test that changes the spec (say identity on category to bucket on value) and then commits a delete under the old spec in another partition would pin it.

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
95 changes: 93 additions & 2 deletions tests/table/test_commit_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -568,11 +568,17 @@ def test_file_overwrite_validates_concurrent_file_delete(


def commit_partition_position_delete(
table: Table, partition: Record, file_path: str, pos: int, row: dict[str, Any] | None = None
table: Table,
partition: Record,
file_path: str,
pos: int,
row: dict[str, Any] | None = None,
spec_id: int | None = None,
) -> None:
"""PyIceberg cannot write delete files, so commit one without path bounds, as other engines write them.

If ``row`` is given, it is stored as the deleted row, which gives the delete file bounds on the data columns.
``spec_id`` defaults to the current spec.
"""
import pyarrow as pa
import pyarrow.parquet as pq
Expand Down Expand Up @@ -613,7 +619,7 @@ def new_delete_manifest_writer(producer: _OverwriteFiles, spec: PartitionSpec) -
file_size_in_bytes=len(table.io.new_input(delete_path)),
lower_bounds=bounds,
upper_bounds=bounds,
spec_id=table.spec().spec_id,
spec_id=table.spec().spec_id if spec_id is None else spec_id,
)

with patch.object(_OverwriteFiles, "new_manifest_writer", new_delete_manifest_writer):
Expand Down Expand Up @@ -682,6 +688,91 @@ 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 test_partition_filtered_write_validates_concurrent_position_delete_under_older_spec(catalog: Catalog) -> None:
"""A delete file written under an older spec is scoped by that spec's partition, not the current one."""
import pyarrow as pa

from pyiceberg.partitioning import PartitionField, PartitionSpec
from pyiceberg.transforms import BucketTransform, 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 delete_partition, expect_conflict in (("a", True), ("b", False)):
identifier = f"default.concurrent_position_delete_older_spec_{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]}))
old_spec_id = table.spec().spec_id
target_file = next(task.file for task in table.scan().plan_files() if task.file.partition[0] == delete_partition)

with table.update_spec() as update:
update.remove_field("category")
update.add_field("value", BucketTransform(4), "value_bucket")
assert table.spec().spec_id != old_spec_id

writing_table = catalog.load_table(identifier)

# Another engine commits a delete of a file written under the older identity spec.
commit_partition_position_delete(table, Record(delete_partition), target_file.file_path, pos=0, spec_id=old_spec_id)

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

writing_table.delete("category == 'a'")
assert sorted(catalog.load_table(identifier).scan().to_arrow()["value"].to_pylist()) == [4]


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
Loading