Skip to content

[Data] Add ORC support to DataSourceV2 - #66524

Merged
richardliaw merged 24 commits into
ray-project:masterfrom
jiangxt2:feature/orc-scanner-reader
Oct 15, 2026
Merged

richardliaw merged 24 commits into
ray-project:masterfrom
jiangxt2:feature/orc-scanner-reader

Conversation

@jiangxt2

@jiangxt2 jiangxt2 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR adds an internal ORC scanner and reader to DataSourceV2. OrcScanner and OrcFileReader reuse ArrowFileScanner and FileReader with PyArrow OrcFileFormat to scan whole-file fragments in batches. They support column projection, Arrow-evaluated row filters, limits, synthesized path/partition columns, and alignment to a supplied schema (including nulls for missing file columns). OrcFileReader retains Ray's pickled-object-column safety check. The PR also registers FileFormat.ORC and adds direct FileManifest tests.

This PR also wires public read_orc() to OrcDatasourceV2 through the shared DataContext.use_datasource_v2 flag, which defaults to true. Setting it to false selects V1; RAY_DATA_USE_DATASOURCE_V2 configures the same flag. Path filtering via partition_filter is supported. The datasource reuses generic file components and bounded schema sampling; columns present only in files outside the sample may be omitted. Stripe-level Ray task splitting and ORC-native predicate pruning remain follow-up work; DataSourceV2 abstract interfaces are unchanged.

When partitioning is enabled in V2, directory values take precedence over same-named file columns. Partition predicates prune known nonmatching files before scanning; files with missing path keys retain the complete read filter. Existing partition-directory validation remains unchanged.

The related ORC V2 PR #64540 is closed and unmerged; it used the retired FileChunker design. This implementation reuses the existing ArrowFileScanner and FileReader interfaces.

Related issues

Fixes #66526.

Additional information

Known limitations

ORC V2 shares two filtering issues with Parquet V2 in the common file-reading path. Partition pruning can fail when parsed partition-value types differ from the Dataset's logical schema, as tracked in #66915. Expression filters on a synthesized path column can return incorrect rows when a partition directory is also named path, or raise a missing-field error without partitioning, as tracked in #66916. Both issues are tracked separately and remain unresolved by this PR. Path selection through partition_filter is distinct from expression filtering on the synthesized path column.

Validation

  • python -m pytest -q python/ray/data/tests/unit/datasource_v2/test_orc_file_reader.py python/ray/data/tests/unit/datasource_v2/test_orc_datasource_v2.py python/ray/data/tests/unit/datasource/test_pickle_gate_coverage.py python/ray/data/tests/unit/datasource_v2/test_file_scanner.py python/ray/data/tests/unit/datasource_v2/test_derive_list_files_pushdown.py passed with Python 3.12.13 and PyArrow 23.0.1: 426 tests, with no failures, errors, or skips.
  • python -m pytest -q python/ray/data/tests/datasource/test_orc.py passed with Python 3.12.13 and PyArrow 23.0.1: 149 tests covering V1/V2 public reads, partition handling, filtering, projection, limits, and ORC read/write round trips, with no failures, errors, or skips.
  • Pyrefly 0.51.0 checked all ORC implementation and test files: 0 errors.
  • python ci/pipeline/check-test-run.py passed.
  • Repository hooks passed for the changed files, including Ruff, Black, pydoclint, AST, docstyle, and import checks.
  • Semgrep checked orc_scanner.py and test_orc_file_reader.py: no findings or errors.
  • PyArrow 17 compatibility was verified for OrcFileFormat fragment scanning, batch_size, batch_readahead, and missing-column null-fill alignment.

PyArrow applies ORC row filters after reading selected columns; this PR does not claim ORC-native stripe pruning or a fixed decoded-memory bound from batch_size.

AI assistance was used: Codex helped implement the change and draft this PR; Claude assisted with planning and code review.

@jiangxt2
jiangxt2 marked this pull request as ready for review September 30, 2026 12:04
@jiangxt2
jiangxt2 requested a review from a team as a code owner September 30, 2026 12:04

jiangxt2 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Non-blocking follow-up: stop reading promptly after reaching limit

FileReader.read() checks whether the limit has been reached only after requesting the next (table, position) pair from _read_fragment_batches():

