From 52999c154e49a46bddaa9d6c54c47273a4ff0db1 Mon Sep 17 00:00:00 2001 From: Surender Gulia Date: Tue, 1 Dec 2026 09:48:37 +0000 Subject: [PATCH 1/2] feat(rest): preserve column bounds and key metadata during REST scan planning Signed-off-by: Surender Gulia --- pyiceberg/catalog/rest/__init__.py | 31 +++++++++++---- pyiceberg/table/__init__.py | 45 ++++++++++++++++++++-- tests/catalog/test_scan_planning_models.py | 25 ++++++++++++ 3 files changed, 90 insertions(+), 11 deletions(-) diff --git a/pyiceberg/catalog/rest/__init__.py b/pyiceberg/catalog/rest/__init__.py index 12c73610bc..24d3943600 100644 --- a/pyiceberg/catalog/rest/__init__.py +++ b/pyiceberg/catalog/rest/__init__.py @@ -855,14 +855,22 @@ def _poll_until_completed(self, identifier: str | Identifier, plan_id: str) -> P retries += 1 def _expand_plan_tasks( - self, identifier: str | Identifier, response: PlanCompleted, fallback_residual: BooleanExpression + self, + identifier: str | Identifier, + response: PlanCompleted, + fallback_residual: BooleanExpression, + table_schema: Schema | None = None, ) -> list[FileScanTask]: """Expand a completed plan response into FileScanTask objects, including pagination.""" tasks: list[FileScanTask] = [] # Collect tasks from initial response for task in response.file_scan_tasks: - tasks.append(FileScanTask.from_rest_response(task, response.delete_files, fallback_residual=fallback_residual)) + tasks.append( + FileScanTask.from_rest_response( + task, response.delete_files, fallback_residual=fallback_residual, table_schema=table_schema + ) + ) # Fetch and collect from additional batches pending_tasks = deque(response.plan_tasks) @@ -870,12 +878,18 @@ def _expand_plan_tasks( plan_task = pending_tasks.popleft() batch = self._fetch_scan_tasks(identifier, plan_task) for task in batch.file_scan_tasks: - tasks.append(FileScanTask.from_rest_response(task, batch.delete_files, fallback_residual=fallback_residual)) + tasks.append( + FileScanTask.from_rest_response( + task, batch.delete_files, fallback_residual=fallback_residual, table_schema=table_schema + ) + ) pending_tasks.extend(batch.plan_tasks) return tasks - def _plan_scan_result(self, identifier: str | Identifier, request: PlanTableScanRequest) -> PlannedScanResult: + def _plan_scan_result( + self, identifier: str | Identifier, request: PlanTableScanRequest, table_schema: Schema | None = None + ) -> PlannedScanResult: """Plan a table scan and return tasks with optional plan storage credentials. Handles the full scan planning lifecycle including async polling and pagination. @@ -894,10 +908,13 @@ def _plan_scan_result(self, identifier: str | Identifier, request: PlanTableScan raise ValueError("Async scan planning submitted without plan-id") response = self._poll_until_completed(identifier, response.plan_id) - if not isinstance(response, PlanCompleted): - raise RuntimeError(f"Invalid planStatus for response: {type(response).__name__}") + if table_schema is None: + try: + table_schema = self.load_table(identifier).schema() + except Exception: + pass - tasks = self._expand_plan_tasks(identifier, response, request.filter or AlwaysTrue()) + tasks = self._expand_plan_tasks(identifier, response, request.filter or AlwaysTrue(), table_schema=table_schema) return PlannedScanResult( tasks=tasks, storage_credentials=response.storage_credentials, diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 7676dc4079..862940a043 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -16,6 +16,8 @@ # under the License. from __future__ import annotations +import base64 +import itertools import itertools import logging import math @@ -34,6 +36,8 @@ from cachetools import LRUCache from pydantic import Field +from pyiceberg.conversions import to_bytes +from pyiceberg.types import PrimitiveType from pyiceberg.encryption.kms import KeyManagementClient from pyiceberg.exceptions import CommitFailedException, CommitStateUnknownException, ValidationException from pyiceberg.expressions import AlwaysFalse, AlwaysTrue, And, BooleanExpression, EqualTo, IsNaN, IsNull, Or, Reference @@ -2424,6 +2428,7 @@ def from_rest_response( delete_files: list[RESTDeleteFile], *, fallback_residual: BooleanExpression = ALWAYS_TRUE, + table_schema: Schema | None = None, ) -> FileScanTask: """Convert a RESTFileScanTask to a FileScanTask. @@ -2431,6 +2436,7 @@ def from_rest_response( rest_task: The REST file scan task. delete_files: The list of delete files from the ScanTasks response. fallback_residual: The scan filter to use when the server omits the residual. + table_schema: The table schema used to serialize column bounds. Returns: A FileScanTask with the converted data and delete files. @@ -2440,7 +2446,7 @@ def from_rest_response( """ from pyiceberg.catalog.rest.scan_planning import RESTEqualityDeleteFile - data_file = _rest_file_to_data_file(rest_task.data_file) + data_file = _rest_file_to_data_file(rest_task.data_file, table_schema=table_schema) resolved_deletes: set[DataFile] = set() if rest_task.delete_file_references: @@ -2448,7 +2454,11 @@ def from_rest_response( delete_file = delete_files[idx] if isinstance(delete_file, RESTEqualityDeleteFile): raise NotImplementedError(f"PyIceberg does not yet support equality deletes: {delete_file.file_path}") - resolved_deletes.add(_rest_file_to_data_file(delete_file, default_referenced_data_file=data_file.file_path)) + resolved_deletes.add( + _rest_file_to_data_file( + delete_file, default_referenced_data_file=data_file.file_path, table_schema=table_schema + ) + ) return FileScanTask( data_file=data_file, @@ -2457,7 +2467,25 @@ def from_rest_response( ) -def _rest_file_to_data_file(rest_file: RESTContentFile, default_referenced_data_file: str | None = None) -> DataFile: +def _serialize_bounds(raw_bounds: dict[int, Any] | None, schema: Schema | None) -> dict[int, bytes] | None: + if not raw_bounds: + return None + serialized: dict[int, bytes] = {} + for field_id, val in raw_bounds.items(): + if isinstance(val, bytes): + serialized[field_id] = val + elif schema is not None: + field = schema.find_field(field_id) + if field is not None and isinstance(field.field_type, PrimitiveType): + serialized[field_id] = to_bytes(field.field_type, val) + return serialized or None + + +def _rest_file_to_data_file( + rest_file: RESTContentFile, + default_referenced_data_file: str | None = None, + table_schema: Schema | None = None, +) -> DataFile: """Convert a REST content file to a manifest DataFile.""" from pyiceberg.catalog.rest.scan_planning import RESTDataFile, RESTPositionDeleteFile @@ -2466,11 +2494,17 @@ def _rest_file_to_data_file(rest_file: RESTContentFile, default_referenced_data_ value_counts = rest_file.value_counts.to_dict() if rest_file.value_counts else None null_value_counts = rest_file.null_value_counts.to_dict() if rest_file.null_value_counts else None nan_value_counts = rest_file.nan_value_counts.to_dict() if rest_file.nan_value_counts else None + lower_bounds = _serialize_bounds(rest_file.lower_bounds.to_dict() if rest_file.lower_bounds else None, table_schema) + upper_bounds = _serialize_bounds(rest_file.upper_bounds.to_dict() if rest_file.upper_bounds else None, table_schema) else: column_sizes = None value_counts = None null_value_counts = None nan_value_counts = None + lower_bounds = None + upper_bounds = None + + key_metadata = base64.b64decode(rest_file.key_metadata, validate=True) if rest_file.key_metadata else None referenced_data_file = None if isinstance(rest_file, RESTPositionDeleteFile): @@ -2494,6 +2528,9 @@ def _rest_file_to_data_file(rest_file: RESTContentFile, default_referenced_data_ value_counts=value_counts, null_value_counts=null_value_counts, nan_value_counts=nan_value_counts, + lower_bounds=lower_bounds, + upper_bounds=upper_bounds, + key_metadata=key_metadata, split_offsets=rest_file.split_offsets, sort_order_id=rest_file.sort_order_id, referenced_data_file=referenced_data_file, @@ -2643,7 +2680,7 @@ def _plan_files_server_side(self) -> Iterable[FileScanTask]: case_sensitive=self.case_sensitive, ) - result = self.catalog._plan_scan_result(self.table_identifier, request) + result = self.catalog._plan_scan_result(self.table_identifier, request, table_schema=self.table_metadata.schema()) location = result.tasks[0].file.file_path if result.tasks else None plan_io = self.catalog._file_io_from_plan(self.io.properties, result.storage_credentials, location) if plan_io is not None: diff --git a/tests/catalog/test_scan_planning_models.py b/tests/catalog/test_scan_planning_models.py index 5921811b67..96dc6887e3 100644 --- a/tests/catalog/test_scan_planning_models.py +++ b/tests/catalog/test_scan_planning_models.py @@ -632,7 +632,32 @@ def test_rest_task_preserves_whole_delete_file_reference(file_format: str) -> No assert dv.content_offset is None assert dv.content_size_in_bytes is None +def test_rest_task_preserves_bounds_and_key_metadata() -> None: + import base64 + from pyiceberg.schema import Schema + from pyiceberg.types import IntegerType, NestedField + + schema = Schema(NestedField(field_id=1, name="id", field_type=IntegerType(), required=True)) + key_metadata_bytes = b"secret-encryption-key-data" + key_metadata_b64 = base64.b64encode(key_metadata_bytes).decode("utf-8") + + rest_data_file = { + **_rest_data_file(), + "lower-bounds": {"keys": [1], "values": [10]}, + "upper-bounds": {"keys": [1], "values": [20]}, + "key-metadata": key_metadata_b64, + } + task = FileScanTask.from_rest_response( + RESTFileScanTask.model_validate({"data-file": rest_data_file}), + [], + table_schema=schema, + ) + + assert task.file.lower_bounds == {1: b"\n\x00\x00\x00"} + assert task.file.upper_bounds == {1: b"\x14\x00\x00\x00"} + assert task.file.key_metadata == key_metadata_bytes + def test_plan_scan_async_poll_completes( rest_scan_catalog: RestCatalog, requests_mock: Mocker, monkeypatch: pytest.MonkeyPatch ) -> None: From c61e6521c5e52569cf18a2c892f77275a87a78d3 Mon Sep 17 00:00:00 2001 From: Surender Gulia Date: Tue, 1 Dec 2026 10:52:01 +0000 Subject: [PATCH 2/2] style: format with ruff Signed-off-by: Surender Gulia --- pyiceberg/table/__init__.py | 4 +--- tests/catalog/test_scan_planning_models.py | 4 +++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 862940a043..02268d2fee 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -18,7 +18,6 @@ import base64 import itertools -import itertools import logging import math import random @@ -37,7 +36,6 @@ from pydantic import Field from pyiceberg.conversions import to_bytes -from pyiceberg.types import PrimitiveType from pyiceberg.encryption.kms import KeyManagementClient from pyiceberg.exceptions import CommitFailedException, CommitStateUnknownException, ValidationException from pyiceberg.expressions import AlwaysFalse, AlwaysTrue, And, BooleanExpression, EqualTo, IsNaN, IsNull, Or, Reference @@ -120,7 +118,7 @@ Record, TableVersion, ) -from pyiceberg.types import strtobool +from pyiceberg.types import PrimitiveType, strtobool from pyiceberg.utils.concurrent import ExecutorFactory from pyiceberg.utils.config import Config from pyiceberg.utils.properties import property_as_bool, property_as_int diff --git a/tests/catalog/test_scan_planning_models.py b/tests/catalog/test_scan_planning_models.py index 96dc6887e3..c98b87eca2 100644 --- a/tests/catalog/test_scan_planning_models.py +++ b/tests/catalog/test_scan_planning_models.py @@ -632,8 +632,10 @@ def test_rest_task_preserves_whole_delete_file_reference(file_format: str) -> No assert dv.content_offset is None assert dv.content_size_in_bytes is None + def test_rest_task_preserves_bounds_and_key_metadata() -> None: import base64 + from pyiceberg.schema import Schema from pyiceberg.types import IntegerType, NestedField @@ -657,7 +659,7 @@ def test_rest_task_preserves_bounds_and_key_metadata() -> None: assert task.file.upper_bounds == {1: b"\x14\x00\x00\x00"} assert task.file.key_metadata == key_metadata_bytes - + def test_plan_scan_async_poll_completes( rest_scan_catalog: RestCatalog, requests_mock: Mocker, monkeypatch: pytest.MonkeyPatch ) -> None: