-
Notifications
You must be signed in to change notification settings - Fork 535
Cache residuals with stateless evaluators #3666
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dossett
wants to merge
3
commits into
apache:main
Choose a base branch
from
dossett:stateless-residual-evaluator
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -28,6 +28,7 @@ | |
| from types import TracebackType | ||
| from typing import TYPE_CHECKING, Any, TypeVar | ||
|
|
||
| from cachetools import LRUCache | ||
| from pydantic import Field | ||
|
|
||
| import pyiceberg.expressions.parser as parser | ||
|
|
@@ -37,6 +38,7 @@ | |
| _InclusiveMetricsEvaluator, | ||
| bind, | ||
| expression_evaluator, | ||
| extract_field_ids, | ||
| inclusive_projection, | ||
| manifest_evaluator, | ||
| ) | ||
|
|
@@ -117,6 +119,9 @@ | |
|
|
||
| ALWAYS_TRUE = AlwaysTrue() | ||
| DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE = "downcast-ns-timestamp-to-us-on-write" | ||
| # Retain a small working set for repeated relevant partition values without adding | ||
| # unbounded key storage when scans contain a distinct value for every data file. | ||
| _RESIDUAL_CACHE_MAX_SIZE = 128 | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we have this as a property with this as the default? That would help with some of the monkeypatching below |
||
|
|
||
|
|
||
| @dataclass() | ||
|
|
@@ -2620,7 +2625,32 @@ def plan_files( | |
| data_entries: list[ManifestEntry] = [] | ||
| delete_index = DeleteFileIndex() | ||
|
|
||
| residual_evaluators: dict[int, Callable[[DataFile], ResidualEvaluator]] = KeyDefaultDict(self._build_residual_evaluator) | ||
| residual_evaluators: dict[int, ResidualEvaluator] = KeyDefaultDict(self._build_residual_evaluator) | ||
| referenced_field_ids = extract_field_ids( | ||
| bind(self.table_metadata.schema(), self.row_filter, case_sensitive=self.case_sensitive) | ||
| ) | ||
| partition_specs = self.table_metadata.specs() | ||
| residual_cache_key_positions: dict[int, tuple[int, ...]] = KeyDefaultDict( | ||
| lambda spec_id: tuple( | ||
| pos | ||
| for pos, partition_field in enumerate(partition_specs[spec_id].fields) | ||
| if partition_field.source_id in referenced_field_ids | ||
| ) | ||
| ) | ||
| # A residual can only depend on partition fields derived from source columns | ||
| # referenced by the scan filter. Keep the cache local and bounded. | ||
| residual_cache: LRUCache[tuple[int, tuple[Any, ...]], BooleanExpression] = LRUCache(maxsize=_RESIDUAL_CACHE_MAX_SIZE) | ||
|
|
||
| def residual_for(data_file: DataFile) -> BooleanExpression: | ||
| partition = data_file.partition | ||
| partition_values = tuple(partition[pos] for pos in residual_cache_key_positions[data_file.spec_id]) | ||
| cache_key = data_file.spec_id, partition_values | ||
| try: | ||
| return residual_cache[cache_key] | ||
| except KeyError: | ||
| residual = residual_evaluators[data_file.spec_id].residual_for(partition) | ||
| residual_cache[cache_key] = residual | ||
| return residual | ||
|
|
||
| for manifest_entry in chain.from_iterable(self.plan_manifest_entries(manifests)): | ||
| if not manifest_entry_filter(manifest_entry): | ||
|
|
@@ -2644,9 +2674,7 @@ def plan_files( | |
| data_entry.data_file, | ||
| partition_key=data_entry.data_file.partition, | ||
| ), | ||
| residual=residual_evaluators[data_entry.data_file.spec_id](data_entry.data_file).residual_for( | ||
| data_entry.data_file.partition | ||
| ), | ||
| residual=residual_for(data_entry.data_file), | ||
| ) | ||
| for data_entry in data_entries | ||
| ] | ||
|
|
@@ -2684,15 +2712,12 @@ def _build_metrics_evaluator(self) -> Callable[[DataFile], bool]: | |
| include_empty_files, | ||
| ).eval(data_file) | ||
|
|
||
| def _build_residual_evaluator(self, spec_id: int) -> Callable[[DataFile], ResidualEvaluator]: | ||
| def _build_residual_evaluator(self, spec_id: int) -> ResidualEvaluator: | ||
| spec = self.table_metadata.specs()[spec_id] | ||
|
|
||
| from pyiceberg.expressions.visitors import residual_evaluator_of | ||
|
|
||
| # The lambda created here is run in multiple threads. | ||
| # So we avoid creating _EvaluatorExpression methods bound to a single | ||
| # shared instance across multiple threads. | ||
| return lambda datafile: residual_evaluator_of( | ||
| return residual_evaluator_of( | ||
| spec=spec, | ||
| expr=self.row_filter, | ||
| case_sensitive=self.case_sensitive, | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| # 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 residual planning with a realistic 15-leaf predicate. | ||
|
|
||
| Every file has a unique unreferenced partition-hash value. The repeated case | ||
| measures cache reuse by relevant partition values, while the unique case forces | ||
| cache misses. | ||
|
|
||
| Run with: | ||
| uv run pytest tests/benchmark/test_residual_evaluator_benchmark.py -v -s -m benchmark | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import statistics | ||
| import timeit | ||
|
|
||
| import pytest | ||
|
|
||
| from pyiceberg.expressions import And, BooleanExpression, EqualTo, GreaterThanOrEqual, LessThanOrEqual, Or | ||
| from pyiceberg.manifest import DataFile, DataFileContent, FileFormat, ManifestEntry, ManifestEntryStatus | ||
| from pyiceberg.partitioning import PartitionField, PartitionSpec | ||
| from pyiceberg.schema import Schema | ||
| from pyiceberg.table import ManifestGroupPlanner, Table | ||
| from pyiceberg.table.metadata import TableMetadataV2 | ||
| from pyiceberg.transforms import IdentityTransform | ||
| from pyiceberg.typedef import Record | ||
| from pyiceberg.types import LongType, NestedField | ||
|
|
||
|
|
||
| def _row_filter() -> BooleanExpression: | ||
| """Select five day ranges, each scoped to a region.""" | ||
| windows = ((0, 1, 1), (2, 3, 4), (4, 5, 7), (6, 7, 10), (8, 10, 13)) | ||
| branches = [ | ||
| And( | ||
| And(GreaterThanOrEqual("event_day", start_day), LessThanOrEqual("event_day", end_day)), | ||
| EqualTo("region_id", region_id), | ||
| ) | ||
| for start_day, end_day, region_id in windows | ||
| ] | ||
|
|
||
| combined = branches[0] | ||
| for branch in branches[1:]: | ||
| combined = Or(combined, branch) | ||
| return combined | ||
|
|
||
|
|
||
| def _manifest_entry(file_number: int, relevant_partition: int) -> ManifestEntry: | ||
| data_file = DataFile.from_args( | ||
| content=DataFileContent.DATA, | ||
| file_path=f"s3://bucket/data-{file_number}.parquet", | ||
| file_format=FileFormat.PARQUET, | ||
| partition=Record(relevant_partition, file_number), | ||
| record_count=1, | ||
| file_size_in_bytes=1, | ||
| ) | ||
| data_file.spec_id = 0 | ||
| return ManifestEntry.from_args( | ||
| status=ManifestEntryStatus.ADDED, | ||
| snapshot_id=1, | ||
| sequence_number=1, | ||
| file_sequence_number=1, | ||
| data_file=data_file, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.benchmark | ||
| @pytest.mark.parametrize( | ||
| "num_relevant_partitions", | ||
| [7, 2_000], | ||
| ids=["repeated-relevant-partitions", "unique-relevant-partitions"], | ||
| ) | ||
| def test_residual_planning(table_v2: Table, monkeypatch: pytest.MonkeyPatch, num_relevant_partitions: int) -> None: | ||
| num_files = 2_000 | ||
| entries = [_manifest_entry(file_number, file_number % num_relevant_partitions) for file_number in range(num_files)] | ||
| schema = Schema( | ||
| NestedField(1, "event_day", LongType(), required=True), | ||
| NestedField(2, "region_id", LongType(), required=True), | ||
| NestedField(3, "partition_hash", LongType(), required=True), | ||
| ) | ||
| spec = PartitionSpec( | ||
| PartitionField(1, 1000, IdentityTransform(), "event_day"), | ||
| PartitionField(3, 1001, IdentityTransform(), "partition_hash"), | ||
| spec_id=0, | ||
| ) | ||
| metadata = TableMetadataV2( | ||
| location="s3://bucket/table", | ||
| last_column_id=3, | ||
| schemas=[schema], | ||
| current_schema_id=schema.schema_id, | ||
| partition_specs=[spec], | ||
| default_spec_id=spec.spec_id, | ||
| ) | ||
| planner = ManifestGroupPlanner(table_metadata=metadata, io=table_v2.io, row_filter=_row_filter()) | ||
|
|
||
| monkeypatch.setattr(planner, "plan_manifest_entries", lambda _: iter([entries])) | ||
|
|
||
| timings = timeit.repeat(lambda: list(planner.plan_files([])), number=1, repeat=3) | ||
|
|
||
| assert len(list(planner.plan_files([]))) == num_files | ||
| print( | ||
| f"Planned {num_files} files across {num_relevant_partitions} relevant partitions " | ||
| f"with a 15-leaf predicate in {statistics.mean(timings):.3f}s (best: {min(timings):.3f}s)" | ||
| ) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We're making this class private. That may be a breaking change. I'll let a maintainer decide if we can do this.