for table, position in self._read_fragment_batches(...):
    if self._limit is not None:
        if rows_read >= self._limit:
            break

If the previously yielded table already brought rows_read to the limit, requesting the next pair can read another batch or advance to the next fragment before this guard runs. The output row count is still bounded by the limit, but the reader can perform avoidable I/O, especially with remote filesystems.

OrcFileReader and ParquetFileReader are sibling subclasses: both inherit directly from FileReader, and both pass limit to the base class. Neither inherits from the other. As a result, this behavior is shared with the V2 read_parquet path. Could we track or fix this once in FileReader and add a multi-fragment regression test? I don’t think an ORC-only workaround is needed in this PR.

References: FileReader.read(), OrcFileReader, ParquetFileReader, read_parquet V2 routing.

@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 adds support for reading ORC files in Ray Data (v2 datasource) by introducing OrcFileReader and OrcScanner, along with comprehensive unit tests. The feedback suggests improving the robustness of OrcScanner.read_schema to handle projected synthesized columns without raising an AssertionError from the base class, and calling super()._on_batch_read in OrcFileReader to ensure base class hooks are properly executed.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Sep 30, 2026
Move the ORC reader and scanner into the current DataSourceV2 format layout. Handle projected synthesized columns missing from the input schema, align synthesized output types, and call the base batch hook before applying the ORC pickle check.

Signed-off-by: jiangxt2 <[email protected]>
@AarryaSaraf AarryaSaraf self-assigned this Oct 1, 2026
@richardliaw

Copy link
Copy Markdown
Contributor

will review this tomorrow

@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.

Stale Bugbot comment from a previous run.

- Column pruning
- Filter pushdown (row group pruning)
- Batch-level filtering
PyArrow's Dataset API handles column pruning and batch-level filtering.

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.

let's leave this here

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.

Agreed. The updated docstring clarifies that metadata pruning depends on the file format, so I’ll keep it as is.

Comment on lines +42 to +54
"""Configure a whole-file ORC scan.

Args:
batch_size: Maximum number of output rows per Arrow batch.
columns: Columns to read, or None for all columns.
predicate: Row filter applied by the Arrow scanner.
limit: Maximum number of output rows.
filesystem: Filesystem used to open ORC files.
partitioning: Optional path partitioning specification.
ignore_prefixes: File prefixes to ignore.
synthesized_columns: Columns appended after scanning each batch.
schema: Logical schema used to align file fragments.
"""

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.

since this is a passthrough function you can probably just skip this

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.

Removed the pass-through __init__ from OrcFileReader; OrcScanner now passes format=FileFormat.ORC directly to FileReader. Thanks for the suggestion.

@richardliaw

Copy link
Copy Markdown
Contributor

shouldn't we update the read api as well so that it uses this codepath?

index = self.schema.get_field_index(name)
assert index >= 0, f"Column {name} not found in schema"
fields.append(self.schema.field(index))
return 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.

we will want to make this generalized later on / put this inside arrow file scanner and invoke it in orc scanner

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.

Agreed. I’ll keep the ORC-specific read_schema() implementation in this PR. We can generalize this schema handling in ArrowFileScanner later and have OrcScanner call the shared implementation.

# (pyarrow reads these) and ones we need to synthesize post-read
# (hive partition keys, ``path``, ``row_hash``). ``self._columns
# is None`` means "no projection" — read every file column and
# synthesize every available partition/synthesized column.

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.

Why does this need to change the shared reader? It only seems to matter when Hive field_names is unset, and the datasource sets it before reading (ParquetDatasourceV2.resolve_partitioning). Is there a path where it stays unset?

@jiangxt2 jiangxt2 Oct 2, 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.

field_names can remain unset for mixed paths when the first sampled file is unpartitioned. I’ve reverted the shared Hive fallback and Parquet test, keeping this PR focused on ORC. Unprojected ORC output ordering is now handled in OrcFileReader. I’d welcome your thoughts.


index = self.schema.get_field_index(name)
assert index >= 0, f"Column {name} not found in schema"
fields.append(self.schema.field(index))

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.

Theres a small difference in how synthesized columns are handled rn but its fine without that. I think the read_schema should move to ArrowFileScanner and Parquet should still keep its check_for_legacy_tensor_types.

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.

Thanks, this is aligned with Richard’s suggestion. I’m inclined to keep the ORC-specific read_schema() in this PR and generalize the shared schema handling in ArrowFileScanner in a follow-up. Your note about preserving Parquet’s check_for_legacy_tensor_types is helpful; I’ll account for it in that design. Would that scope work for you?

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.

That works. I'll move read_schema into ArrowFileScanner in a separate PR (Parquet keeps its tensor check), together with resolve_partitioning and the partition/synthesized-column step of infer_schema, which are the same as Parquet's. ORC can drop its copies after that; nothing to change here.

@AarryaSaraf

Copy link
Copy Markdown
Contributor

Thanks, this is a clean, small base for ORC on DSv2. Some ideas for later, not for this PR:

  1. We, of course, needs to implement the DataSource, indexer, partitioner etc for this.
  2. We want a smaller granularity for a read
  3. We can have min/max pruning
  4. A better size estimator is needed.

fields.append(self.schema.field(index))
return pa.schema(fields)

def create_reader(self) -> OrcFileReader:

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.

The batch size is always 131,072 rows, independent of the row width. ParquetFileReader._resolve_batch_size derives the row count from target_block_size instead. Something similar could work here.

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.

Good point. The default batch size is 131,072 rows regardless of row width. The large-stripe measurement for this PR used an explicit batch_size of 4,096, so it does not characterize the default for wide rows or establish a memory bound. I’m inclined to keep this PR focused on the file-level reader and evaluate adaptive sizing separately, once OrcDatasourceV2 can pass the target block size and we can benchmark an ORC-specific estimate. Would that split work for you, or do you consider adaptive sizing necessary for this PR?

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.

That split works. Since OrcDatasourceV2 is in this PR now, the follow-up can pass target_max_block_size through create_scanner the way ParquetDatasourceV2.create_scanner does.

@jiangxt2

jiangxt2 commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

shouldn’t we update the read api as well so that it uses this codepath?

Thanks for raising this. I’m inclined to keep this PR focused on the file-level ORC scanner and reader, then add OrcDatasourceV2 with file discovery, partitioning, and bounded schema inference in a follow-up. Once that datasource is in place, we can wire read_orc through an opt-in V1/V2 path, keeping V1 as the default while we validate end-to-end compatibility. A default switch can be considered separately after we have compatibility and performance results. This lets the scanner and reader be tested directly with a FileManifest without routing the public API to an incomplete datasource.

I’d be interested to hear your thoughts on this staged approach.

@richardliaw

Copy link
Copy Markdown
Contributor

It seems pretty easy to wire it in? I would opt to do that all together in this PR

self._broadcast_partition_value(name, value, table.num_rows),
)
if residual_predicate is not None:
table = table.filter(residual_predicate.to_pyarrow())

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.

This could be hoisted outside the loop

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 residual_predicate.to_pyarrow() before the batch loop. The converted expression is reused for each batch; table.filter() still runs after partition values are appended and before the table is yielded.

) -> Tuple["ArrowFileScanner", Optional[Expr]]:
"""Keep predicates on post-read synthesized columns above the read."""
if self.partitioning is not None:
# These columns are generated by the base reader after the fragment

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.

Comment could be simplified.

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.

Simplified the comment to explain that synthesized columns are added after scanning, so filters referencing them stay above the read.

@DeveloperAPI
@dataclass(frozen=True)
class OrcScanner(ArrowFileScanner):
"""Configure a file-level ORC scan through PyArrow Dataset."""

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.

nit: this doesn't say what OrcScanner changes from ArrowFileScanner.

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 the class docstring to describe the ORC reader setup and the schema, partition-pruning, and synthesized-column handling it adds to ArrowFileScanner.

yield table

@override
def _iter_fragment_tables(

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.

nit: could this have a docstring?

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.

Added a docstring describing physical-column scanning, path-derived partition synthesis, and residual filtering.

Remove a redundant column assignment, convert the residual filter once before batch scanning, and clarify ORC-specific partition and synthesized-column behavior.

Signed-off-by: jiangxt2 <[email protected]>
@jiangxt2

Copy link
Copy Markdown
Contributor Author

Thank you for raising these issues. Would you like to work on them? As for the PR, I am happy with this implementation. Theres a few code quality nits after which I'd be glad to approve.

Thanks for the review. I've addressed the code quality comments in this PR, and I'd be happy to work on the three follow-up issues. I'll design experiments to further validate the reported behavior and explore fixes that fit Ray Data's existing design.

Remove partial-key predicate evaluation that cannot be reached through read_orc planning and drop its dedicated type/schema dependencies. Keep missing-key file retention, complete partition pruning, and reader filtering.

Retain direct scanner/reader regression cases with updated deferral expectations and use resolved fields in the pruning matrix.

Signed-off-by: jiangxt2 <[email protected]>
@abhishekverma-ray

Copy link
Copy Markdown
Contributor

LGTM, and thanks for the careful iteration on the partition handling, the regression tests cover the tricky cases well. Two small follow-ups I’d like to see tracked since V2 is now the default for ORC: wiring target_max_block_size through create_scanner so batch sizing matches Parquet V2 rather than a fixed 131k rows, and a short note in the read_orc docs that RAY_DATA_USE_DATASOURCE_V2=0 restores the V1 reader for anyone affected by the known limitations. Neither needs to block this PR.

@abhishekverma-ray abhishekverma-ray self-assigned this Oct 15, 2026
@abhishekverma-ray
abhishekverma-ray self-requested a review October 15, 2026 04:14

@abhishekverma-ray abhishekverma-ray 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.

LGTM, please do check my comment regarding doc update and debt tracking.

@richardliaw
richardliaw merged commit ed8ddca into ray-project:master Oct 15, 2026
6 checks passed
matthewdeng pushed a commit that referenced this pull request Oct 15, 2026
…ing (#67071)

## Why are these changes needed?

#66524 added a note to the `read_orc` docstring that links
`use_datasource_v2` with `:attr:`. `DataContext` documents its fields in
its class docstring rather than as separate attribute targets, so the
reference doesn't resolve. Read the Docs treats warnings as errors, so
every master docs build since that merge fails:

```
python/ray/data/read_api.py:docstring of ray.data.read_api.read_orc:5: WARNING:
py:attr reference target not found: ray.data.context.DataContext.use_datasource_v2 [ref.attr]
```

First failing master build:
https://app.readthedocs.com/projects/anyscale-ray/builds/4574050/

This PR links the `DataContext` class, which resolves, and names the
setting as inline code. It changes no other wording.

The RtD preview on #66524 never ran. Code-only PRs skip the preview, and
each of its three preview builds was cancelled within about 25 seconds.
The check still showed green. This commit carries an `@rtd-build` line
so this PR's preview actually builds the docs.

cc @jiangxt2 @richardliaw

## Related issue number

Follow-up to #66524.

## Checks

- Not a duplicate: no open PR touches this reference. Searched open PRs
for `use_datasource_v2` and `read_orc`.
- `python ci/ray_ci/doc/check_docstring_only.py --base upstream/master`:
passes, 1 file, docstrings only. This PR carries the `docstring-only`
label.
- `pre-commit run --files python/ray/data/read_api.py`: passes.
- I didn't run a full Sphinx build locally. The `@rtd-build` preview on
this PR verifies the build.
- AI assistance (Claude Code) was used to triage the build failure and
draft this change. I reviewed the change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
richardliaw pushed a commit that referenced this pull request Oct 27, 2026
## Description
Document the V1 fallback in `ray.data.read_orc()` for users who
encounter DataSourceV2 limitations. The API note leads with
`ray.data.DataContext.get_current().use_datasource_v2 = False`, which
can be set after importing Ray and before calling `read_orc()`. It also
documents `RAY_DATA_USE_DATASOURCE_V2=0` before importing Ray. The
shared setting affects `read_parquet()` as well.

This is the non-blocking documentation follow-up requested in
[#66524](#66524 (comment)).

## Related issues
Fixes #67062.

## Additional information
- This PR addresses the documentation task tracked by #67062; no open PR
for this issue was found.
- Documentation-only change; runtime behavior is unchanged.
- Validation: `pre-commit run --files python/ray/data/read_api.py` and
`python3 ci/pipeline/check-test-run.py` passed; Semgrep reported zero
findings for `python/ray/data/read_api.py`.
- Runtime tests were not run. The pre-push hook mapped
`test_delta_sharing.py`, `test_datasource_v2.py`, and
`test_orc_datasource_v2.py` as manual because Ray could not be imported
without `_raylet.so` in this worktree.
- The targeted Sphinx build could not run because `sphinx-build` is
unavailable.
- AI assistance was used to prepare this change.

---------

Signed-off-by: jiangxt2 <[email protected]>
richardliaw pushed a commit that referenced this pull request Oct 27, 2026
## Description

Make ORC DataSourceV2 choose its initial Arrow batch row count from
`DataContext.target_max_block_size` and estimated projected row width,
following the Parquet DSV2 sizing path. An explicit `batch_size` always
takes precedence.

- Pass the target through `OrcDatasourceV2.create_scanner` and
`OrcScanner` to `OrcFileReader`, preserving it across pushdowns.
- Estimate Arrow buffer sizes from the first file's
`serialized_file_tail()` using a small protobuf field subset and the
native ORC type IDs. This adds no data sampling or dependencies.
- Cache the initial estimate or the existing 131,072-row fallback.
Actual output batches refine subsequent `read()` calls on the same
reader.

Projection, filtering, limits, retries, partition handling,
pickle-column checks, and the V1 read path are preserved. There are no
scheduling or stripe-splitting changes.

## Related issues

Fixes #66994. Implements the batch-sizing follow-up agreed in
[#66524](#66524 (comment)).
Searches for open PRs covering #66994 found no duplicate beyond this PR.

## Additional information

### Estimation and limits

The estimate includes selected physical columns and recursively
supported struct/list/map layouts, excluding fields replaced by
partition or synthesized values. Struct children retain parent slots,
including null parents. List element counts require explicit non-null
statistics; map key counts determine entry slots, including nullable
values. The estimate does not trust
`collection_statistics.total_children`. Unsupported selected layouts,
insufficient or invalid statistics, incompatible schemas, and
unavailable metadata fall back without partially summing known columns.

Initial sizing is bounded to at least one row and at most the inspected
file's row count. Metadata estimation can add one file open per reader;
the input closes before scanning. File averages can miss local width
changes. Each `read()` keeps fixed scanner parameters across fragments
and retries, as in Parquet DSV2; observed batches affect later calls.
This does not guarantee a bound on Arrow batch bytes, ORC decoder
memory, or stripe materialization.

### Validation

Linux, Python 3.12.14; all covered runtime cases completed with zero
failures, errors, or skips:

- PyArrow 23.0.1 and 17.0.0: targeted unit coverage for projected layout
sizes, metadata fallbacks, configuration through pushdowns, feedback,
fixed fragment parameters, and limits, with independent expectations for
layout sizes and projection results.
- Both PyArrow versions: nine targeted metadata cases per environment
cover missing private interfaces and DEBUG diagnostics, fallback and
input closure, and valid initial estimates for uncompressed and zstd
files.
- PyArrow 23.0.1: 121 ORC V2 public API cases. Fresh readers scanning
256 rows with approximately 4 KiB strings use 16/32 rows for 64/128 KiB
targets; projection to the narrow column is also verified.
- Cross-version files: six representative layouts in each direction,
verifying estimates/fallback and complete contents. The new parser also
passes a six-file check with protobuf 3.20.3; this is not a full Ray
regression on that protobuf version.
- Real-file I/O and lifetime tests cover metadata-only estimation,
closure on success/fallback/failure, and early termination. Other
coverage includes explicit overrides, negative caching, fixed scan/retry
parameters, and within-file width variation.
- Configured pre-commit checks, Bazel test registration, and Semgrep's
151 Python rules pass. Pyrefly adds no diagnostics; two existing
`infer_schema` diagnostics remain.

Commands to reproduce the covered tests:

```bash
orc_unit_tests=python/ray/data/tests/unit/datasource_v2

# Run in each environment: PyArrow 23.0.1 and 17.0.0
python -m pytest -q \
  "$orc_unit_tests/test_orc_batch_size_estimator.py::test_supported_layouts_use_real_metadata" \
  "$orc_unit_tests/test_orc_batch_size_estimator.py::test_projection_uses_original_type_ids" \
  "$orc_unit_tests/test_orc_batch_size_estimator.py::test_indexless_collection_counts_fall_back" \
  "$orc_unit_tests/test_orc_batch_size_estimator.py::test_metadata_failure_falls_back_and_closes_input" \
  "$orc_unit_tests/test_orc_batch_size_estimator.py::test_first_wide_batch_tracks_target" \
  "$orc_unit_tests/test_orc_file_reader.py::test_orc_reader_batch_sizing_feedback" \
  "$orc_unit_tests/test_orc_file_reader.py::test_orc_reader_batch_sizing_ignores_invalid_observation" \
  "$orc_unit_tests/test_orc_file_reader.py::test_orc_reader_batch_sizing_fragments_are_fixed" \
  "$orc_unit_tests/test_orc_datasource_v2.py::test_orc_batch_sizing_config_survives_pushdowns"

# PyArrow 23.0.1
python -m pytest -q \
  "$orc_unit_tests/test_orc_file_reader.py::test_orc_reader_batch_sizing_retry_keeps_scan_parameters" \
  "$orc_unit_tests/test_orc_file_reader.py::test_orc_reader_local_width_changes_keep_scan_fixed"
python -m pytest -q python/ray/data/tests/datasource/test_orc.py -k "v2 and not v1"
```

AI assistance: Codex assisted with implementation, tests, and code
review.

---------

Signed-off-by: jiangxt2 <[email protected]>
@jiangxt2
jiangxt2 deleted the feature/orc-scanner-reader branch October 27, 2026 07:07
justinyeh1995 pushed a commit to justinyeh1995/ray that referenced this pull request Oct 28, 2026
## Description
Document the V1 fallback in `ray.data.read_orc()` for users who
encounter DataSourceV2 limitations. The API note leads with
`ray.data.DataContext.get_current().use_datasource_v2 = False`, which
can be set after importing Ray and before calling `read_orc()`. It also
documents `RAY_DATA_USE_DATASOURCE_V2=0` before importing Ray. The
shared setting affects `read_parquet()` as well.

This is the non-blocking documentation follow-up requested in
[ray-project#66524](ray-project#66524 (comment)).

## Related issues
Fixes ray-project#67062.

## Additional information
- This PR addresses the documentation task tracked by ray-project#67062; no open PR
for this issue was found.
- Documentation-only change; runtime behavior is unchanged.
- Validation: `pre-commit run --files python/ray/data/read_api.py` and
`python3 ci/pipeline/check-test-run.py` passed; Semgrep reported zero
findings for `python/ray/data/read_api.py`.
- Runtime tests were not run. The pre-push hook mapped
`test_delta_sharing.py`, `test_datasource_v2.py`, and
`test_orc_datasource_v2.py` as manual because Ray could not be imported
without `_raylet.so` in this worktree.
- The targeted Sphinx build could not run because `sphinx-build` is
unavailable.
- AI assistance was used to prepare this change.

---------

Signed-off-by: jiangxt2 <[email protected]>
justinyeh1995 pushed a commit to justinyeh1995/ray that referenced this pull request Oct 28, 2026
## Description

Make ORC DataSourceV2 choose its initial Arrow batch row count from
`DataContext.target_max_block_size` and estimated projected row width,
following the Parquet DSV2 sizing path. An explicit `batch_size` always
takes precedence.

- Pass the target through `OrcDatasourceV2.create_scanner` and
`OrcScanner` to `OrcFileReader`, preserving it across pushdowns.
- Estimate Arrow buffer sizes from the first file's
`serialized_file_tail()` using a small protobuf field subset and the
native ORC type IDs. This adds no data sampling or dependencies.
- Cache the initial estimate or the existing 131,072-row fallback.
Actual output batches refine subsequent `read()` calls on the same
reader.

Projection, filtering, limits, retries, partition handling,
pickle-column checks, and the V1 read path are preserved. There are no
scheduling or stripe-splitting changes.

## Related issues

Fixes ray-project#66994. Implements the batch-sizing follow-up agreed in
[ray-project#66524](ray-project#66524 (comment)).
Searches for open PRs covering ray-project#66994 found no duplicate beyond this PR.

## Additional information

### Estimation and limits

The estimate includes selected physical columns and recursively
supported struct/list/map layouts, excluding fields replaced by
partition or synthesized values. Struct children retain parent slots,
including null parents. List element counts require explicit non-null
statistics; map key counts determine entry slots, including nullable
values. The estimate does not trust
`collection_statistics.total_children`. Unsupported selected layouts,
insufficient or invalid statistics, incompatible schemas, and
unavailable metadata fall back without partially summing known columns.

Initial sizing is bounded to at least one row and at most the inspected
file's row count. Metadata estimation can add one file open per reader;
the input closes before scanning. File averages can miss local width
changes. Each `read()` keeps fixed scanner parameters across fragments
and retries, as in Parquet DSV2; observed batches affect later calls.
This does not guarantee a bound on Arrow batch bytes, ORC decoder
memory, or stripe materialization.

### Validation

Linux, Python 3.12.14; all covered runtime cases completed with zero
failures, errors, or skips:

- PyArrow 23.0.1 and 17.0.0: targeted unit coverage for projected layout
sizes, metadata fallbacks, configuration through pushdowns, feedback,
fixed fragment parameters, and limits, with independent expectations for
layout sizes and projection results.
- Both PyArrow versions: nine targeted metadata cases per environment
cover missing private interfaces and DEBUG diagnostics, fallback and
input closure, and valid initial estimates for uncompressed and zstd
files.
- PyArrow 23.0.1: 121 ORC V2 public API cases. Fresh readers scanning
256 rows with approximately 4 KiB strings use 16/32 rows for 64/128 KiB
targets; projection to the narrow column is also verified.
- Cross-version files: six representative layouts in each direction,
verifying estimates/fallback and complete contents. The new parser also
passes a six-file check with protobuf 3.20.3; this is not a full Ray
regression on that protobuf version.
- Real-file I/O and lifetime tests cover metadata-only estimation,
closure on success/fallback/failure, and early termination. Other
coverage includes explicit overrides, negative caching, fixed scan/retry
parameters, and within-file width variation.
- Configured pre-commit checks, Bazel test registration, and Semgrep's
151 Python rules pass. Pyrefly adds no diagnostics; two existing
`infer_schema` diagnostics remain.

Commands to reproduce the covered tests:

```bash
orc_unit_tests=python/ray/data/tests/unit/datasource_v2

# Run in each environment: PyArrow 23.0.1 and 17.0.0
python -m pytest -q \
  "$orc_unit_tests/test_orc_batch_size_estimator.py::test_supported_layouts_use_real_metadata" \
  "$orc_unit_tests/test_orc_batch_size_estimator.py::test_projection_uses_original_type_ids" \
  "$orc_unit_tests/test_orc_batch_size_estimator.py::test_indexless_collection_counts_fall_back" \
  "$orc_unit_tests/test_orc_batch_size_estimator.py::test_metadata_failure_falls_back_and_closes_input" \
  "$orc_unit_tests/test_orc_batch_size_estimator.py::test_first_wide_batch_tracks_target" \
  "$orc_unit_tests/test_orc_file_reader.py::test_orc_reader_batch_sizing_feedback" \
  "$orc_unit_tests/test_orc_file_reader.py::test_orc_reader_batch_sizing_ignores_invalid_observation" \
  "$orc_unit_tests/test_orc_file_reader.py::test_orc_reader_batch_sizing_fragments_are_fixed" \
  "$orc_unit_tests/test_orc_datasource_v2.py::test_orc_batch_sizing_config_survives_pushdowns"

# PyArrow 23.0.1
python -m pytest -q \
  "$orc_unit_tests/test_orc_file_reader.py::test_orc_reader_batch_sizing_retry_keeps_scan_parameters" \
  "$orc_unit_tests/test_orc_file_reader.py::test_orc_reader_local_width_changes_keep_scan_fixed"
python -m pytest -q python/ray/data/tests/datasource/test_orc.py -k "v2 and not v1"
```

AI assistance: Codex assisted with implementation, tests, and code
review.

---------

Signed-off-by: jiangxt2 <[email protected]>
richardliaw pushed a commit that referenced this pull request Nov 6, 2026
…, row_id (#66654)

## Description

Part 1 of 3 of the `read_mcap` move to Datasource V2, based on master.
#67166 is stacked on it, and #67167 on #67166. The rest of the
`read_mcap` stack (#67189 onward) sits on top.

**Problem.** One task reads one whole file:

- Parallelism is capped by the file count: ten 30 GB recordings are ten
tasks.
- Every file is opened, even when its index shows it holds nothing
selected.
- Rows have no stable id, so a checkpointed pipeline cannot resume.

**Change.** `read_mcap` moves to Datasource V2, on by default as for
`read_parquet` (`DataContext.use_datasource_v2`). The legacy datasource
stays as the fallback.

```
files
  │  listing: read each file's index (a few ranged reads)
  │           one row per chunk, weighted by the memory reading it takes
  │           drop chunks that cannot match topics / time_range
  ▼
chunk rows
  │  packing: about 128 MiB per read task
  │           one big file ──► many tasks;  small files ──► one task
  │           with preserve_order: one task per file, in listing order
  ▼
read tasks: seek to their chunks, merge them by log time
```

- New code lives in `datasource_v2/formats/mcap/`. The V2 interfaces do
not change.
- Columns and types match the legacy path, with two changes.
`schema_data` is dictionary-encoded. A new `channel_metadata` column
holds each channel's metadata map as JSON text, dictionary-encoded, so a
block stores it once per channel.
- `data` holds decoded JSON only when every selected channel is JSON.
Otherwise it holds bytes. Planning types it from the selected messages
of the first chunk that holds one, as a read task types the messages it
holds.
- `row_id` is `<path>#c=<chunk offset>:<index>`, stable however the read
is split. It is on with `include_row_id=True`, or automatically under
`CheckpointConfig(id_column="row_id")`.
- New `log_time_order` argument, default `True`. Each task returns each
of its files in `log_time` order. With `preserve_order`, each file is
read by one task, so it comes out in order from start to end, and files
come out in the order they were listed. #67166 splits a large file there
too, only where its order holds.
- A file whose summary cannot be read gets a read task of its own, so
`max_errored_blocks` can skip it alone.
- The task size is `RAY_DATA_MCAP_BIN_PACKING_BYTES` (128 MiB).

**Changed after the first review round.** Each is its own commit:

- Summaries and chunks are read in a few ranged requests, not a few
bytes per GET.
- An unreadable file gets a read task of its own.
- Tables are built column by column, cut counting every column, and
chunks are weighted by the memory reading them takes.
- The read stops at the row limit.
- A file without a chunk index is sorted by log time.
- `channel_metadata` is JSON text, stored once per block.
- With `preserve_order`, each file is kept in one read task, and files
keep their listing order.
- Planning skips a chunk it cannot decode, and types `data` from the
first chunk's messages.

**Measured** on an 845 MB recording with 1,052 chunks: reading its 125
KB summary took about 20,000 GETs and now takes 3.

**Decisions to confirm:**

- Splitting is on by default. Block boundaries change; rows do not.
- With `preserve_order`, this PR reads each file in one task, as the
legacy reader does. #67166 lets it split a large file where its log-time
order holds.
- `ds.schema()` comes from the first chunk that holds a selected
message. A field that first appears later is missing from it; the
docstring says so.

## Related issues

- Related to #65640 and #65641.
- No open PR moves MCAP to Datasource V2. #66524 (ORC) and #66182
(Iceberg) are other formats moving to V2.
- The generated-ID stack (#65886 to #65888) is orthogonal.
- `log_time_order` comes from my #66653, now closed. My legacy-path PRs
#65912, #65913 and #65916 are closed in favour of this one.

## Additional information

```
PYTHONPATH=python/ray/data/tests pytest python/ray/data/tests/datasource/test_mcap.py \
  python/ray/data/tests/unit/datasource_v2/test_mcap_*.py \
  python/ray/data/tests/unit/datasource_v2/test_online_bin_packer.py
```

178 passed, 3 skipped. pre-commit and pyrefly clean.

AI assistance (Claude Code) was used to draft this change; I reviewed
every line and ran the tests above locally.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community 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.

[Data] Add ORC scanner and reader for DataSourceV2

4 participants