Skip to content

[Data] Add opt-in full ORC schema inference - #67151

Merged
richardliaw merged 4 commits into
ray-project:masterfrom
jiangxt2:feature-orc-full-schema-inference
Oct 21, 2026
Merged

richardliaw merged 4 commits into
ray-project:masterfrom
jiangxt2:feature-orc-full-schema-inference

Conversation

@jiangxt2

@jiangxt2 jiangxt2 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

An ORC column that appears only outside the default 16-file schema sample can be missing from the planned Dataset schema. Add the keyword-only merge_schema=False option to ray.data.read_orc(). With merge_schema=True, Ray infers the schema from every eligible ORC file before returning the Dataset and retains the discovered candidate set for execution and serialized lineage.

The default bounded sample remains unchanged. Requesting full inference with DataSourceV2 disabled raises NotImplementedError. The implementation reuses the full-discovery and prelisted-file infrastructure introduced for Parquet in #66522.

Related issues

Closes #67065.

Related: #66522 (Parquet full schema inference), #67040 (distributed metadata planning and reuse), and #67064 (separate ORC nested-field reader compatibility).

Additional information

Shared implementation and boundaries

  • Both formats use infer_schema_from_files for driver-side schema-read scheduling, schema unification, and merge-failure diagnosis. Reads use at most 16 threads and batches of up to 256 files, preserving input order.

  • The helper passes the complete schema list to Ray's existing unifier in one call. Pairwise merging is used only to diagnose failures using already-read schemas; if that diagnosis cannot reproduce the conflict, the original merge error is preserved.

  • Format callbacks retain file opening and closing. Parquet's explicit-schema bypass, partition/synthesized-column handling, legacy tensor checks, and the format-specific scanners/readers remain in their existing modules. The helper adds no partial merging, distributed metadata execution, or new reader fallback.

  • Full inference retains O(files) candidate metadata in the plan and per-file schemas on the driver during planning. Later appends are excluded from that Dataset's candidates; directory traversal is not an atomic snapshot, and replacing files at retained paths is outside this guarantee. Remote large-directory performance is not established by the local regressions.

Validation

Tests ran on Linux arm64 with Python 3.12.14 and pytest 8.4.2. The PyArrow 23.0.1 results use real local Ray workers and local files for the execution suites.

python -m pytest -q \
  python/ray/data/tests/unit/datasource_v2/test_schema_inference.py \
  python/ray/data/tests/unit/datasource_v2/test_parquet_datasource_v2.py \
  python/ray/data/tests/unit/datasource_v2/test_orc_datasource_v2.py

python -m pytest -q python/ray/data/tests/datasource/test_orc.py
python -m pytest -q python/ray/data/tests/datasource/test_read_parquet_v2.py
PyArrow Test scope Result
23.0.1 Helper and datasource unit files above 44 passed, 0 skipped
23.0.1 Complete ORC V1/V2 suite 158 passed, 0 skipped
23.0.1 Complete Parquet V2 suite 60 passed, 0 skipped
17.0.0 Helper and datasource unit files above 44 passed, 0 skipped

Coverage includes late-discovered columns, null filling, incompatible schemas, batch boundaries, unifier metadata/nullability, explicit Parquet schemas, no relisting across actions and lineage, initial filters, shuffle, and V1 rejection. PyArrow 17 coverage is limited to the unit selection; the execution suites use PyArrow 23.0.1. Remote storage and multi-node execution were not tested.

Ruff/import sorting, Black, pydoclint, Semgrep, syntax/whitespace checks, and Bazel test-target registration checks passed.

AI assistance

Codex assisted with implementation, tests, documentation, and static review.

Reuse full-schema candidate planning and share bounded schema reads with
Parquet while preserving the existing unifier semantics.

Signed-off-by: jiangxt2 <[email protected]>
@jiangxt2
jiangxt2 requested a review from a team as a code owner October 19, 2026 01:42

@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 extracts and unifies the ordered, bounded schema discovery logic into a shared helper infer_schema_from_files in schema_inference.py, which is then integrated into both Parquet and ORC datasources. Additionally, it introduces a merge_schema parameter to read_orc to enable full schema inference across all eligible ORC files, accompanied by comprehensive tests. The feedback suggests optimizing the batching mechanism in infer_schema_from_files using a sliding window of futures with collections.deque to avoid thread pool underutilization caused by slow file reads.

Comment on lines +29 to +33
per_file_schemas: List[pa.Schema] = []
with ThreadPoolExecutor(max_workers=min(len(paths), 16)) as executor:
for start in range(0, len(paths), _SCHEMA_READ_BATCH_SIZE):
batch = paths[start : start + _SCHEMA_READ_BATCH_SIZE]
per_file_schemas.extend(executor.map(read_schema, batch))

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.

medium

