Skip to content

[Data] Add HiveServer2-backed read_hive datasource - #66573

Merged
richardliaw merged 28 commits into
ray-project:masterfrom
jiangxt2:feature/read-hive-hs2-implementation
Oct 15, 2026
Merged

richardliaw merged 28 commits into
ray-project:masterfrom
jiangxt2:feature/read-hive-hs2-implementation

Conversation

@jiangxt2

@jiangxt2 jiangxt2 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

Add the alpha ray.data.read_hive() API to Ray Data's DataSourceV2 read path. It reads Hive tables and trusted, row-producing SQL through HiveServer2 using a caller-provided, serializable Impyla connection_factory.

  • Table reads infer their Arrow schema from HiveServer2 metadata. Query reads require an explicit Arrow schema and validate the returned columns against it.
  • Each Dataset execution issues at most one HiveServer2 data query and streams bounded batches. Failed reads are not replayed.
  • The table limit argument adds a SQL LIMIT clause. The reader preserves DataContext.max_errored_blocks. It ignores explicit positive override_num_blocks values with a warning to preserve streaming.
  • Because table reads use SELECT *, a table with unsupported column types cannot be read in full. Use query= to select supported columns and provide a matching schema.
  • Ray Data filters, projections, and Dataset.limit() are not pushed into HiveServer2.
  • The real-server run recorded for this PR uses PLAIN with HiveServer2 server mode NONE. NOSASL and GSSAPI have not been verified in that run.

Related issues

Related to #65978.

Additional information

Usage

import os

import pyarrow as pa
import ray


def create_connection():
    from impala.dbapi import connect

    return connect(
        host="hive.example.com",
        port=10000,
        auth_mechanism="PLAIN",
        user="reader",
        password=os.environ["HIVE_NONE_PLACEHOLDER"],
        retries=1,
    )


table_ds = ray.data.read_hive(
    "analytics.events", connection_factory=create_connection
)
query_ds = ray.data.read_hive(
    query="SELECT id FROM analytics.events",
    schema=pa.schema([("id", pa.int64())]),
    connection_factory=create_connection,
)

Tests

  • pre-commit run --files doc/source/data/loading-data.md python/ray/data/BUILD.bazel python/ray/data/_internal/datasource_v2/formats/hive/hive_contract.py python/ray/data/_internal/datasource_v2/formats/hive/hive_hs2.py python/ray/data/tests/datasource/test_hive_integration.py python/ray/data/tests/datasource/test_hive_no_replay.py.
  • Commit-time hooks also checked the API export, datasource, contract-test, and Sphinx registration files.
  • python -m pytest -v -s -p no:cacheprovider python/ray/data/tests/datasource/test_hive.py — 17 passed.
  • python -m pytest -v -s -p no:cacheprovider python/ray/data/tests/datasource/test_hive_no_replay.py — 12 passed.
  • python -m pytest -v -s -p no:cacheprovider python/ray/data/tests/datasource/test_hive_lifecycle.py — 6 passed.
  • python -m pytest -v -s -p no:cacheprovider python/ray/data/tests/datasource/test_hive_integration.py::test_hive_table_query_limit_and_ignored_block_hint against Hive 4.2 with PLAIN/NONE — 1 passed.
  • git diff --check — passed.

Integration and Ray-worker runs used this worktree's ray.data Python sources with an official nightly Ray Core build. A native Core build from the PR base was not available locally.

AI assistance was used for research, implementation, documentation, and test development.

Signed-off-by: jiangxt2 <[email protected]>
(cherry picked from commit d2d30bd79f07261e6be004a0d3741f528a66c959)

jiangxt2 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Future direct-read path (follow-up)

This PR implements the initial HS2 path in RFC #65978. The RFC describes direct reads as a future, capability-gated path that reuses existing Ray readers only for table profiles proven compatible with them. It does not propose general Hadoop InputFormat/Hive SerDe support.

Spark is a concise reference for this conversion boundary: its Hive relation conversion is limited to Parquet/ORC SerDe profiles, each gated by a Spark configuration (conversion rule).

