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
31 changes: 24 additions & 7 deletions pyiceberg/catalog/rest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -855,27 +855,41 @@ 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)
while pending_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.
Expand All @@ -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,
Expand Down
45 changes: 40 additions & 5 deletions pyiceberg/table/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# under the License.
from __future__ import annotations

import base64
import itertools
import logging
import math
Expand All @@ -34,6 +35,7 @@
from cachetools import LRUCache
from pydantic import Field

from pyiceberg.conversions import to_bytes
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
Expand Down Expand Up @@ -116,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
Expand Down Expand Up @@ -2424,13 +2426,15 @@ 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.

Args:
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.
Expand All @@ -2440,15 +2444,19 @@ 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:
for idx in rest_task.delete_file_references:
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,
Expand All @@ -2457,7 +2465,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

Expand All @@ -2466,11 +2492,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):
Expand All @@ -2494,6 +2526,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,
Expand Down Expand Up @@ -2643,7 +2678,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:
Expand Down
27 changes: 27 additions & 0 deletions tests/catalog/test_scan_planning_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,33 @@ def test_rest_task_preserves_whole_delete_file_reference(file_format: str) -> No
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:
Expand Down