The current batching implementation introduces a hard barrier at the end of each batch because per_file_schemas.extend blocks until all 256 files in the current batch are read. If a single file read in a batch is slow (e.g., due to S3 tail latency or network hiccup), all other threads in the pool will sit idle instead of starting to read files from the next batch.\n\nTo avoid this barrier while still strictly bounding the number of active/submitted tasks to _SCHEMA_READ_BATCH_SIZE, we can use a sliding window of futures with a collections.deque. This keeps the thread pool fully utilized and preserves the input order of the schemas.\n\nNote: You will also need to update the test test_schema_reads_bound_submissions_and_preserve_order in test_schema_inference.py to mock executor.submit instead of executor.map.

    from collections import deque\n\n    per_file_schemas: List[pa.Schema] = []\n    with ThreadPoolExecutor(max_workers=min(len(paths), 16)) as executor:\n        futures = deque()\n        path_iter = iter(paths)\n        for _ in range(min(len(paths), _SCHEMA_READ_BATCH_SIZE)):\n            futures.append(executor.submit(read_schema, next(path_iter)))\n        for path in path_iter:\n            per_file_schemas.append(futures.popleft().result())\n            futures.append(executor.submit(read_schema, path))\n        while futures:\n            per_file_schemas.append(futures.popleft().result())

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 PR retains Parquet's existing bounded batching to focus on ORC full-schema inference and shared logic reuse without also changing Parquet's scheduling.

I'd evaluate a bounded sliding window separately if representative workloads with more than 256 files show significant waits between batches, comparing planning latency and checking submission limits, result order, and failure behavior.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Oct 19, 2026
Retained path and size metadata adds O(files) data to serialized lineage.

Follow-up work for distributed planning-time schema reads and metadata
reuse is tracked in https://github.com/ray-project/ray/issues/67040.

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 — nice work. I checked the helper against the old Parquet code line by line and it's a faithful extraction, and the tests are great: the null-fill test actually reads rows, and the candidate-reuse test proves appended files stay excluded even through deserialize_lineage().

One small docs ask, not blocking: this last sentence is carrying a lot of weight. #67064 is an existing V2 bug where, on PyArrow 17, an older file whose struct is missing a field crashes at read time. merge_schema=True merges every file's schema, so a late file with an evolved struct — exactly what this option is meant to surface — now gets planned and then fails on read for PA17 users. Someone hitting that traceback won't connect it to this sentence. Maybe:

This option uses the existing schema unifier and reader and doesn't add support for otherwise unsupported schema changes. In particular, evolved nested struct fields can fail at read time on PyArrow 17 (see https://github.com/ray-project/ray/issues/67064).

(Also agree with how you scoped the batch-stall point gemini raised — that's pre-existing
Parquet behavior and better handled separately against a real workload.)

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.

Updated the Note to clarify that evolved nested struct fields can fail at read time on PyArrow 17, and linked #67064.

@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 check my non blocking comment.

@richardliaw richardliaw added the go add ONLY when ready to merge, run all tests label Oct 21, 2026
@richardliaw
richardliaw merged commit 2ad9e7f into ray-project:master Oct 21, 2026
6 checks passed
@jiangxt2
jiangxt2 deleted the feature-orc-full-schema-inference branch October 22, 2026 01:48
richardliaw added a commit that referenced this pull request Nov 13, 2026
## Description

**Before:** `read_hive()` reads table data through a single HiveServer2
read task.

**After:** Opt-in `read_mode="direct"` lets Ray Data workers read
nonpartitioned Hive Parquet/ORC tables in parallel through native file
readers. The default `read_mode="hs2"` and SQL query behavior remain
unchanged.

HiveServer2 supplies table metadata on the driver; workers read storage
directly. The implementation reuses DataSourceV2 listing, task grouping,
scanners, Arrow decoding, projections, and global limits, adding Hive
type metadata and necessary name, string-length, and timestamp
compatibility rules.

Subsystems: API and IO.

```mermaid
flowchart LR
    API["API: read_hive(direct)"] --> Plan["IO: Hive metadata and file planning (driver)"]
    HS2["HiveServer2"] --> Plan
    Plan --> Read["IO: native Parquet/ORC readers (workers)"]
    Storage["Filesystem"] --> Read
    Read --> Output["Ray Data projections and global limit"]
```

## Related issues

Related to #65978.

Builds on #66573, which introduced HiveServer2-backed `read_hive()`, and
reuses shared schema inference from #67151. Open PR searches found no
overlapping Hive direct-read implementation.

## Additional information

### API and support boundaries

- Use `read_hive(table, connection_factory=..., read_mode="direct",
filesystem=..., merge_schema=False)`. Managed and external non-ACID file
tables are eligible. Storage access uses native filesystem credentials
and dependencies on the driver and workers; it does not inherit HS2
authorization policies.
- Supports the existing scalar Hive type mappings plus ARRAY, MAP,
STRUCT, and supported nested combinations. Top-level CHAR/VARCHAR
lengths are enforced, including CHAR padding. TIMESTAMP output is
timezone-naive microseconds, discarding finer fractional digits
consistently on both sides of the Unix epoch. Nested CHAR/VARCHAR is
rejected. Native Arrow casts support signed integer widening, FLOAT to
DOUBLE, and DECIMAL precision increases with unchanged scale, including
supported nested combinations. Narrowing and other type changes are
rejected.
- Query reads, partitioned tables, Hive ACID, Iceberg/Delta/Hudi, custom
SerDes, and Parquet positional column access are excluded. Known
unsupported Hive configurations are rejected before file planning.
Partition pruning and automatic mode selection are outside this PR.
- Hive metadata column names preserve literal leading and trailing
whitespace. Parquet uses a sampled case-insensitive name mapping and
rejects unsupported per-file case changes. ORC follows the metadata
session's name/position settings, with positional evolution limited to
the top level. ORC direct reads require
`hive.exec.schema.evolution=true` and support only
`orc.force.positional.evolution.level=1`. Legacy ORC layouts whose
top-level names all match `_col[0-9]+` follow the session's
missing-schema tolerance. Per-file mapping validation includes files
outside the sample and columns used only by filters; genuinely missing
columns receive typed NULLs, and ambiguous name mappings are rejected.
- File schema checks reuse native sampling of up to 16 files. For
Parquet and ORC, `merge_schema=True` checks all eligible file schemas
and retains that file set without widening the Hive declaration. ORC
maps each file to the Hive declaration before shared schema unification.
Sampling does not prevalidate every file; file errors follow native
error/retry semantics without replaying the read through HS2.

### Testing

Unit/native-file regressions and real HS2 comparisons passed for name
and top-level position mapping, supported type widening, Unicode names,
and sampled/unsampled files with projection and filter-only columns. ORC
comparisons also cover literal column-name whitespace and
`merge_schema=True`. Complex types were checked against Hive
declarations and typed HS2 projections. No cases were skipped in the
reported coverage.

Test entry points, from the repository root in a configured Ray
development environment:

```bash
python -m pytest -q \
  python/ray/data/tests/unit/datasource_v2/test_hive_direct.py \
  python/ray/data/tests/unit/datasource_v2/test_hive_contract.py \
  python/ray/data/tests/unit/datasource_v2/test_hive_hs2.py \
  python/ray/data/tests/unit/datasource_v2/test_hive_datasource_v2.py \
  python/ray/data/tests/datasource/test_hive.py

python -m pytest -q python/ray/data/tests/datasource/test_hive_direct_integration.py
```

The integration entry point requires `impyla`, configured HS2, HDFS, and
S3 endpoints (`RAY_HIVE_TEST_HOST`, `RAY_HIVE_DIRECT_HDFS_URI`,
`RAY_HIVE_DIRECT_S3_URI`), credentials, and native filesystem
dependencies. Its HS2 profile uses PLAIN against Hive NONE without TLS.
The targeted mapping and schema-evolution tests also accept
`RAY_HIVE_DIRECT_LOCAL_URI` for a shared directory visible to HS2, the
driver, and workers.

Coverage includes Parquet/ORC over HDFS and S3-compatible storage, full
schema/value comparisons with Hive, Hive-written files, at least two
native reading workers, empty tables, global limits, CHAR/VARCHAR
behavior, signed epoch and nested timestamps, sliced/chunked containers,
filters on converted values, retained Parquet/ORC file sets, and
unsampled-file schema failures without HS2 replay. Default HS2 table and
query reads are also covered. Ruff, import sorting, Black, pydoclint,
syntax, and whitespace checks passed.

Runtime: Linux ARM64, Python 3.12, Ray 2.59.0 Core running the modified
Ray Data sources, PyArrow 23.0.1, Hive 4.2.0, Hadoop 3.4.1, and MinIO.
Ray Core was not rebuilt. Real table reads cover external tables;
managed-table acceptance has metadata unit coverage. This does not
establish an AWS/authentication or Arrow-version runtime matrix.

The tested Hive/ORC writer shifts fractions in the final pre-epoch
second on its own readback, and raw Arrow agrees with that readback. The
Hive-written ORC case therefore covers negative fractions before that
second; native ORC file regressions cover `-1 ns`. Writer/codec changes
and universal ORC writer compatibility are outside this PR.

AI assistance: Codex assisted with implementation, tests, and this PR
description.

---------

Signed-off-by: jiangxt2 <[email protected]>
Co-authored-by: Richard Liaw <[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 opt-in full schema inference to read_orc

3 participants