Skip to content

[Data] Define read_hive API contract - #66523

Closed
jiangxt2 wants to merge 2 commits into
ray-project:masterfrom
jiangxt2:feature/read-hive-api-contract-draft
Closed

jiangxt2 wants to merge 2 commits into
ray-project:masterfrom
jiangxt2:feature/read-hive-api-contract-draft

Conversation

@jiangxt2

@jiangxt2 jiangxt2 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR defines the proposed alpha ray.data.read_hive() API contract requested in RFC #65978. It adds validated, immutable input models and focused tests so maintainers can align on the API before reviewing the HiveServer2 reader.

The public read_hive symbol shown below is proposed for a follow-up implementation PR. This PR does not export it, connect to Hive, or read data.

Proposed public API

@PublicAPI(stability="alpha")
def read_hive(
    table: Optional[str] = None,
    *,
    host: str,
    query: Optional[str] = None,
    schema: Optional["pyarrow.Schema"] = None,
    port: int = 10000,
    auth_mechanism: Literal["NOSASL", "PLAIN", "GSSAPI"],
    user: Optional[str] = None,
    password: Optional[str] = None,
    kerberos_service_name: str = "hive",
    use_ssl: bool = False,
    ca_cert: Optional[str] = None,
    timeout: Optional[float] = None,
    limit: Optional[int] = None,
    num_cpus: Optional[float] = None,
    memory: Optional[float] = None,
    resources: Optional[Dict[str, float]] = None,
    label_selector: Optional[Dict[str, str]] = None,
    fallback_strategy: Optional[List[Dict[str, Any]]] = None,
    runtime_env: Optional[Dict[str, Any]] = None,
    override_num_blocks: Optional[int] = None,
) -> Dataset: ...

Decisions for review

  • Exactly one of table and query is required. Table names use the initial simple [database.]table identifier subset. Each identifier segment must match ASCII [A-Za-z_][A-Za-z0-9_]*; an unqualified name uses default. Table reads get their Arrow schema from HS2 metadata during planning. If that metadata cannot fully describe the result, planning fails instead of running an extra data query to infer the schema. A table limit=0 skips the data query.
  • Raw SQL is trusted, row-producing caller input. It requires a nonempty pyarrow.Schema with column names unique after case folding. HS2 result columns must have the same count and order, with names matching case-insensitively. Output keeps the caller's schema names. Unsupported or lossy type mappings fail before emitting a block; non-nullable fields are checked against fetched rows. Schema inference must not execute the data query a second time.
  • auth_mechanism is required. The initial binary HS2 profiles are NOSASL for a Hive server configured as NOSASL, PLAIN for Hive NONE, and GSSAPI for Hive KERBEROS. PLAIN requires an explicit nonempty user and password in this API. For Hive NONE, use a non-sensitive placeholder password: the server does not authenticate it, and PLAIN does not encrypt it without TLS. TLS must verify the server certificate and identity. When set, timeout configures the HS2 transport socket timeout in seconds; it is not a server-side or end-to-end query deadline.
  • Each Dataset execution runs at most one HS2 data query and consumes one result stream incrementally. Read failures fail the execution without replay or switching routes. The reader implementation must disable Ray task retries for the HS2 query (max_retries=0) and verify that failures cannot resubmit it. Source limit applies only to table reads; query SQL is not rewritten for pushdown.
  • Named Ray options control the single read task's resources, placement, runtime environment, and output blocks. override_num_blocks does not create parallel HS2 queries. Parallelism, concurrency, retry, GPU/accelerator placement, and Impyla passthrough arguments are outside the initial public API.
  • Direct storage reads, Catalog routing, LDAP, HTTP transport, and write_hive remain follow-up work.

Related issues

Related to #65978.

Additional information

Scope and prior work

This PR changes only hive_contract.py, its validation tests, and the Bazel test registration. It does not duplicate an open read_hive PR: searches for #65978 and read_hive found none. Closed, unmerged PR #58253 explored direct storage reads; this PR defines the HS2-first API boundary and leaves direct reads for later.

Validation

  • Focused pytest run of python/ray/data/tests/datasource/test_hive_contract.py in an isolated Python 3.13 environment, using the PR branch's Ray Data Python sources with a locally built Ray extension: 34 passed.
  • pre-commit run --files python/ray/data/BUILD.bazel python/ray/data/_internal/datasource/hive_contract.py python/ray/data/tests/datasource/test_hive_contract.py: passed.
  • git diff --check origin/master...HEAD and Ruff: passed.
  • Hive integration tests are not applicable to this validation-only PR; they belong to the reader implementation PR.

AI assistance

AI assistance was used for research, the contract model, tests, and this PR description. Before requesting review, the human submitter must review every changed line and rerun the relevant tests locally.

@richardliaw

Copy link
Copy Markdown
Contributor

I think this looks fine; thanks.

@jiangxt2

jiangxt2 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

I think this looks fine; thanks.

OK, I will submit an implementation PR soon.

@jiangxt2
jiangxt2 marked this pull request as ready for review September 29, 2026 00:44
@jiangxt2
jiangxt2 requested a review from a team as a code owner September 29, 2026 00:44

