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
59 changes: 50 additions & 9 deletions pyiceberg/expressions/visitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
# under the License.
import math
from abc import ABC, abstractmethod
from collections.abc import Callable, Mapping
from bisect import bisect_left
from collections.abc import Callable, Mapping, Sequence
from functools import singledispatch
from typing import (
Any,
Expand Down Expand Up @@ -549,6 +550,22 @@ def visit_or(self, left_result: bool, right_result: bool) -> bool:
IN_PREDICATE_LIMIT = 200


def _collect_sorted_in_literals(expr: BooleanExpression) -> dict[int, list[Any]]:
sorted_literals: dict[int, list[Any]] = {}
stack: list[BooleanExpression] = [expr]
while stack:
node = stack.pop()
if isinstance(node, (And, Or)):
stack.append(node.left)
stack.append(node.right)
elif isinstance(node, Not):
stack.append(node.child)
elif isinstance(node, BoundIn):
value_set = node.value_set
sorted_literals[id(value_set)] = sorted(value_set)
return sorted_literals


def _from_byte_buffer(field_type: IcebergType, val: bytes) -> Any:
if not isinstance(field_type, PrimitiveType):
raise ValueError(f"Expected a PrimitiveType, got: {type(field_type)}")
Expand All @@ -558,9 +575,11 @@ def _from_byte_buffer(field_type: IcebergType, val: bytes) -> Any:
class _ManifestEvalVisitor(BoundBooleanExpressionVisitor[bool]):
partition_fields: list[PartitionFieldSummary]
partition_filter: BooleanExpression
_sorted_literals: Mapping[int, Sequence[Any]]

def __init__(self, partition_struct_schema: Schema, partition_filter: BooleanExpression, case_sensitive: bool) -> None:
self.partition_filter = bind(partition_struct_schema, rewrite_not(partition_filter), case_sensitive)
self._sorted_literals = _collect_sorted_in_literals(self.partition_filter)

def eval(self, manifest: ManifestFile) -> bool:
if partitions := manifest.partitions:
Expand All @@ -577,14 +596,21 @@ def visit_in(self, term: BoundTerm, literals: set[L]) -> bool:
if field.lower_bound is None:
return ROWS_CANNOT_MATCH

lower = _from_byte_buffer(term.ref().field.field_type, field.lower_bound)
sorted_literals = self._sorted_literals.get(id(literals))
if sorted_literals is None:
sorted_literals = sorted(literals)

if all(lower > val for val in literals):
if not sorted_literals:
return ROWS_CANNOT_MATCH

lower = _from_byte_buffer(term.ref().field.field_type, field.lower_bound)
idx = bisect_left(sorted_literals, lower)
if idx == len(sorted_literals):
return ROWS_CANNOT_MATCH

if field.upper_bound is not None:
upper = _from_byte_buffer(term.ref().field.field_type, field.upper_bound)
if all(upper < val for val in literals):
if sorted_literals[idx] > upper:
return ROWS_CANNOT_MATCH

return ROWS_MIGHT_MATCH
Expand Down Expand Up @@ -1186,12 +1212,14 @@ class _InclusiveMetricsEvaluator:

expr: BooleanExpression
include_empty_files: bool
_sorted_literals: Mapping[int, Sequence[Any]]

def __init__(
self, schema: Schema, expr: BooleanExpression, case_sensitive: bool = True, include_empty_files: bool = False
) -> None:
self.include_empty_files = include_empty_files
self.expr = bind(schema, rewrite_not(expr), case_sensitive)
self._sorted_literals = _collect_sorted_in_literals(self.expr)

def eval(self, file: DataFile) -> bool:
"""Test whether the file may contain records that match the expression."""
Expand All @@ -1204,12 +1232,18 @@ def eval(self, file: DataFile) -> bool:
# be updated once we implemented and set correct record count.
return ROWS_MIGHT_MATCH

return visit(self.expr, _InclusiveMetricsEvaluationVisitor(file))
return visit(self.expr, _InclusiveMetricsEvaluationVisitor(file, self._sorted_literals))


class _InclusiveMetricsEvaluationVisitor(_MetricsEvaluationVisitor):
"""Evaluate inclusive metrics for one data file."""

_sorted_literals: Mapping[int, Sequence[Any]]

def __init__(self, file: DataFile, sorted_literals: Mapping[int, Sequence[Any]] = EMPTY_DICT) -> None:
super().__init__(file)
self._sorted_literals = sorted_literals

def _may_contain_null(self, field_id: int) -> bool:
# A missing null count means the count is unknown, so the column may contain nulls.
null_count = self.null_counts.get(field_id)
Expand Down Expand Up @@ -1393,15 +1427,23 @@ def visit_in(self, term: BoundTerm, literals: set[L]) -> bool:
if not isinstance(field.field_type, PrimitiveType):
raise ValueError(f"Expected PrimitiveType: {field.field_type}")

sorted_literals = self._sorted_literals.get(id(literals))
if sorted_literals is None:
sorted_literals = sorted(literals)

if not sorted_literals:
return ROWS_CANNOT_MATCH

idx = 0
lower_bound_bytes = self.lower_bounds.get(field_id)
if lower_bound_bytes is not None:
lower_bound = from_bytes(field.field_type, lower_bound_bytes)
if self._is_nan(lower_bound):
# NaN indicates unreliable bounds. See the InclusiveMetricsEvaluator docs for more.
return ROWS_MIGHT_MATCH

literals = {lit for lit in literals if lower_bound <= lit} # type: ignore[operator]
if len(literals) == 0:
idx = bisect_left(sorted_literals, lower_bound)
if idx == len(sorted_literals):
return ROWS_CANNOT_MATCH

upper_bound_bytes = self.upper_bounds.get(field_id)
Expand All @@ -1411,8 +1453,7 @@ def visit_in(self, term: BoundTerm, literals: set[L]) -> bool:
if self._is_nan(upper_bound):
return ROWS_MIGHT_MATCH

literals = {lit for lit in literals if upper_bound >= lit} # type: ignore[operator]
if len(literals) == 0:
if sorted_literals[idx] > upper_bound:
return ROWS_CANNOT_MATCH

return ROWS_MIGHT_MATCH
Expand Down
163 changes: 163 additions & 0 deletions tests/benchmark/test_in_predicate_benchmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Benchmark large IN predicates in metrics and manifest evaluators.

Run with:
uv run pytest tests/benchmark/test_in_predicate_benchmark.py -v -s -m benchmark
"""

from __future__ import annotations

import statistics
import timeit
from collections.abc import Callable
from typing import Any

import pytest

import pyiceberg.table as table_module
from pyiceberg.conversions import to_bytes
from pyiceberg.expressions import In
from pyiceberg.expressions.visitors import _ManifestEvalVisitor
from pyiceberg.manifest import DataFile, FileFormat, ManifestContent, ManifestFile, PartitionFieldSummary
from pyiceberg.schema import Schema
from pyiceberg.table import ManifestGroupPlanner, Table
from pyiceberg.typedef import Record
from pyiceberg.types import LongType, NestedField
from pyiceberg.utils.concurrent import ExecutorFactory

NUM_FILES = 10_000
NUM_KEYS = 100_000
KEYS_PER_FILE = NUM_KEYS


def _data_file(file_number: int) -> DataFile:
lower = file_number * KEYS_PER_FILE
upper = lower + KEYS_PER_FILE - 1
return DataFile.from_args(
file_path=f"s3://bucket/data-{file_number}.parquet",
file_format=FileFormat.PARQUET,
partition=Record(),
record_count=100,
file_size_in_bytes=1,
value_counts={1: 100},
null_value_counts={1: 0},
lower_bounds={1: to_bytes(LongType(), lower)},
upper_bounds={1: to_bytes(LongType(), upper)},
)


def _manifest_file(manifest_number: int) -> ManifestFile:
lower = manifest_number * KEYS_PER_FILE
upper = lower + KEYS_PER_FILE - 1
return ManifestFile.from_args(
manifest_path=f"s3://bucket/manifest-{manifest_number}.avro",
manifest_length=1,
partition_spec_id=0,
content=ManifestContent.DATA,
sequence_number=1,
min_sequence_number=1,
added_snapshot_id=1,
partitions=[
PartitionFieldSummary.from_args(
contains_null=False,
contains_nan=False,
lower_bound=to_bytes(LongType(), lower),
upper_bound=to_bytes(LongType(), upper),
)
],
)


class _SerialExecutor:
def map(self, function: Callable[..., Any], *iterables: Any, **_kwargs: Any) -> Any:
return map(function, *iterables)


def _keys_for_scenario(scenario: str) -> list[int]:
if scenario == "single-file":
start = (NUM_FILES // 2) * KEYS_PER_FILE
return list(range(start, start + NUM_KEYS))
keys_per_bucket = NUM_KEYS // NUM_FILES
return [file_number * KEYS_PER_FILE + offset for file_number in range(NUM_FILES) for offset in range(keys_per_bucket)]


@pytest.mark.benchmark
@pytest.mark.parametrize(
("scenario", "expected_matches"),
[("single-file", 1), ("all-files", NUM_FILES)],
)
def test_large_in_metrics_evaluator_benchmark(
table_v2: Table,
monkeypatch: pytest.MonkeyPatch,
scenario: str,
expected_matches: int,
) -> None:
schema = Schema(
NestedField(1, "id", LongType(), required=True),
schema_id=table_v2.metadata.current_schema_id,
)
metadata = table_v2.metadata.model_copy(update={"schemas": [schema]})
row_filter = In("id", _keys_for_scenario(scenario))
data_files = [_data_file(file_number) for file_number in range(NUM_FILES)]
manifest = _manifest_file(0)

def open_manifest(
_io: Any,
_manifest: ManifestFile,
partition_evaluator: Callable[[DataFile], bool],
metrics_evaluator: Callable[[DataFile], bool],
) -> list[DataFile]:
return [data_file for data_file in data_files if partition_evaluator(data_file) and metrics_evaluator(data_file)]

monkeypatch.setattr(table_module, "_open_manifest", open_manifest)
monkeypatch.setattr(ExecutorFactory, "get_or_create", staticmethod(lambda: _SerialExecutor()))

def plan_files() -> int:
planner = ManifestGroupPlanner(table_metadata=metadata, io=table_v2.io, row_filter=row_filter)
monkeypatch.setattr(planner, "_build_manifest_evaluator", lambda _: lambda _: True)
monkeypatch.setattr(planner, "_build_partition_evaluator", lambda _: lambda _: True)
return sum(len(entries) for entries in planner.plan_manifest_entries([manifest]))

assert plan_files() == expected_matches
timings_ms = [timing * 1_000 for timing in timeit.repeat(plan_files, number=1, repeat=3)]
print(
f"InclusiveMetricsEvaluator planned {NUM_FILES:,} files with {NUM_KEYS:,} IN keys ({scenario}, "
f"{expected_matches:,} matched) in {statistics.mean(timings_ms):.2f}ms (best: {min(timings_ms):.2f}ms)"
)


@pytest.mark.benchmark
@pytest.mark.parametrize(
("scenario", "expected_matches"),
[("single-file", 1), ("all-files", NUM_FILES)],
)
def test_large_in_manifest_evaluator_benchmark(scenario: str, expected_matches: int) -> None:
partition_schema = Schema(NestedField(1, "id", LongType(), required=True))
partition_filter = In("id", _keys_for_scenario(scenario))
manifests = [_manifest_file(manifest_number) for manifest_number in range(NUM_FILES)]

def evaluate_manifests() -> int:
evaluator = _ManifestEvalVisitor(partition_schema, partition_filter, case_sensitive=True)
return sum(1 for manifest in manifests if evaluator.eval(manifest))

assert evaluate_manifests() == expected_matches
timings_ms = [timing * 1_000 for timing in timeit.repeat(evaluate_manifests, number=1, repeat=3)]
print(
f"ManifestEvalVisitor evaluated {NUM_FILES:,} manifests with {NUM_KEYS:,} IN keys ({scenario}, "
f"{expected_matches:,} matched) in {statistics.mean(timings_ms):.2f}ms (best: {min(timings_ms):.2f}ms)"
)
35 changes: 35 additions & 0 deletions tests/expressions/test_evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,41 @@ def test_integer_in_at_limit(schema_data_file: Schema, data_file: DataFile) -> N
assert not should_read, "Should not read: no id between lower and upper bounds"


def test_inclusive_in_reuses_evaluator_and_handles_partial_bounds(schema_data_file: Schema) -> None:
evaluator = _InclusiveMetricsEvaluator(
schema_data_file,
Or(In("id", {10, 50, 90}), In("id", {200, 300})),
)

def _file_with_bounds(lower: int | None, upper: int | None) -> DataFile:
return DataFile.from_args(
file_path="file.parquet",
file_format=FileFormat.PARQUET,
partition=Record(),
record_count=10,
file_size_in_bytes=100,
value_counts={1: 10},
null_value_counts={1: 0},
lower_bounds={1: _to_byte_buffer(IntegerType(), lower)} if lower is not None else {},
upper_bounds={1: _to_byte_buffer(IntegerType(), upper)} if upper is not None else {},
)

assert not evaluator.eval(_file_with_bounds(0, 9)), "All literals above upper bound"
assert evaluator.eval(_file_with_bounds(10, 20)), "Matches lower bound"
assert not evaluator.eval(_file_with_bounds(11, 49)), "Literals straddle bounds with no overlap"
assert evaluator.eval(_file_with_bounds(40, 60)), "Matches interior literal"
assert evaluator.eval(_file_with_bounds(250, 300)), "Matches second In branch in Or"
assert not evaluator.eval(_file_with_bounds(301, 400)), "All literals below lower bound"
# Only upper bound present
assert not evaluator.eval(_file_with_bounds(None, 9)), "Smallest literal > upper bound"
assert evaluator.eval(_file_with_bounds(None, 10)), "Smallest literal == upper bound"
# Only lower bound present
assert evaluator.eval(_file_with_bounds(300, None)), "Largest literal == lower bound"
assert not evaluator.eval(_file_with_bounds(301, None)), "Largest literal < lower bound"
# Neither bound present
assert evaluator.eval(_file_with_bounds(None, None)), "No bounds cannot prune"


def test_integer_not_in(schema_data_file: Schema, data_file: DataFile) -> None:
should_read = _InclusiveMetricsEvaluator(schema_data_file, NotIn("id", {INT_MIN_VALUE - 25, INT_MIN_VALUE - 24})).eval(
data_file
Expand Down
31 changes: 29 additions & 2 deletions tests/expressions/test_visitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1393,11 +1393,38 @@ def test_integer_in_above_limit(schema: Schema, manifest: ManifestFile) -> None:
)

outside_both = [*range(INT_MIN_VALUE - IN_PREDICATE_LIMIT, INT_MIN_VALUE), INT_MAX_VALUE + 1]
assert _ManifestEvalVisitor(schema, In(Reference("id"), outside_both), case_sensitive=True).eval(manifest), (
"Should read: id range covers bounds"
assert not _ManifestEvalVisitor(schema, In(Reference("id"), outside_both), case_sensitive=True).eval(manifest), (
"Should not read: no id between lower and upper bounds"
)


def test_manifest_eval_in_reuses_sorted_literals_and_handles_missing_upper_bound(schema: Schema) -> None:
evaluator = _ManifestEvalVisitor(
schema,
Or(In(Reference("id"), {10, 50, 90}), In(Reference("id"), {200, 300})),
case_sensitive=True,
)

def _id_manifest(lower: int | None, upper: int | None) -> ManifestFile:
return _to_manifest_file(
PartitionFieldSummary.from_args(
contains_null=False,
contains_nan=False,
lower_bound=to_bytes(IntegerType(), lower) if lower is not None else None,
upper_bound=to_bytes(IntegerType(), upper) if upper is not None else None,
)
)

assert not evaluator.eval(_id_manifest(0, 9)), "All literals above upper bound"
assert evaluator.eval(_id_manifest(10, 20)), "Matches lower bound"
assert not evaluator.eval(_id_manifest(11, 49)), "Literals straddle bounds with no overlap"
assert evaluator.eval(_id_manifest(40, 60)), "Matches interior literal"
assert evaluator.eval(_id_manifest(250, 300)), "Matches second In branch in Or"
assert not evaluator.eval(_id_manifest(301, 400)), "All literals below lower bound"
assert evaluator.eval(_id_manifest(90, None)), "Missing upper bound with literal >= lower bound"
assert not evaluator.eval(_id_manifest(301, None)), "Missing upper bound with all literals < lower bound"


def test_integer_not_in(schema: Schema, manifest: ManifestFile) -> None:
assert _ManifestEvalVisitor(
schema, NotIn(Reference("id"), (INT_MIN_VALUE - 25, INT_MIN_VALUE - 24)), case_sensitive=True
Expand Down