Skip to content

[Data][DatasourceV2][3/n] Parquet scanner and file reader - #62182

Merged
richardliaw merged 11 commits into
ray-project:masterfrom
goutamvenkat-anyscale:datasource-v2/parquet-scanner-reader
Apr 11, 2026
Merged

richardliaw merged 11 commits into
ray-project:masterfrom
goutamvenkat-anyscale:datasource-v2/parquet-scanner-reader

Conversation

@goutamvenkat-anyscale

@goutamvenkat-anyscale goutamvenkat-anyscale commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Introduces the V2 scanner and reader hierarchy for file-based datasources, starting with Parquet. This lays the groundwork for migrating from the monolithic ParquetDatasource to 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 : creates
Loading

Key design decisions

  • Immutable: All scanners are frozen dataclasses. Pushdown operations return new instances via dataclasses.replace().
  • scan_batches() over to_batches(): Uses PyArrow's TaggedRecordBatch to track which fragment each batch came from, enabling include_paths without per-file iteration.
  • Adaptive batch sizing: ParquetFileReader estimates batch size from row group metadata (no remote sampling tasks), then refines from actual in-memory sizes at read time.
  • Trait-based pushdowns: SupportsFilterPushdown, SupportsColumnPruning, SupportsLimitPushdown, SupportsPartitionPruning mixins 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 reading
  • File shuffle: Randomizing file read order across executions
  • Legacy tensor type check: check_for_legacy_tensor_type() for old extension types
  • Ray Client local scheduling: NodeAffinitySchedulingStrategy for local file reads
  • Stub column for empty projections: _BATCH_SIZE_PRESERVING_STUB_COL_NAME

Integration work:

  • ReadV2 logical operator wiring scanner into the logical plan
  • Schema propagation: bottom-up output_schema on all logical operators
  • Lazy file listing: LazyFileIndex with budget-based driver/worker split
  • read_parquet() flag: _use_v2 / DataContext.use_datasource_v2 toggle

🤖 Generated with Claude Code

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]>
@goutamvenkat-anyscale
goutamvenkat-anyscale requested a review from a team as a code owner March 30, 2026 08:26

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Fix in Cursor Fix in Web

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]>
@goutamvenkat-anyscale goutamvenkat-anyscale changed the title [Data] Add DatasourceV2 Parquet scanner and file reader [Data][DatasourceV2] Parquet scanner and file reader Mar 30, 2026
@goutamvenkat-anyscale goutamvenkat-anyscale changed the title [Data][DatasourceV2] Parquet scanner and file reader [Data][DatasourceV2][4/n] Parquet scanner and file reader Mar 30, 2026
@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Mar 30, 2026
@goutamvenkat-anyscale goutamvenkat-anyscale changed the title [Data][DatasourceV2][4/n] Parquet scanner and file reader [Data][DatasourceV2][3.5/n] Parquet scanner and file reader Mar 30, 2026
@goutamvenkat-anyscale goutamvenkat-anyscale changed the title [Data][DatasourceV2][3.5/n] Parquet scanner and file reader [Data][DatasourceV2][3/n] Parquet scanner and file reader Mar 30, 2026

@iamjustinhsu iamjustinhsu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mostly questions + nits


@abstractmethod
def read(self, input_split: FileManifest) -> Iterator[pa.Table]:
def read(self, input_split: FileManifest) -> Generator[pa.Table, None, None]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched it to an iterator

def __init__(
self,
format: FileFormat,
batch_size: int = _ARROW_DEFAULT_BATCH_SIZE,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just want to double check -- are we assuming all subclasses will use pyarrow tables? for example, will there be some read_json using pandas

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an opportunity for us to use Arrow for json workloads to unify things

@goutamvenkat-anyscale goutamvenkat-anyscale Apr 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh we want a subset of the row group that the fragment is referring to.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is residual supposed to be a fallback if the underlying datasource cannot prune at read time?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how come you have to convert to str()?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just so i understand -- self.partitioning is for path filtering, and partition_predicate is another filter for those that match that predicate?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes


Args:
predicate: Expression to evaluate against partition values.
partition_columns: Set of column names that are partition columns.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how come you removed from the base?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The partition columns will be a property of the Scanner so it's not needed to be passed in explicitly in this interface.

Comment on lines +149 to +160
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i feel like this should be in its own method

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved it

@goutamvenkat-anyscale goutamvenkat-anyscale added the go add ONLY when ready to merge, run all tests label Apr 9, 2026
@goutamvenkat-anyscale
goutamvenkat-anyscale requested a review from a team as a code owner April 10, 2026 20:08
- 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]>
@goutamvenkat-anyscale
goutamvenkat-anyscale force-pushed the datasource-v2/parquet-scanner-reader branch from 7659168 to 103046a Compare April 10, 2026 20:11
Signed-off-by: Goutam <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Signed-off-by: Goutam <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 3c2aba2. Configure here.

pa.array([fragment_path] * table.num_rows, type=pa.string()),
)

self._on_batch_read(table)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3c2aba2. Configure here.

@richardliaw
richardliaw merged commit 947d18a into ray-project:master Apr 11, 2026
3 checks passed
@goutamvenkat-anyscale
goutamvenkat-anyscale deleted the datasource-v2/parquet-scanner-reader branch April 11, 2026 01:30
goutamvenkat-anyscale added a commit that referenced this pull request Apr 21, 2026
…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]>
HLDKNotFound pushed a commit to chichic21039/ray that referenced this pull request Apr 22, 2026
HLDKNotFound pushed a commit to chichic21039/ray that referenced this pull request Apr 22, 2026
…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]>
Lucas61000 pushed a commit to Lucas61000/ray that referenced this pull request May 15, 2026
Lucas61000 pushed a commit to Lucas61000/ray that referenced this pull request May 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants