Repository navigation
[Data][DatasourceV2][3/n] Parquet scanner and file reader - #62182
richardliaw merged 11 commits into
Conversation
Introduces the V2 scanner and reader hierarchy for file-based datasources, starting with Parquet: - ArrowFileScanner: base scanner for Arrow-backed formats with filter pushdown, column pruning, limit pushdown, and partition pruning via immutable frozen dataclasses - ParquetScanner: Parquet-specific scanner with adaptive batch sizing and include_paths support - FileReader: generic file reader using PyArrow Dataset API with scan_batches() for fragment-level path tracking - ParquetFileReader: Parquet reader with metadata-based batch size estimation and adaptive refinement from actual data - InMemorySizeEstimator: format-aware in-memory size estimation - Updated partitioning to support predicate evaluation on partition values from file paths Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a new architecture for file-based data reading in Ray Data (v2), specifically focusing on PyArrow Dataset integration. It adds ArrowFileScanner and ParquetScanner to handle logical optimizations like filter pushdown, column pruning, and partition pruning. A key feature is the introduction of adaptive batch sizing in ParquetFileReader, which estimates optimal batch sizes using Parquet metadata and refines them based on actual in-memory data. Additionally, it includes utility methods for converting Ray partitioning configurations to PyArrow and a new ParquetInMemorySizeEstimator. I have no feedback to provide.
| row_group_meta.column(i).total_uncompressed_size for i in col_indices | ||
| ) | ||
|
|
||
| estimated_in_mem_size = uncompressed_size * PARQUET_ENCODING_RATIO_ESTIMATE_DEFAULT |
There was a problem hiding this comment.
Encoding ratio misapplied to uncompressed Parquet sizes
Medium Severity
_estimate_batch_size_from_metadata multiplies total_uncompressed_size by PARQUET_ENCODING_RATIO_ESTIMATE_DEFAULT (5), but this constant represents the ratio of in-memory size to on-disk compressed size (as defined in V1's _estimate_files_encoding_ratio and V2's own ParquetInMemorySizeEstimator). Applying it to the already-uncompressed size overestimates in-memory size by the compression ratio (~2–3×), producing batch sizes that are roughly half the intended size.
Make batch_size optional on ArrowFileScanner (default None) so that ParquetScanner can omit it, allowing ParquetFileReader to fall through to metadata-based estimation and adaptive refinement. Previously batch_size was a required int, always truthy, so _explicit_batch_size was always set and target_block_size was dead. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
iamjustinhsu
left a comment
There was a problem hiding this comment.
mostly questions + nits
|
|
||
| @abstractmethod | ||
| def read(self, input_split: FileManifest) -> Iterator[pa.Table]: | ||
| def read(self, input_split: FileManifest) -> Generator[pa.Table, None, None]: |
There was a problem hiding this comment.
ooc, what is Nones susposed to represent? Unrelated, but could be good in the future to either have more of a descriptive yields comment, or just type annotate that away
There was a problem hiding this comment.
Switched it to an iterator
| def __init__( | ||
| self, | ||
| format: FileFormat, | ||
| batch_size: int = _ARROW_DEFAULT_BATCH_SIZE, |
There was a problem hiding this comment.
Just want to double check -- are we assuming all subclasses will use pyarrow tables? for example, will there be some read_json using pandas
There was a problem hiding this comment.
This is an opportunity for us to use Arrow for json workloads to unify things
There was a problem hiding this comment.
To make this explicit, we can make an ArrowFileReader that extends from FileReader to separate responsibilities. Can make this a follow up
| Estimated batch size in rows, or None if metadata is unavailable. | ||
| """ | ||
| try: | ||
| metadata: pq.FileMetaData = fragment.metadata |
There was a problem hiding this comment.
when can this error out? Should there be retries? I'm wondering if we should log at least once, but not sure what exceptions should be thrown. Should we narrow the exceptions?
There was a problem hiding this comment.
Expanded on the underlying exceptions, and clarified in the comments about how it can arise.
| return None | ||
|
|
||
| row_group_idx = fragment.row_groups[0].id if fragment.row_groups else 0 | ||
| row_group_meta: pq.RowGroupMetaData = metadata.row_group(row_group_idx) |
There was a problem hiding this comment.
how come you can't do something like this:
row_group_meta: pq.RowGroupMetaData = metadata.row_group(row_group_idx)or is the row_group_idx won't necessarily start at 0?
There was a problem hiding this comment.
Oh we want a subset of the row group that the fragment is referring to.
There was a problem hiding this comment.
Going to simplify by just fetching fragment.row_groups[0].id
|
|
||
| Returns: | ||
| A pair ``(scanner, residual)`` where ``scanner`` has the predicate | ||
| merged into its PyArrow filter. ``residual`` is ``None`` because |
There was a problem hiding this comment.
is residual supposed to be a fallback if the underlying datasource cannot prune at read time?
There was a problem hiding this comment.
Yes. Some datasources don't support pruning at read time.
|
|
||
| for i, path in enumerate(manifest.paths): | ||
| if parser.evaluate_predicate_on_partition( | ||
| str(path), self.partition_predicate |
There was a problem hiding this comment.
how come you have to convert to str()?
There was a problem hiding this comment.
path has to be a string. Let me try without the explicit cast
| Returns: | ||
| A new FileManifest containing only matching files. | ||
| """ | ||
| parser = PathPartitionParser(self.partitioning) |
There was a problem hiding this comment.
just so i understand -- self.partitioning is for path filtering, and partition_predicate is another filter for those that match that predicate?
|
|
||
| Args: | ||
| predicate: Expression to evaluate against partition values. | ||
| partition_columns: Set of column names that are partition columns. |
There was a problem hiding this comment.
how come you removed from the base?
There was a problem hiding this comment.
The partition columns will be a property of the Scanner so it's not needed to be passed in explicitly in this interface.
| type_map = { | ||
| int: pa.int64(), | ||
| float: pa.float64(), | ||
| bool: pa.bool_(), | ||
| str: pa.string(), | ||
| } | ||
| fields = [] | ||
| for name in field_names: | ||
| py_type: PartitionDataType = field_types.get(name, str) | ||
| pa_type = type_map.get(py_type, pa.string()) | ||
| fields.append(pa.field(name, pa_type)) | ||
| schema = pa.schema(fields) |
There was a problem hiding this comment.
i feel like this should be in its own method
There was a problem hiding this comment.
Moved it
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
- Guard against fragment.row_groups being None for whole-file fragments - Use per-column total_uncompressed_size instead of total_byte_size which can return compressed size (apache/arrow#48138) - Lazily fetch only the first fragment instead of materializing all - Reuse local metadata variable instead of re-accessing fragment.metadata Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
7659168 to
103046a
Compare
Signed-off-by: Goutam <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 2 total unresolved issues (including 1 from previous review).
Reviewed by Cursor Bugbot for commit 3c2aba2. Configure here.
| pa.array([fragment_path] * table.num_rows, type=pa.string()), | ||
| ) | ||
|
|
||
| self._on_batch_read(table) |
There was a problem hiding this comment.
Batch size estimate inflated by synthetic path column
Low Severity
_on_batch_read is called after the synthetic "path" column is appended to the table (when include_paths=True). ParquetFileReader._on_batch_read uses table.nbytes / table.num_rows to estimate row size for adaptive batch sizing, so the path strings inflate the estimate. For narrow tables (e.g., a few integer columns), long file paths can significantly inflate nbytes, causing _sampled_batch_size to be much smaller than optimal. Moving the _on_batch_read call before the path-column append would give an accurate estimate of the actual Parquet data size.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 3c2aba2. Configure here.
…sor check, local scheduling (#62785) ## Description Followups from #62182 Basically this ports over remaining functionality from V1 parquet datasource. Also not porting over `block_udf`. We will be deprecating that param in DatasourceV2, since it's only used in tests. ## Related issues > Link related issues: "Fixes #1234", "Closes #1234", or "Related to #1234". ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Goutam <[email protected]>
…sor check, local scheduling (ray-project#62785) ## Description Followups from ray-project#62182 Basically this ports over remaining functionality from V1 parquet datasource. Also not porting over `block_udf`. We will be deprecating that param in DatasourceV2, since it's only used in tests. ## Related issues > Link related issues: "Fixes ray-project#1234", "Closes ray-project#1234", or "Related to ray-project#1234". ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Goutam <[email protected]>
…sor check, local scheduling (ray-project#62785) ## Description Followups from ray-project#62182 Basically this ports over remaining functionality from V1 parquet datasource. Also not porting over `block_udf`. We will be deprecating that param in DatasourceV2, since it's only used in tests. ## Related issues > Link related issues: "Fixes ray-project#1234", "Closes ray-project#1234", or "Related to ray-project#1234". ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Goutam <[email protected]>


Summary
Introduces the V2 scanner and reader hierarchy for file-based datasources, starting with Parquet. This lays the groundwork for migrating from the monolithic
ParquetDatasourceto a modular, immutable, layered architecture.Class Hierarchy
classDiagram class Scanner~InputBucket~ { <<abstract>> +read_schema() Schema +plan(manifest, parallelism) List~InputBucket~ +create_reader() Reader } class FileScanner { +plan(manifest, parallelism) List~FileManifest~ } class ArrowFileScanner { +schema: Schema +columns: Tuple[str] +predicate: Expression +limit: int +push_filters(predicate) +prune_columns(columns) +push_limit(limit) +prune_partitions(predicate) } class ParquetScanner { +target_block_size: int +include_paths: bool +read_schema() Schema +create_reader() ParquetFileReader } class Reader~InputBucket~ { <<abstract>> +read(input_split) Iterator~Table~ } class FileReader { +read(manifest) Generator~Table~ } class ParquetFileReader { +_resolve_batch_size(dataset) int +_on_batch_read(table) } Scanner <|-- FileScanner FileScanner <|-- ArrowFileScanner ArrowFileScanner <|-- ParquetScanner Reader <|-- FileReader FileReader <|-- ParquetFileReader ArrowFileScanner ..|> SupportsFilterPushdown ArrowFileScanner ..|> SupportsColumnPruning ArrowFileScanner ..|> SupportsLimitPushdown ArrowFileScanner ..|> SupportsPartitionPruning ParquetScanner --> ParquetFileReader : createsKey design decisions
dataclasses.replace().scan_batches()overto_batches(): Uses PyArrow'sTaggedRecordBatchto track which fragment each batch came from, enablinginclude_pathswithout per-file iteration.ParquetFileReaderestimates batch size from row group metadata (no remote sampling tasks), then refines from actual in-memory sizes at read time.SupportsFilterPushdown,SupportsColumnPruning,SupportsLimitPushdown,SupportsPartitionPruningmixins on the scanner — the optimizer dispatches on these.Follow-up work (not in this PR)
Features from V1
ParquetDatasource:block_udf: User-supplied transform applied per batch after readingcheck_for_legacy_tensor_type()for old extension typesNodeAffinitySchedulingStrategyfor local file reads_BATCH_SIZE_PRESERVING_STUB_COL_NAMEIntegration work:
ReadV2logical operator wiring scanner into the logical planoutput_schemaon all logical operatorsLazyFileIndexwith budget-based driver/worker splitread_parquet()flag:_use_v2/DataContext.use_datasource_v2toggle🤖 Generated with Claude Code