private def isConvertible(storage: CatalogStorageFormat): Boolean = {
  val serde = storage.serde.getOrElse("").toLowerCase(Locale.ROOT)
  serde.contains("parquet") && conf.getConf(HiveUtils.CONVERT_METASTORE_PARQUET) ||
    serde.contains("orc") && conf.getConf(HiveUtils.CONVERT_METASTORE_ORC)
}

For a converted table, Spark builds a file relation from metastore-derived locations and partition metadata (relation construction).

val fsRelation = HadoopFsRelation(
  location = fileIndex,
  partitionSchema = partitionSchema,
  dataSchema = updatedTable.dataSchema,
  bucketSpec = hiveBucketSpec,
  fileFormat = fileFormat,
  options = enableDynamicPartition)(sparkSession = sparkSession)

Other Hive relations remain on Spark’s Hive scan path, using the table’s Hive InputFormat/SerDe (scan implementation). This is an engine-specific path; Ray’s RFC limits direct reads to reusing existing Ray readers.

In Ray, a future Hive planner could inspect table metadata and select direct reading only for allowlisted profiles that preserve the table’s semantics. The check should distinguish table format from physical file format and account for transaction/snapshot behavior and delete semantics, SerDe/InputFormat, schema, partition metadata, storage location, and worker credentials. A file extension alone does not establish compatibility.

Ray’s Catalog may resolve a selected reader’s source and credentials after Hive planning. For example, read_parquet resolves a Parquet source and uses the returned path and filesystem (Catalog API, Parquet integration).

resolved = catalog.resolve(paths, reader=ReaderFormat.PARQUET)
paths = resolved.path
if resolved.filesystem is not None:
    filesystem = resolved.filesystem

The Catalog is a source-resolution component, not the Hive capability classifier; Hive relation classification and route selection remain in Hive planning, as specified by the RFC.

Metadata-provider adapters could be useful for deployments that already use them. Gravitino’s Hive catalog exposes HMS-backed table location, type, format, InputFormat, and SerDe properties, and Gravitino documents credential vending (Hive catalog, credential vending). Unity Catalog’s Hive metastore federation can expose federated Hive tables under governance; its direct table-credential flow has eligibility and privilege requirements (federation). Either would require a Ray adapter and would supply metadata or credentials, not prove that a table profile is safe for direct reading.

Proposed routing policy: select direct reading automatically during planning for allowlisted, proven-compatible table profiles; route unknown or unsupported profiles to HS2. This allows existing readers to provide their own parallelism where available. If a direct-only option is later exposed, an unsupported profile should fail during planning. Once direct reading begins, a failure should fail that read rather than start an HS2 query. Raw query= reads remain on HS2.

Direct storage access changes the security boundary: Ray workers need storage access, and direct reads may not preserve HS2 authorization or server-side policies. Each allowlisted profile should be compared with HS2 for schema, values, nulls, partition behavior, and relevant table-format semantics. Validation should also cover worker credential propagation and failure behavior after direct reading begins.

@Chang-Tong
Chang-Tong force-pushed the feature/read-hive-hs2-implementation branch from ab2172b to 87d4572 Compare September 30, 2026 12:57
@jiangxt2
jiangxt2 force-pushed the feature/read-hive-hs2-implementation branch from 87d4572 to ead703f Compare September 30, 2026 13:18
@jiangxt2
jiangxt2 marked this pull request as ready for review September 30, 2026 14:20
@jiangxt2
jiangxt2 requested review from a team as code owners September 30, 2026 14:20

@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 HiveServer2 datasource reader (read_hive) for Ray Data, complete with documentation, public API endpoints, internal datasource implementations, and comprehensive unit and integration tests. The review feedback identifies critical issues in hive_hs2.py where a connection failure in _connect can trigger unhandled NameError exceptions in the finally blocks of infer_table_schema and read_hs2_batches due to referencing undefined variables. Initializing connection and cursor to None before attempting to connect is recommended to ensure safe cleanup.