@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 read API contract, defining HiveConnectionOptions and HiveReadSpec dataclasses to handle input validation for table and query reads. It also includes comprehensive unit tests and a new Bazel build target for these components. The reviewer suggested a minor optimization to the identifier regex pattern by removing the redundant \Z anchor, as re.fullmatch already enforces a full string match.


HiveAuthMechanism = Literal["NOSASL", "PLAIN", "GSSAPI"]

_IDENTIFIER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")

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 \Z anchor in the regular expression is redundant because re.fullmatch is used to validate the identifier segments. re.fullmatch inherently requires the entire string to match the pattern. Removing \Z simplifies the regex pattern.

Suggested change
_IDENTIFIER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
_IDENTIFIER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")

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.

You’re right that \Z is redundant with re.fullmatch(). Since it has no behavioral impact, I’ll leave it unchanged in this PR.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Sep 29, 2026
@jiangxt2
jiangxt2 marked this pull request as draft September 29, 2026 05:36
@AarryaSaraf AarryaSaraf self-assigned this Oct 1, 2026

This module defines the API boundary without opening a Hive connection or
creating a Ray read task. The public call shape is specified separately in the
read_hive API contract proposal.

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 module says the public call shape is "specified separately", and right now that means the PR description. The thing we need to align on is the read_hive() signature and its semantics, and a later PR can change those freely because nothing here is imported or exported.

Could you put the contract in the code so approving this PR locks it? A stub in read_api.py with the full signature and docstring that raises NotImplementedError would do. Then this module can be reviewed as the validation layer behind that signature instead of standing alone.

auth_mechanism: HiveAuthMechanism
port: int = 10000
user: Optional[str] = None
password: Optional[str] = field(default=None, repr=False)

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.

repr=False hides the password from repr, but it is not a security boundary. This dataclass gets pickled into the read task and into Dataset.serialize_lineage(), and a password= kwarg on read_hive() ends up in notebooks and job specs.

It also means nine connection parameters on the public function, and the PR already lists LDAP, HTTP transport and Impyla passthrough as follow-ups, so the signature will keep growing.

Existing readers avoid both problems: read_sql takes a connection_factory, read_snowflake a connection_parameters dict, read_databricks_tables reads a token from the environment. Impyla's connect is already a callable the user can configure. Can read_hive take a connection_factory (or a single public options object) and drop password from the public API?

):
raise ValueError("query must be a non-empty SQL string")
if not isinstance(self.schema, pa.Schema) or len(self.schema) == 0:
raise ValueError("query reads require a non-empty pyarrow.Schema")

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.

HiveServer2 returns result metadata after execute and before any row is fetched, and impyla exposes it as cursor.description. That already satisfies the "no second data query" rule.

Requiring every SQL user to hand-write a pyarrow.Schema is a real usability cost for something the server can tell us. Can schema be optional for query reads, inferred from the cursor description, and used as an override when given?


@dataclass(frozen=True)
class HiveReadSpec:
"""A single table or trusted SQL read, before datasource execution."""

@abhishekverma-ray abhishekverma-ray Oct 7, 2026 •

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 one-query, one-task, no-retry model is a clear and safe choice for the first version. Two consequences are worth stating in the public docs so users aren't surprised: reads won't run in parallel, and if the worker running the query is lost the whole dataset fails, since Ray can't re-run that task.

With those semantics the read path looks close to read_sql(sql, impyla_connect) plus a table-name helper and Arrow type mapping. Could you add a short note on what read_hive provides beyond that today? If the main gains are the Arrow typing from HS2 metadata and incremental fetching, it might be worth a quick discussion on whether some of that could strengthen read_sql as well. Not a blocker for the direction, just want the distinction written down.



@dataclass(frozen=True)
class HiveReadSpec:

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.

One thing I'd love to see covered here, since DataSourceV2 alignment came up early in the RFC: a short note on how this spec maps onto the DataSourceV2 interfaces. For example, one input split per query, schema coming from HS2 metadata through the metadata interface, streaming happening inside the scanner, and how cancellation and cleanup fit in.

It doesn't need to be code yet, a paragraph here or in the PR body is enough. It's the trickiest part of the integration, so agreeing on it now should make the implementation PR much smoother to review.

@abhishekverma-ray

abhishekverma-ray commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Hey @jiangxt2! Thanks for splitting the contract out ahead of the implementation, this is exactly the right order and it makes the review much easier.

I left five inline comments that touch the public API shape: putting the read_hive signature itself in code, using a connection factory instead of flat connection kwargs and a password argument, making schema optional for query reads, spelling out the single-task semantics and how they compare with read_sql, and sketching the DataSourceV2 mapping. I think it's worth settling those before we treat this as the agreed contract, since they're the parts a follow-up PR can't easily change.

The remaining code-level points are small and can come along in the same push. Happy to discuss any of them here or on the RFC thread.

Copy link
Copy Markdown
Contributor Author

PR #66523 was opened to define and validate the proposed ray.data.read_hive() API contract before implementation. The complete implementation, including the public API, HiveServer2-backed DataSourceV2 read path, tests, and documentation, is now in PR #66573. With #66573 approved and nearing merge, I plan to close this contract-only PR.

@jiangxt2 jiangxt2 closed this Oct 15, 2026
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants