Repository navigation
[Data] Adapt ORC V2 batch sizing to row width - #67111
richardliaw merged 7 commits into
Conversation
Pass the target block size through ORC scans and refine subsequent reads from normal Arrow batches, preserving explicit overrides and the default fallback. Signed-off-by: jiangxt2 <[email protected]>
Estimate projected Arrow row widths from serialized ORC file tails before the first scan. Preserve default fallback and scan boundaries, and cover nested layouts and PyArrow 17/23 compatibility. Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces dynamic batch size estimation for ORC files in Ray Data (DSV2) by analyzing the ORC file footer's metadata to target a specific block size, with subsequent refinements based on observed batch sizes. The feedback suggests enhancing the robustness of this non-critical optimization by wrapping the estimation logic in _resolve_batch_size in a try...except block to prevent read failures, and defensively catching AttributeError in estimate_batch_size to handle potential compatibility issues with older PyArrow environments.
| batch_size = _ARROW_DEFAULT_BATCH_SIZE | ||
| fragment = next(dataset.get_fragments(), None) | ||
| if fragment is not None: | ||
| excluded = {column.name for column in self._synthesized_columns} | ||
| if self._partition_parser is not None: | ||
| excluded.update(self._partition_parser(fragment.path)) | ||
| estimated = estimate_batch_size( | ||
| fragment, | ||
| self._columns, | ||
| self._target_block_size, | ||
| schema=self._file_dataset_schema, | ||
| excluded_columns=tuple(excluded), | ||
| ) | ||
| if estimated is not None: | ||
| batch_size = estimated |
There was a problem hiding this comment.
Wrap the batch size estimation logic in _resolve_batch_size in a try...except block. Since batch size estimation is a non-critical optimization, any unexpected error (e.g., in get_fragments or _partition_parser) should be caught and logged as a debug message, falling back to _ARROW_DEFAULT_BATCH_SIZE rather than failing the entire read operation.
| batch_size = _ARROW_DEFAULT_BATCH_SIZE | |
| fragment = next(dataset.get_fragments(), None) | |
| if fragment is not None: | |
| excluded = {column.name for column in self._synthesized_columns} | |
| if self._partition_parser is not None: | |
| excluded.update(self._partition_parser(fragment.path)) | |
| estimated = estimate_batch_size( | |
| fragment, | |
| self._columns, | |
| self._target_block_size, | |
| schema=self._file_dataset_schema, | |
| excluded_columns=tuple(excluded), | |
| ) | |
| if estimated is not None: | |
| batch_size = estimated | |
| batch_size = _ARROW_DEFAULT_BATCH_SIZE | |
| try: | |
| fragment = next(dataset.get_fragments(), None) | |
| if fragment is not None: | |
| excluded = {column.name for column in self._synthesized_columns} | |
| if self._partition_parser is not None: | |
| excluded.update(self._partition_parser(fragment.path)) | |
| estimated = estimate_batch_size( | |
| fragment, | |
| self._columns, | |
| self._target_block_size, | |
| schema=self._file_dataset_schema, | |
| excluded_columns=tuple(excluded), | |
| ) | |
| if estimated is not None: | |
| batch_size = estimated | |
| except Exception as e: | |
| import logging | |
| logging.getLogger(__name__).debug("Failed to estimate ORC batch size: %s", e) |
There was a problem hiding this comment.
Expected metadata failures already fall back. Fragment enumeration and partition parsing are also required by normal reads, so I suggest keeping the current exception boundary, consistent with Parquet DSV2.
| except ( | ||
| OSError, | ||
| pa.ArrowInvalid, | ||
| pa.ArrowNotImplementedError, | ||
| DecodeError, | ||
| ValueError, | ||
| ) as e: |
There was a problem hiding this comment.
Defensively catch AttributeError in estimate_batch_size to handle cases where certain PyArrow properties (like writer_version, nrows, or row_index_stride) might be missing or raise an AttributeError in older or custom PyArrow environments.
| except ( | |
| OSError, | |
| pa.ArrowInvalid, | |
| pa.ArrowNotImplementedError, | |
| DecodeError, | |
| ValueError, | |
| ) as e: | |
| except ( | |
| OSError, | |
| pa.ArrowInvalid, | |
| pa.ArrowNotImplementedError, | |
| DecodeError, | |
| ValueError, | |
| AttributeError, | |
| ) as e: |
There was a problem hiding this comment.
These properties exist in PyArrow 17/23, and serialized_file_tail availability is already checked. Without a specific compatibility failure, I suggest keeping the current handling.
| with fragment.filesystem.open_input_file(fragment.path) as source: | ||
| reader = orc.ORCFile(source) | ||
| get_tail = getattr( | ||
| getattr(reader, "reader", None), "serialized_file_tail", None |
There was a problem hiding this comment.
.reader is an undocumented instance attribute ('reader' in dir(ORCFile) is False, no docstring) exposing pyarrow._orc.ORCReader — a private Cython module. A future pyarrow rename silently disables the feature rather than crashing. That’s the right failure mode, but it means the optimization could vanish on a pyarrow upgrade with zero signal.
Ask: add a one-line logger.debug/comment when get_tail is unavailable so a regression is diagnosable, and note the private-API dependency in the module docstring.
There was a problem hiding this comment.
Thanks! Added a module-level note about the private PyArrow API and a DEBUG log when the file-tail interface is unavailable.
abhishekverma-ray
left a comment
There was a problem hiding this comment.
Please follow up with my feedback on documentation. Rest looks good. Thanks!
Document the private PyArrow file-tail API and log unavailable interfaces. Strengthen layout, projection, metadata fallback, feedback and batch-size configuration tests. Signed-off-by: jiangxt2 <[email protected]>
|
Commit 59fa1c813d also strengthens the batch sizing tests with independent layout/projection expectations and stronger fallback, feedback, and limit assertions, and clarifies schema compatibility and average row width documentation. Batch sizing decisions and scan behavior are unchanged. |
Preserve upstream full ORC schema inference and the existing batch sizing configuration while resolving the import conflict. Signed-off-by: jiangxt2 <[email protected]>
Narrow the batch iterator to GeneratorType before closing it in the early-stop test. Signed-off-by: jiangxt2 <[email protected]>
Document that the batch size estimator reads schema and file-tail metadata without materializing data batches. Actual batch reads remain gated in OrcFileReader. Signed-off-by: jiangxt2 <[email protected]>
## 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]>
Description
Make ORC DataSourceV2 choose its initial Arrow batch row count from
DataContext.target_max_block_sizeand estimated projected row width, following the Parquet DSV2 sizing path. An explicitbatch_sizealways takes precedence.OrcDatasourceV2.create_scannerandOrcScannertoOrcFileReader, preserving it across pushdowns.serialized_file_tail()using a small protobuf field subset and the native ORC type IDs. This adds no data sampling or dependencies.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. 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:
infer_schemadiagnostics remain.Commands to reproduce the covered tests:
AI assistance: Codex assisted with implementation, tests, and code review.