@ray-gardener ray-gardener Bot added docs An issue or change related to documentation data Ray Data-related issues community-contribution Contributed by the community labels Sep 30, 2026
@AarryaSaraf AarryaSaraf self-assigned this Oct 1, 2026
Comment on lines +889 to +906
Install `impyla` on the driver and Ray workers, then call {func}`~ray.data.read_hive`
with a table name. Table reads obtain their Arrow schema from HiveServer2 metadata.
For a trusted, row-producing SQL query, pass `query` and an explicit
`pyarrow.Schema` instead. The query must return a result set and is sent to
HiveServer2 as given.
Query schema columns must match the server result in count and order; names
match case-insensitively, and types must match the supported Arrow mapping.
Non-nullable schema fields reject null rows. Table reads map supported Hive
scalar booleans, integers, floats, strings, binary values, dates, and decimals
to Arrow when HS2 metadata agrees with the planned schema. Timestamp and
complex column types raise an error.
Choose `auth_mechanism` explicitly. Use `NOSASL` only with a HiveServer2
configured for `NOSASL`. Hive server mode `NONE` uses `PLAIN` SASL; use a
non-sensitive placeholder password because the server doesn't check it.
`PLAIN` doesn't encrypt the password when `use_ssl=False`.
For Hive `KERBEROS`, use `GSSAPI`, install `impyla[kerberos]`, and provide
Kerberos credentials on both the driver and read worker.

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 is a pretty verbose paragraph - can you shorten to be similar to the other readers?

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.

Fixed in 8f1f442. I shortened the HiveServer2 guidance while retaining the schema-matching rules, supported types, authentication and TLS notes, trusted-query requirement, and single-query execution semantics.

Comment thread python/ray/data/read_api.py Outdated
Comment on lines +3955 to +3963
num_cpus: CPUs reserved for the read task.
memory: Heap memory in bytes reserved for the read task.
resources: Custom resources reserved for the read task.
label_selector: Labels required on the read task's node.
fallback_strategy: Alternative label requirements.
runtime_env: Runtime environment of the read task.
override_num_blocks: Repartition the output into this many blocks
after the single HS2 read. This can incur data movement and does
not increase the number of HS2 queries.

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.

align with other read API docstrings

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.

Fixed in 6783c89. I aligned the docstring structure with other read APIs: summary, note, examples, complete argument descriptions, and a Dataset return description.

