Repository navigation
[Data] Add file-level predicate pushdown and metadata filtering for MCAP datasource - #58403
soffer-anyscale wants to merge 13 commits into
Conversation
- Add MCAP library URLs to documentation - Fix TYPE_CHECKING imports for proper type hints - Fix all linting issues (whitespace, quotes, formatting) - Improve test coverage with comprehensive edge cases - Add tests for TimeRange validation, OR logic, multiple operators - Ensure tests follow Ray Data testing standards - Add better comments and documentation throughout Signed-off-by: soffer-anyscale <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request significantly enhances the MCAP datasource by introducing a robust, two-stage predicate pushdown mechanism, which will greatly improve performance for filtered reads. The implementation, including file-level metadata filtering and fallback to in-memory block filtering, is well-designed. The accompanying documentation improvements and comprehensive test suite are also excellent. I've identified a critical issue in the handling of OR predicates and a high-severity issue with commutative expressions that should be addressed to ensure correctness and completeness of this new feature.
| # Handle OR operations - recursively visit both sides | ||
| if expr.op == Operation.OR: | ||
| visit_expr(expr.left) | ||
| visit_expr(expr.right) | ||
| return |
There was a problem hiding this comment.
The current implementation for OR predicates is incorrect when combining filters on different columns (e.g., col("topic") == "A" | col("log_time") > 1000). When visit_expr recursively processes both sides of the OR, it extracts filters for both topic and time. However, the _should_include_file method then applies these filters with AND logic, requiring a file to match both conditions. This contradicts the OR semantics of the predicate and will lead to incorrect filtering, likely returning fewer rows than expected or none at all.
To fix this, visit_expr should detect OR operations that combine predicates on different columns and avoid pushing them down. The filtering for such complex OR predicates should be handled entirely by the block-level filtering mechanism later in the process, which can correctly evaluate the full expression.
| # Process binary operations with column on left | ||
| if isinstance(expr.left, ColumnExpr): | ||
| col_name = expr.left.name | ||
|
|
||
| # Handle is_in() operations | ||
| if expr.op == Operation.IN: | ||
| value = extract_value_from_literal(expr.right) | ||
| if value is not None: | ||
| if col_name == "topic": | ||
| topics = add_to_set(topics, value) | ||
| elif col_name == "schema_name": | ||
| message_types = add_to_set(message_types, value) | ||
| return | ||
|
|
||
| # Handle equality operations | ||
| if expr.op == Operation.EQ and isinstance(expr.right, LiteralExpr): | ||
| value = expr.right.value | ||
| if col_name == "topic": | ||
| topics = add_to_set(topics, {value}) | ||
| elif col_name == "schema_name": | ||
| message_types = add_to_set(message_types, {value}) | ||
| return | ||
|
|
||
| # Handle time range operations | ||
| if col_name == "log_time" and isinstance(expr.right, LiteralExpr): | ||
| value = expr.right.value | ||
| if expr.op in (Operation.GT, Operation.GE): | ||
| # Update start time (take maximum for GT/GE) | ||
| if time_range_start is None or value > time_range_start: | ||
| time_range_start = value | ||
| elif expr.op in (Operation.LT, Operation.LE): | ||
| # Update end time (take minimum for LT/LE) | ||
| if time_range_end is None or value < time_range_end: | ||
| time_range_end = value | ||
|
|
There was a problem hiding this comment.
The predicate extraction logic only handles binary expressions where the column is on the left-hand side (e.g., col("log_time") > 1000). It does not support the commutative case where the column is on the right-hand side (e.g., 1000 < col("log_time")). This will cause predicate pushdown to fail for such filters, leading to suboptimal performance as the filtering will happen at the block level instead of the file level.
To ensure predicate pushdown works for these common filter patterns, the logic should be updated to handle expressions where the literal is on the left and the column is on the right. You can achieve this by detecting this pattern, swapping the operands, and inverting the comparison operator accordingly.
# Process binary operations with column on left
left, right = expr.left, expr.right
op = expr.op
# Handle commutative cases like `1000 < col("log_time")`
if isinstance(right, ColumnExpr) and isinstance(left, LiteralExpr):
left, right = right, left
op_map = {
Operation.LT: Operation.GT,
Operation.LE: Operation.GE,
Operation.GT: Operation.LT,
Operation.GE: Operation.LE,
Operation.EQ: Operation.EQ,
Operation.NE: Operation.NE,
}
if op in op_map:
op = op_map[op]
else:
# Not a supported commutative operation for pushdown, bail out.
return
if isinstance(left, ColumnExpr):
col_name = left.name
# Handle is_in() operations
if op == Operation.IN:
value = extract_value_from_literal(right)
if value is not None:
if col_name == "topic":
topics = add_to_set(topics, value)
elif col_name == "schema_name":
message_types = add_to_set(message_types, value)
return
# Handle equality operations
if op == Operation.EQ and isinstance(right, LiteralExpr):
value = right.value
if col_name == "topic":
topics = add_to_set(topics, {value})
elif col_name == "schema_name":
message_types = add_to_set(message_types, {value})
return
# Handle time range operations
if col_name == "log_time" and isinstance(right, LiteralExpr):
value = right.value
if op in (Operation.GT, Operation.GE):
# Update start time (take maximum for GT/GE)
if time_range_start is None or value > time_range_start:
time_range_start = value
elif op in (Operation.LT, Operation.LE):
# Update end time (take minimum for LT/LE)
if time_range_end is None or value < time_range_end:
time_range_end = value| except Exception as e: | ||
| # If predicate conversion fails, log and continue without filtering | ||
| # This can happen with unsupported expressions | ||
| logger.debug(f"Could not apply predicate expression to MCAP block: {e}") |
There was a problem hiding this comment.
Bug: Duplicate predicate application during stream read
The predicate expression is applied twice to the same data. In _read_stream, the code first applies filters extracted from the predicate (topics, time_range, message_types) through MCAP's iter_messages() and _should_include_message(). Then at lines 731-743, it applies the ENTIRE original predicate expression again to the block, including the parts that were already filtered. This means filters like col("topic") == "/camera" are applied twice: once through MCAP's topic filtering and once through the PyArrow filter expression. The comment at line 729-730 suggests only "remaining" predicates should be applied, but the code doesn't actually remove the already-pushed-down parts from self._predicate_expr before applying it.
There was a problem hiding this comment.
Code Review
This pull request introduces a significant improvement to the MCAP datasource by adding support for predicate pushdown, which enables efficient file-level filtering. The changes are well-structured, with a new MCAPFileMetadataProvider for handling metadata extraction and extensive test coverage for the new functionality. The documentation has also been updated nicely.
However, I've found a critical issue in the predicate extraction logic (_extract_filters_from_predicate) that incorrectly handles AND and OR operators in certain cases. This can lead to incorrect filtering or reduced pushdown effectiveness. I've detailed this in a specific comment. Once this is addressed, this will be a great addition to Ray Data.
Fixes critical issues in predicate pushdown:
1. OR predicates: Only push down when both sides reference same column type.
Skip pushdown for OR on different columns (e.g., topic | log_time) to avoid
incorrect AND logic.
2. AND predicates: Correctly intersect filters for same column (e.g.,
topic.is_in([A,B]) & topic.is_in([B,C]) -> {B}), union for different columns.
3. Commutative expressions: Handle both col("log_time") > 1000 and
1000 < col("log_time") by swapping operands and inverting operators.
4. Duplicate filtering: Track pushed-down filters to avoid applying predicate
expression twice. Still apply predicate if it contains unpushed parts.
This ensures correct filtering behavior and optimal performance.
Signed-off-by: soffer-anyscale <[email protected]>
- Shortened verbose docstrings to match other Ray Data datasources - Consolidated helper functions (intersect_sets/union_sets -> update_set) - Removed redundant comments and explanations - Simplified predicate extraction logic while preserving functionality - Reduced file from 948 to 628 lines (~34% reduction) Signed-off-by: soffer-anyscale <[email protected]>
Removed _has_unpushed_predicate method and _pushed_down_* attributes that were not providing value. Simplifies code while maintaining correctness - predicate expression is always applied if present to ensure all filters are handled correctly. Signed-off-by: soffer-anyscale <[email protected]>
Signed-off-by: soffer-anyscale <[email protected]>
- Add get_column_name() helper that recursively extracts column names from nested BinaryExpr objects
- Add can_pushdown_or() to detect when both sides of OR reference the same column
- Fix OR expression handling to properly detect identical columns in comparisons
- Add comprehensive test for OR expressions with same column
Previously, get_column_name() only checked direct ColumnExpr objects,
causing it to return None for BinaryExpr objects like (col("topic") == value).
This prevented can_pushdown_or() from detecting that both sides of an OR
expression reference the same column, preventing pushdown optimization.
Now expressions like (col("topic") == "/a") | (col("topic") == "/b")
are correctly detected and pushed down as topics={"/a", "/b"}.
Signed-off-by: soffer-anyscale <[email protected]>
- Add clarifying comment about _predicate_expr initialization - Use explicit None check for predicate expression - Fix formatting for long lines (ruff auto-fix) Signed-off-by: soffer-anyscale <[email protected]>
Resolved conflicts by merging best parts from both branches:
- Kept recursive get_column_name from HEAD (handles nested expressions)
- Integrated commutative expression handling from remote (e.g., 1000 < col("log_time"))
- Used is_and_context parameter for proper AND/OR handling
- Simplified docstrings for cleaner code
- Fixed can_pushdown_or to use recursive column extraction
Signed-off-by: soffer-anyscale <[email protected]>
- Simplify predicate extraction using get_column_references utility - Remove complex expression parsing code (~75% reduction) - Add MCAP library documentation URLs in comments - Extract only simple filters (EQ/IN, comparisons) for file-level pushdown - Let PyArrow handle complex predicates at block level - Add helper methods to TimeRange for cleaner code - Remove unused helper functions and constants - Improve code comments with third-party library references Signed-off-by: soffer-anyscale <[email protected]>
- Remove manual path column addition in _message_to_dict (FileBasedDatasource handles it) - Fix _merge_filters to distinguish None (no filter) from empty set (filter to nothing) - Use 'is None' check instead of falsy check for proper filter merging Signed-off-by: soffer-anyscale <[email protected]>
- Fix _merge_time_ranges using wrong falsy check (use 'is None' not falsy) - Fix resource leak: move summary extraction inside context manager - Fix topics_list: distinguish empty set (exclude all) from None (no filter) - Fix IN operation: handle string values correctly (single value, not chars) - Fix integer overflow: validate time values before arithmetic operations - Fix empty string handling: allow empty strings as valid topic/schema names - Fix _should_include_file: correct logic for empty sets vs None - Fix duplicate message.data check: remove redundant condition - Add null checks: validate channel, message, schema, reader, filesystem - Add validation: negative file sizes, negative time values, invalid ranges - Add validation: file_sizes length matching paths, duplicate paths - Add validation: None checks for arrow tables, filter expressions - Add validation: path normalization, empty string filtering - Add validation: time range bounds validation before creation - Add error handling: better exception messages and validation - Fix edge cases: None handling in statistics, channels, schemas - Fix edge cases: empty iterator handling, invalid message items - Fix edge cases: predicate expression combination failures Signed-off-by: soffer-anyscale <[email protected]>
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
|
This pull request has been automatically closed because there has been no more activity in the 14 days Please feel free to reopen or open a new pull request if you'd still like this to be addressed. Again, you can always ask for help on our discussion forum or Ray's public slack channel. Thanks again for your contribution! |
Add file-level predicate pushdown and metadata filtering for MCAP datasource
Description
This PR adds file-level predicate pushdown and comprehensive filtering capabilities to the MCAP (Message Capture) datasource. The implementation enables reading from directories with efficient file-level filtering using metadata, significantly improving performance when processing large collections of MCAP files.
New Features
File-Level Predicate Pushdown
ray.data.filter()for topic, time range, and message type filteringFiltering Capabilities
topicsparameter orcol("topic")expressionsTimeRangeobjects or tuples, supportscol("log_time")comparisons (<,<=,>,>=)message_typesparameter orcol("schema_name")expressionsTimeRange Dataclass
TimeRangedataclass for specifying time ranges with validationTimeRangeobjectsImplementation Details
supports_predicate_pushdown()andapply_predicate()expand_paths()filters files based on metadata before readingCode Quality Improvements
API Changes
New Parameters
topics: Optional list/set of topic names to filter messagestime_range: OptionalTimeRangeobject or tuple(start_time, end_time)for time-based filteringmessage_types: Optional list/set of schema names to filter messagesinclude_metadata: Whether to include MCAP metadata fields (default: True)New Classes
MCAPFileMetadataProvider: File metadata provider for efficient file-level filteringTimeRange: Dataclass for time range filtering with validationPredicate Pushdown Support
supports_predicate_pushdown(): ReturnsTruefor MCAP datasourceapply_predicate(): Extracts filters from predicate expressions and applies file-level filteringcol("topic"),col("log_time"), andcol("schema_name")expressionsUsage Examples
Basic Reading with Filters
Predicate Pushdown with File-Level Filtering
Time Range Filtering (Backwards Compatible)
Changes
New Features
col()expressions for pushdownDocumentation and Code Quality
https://mcap.dev/andhttps://github.com/foxglove/mcap) to documentationRetryingPyFileSystem,Partitioning)ruff checkwith zero errorsTest Coverage Improvements
TimeRangevalidation (start >= end, negative times)<,>=,>,<=)Code Structure
parquet_datasource.py,json_datasource.py)Testing
All tests follow Ray Data testing standards:
ray_start_regular_shared,tmp_path)count(),input_files())Test Coverage
Basic Functionality:
Filtering:
topicsparameter)TimeRangeformats)message_typesparameter)Predicate Pushdown:
col("topic")expressionscol("log_time")with<,<=,>,>=operatorscol("schema_name")expressionsFile-Level Filtering:
Edge Cases:
TimeRangevalidation (start >= end, negative times)Configuration:
include_metadataoptioninclude_pathsoptionoverride_num_blocksparameterignore_missing_pathsparameterRelated Issues
Related to the MCAP datasource feature implementation with file-level predicate pushdown support.