Repository navigation
[Data] Add HiveServer2-backed read_hive datasource - #66573
richardliaw merged 28 commits into
Conversation
Signed-off-by: jiangxt2 <[email protected]> (cherry picked from commit d2d30bd79f07261e6be004a0d3741f528a66c959)
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
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 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 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 resolved = catalog.resolve(paths, reader=ReaderFormat.PARQUET)
paths = resolved.path
if resolved.filesystem is not None:
filesystem = resolved.filesystemThe 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 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. |
Signed-off-by: Silas <[email protected]>
ab2172b to
87d4572
Compare
Signed-off-by: jiangxt2 <[email protected]>
87d4572 to
ead703f
Compare
There was a problem hiding this comment.
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.
| 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. | ||
|
|
There was a problem hiding this comment.
this is a pretty verbose paragraph - can you shorten to be similar to the other readers?
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
align with other read API docstrings
There was a problem hiding this comment.
Fixed in 6783c89. I aligned the docstring structure with other read APIs: summary, note, examples, complete argument descriptions, and a Dataset return description.
| ) -> 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 |
There was a problem hiding this comment.
why is it an "initial binary reader"?
There was a problem hiding this comment.
Fixed in 6783c89. I removed “initial binary reader” and clarified that the port is for the HiveServer2 binary protocol.
| except Exception: | ||
| raise ValueError( | ||
| "HiveServer2 rows could not be converted to the read schema" | ||
| ) from None |
There was a problem hiding this comment.
everywhere - this exception handling mechanism seems very aggressive / hides the root error; any way to show something more useful?
There was a problem hiding this comment.
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.
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
|
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. |
926351b to
5842898
Compare
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]>
Thanks for the reminder. The Hive datasource now uses the current DataSourceV2 interfaces. |
|
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
Signed-off-by: jiangxt2 <[email protected]>
Added |
Signed-off-by: jiangxt2 <[email protected]>
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
left a comment
There was a problem hiding this comment.
Looks good. Kindly check my recommendation comment, mostly regarding documentation and tracking.
Signed-off-by: jiangxt2 <[email protected]>
|
|
||
| Ray Data reads from databases such as MySQL, PostgreSQL, MongoDB, and BigQuery. | ||
|
|
||
| ### Reading HiveServer2 |
There was a problem hiding this comment.
generally this is a bit too verbose, but will fix this later
## 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]>
… 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]>
## 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]>
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 Impylaconnection_factory.limitargument adds a SQLLIMITclause. The reader preservesDataContext.max_errored_blocks. It ignores explicit positiveoverride_num_blocksvalues with a warning to preserve streaming.SELECT *, a table with unsupported column types cannot be read in full. Usequery=to select supported columns and provide a matching schema.Dataset.limit()are not pushed into HiveServer2.PLAINwith HiveServer2 server modeNONE.NOSASLandGSSAPIhave not been verified in that run.Related issues
Related to #65978.
Additional information
Usage
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.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_hintagainst Hive 4.2 with PLAIN/NONE — 1 passed.git diff --check— passed.Integration and Ray-worker runs used this worktree's
ray.dataPython 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.