Comment thread python/ray/data/read_api.py Outdated
) -> Dataset:
"""Read a HiveServer2 table or trusted SQL query into a Dataset.

This initial binary HS2 reader executes one data statement in one Ray task

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 is it an "initial binary reader"?

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.

Fixed in 6783c89. I removed “initial binary reader” and clarified that the port is for the HiveServer2 binary protocol.

Comment on lines +206 to +209
except Exception:
raise ValueError(
"HiveServer2 rows could not be converted to the read schema"
) from 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.

everywhere - this exception handling mechanism seems very aggressive / hides the root error; any way to show something more useful?

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.

Fixed in 5842898. The Hive reader now adds operation context and chains the original exception with raise ... from exc, following Ray Data’s contextual-error pattern and Spark JDBC’s cause-preserving behavior. The tests now verify that the original exception remains available through the cause chain.

@AarryaSaraf

AarryaSaraf commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Thank you for your contribution! A large refactoring of DSv2 has been done. Can you rebase your changes on top of that? Ill take a look once done.

@jiangxt2
jiangxt2 force-pushed the feature/read-hive-hs2-implementation branch 2 times, most recently from 926351b to 5842898 Compare October 2, 2026 06:31
Merge the current master ref into the original PR history, align the Hive datasource with the current V2 interfaces, and validate HS2 table metadata.

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

jiangxt2 commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for your contribution! A large refactoring of DSv2 has been done. Can you rebase your changes on top of that? Ill take a look once done.

Thanks for the reminder. The Hive datasource now uses the current DataSourceV2 interfaces.

@AarryaSaraf

Copy link
Copy Markdown
Contributor

It is not just the interfaces, but also the structure. For example, hive would go under formats/hive/...

)
next(batches)
batches.close()
assert cursor.cancelled and cursor.closed and connection.closed

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.

Thanks for adding the cleanup test. Following up on the lifecycle point in #66523, could we also test early termination through an actual Ray Dataset? This test closes the helper directly; it would be useful to check whether stopping downstream consumption reaches the HS2 cancellation and connection cleanup, and document any limitations. The existing warning about abrupt worker death makes sense.

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 test_hive_lifecycle.py using public read_hive() and real Ray workers with a recording HS2 client. It covers normal completion, Dataset.limit(1), and closing a held iterator after the first batch. Early-termination checks run before teardown while the source has not reached EOF, and every case verifies exactly one query execution.

The limit case reaches cancel_operation() and closes the cursor and connection. Closing the held iterator force-stops the worker before those cleanup calls run. The API docs, loading guide, and DSv2 README now describe this limitation and retain the warning about abrupt worker termination.

jiangxt2 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Could the docs show an example? Both examples use SELECT event_id FROM analytics.events, which isn't prefixed, so the SELECT * case isn't shown.

Added SELECT * FROM analytics.events examples to both the API docstring and the loading guide, using the qualified HS2 labels events.id and events.name in the Arrow schema. The examples state their assumed column types and order, and also show explicit SQL aliases with matching unqualified schema names. Readers are instructed to use the labels their HS2 instance returns.

Cover completion, downstream limits, and iterator closure through real Ray workers. Document the cleanup limitation when iterator closure stops the read worker.

Signed-off-by: jiangxt2 <[email protected]>
Ignore explicit override_num_blocks values with a warning instead of applying a blocking repartition. Preserve parameter validation and document the HiveServer2 reader limitation.

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

Copy link
Copy Markdown
Contributor

Thanks for the thorough follow-through on this one. All of my earlier comments are addressed: the connection factory removes credentials from the public API, the RFC now states the TLS and error-cause behavior clearly, the lifecycle test exercises a real Dataset, and override_num_blocks no longer blocks streaming. The test coverage around no-replay and error tolerance is especially appreciated.

LGTM for an alpha API. A couple of small things that would be nice to land alongside or shortly after, none of which I consider blocking:

  • Could the docs narrow the authentication claims to what was verified against a real server, that is PLAIN, and mark NOSASL and GSSAPI as untested for now? That keeps user expectations honest until we have a CI-run integration test.
  • Would you mind opening follow-up issues for a dockerized HiveServer2 integration test in CI, and for server-side operation cleanup when a worker is terminated? Both are documented limitations today, and tracking issues will keep them visible.
  • One doc addition: tables with an unsupported column type currently can't be read as a whole, since table reads use SELECT *. A sentence pointing users to query= with an explicit column list and matching schema would save them some confusion.

Nice work getting this into shape.

@abhishekverma-ray abhishekverma-ray self-assigned this Oct 14, 2026

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

Looks good. Kindly check my recommendation comment, mostly regarding documentation and tracking.


Ray Data reads from databases such as MySQL, PostgreSQL, MongoDB, and BigQuery.

### Reading HiveServer2

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.

generally this is a bit too verbose, but will fix this later

@richardliaw
richardliaw merged commit 6fae1c1 into ray-project:master Oct 15, 2026
6 checks passed
@jiangxt2
jiangxt2 deleted the feature/read-hive-hs2-implementation branch October 16, 2026 01:42
richardliaw pushed a commit that referenced this pull request Nov 6, 2026
## Description

Adds the HiveServer2 integration tests to premerge CI. These tests were
previously marked `manual`.

The job starts Hive 4.2.0, waits for a SQL query to succeed, runs the
tests, and cleans up the service. It uses the existing Data integration
image with Impyla installed and skips `docstring-only` PRs.

## Related issues

Fixes #67042. Follow-up to #66573. No other open PR was found covering
this CI setup.

## Testing

- `python -m pytest -q ci/ray_ci/data/test_run_hive_integration.py` — 14
passed, including cleanup failures and already absent resources.
- `python -m pytest -q python/ray/data/tests/datasource/test_hive.py` —
17 passed.
- `python -m pytest -q
python/ray/data/tests/datasource/test_hive_lifecycle.py
python/ray/data/tests/datasource/test_hive_no_replay.py` — 18 passed.
- CI routing checks: 166 passed. Pre-commit checks, pipeline YAML
parsing, and `git diff --check` passed.
- [Linux run against Hive
4.2.0](https://github.com/Chang-Tong/ray/actions/runs/39127834914):
`python -m pytest -v -rs
python/ray/data/tests/datasource/test_hive_integration.py` — 3 passed, 1
skipped. TLS is skipped because the fixture uses PLAIN/NONE
authentication without TLS.

Ray tests used this branch's Python code with nightly Ray Core wheels.
The linked Linux run used host pytest and Dockerized Hive; it did not
exercise the full Buildkite Docker/Bazel path.

AI tools assisted with the code and tests.

---------

Signed-off-by: Silas <[email protected]>
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 9, 2026
… source's own metadata (#67037)

Three changes to shared Datasource V2 code so a source whose listing
already knows
more than a path and a size can use the common machinery instead of
forking it. 1 of
5 in a stack moving `read_iceberg` onto DSv2; this one touches only
shared code.

**A source's own manifest columns survive bin packing** —
`interfaces/file_manifest.py`,
`common/online_bin_packer.py`. `FileManifest` already lets a source add
columns beside
the three required ones, but `OnlineBinPacker` rebuilt each bin from
those three alone,
so the rest were dropped. Adds `FileManifest.extra_columns` and an
`extra_columns`
argument to `construct_manifest`, and carries a zero-copy one-row table
on each
`BinItem`. Packing a manifest with two source columns and reading the
names back out:

```
master:   ['__path', '__file_size', '__file_chunk_metadata']
this PR:  [... , '__ib_record_count', '__ib_delete_paths']
```

```mermaid
flowchart TD
    L["ListFiles task"] -->|"FileManifest: 3 required + 2 source columns"| P["OnlineBinPacker"]
    P -->|"before: rebuilt from the 3 required"| B["ReadFiles sees 3"]
    P -->|"after: BinItem.extra_columns carries each row"| A["ReadFiles sees 5"]
```

**The pushdown mixins carry their own state** —
`interfaces/pushdown.py`,
`common/arrow_file_scanner.py`. `SupportsColumnPruning` and
`SupportsLimitPushdown` were
pure interfaces, so every scanner rewrote the same field and the same
`replace(self, ...)` body. They are now frozen dataclasses with
keyword-only fields and
default implementations: pruning intersects, limit takes the smaller.
`ArrowFileScanner`
drops 46 lines. Intersecting also fixes a bug — the old bodies overwrote
the projection
and tested it for truthiness, so an empty projection (what `count()`
pushes down)
re-widened:

```python
scanner.prune_columns([]).prune_columns(["a"]).pruned_column_names()
# master: ('a',)   this PR: ()
```

**`ListFiles.pushdown_is_final`** —
`logical/operators/read_operator.py`,
`logical/rules/derive_list_files_pushdown.py`,
`logical/rules/pushdown_count_files.py`.
`DeriveListFilesPushdown` clears a listing's constraints when the
consumer is not a
`ReadFiles`, since an arbitrary consumer will not apply them.
`PushdownCountFiles`
rewrites `Count(ReadFiles(ListFiles))` into `MapBatches(count_rows,
ListFiles)`, and its
`count_rows` does apply the scanner's filter, through the same reader
the deleted
`ReadFiles` would have used. The flag lets that rule say so instead of
silently losing
the predicate and returning an unfiltered count.

---

Tests: `pytest
python/ray/data/tests/unit/datasource_v2/test_online_bin_packer.py
test_pushdown_mixins.py test_derive_list_files_pushdown.py` — 31 passed.
`test_pushdown_mixins.py` is new; the other two gain cases for extra
columns surviving
packing/splitting/merging and for `pushdown_is_final`. ruff 0.8.4
(default and
`--select I`), black 22.10.0, pydoclint 0.9.1 and pyrefly 0.51.0 clean
on these files.

Not a duplicate: no open PR changes `OnlineBinPacker`, the pushdown
mixins or
`PushdownCountFiles`. #66654 (MCAP) and #66573 (Hive HS2) consume this
shared code
rather than modify it, and the mixin consolidation is what review on
#66654 asked for.

AI assistance (Claude Code) was used. I have reviewed every changed line
and ran the
tests above locally.

Signed-off-by: Aarrya <[email protected]>

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

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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 docs An issue or change related to documentation go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants