From b9c51122455658fb315e6b75aa10a65f0e511263 Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Tue, 17 Nov 2026 18:12:01 +0000 Subject: [PATCH 1/3] Only apply position deletes to the data files they are attached to _read_all_delete_files merged the positions of every position delete file in a scan by data file path, so a delete file that also names another data file removed that file's rows, even when the planner had not attached the delete to it (for example an older delete for a file that add_files registered again). Keep, per delete file, only the positions of the data files whose task has it attached, reading each delete file once. Co-authored-by: Isaac --- pyiceberg/io/pyarrow.py | 7 ++++++- tests/io/test_pyarrow.py | 33 +++++++++++++++++++++++++++++ tests/table/test_commit_retry.py | 15 +++++++------ tests/table/test_init.py | 36 +++++++++++++++++++++++++++++++- 4 files changed, 83 insertions(+), 8 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 53db9cd6b7..ebf296792a 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -1884,18 +1884,23 @@ def _read_all_delete_files(io: FileIO, tasks: Iterable[FileScanTask]) -> dict[st deletes_per_file: dict[str, list[ChunkedArray]] = {} # DataFile equality uses only the path; DVs from different tasks may share a file. unique_deletes: dict[_DeleteFileKey, DataFile] = {} + # Data files whose task has the delete file attached; a delete file can also list rows of other data files. + attached_paths: dict[_DeleteFileKey, set[str]] = {} for task in tasks: for delete_file in task.delete_files: key = _DeleteFileKey(delete_file.file_path, delete_file.content_offset, delete_file.content_size_in_bytes) unique_deletes.setdefault(key, delete_file) + attached_paths.setdefault(key, set()).add(task.file.file_path) if len(unique_deletes) > 0: executor = ExecutorFactory.get_or_create() deletes_per_files: Iterator[dict[str, ChunkedArray]] = executor.map( lambda args: _read_deletes(*args), [(io, delete_file) for delete_file in unique_deletes.values()], ) - for delete in deletes_per_files: + for key, delete in zip(unique_deletes, deletes_per_files, strict=True): for file, arr in delete.items(): + if file not in attached_paths[key]: + continue if file in deletes_per_file: deletes_per_file[file].append(arr) else: diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index b0f1cdde37..e1b223e093 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -2253,6 +2253,39 @@ def test_read_all_delete_files_keeps_multiple_dv_content_ranges_for_same_path(tm } +def test_read_all_delete_files_only_loads_positions_for_tasks_it_is_attached_to(tmp_path: Path) -> None: + """A delete file that names rows of two data files only applies to the data files whose task has it attached.""" + first_path, second_path = f"{tmp_path}/data-0.parquet", f"{tmp_path}/data-1.parquet" + old_path, new_path = f"{tmp_path}/old-deletes.parquet", f"{tmp_path}/new-deletes.parquet" + pq.write_table(pa.table({"file_path": [first_path, second_path], "pos": [0, 0]}), old_path) + pq.write_table(pa.table({"file_path": [first_path], "pos": [1]}), new_path) + old_deletes = DataFile.from_args( + content=DataFileContent.POSITION_DELETES, file_path=old_path, file_format=FileFormat.PARQUET, record_count=2 + ) + new_deletes = DataFile.from_args( + content=DataFileContent.POSITION_DELETES, file_path=new_path, file_format=FileFormat.PARQUET, record_count=1 + ) + first_data = DataFile.from_args( + content=DataFileContent.DATA, file_path=first_path, file_format=FileFormat.PARQUET, record_count=10 + ) + second_data = DataFile.from_args( + content=DataFileContent.DATA, file_path=second_path, file_format=FileFormat.PARQUET, record_count=10 + ) + # (delete files attached to the first task, delete files attached to the second task) -> expected positions + shapes = [ + (set(), {old_deletes}, {second_path: [pa.chunked_array([[0]])]}), + ({old_deletes}, {old_deletes}, {first_path: [pa.chunked_array([[0]])], second_path: [pa.chunked_array([[0]])]}), + # The first data file has a newer delete file too; the old one must not add its row 0 to it. + ({new_deletes}, {old_deletes}, {first_path: [pa.chunked_array([[1]])], second_path: [pa.chunked_array([[0]])]}), + ] + for first_task_deletes, second_task_deletes, expected in shapes: + tasks = [ + FileScanTask(data_file=first_data, delete_files=first_task_deletes), + FileScanTask(data_file=second_data, delete_files=second_task_deletes), + ] + assert _read_all_delete_files(PyArrowFileIO(), tasks) == expected + + @pytest.mark.parametrize("selected_indices", [(0, 1, 2, 3, 4, 5), (0, 3, 5)]) @pytest.mark.parametrize("planning_mode", ["local", "rest"]) def test_read_all_delete_files_from_external_packed_deletion_vectors( diff --git a/tests/table/test_commit_retry.py b/tests/table/test_commit_retry.py index 67653be957..deed091d60 100644 --- a/tests/table/test_commit_retry.py +++ b/tests/table/test_commit_retry.py @@ -544,11 +544,13 @@ 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, rows: list[tuple[str, int]], row: dict[str, Any] | 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. + Each ``(file_path, pos)`` in ``rows`` goes into the same delete file, which may name several data files. + If ``row`` is given, it is stored as the deleted row of a single-row delete file, which gives the delete file + bounds on the data columns. """ import pyarrow as pa import pyarrow.parquet as pq @@ -571,7 +573,8 @@ def new_delete_manifest_writer(producer: _OverwriteFiles, spec: PartitionSpec) - spec, producer.schema(), producer.new_manifest_output(), producer._snapshot_id, producer._compression ) - columns: dict[str, list[Any]] = {"file_path": [file_path], "pos": [pos]} + rows = sorted(rows) # the spec requires delete rows sorted by file_path, then pos + columns: dict[str, list[Any]] = {"file_path": [file_path for file_path, _ in rows], "pos": [pos for _, pos in rows]} bounds = None if row is not None: columns["row"] = [row] @@ -585,7 +588,7 @@ def new_delete_manifest_writer(producer: _OverwriteFiles, spec: PartitionSpec) - file_path=delete_path, file_format=FileFormat.PARQUET, partition=partition, - record_count=1, + record_count=len(rows), file_size_in_bytes=len(table.io.new_input(delete_path)), lower_bounds=bounds, upper_bounds=bounds, @@ -628,7 +631,7 @@ def test_file_overwrite_validates_concurrent_position_delete_in_nan_partition(ca overwrite.delete_data_file(file_to_replace) overwrite.append_data_file(replacement_file) - commit_partition_position_delete(deleting_table, Record(float("nan")), file_to_replace.file_path, pos=0) + commit_partition_position_delete(deleting_table, Record(float("nan")), [(file_to_replace.file_path, 0)]) with pytest.raises(ValidationException, match="found new delete for replace data file"): replacing_transaction.commit_transaction() @@ -650,7 +653,7 @@ def test_partial_delete_validates_concurrent_delete_outside_the_filter(catalog: deleting_table = catalog.load_table(identifier) # The delete file stores the deleted row (2, 'b'), so its bounds can't match k = 1. - commit_partition_position_delete(table, Record(), data_file.file_path, pos=1, row={"k": 2, "v": "b"}) + commit_partition_position_delete(table, Record(), [(data_file.file_path, 1)], row={"k": 2, "v": "b"}) with pytest.raises(ValidationException, match="found new delete for replace data file"): deleting_table.delete("k = 1") diff --git a/tests/table/test_init.py b/tests/table/test_init.py index af9a11a452..a2b9a34576 100644 --- a/tests/table/test_init.py +++ b/tests/table/test_init.py @@ -2470,6 +2470,40 @@ def test_overwrite_delete_data_file_on_bucket_partition(catalog: Catalog) -> Non assert table.scan().to_arrow().num_rows == 0 +def test_position_delete_respects_sequence_number_of_readded_file(catalog: Catalog) -> None: + """A position delete that names two data files applies to a file only if the file is not newer than the delete.""" + import pyarrow as pa + + catalog.create_namespace("default") + schema = Schema(NestedField(1, "id", LongType(), required=False)) + shapes = [ + # The delete predates the re-registered file P, so it keeps P's row 0 but still removes Q's row 0. + (True, [*range(10), *range(101, 110)]), + # The delete is committed after P is re-registered, so it removes row 0 of both files. + (False, [*range(1, 10), *range(101, 110)]), + ] + for index, (delete_before_readd, expected) in enumerate(shapes): + table = catalog.create_table( + f"default.readded_position_delete_{index}", schema=schema, properties={"format-version": "2"} + ) + table.append(pa.table({"id": pa.array(range(10), pa.int64())})) + table.append(pa.table({"id": pa.array(range(100, 110), pa.int64())})) + p_path = next(task.file.file_path for task in table.scan(row_filter="id = 0").plan_files()) + q_path = next(task.file.file_path for task in table.scan(row_filter="id = 100").plan_files()) + rows = [(p_path, 0), (q_path, 0)] + + if delete_before_readd: + commit_partition_position_delete(table, Record(), rows) + table.delete("id < 10") # removes P, the whole file + table.add_files([p_path]) # registers P again with a newer data sequence number + if not delete_before_readd: + commit_partition_position_delete(table, Record(), rows) + + assert sorted(table.scan().to_arrow()["id"].to_pylist()) == expected + assert table.scan().count() == len(expected) + assert sorted(table.scan(row_filter="id < 10").to_arrow()["id"].to_pylist()) == [i for i in expected if i < 10] + + def test_partial_delete_keeps_earlier_deletes_outside_the_filter(catalog: Catalog) -> None: """Rewriting a file applies all of its delete files, not only those whose bounds can match the delete filter.""" import pyarrow as pa @@ -2481,7 +2515,7 @@ def test_partial_delete_keeps_earlier_deletes_outside_the_filter(catalog: Catalo data_file = next(iter(table.scan().plan_files())).file # The delete file stores the deleted row (2, 'b'), so a scan for k = 1 skips it. - commit_partition_position_delete(table, Record(), data_file.file_path, pos=1, row={"k": 2, "v": "b"}) + commit_partition_position_delete(table, Record(), [(data_file.file_path, 1)], row={"k": 2, "v": "b"}) assert [task.delete_files for task in table.scan(row_filter="k = 1").plan_files()] == [set()] table.delete("k = 1") From d37ef112bb862f88579e0a5aeadda0009010575e Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Tue, 17 Nov 2026 22:37:53 +0000 Subject: [PATCH 2/3] Retrigger CI Co-authored-by: Isaac From 7056891e39657aa70b8fcaf32ea9b098477c3f5d Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Wed, 25 Nov 2026 00:20:38 +0000 Subject: [PATCH 3/3] Gather position deletes per task The same path can be live twice in a snapshot (add_files with check_duplicate_files=False), and the planner attaches a position delete only to the entries it applies to. Looking the positions up by path applied it to every entry of the path. Keep the positions per delete file and gather them for each task from task.delete_files, as ptimizeroracle suggested. Co-authored-by: Isaac --- pyiceberg/io/pyarrow.py | 52 +++++++++++++++++++++------------------- tests/io/test_pyarrow.py | 43 ++++++++++++++++++--------------- tests/table/test_init.py | 18 ++++++++++++++ 3 files changed, 70 insertions(+), 43 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index ebf296792a..6ac852ddbd 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -1880,33 +1880,37 @@ class _DeleteFileKey: content_size_in_bytes: int | None -def _read_all_delete_files(io: FileIO, tasks: Iterable[FileScanTask]) -> dict[str, list[ChunkedArray]]: - deletes_per_file: dict[str, list[ChunkedArray]] = {} +def _delete_file_key(delete_file: DataFile) -> _DeleteFileKey: + return _DeleteFileKey(delete_file.file_path, delete_file.content_offset, delete_file.content_size_in_bytes) + + +def _read_all_delete_files(io: FileIO, tasks: Iterable[FileScanTask]) -> dict[_DeleteFileKey, dict[str, ChunkedArray]]: + """Read each delete file of the tasks once and return its positions per data file path.""" # DataFile equality uses only the path; DVs from different tasks may share a file. unique_deletes: dict[_DeleteFileKey, DataFile] = {} - # Data files whose task has the delete file attached; a delete file can also list rows of other data files. - attached_paths: dict[_DeleteFileKey, set[str]] = {} for task in tasks: for delete_file in task.delete_files: - key = _DeleteFileKey(delete_file.file_path, delete_file.content_offset, delete_file.content_size_in_bytes) - unique_deletes.setdefault(key, delete_file) - attached_paths.setdefault(key, set()).add(task.file.file_path) - if len(unique_deletes) > 0: - executor = ExecutorFactory.get_or_create() - deletes_per_files: Iterator[dict[str, ChunkedArray]] = executor.map( - lambda args: _read_deletes(*args), - [(io, delete_file) for delete_file in unique_deletes.values()], - ) - for key, delete in zip(unique_deletes, deletes_per_files, strict=True): - for file, arr in delete.items(): - if file not in attached_paths[key]: - continue - if file in deletes_per_file: - deletes_per_file[file].append(arr) - else: - deletes_per_file[file] = [arr] + unique_deletes.setdefault(_delete_file_key(delete_file), delete_file) + if len(unique_deletes) == 0: + return {} + executor = ExecutorFactory.get_or_create() + deletes_per_files: Iterator[dict[str, ChunkedArray]] = executor.map( + lambda args: _read_deletes(*args), + [(io, delete_file) for delete_file in unique_deletes.values()], + ) + return dict(zip(unique_deletes, deletes_per_files, strict=True)) + - return deletes_per_file +def _positional_deletes_for_task( + task: FileScanTask, deletes_per_file: dict[_DeleteFileKey, dict[str, ChunkedArray]] +) -> list[ChunkedArray]: + """Return the positions of the task's data file in the delete files attached to the task. + + A delete file can list rows of several data files, and the same path can be live twice in a snapshot + with different delete files, so the positions are gathered per task and not per path. + """ + positions = (deletes_per_file[_delete_file_key(delete_file)].get(task.file.file_path) for delete_file in task.delete_files) + return [arr for arr in positions if arr is not None] class ArrowScan: @@ -2044,7 +2048,7 @@ def batches_for_task(task: FileScanTask) -> list[pa.RecordBatch]: break def _record_batches_from_scan_tasks_and_deletes( - self, tasks: Iterable[FileScanTask], deletes_per_file: dict[str, list[ChunkedArray]] + self, tasks: Iterable[FileScanTask], deletes_per_file: dict[_DeleteFileKey, dict[str, ChunkedArray]] ) -> Iterator[pa.RecordBatch]: total_row_count = 0 for task in tasks: @@ -2057,7 +2061,7 @@ def _record_batches_from_scan_tasks_and_deletes( self._projected_schema, self._table_metadata.schema(), self._projected_field_ids, - deletes_per_file.get(task.file.file_path), + _positional_deletes_for_task(task, deletes_per_file), self._case_sensitive, self._table_metadata.name_mapping(), self._table_metadata.specs().get(task.file.spec_id), diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index e1b223e093..b518166495 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -87,6 +87,7 @@ _ConvertToArrowSchema, _create_arrow_read_format, _determine_partitions, + _positional_deletes_for_task, _primitive_to_physical, _read_all_delete_files, _read_deletes, @@ -2239,22 +2240,20 @@ def test_read_all_delete_files_keeps_multiple_dv_content_ranges_for_same_path(tm for referenced_data_file in referenced_data_files ] - deletes = _read_all_delete_files( - PyArrowFileIO(), - [ - FileScanTask(data_file=data_file, delete_files={dv}) - for data_file, dv in zip(data_files, [first_dv, second_dv], strict=True) - ], - ) + tasks = [ + FileScanTask(data_file=data_file, delete_files={dv}) + for data_file, dv in zip(data_files, [first_dv, second_dv], strict=True) + ] + deletes = _read_all_delete_files(PyArrowFileIO(), tasks) - assert deletes == { + assert {task.file.file_path: _positional_deletes_for_task(task, deletes) for task in tasks} == { referenced_data_files[0]: [pa.chunked_array([[1, 3]])], referenced_data_files[1]: [pa.chunked_array([[5]])], } -def test_read_all_delete_files_only_loads_positions_for_tasks_it_is_attached_to(tmp_path: Path) -> None: - """A delete file that names rows of two data files only applies to the data files whose task has it attached.""" +def test_positional_deletes_for_task_use_only_the_delete_files_attached_to_it(tmp_path: Path) -> None: + """A delete file that names rows of two data files only applies to the tasks that have it attached.""" first_path, second_path = f"{tmp_path}/data-0.parquet", f"{tmp_path}/data-1.parquet" old_path, new_path = f"{tmp_path}/old-deletes.parquet", f"{tmp_path}/new-deletes.parquet" pq.write_table(pa.table({"file_path": [first_path, second_path], "pos": [0, 0]}), old_path) @@ -2271,19 +2270,24 @@ def test_read_all_delete_files_only_loads_positions_for_tasks_it_is_attached_to( second_data = DataFile.from_args( content=DataFileContent.DATA, file_path=second_path, file_format=FileFormat.PARQUET, record_count=10 ) - # (delete files attached to the first task, delete files attached to the second task) -> expected positions + readded_first_data = DataFile.from_args( + content=DataFileContent.DATA, file_path=first_path, file_format=FileFormat.PARQUET, record_count=10 + ) + # (data file and delete files of the first task, of the second task) -> expected positions of each task shapes = [ - (set(), {old_deletes}, {second_path: [pa.chunked_array([[0]])]}), - ({old_deletes}, {old_deletes}, {first_path: [pa.chunked_array([[0]])], second_path: [pa.chunked_array([[0]])]}), + ((first_data, set()), (second_data, {old_deletes}), [[], [pa.chunked_array([[0]])]]), + ((first_data, {old_deletes}), (second_data, {old_deletes}), [[pa.chunked_array([[0]])], [pa.chunked_array([[0]])]]), # The first data file has a newer delete file too; the old one must not add its row 0 to it. - ({new_deletes}, {old_deletes}, {first_path: [pa.chunked_array([[1]])], second_path: [pa.chunked_array([[0]])]}), + ((first_data, {new_deletes}), (second_data, {old_deletes}), [[pa.chunked_array([[1]])], [pa.chunked_array([[0]])]]), + # The same path is live twice; the delete applies only to the entry it is attached to. + ((first_data, {old_deletes}), (readded_first_data, set()), [[pa.chunked_array([[0]])], []]), ] - for first_task_deletes, second_task_deletes, expected in shapes: + for first_task, second_task, expected in shapes: tasks = [ - FileScanTask(data_file=first_data, delete_files=first_task_deletes), - FileScanTask(data_file=second_data, delete_files=second_task_deletes), + FileScanTask(data_file=data_file, delete_files=delete_files) for data_file, delete_files in [first_task, second_task] ] - assert _read_all_delete_files(PyArrowFileIO(), tasks) == expected + deletes = _read_all_delete_files(PyArrowFileIO(), tasks) + assert [_positional_deletes_for_task(task, deletes) for task in tasks] == expected @pytest.mark.parametrize("selected_indices", [(0, 1, 2, 3, 4, 5), (0, 3, 5)]) @@ -2392,7 +2396,8 @@ def test_read_all_delete_files_from_external_packed_deletion_vectors( # Repeated tasks must not cause a DV to be loaded more than once. deletes = _read_all_delete_files(PyArrowFileIO(), iter(tasks + tasks[::-1])) - assert deletes == expected_deletes + assert len(deletes) == len(tasks) + assert {task.file.file_path: _positional_deletes_for_task(task, deletes) for task in tasks} == expected_deletes result = ArrowScan( table_metadata=TableMetadataV3( diff --git a/tests/table/test_init.py b/tests/table/test_init.py index a2b9a34576..173a2b00b5 100644 --- a/tests/table/test_init.py +++ b/tests/table/test_init.py @@ -2504,6 +2504,24 @@ def test_position_delete_respects_sequence_number_of_readded_file(catalog: Catal assert sorted(table.scan(row_filter="id < 10").to_arrow()["id"].to_pylist()) == [i for i in expected if i < 10] +def test_position_delete_applies_only_to_the_entry_of_a_path_it_is_attached_to(catalog: Catalog) -> None: + """The same path can be live twice in a snapshot; a position delete only removes rows of the older entry.""" + import pyarrow as pa + + catalog.create_namespace("default") + schema = Schema(NestedField(1, "id", LongType(), required=False)) + table = catalog.create_table("default.duplicate_path_position_delete", schema=schema, properties={"format-version": "2"}) + table.append(pa.table({"id": pa.array(range(10), pa.int64())})) + path = next(iter(table.scan().plan_files())).file.file_path + + commit_partition_position_delete(table, Record(), [(path, 0)]) + table.add_files([path], check_duplicate_files=False) # registers P again, newer than the delete + + expected = sorted([*range(1, 10), *range(10)]) + assert sorted(table.scan().to_arrow()["id"].to_pylist()) == expected + assert table.scan().count() == len(expected) + + def test_partial_delete_keeps_earlier_deletes_outside_the_filter(catalog: Catalog) -> None: """Rewriting a file applies all of its delete files, not only those whose bounds can match the delete filter.""" import pyarrow as pa