Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a native DeltaDatasource for Ray Data, enabling partition-level predicate pushdown for Delta Lake tables by leveraging delta-rs. It refactors the read_delta API to use this new datasource and adds a suite of tests to verify the pushdown logic. Feedback highlights critical issues in the ParquetDatasource instantiation within _build_inner, specifically regarding argument conflicts and incorrect parameter propagation. Additionally, it is suggested to handle commutative comparisons in the predicate translator and to implement projection pushdown support to avoid performance regressions.
| inner = ParquetDatasource( | ||
| paths=list(uris), | ||
| # Use Delta's schema so PyArrow doesn't inspect parquet footers | ||
| # (issue #61547 explicitly calls out "even just for tail metadata"). | ||
| schema=self.delta_table.schema().to_arrow(), | ||
| columns=self._columns, | ||
| filesystem=self._filesystem, | ||
| partition_filter=self._partition_filter, | ||
| # We've already pruned at the Delta level. Disable ParquetDatasource's | ||
| # own Hive partition parsing to avoid a no-op second pass and to | ||
| # keep partition columns resolved from the parquet files themselves | ||
| # (Delta writes them into both the path AND the file). | ||
| partitioning=None, | ||
| shuffle=self._shuffle, | ||
| include_paths=self._include_paths, | ||
| **self._arrow_parquet_args, | ||
| ) |
There was a problem hiding this comment.
The current implementation of _build_inner has several issues with how it constructs the ParquetDatasource:
- Argument Conflict: If a user provides a
schemaviaarrow_parquet_argsinread_delta, it will be passed twice to theParquetDatasourceconstructor (once explicitly and once via**self._arrow_parquet_args), causing aTypeError. - Invalid Arguments:
ParquetDatasourcedoes not accept**kwargs. Passing**self._arrow_parquet_argswill crash if it contains keys that are not named arguments ofParquetDatasource(e.g.,batch_size, which should be into_batch_kwargs). - Missing Propagation: Arguments like
dataset_kwargsand_block_udfare not correctly extracted and passed to their respective named parameters inParquetDatasource.
The implementation should follow the pattern used in read_parquet to resolve and pop these arguments.
# Separate known ParquetDatasource arguments from to_batch_kwargs.
parquet_args = self._arrow_parquet_args.copy()
dataset_kwargs = parquet_args.pop("dataset_kwargs", None)
_block_udf = parquet_args.pop("_block_udf", None)
schema = parquet_args.pop("schema", self.delta_table.schema().to_arrow())
inner = ParquetDatasource(
paths=list(uris),
# Use Delta's schema (or user override) so PyArrow doesn't inspect parquet footers.
schema=schema,
columns=self._columns,
filesystem=self._filesystem,
partition_filter=self._partition_filter,
# We've already pruned at the Delta level. Disable ParquetDatasource's
# own Hive partition parsing to avoid a no-op second pass.
partitioning=None,
shuffle=self._shuffle,
include_paths=self._include_paths,
dataset_kwargs=dataset_kwargs,
_block_udf=_block_udf,
to_batch_kwargs=parquet_args,
)There was a problem hiding this comment.
All three points addressed in e60b5fb. The fix follows the read_parquet pattern in read_api.py: parquet_args = dict(self._arrow_parquet_args); dataset_kwargs = parquet_args.pop("dataset_kwargs", None); _block_udf = parquet_args.pop("_block_udf", None); schema = parquet_args.pop("schema", self.delta_table.schema().to_arrow()) — that handles the duplicate-schema conflict, the missing dataset_kwargs / _block_udf propagation, and the no-**kwargs constraint by routing residual scanner options as to_batch_kwargs=parquet_args. Regression test added (test_delta_arrow_parquet_args_routed_to_scanner).
| if not isinstance(expr.left, ColumnExpr): | ||
| raise NotImplementedError( | ||
| "Left-hand side of a Delta partition predicate must be a column" | ||
| ) | ||
| if not isinstance(expr.right, LiteralExpr): | ||
| raise NotImplementedError( | ||
| "Right-hand side of a Delta partition predicate must be a literal" | ||
| ) |
There was a problem hiding this comment.
There was a problem hiding this comment.
Added the swap for EQ/NE in e60b5fb. Worth noting Python's __eq__ overload already normalises the operator-style case for free — 5 == col("a") calls int.__eq__ first, gets NotImplemented (no __req__ exists in Python's data model), then falls back to ColumnExpr.__eq__, which constructs the column-on-LHS BinaryExpr. So the swap is mainly insurance against a hand-constructed flipped BinaryExpr rather than a real correctness gap from user expression syntax. Kept the swap scoped to EQ/NE since IN/NOT_IN aren't symmetric in any reasonable interpretation.
| def supports_predicate_pushdown(self) -> bool: | ||
| return True |
There was a problem hiding this comment.
DeltaDatasource should override supports_projection_pushdown to return True and ensure that any applied projection is propagated to the inner ParquetDatasource. Since read_delta is intended as a more efficient replacement for read_parquet (which supports projection pushdown), missing this optimization could lead to performance regressions where unnecessary columns are read from storage.
There was a problem hiding this comment.
Agreed — without this read_delta is strictly slower than read_parquet for projected reads. Fixed in e60b5fb: DeltaDatasource now overrides supports_projection_pushdown() -> True, initialises self._projection_map = None in __init__ (Datasource.__init__ only inits the predicate mixin), and _build_inner forwards any applied projection via inner = inner.apply_projection(self._projection_map) so the inner ParquetDatasource's _combine_projection_map composes it with whatever columns= was passed at construction. Regression test test_delta_select_columns_pushed_down covers ds.select_columns(["x"]).
These tests scaffold the predicate-pushdown contract that ray-project#61547 asks for. They are written before the DeltaDatasource implementation lands (TDD): the contract tests fail with ModuleNotFoundError on the not-yet-created ray.data._internal.datasource.delta_datasource module, and the integration tests fail because today's read_delta does not push partition_filters into DeltaTable.file_uris. Coverage: - Pushdown contract (supports_predicate_pushdown, apply_predicate AND-combine) - Partition pruning via logical-plan inspection (Filter operator removed), matching the Iceberg pattern in test_iceberg.py - Partition pruning end-to-end via row counts, including =, !=, and is_in - File-uri spy: asserts DeltaTable.file_uris is invoked with the expected partition_filters DNF (and not invoked with garbage filters when no predicate is applied) -- the unique check that proves files were skipped - Graceful fallback when a predicate cannot be translated - Existing-behavior regression: version time travel and column projection Stats-based / non-partition file skipping (delta-io/delta-rs#3014) is out of scope and deferred to a follow-up PR. Signed-off-by: tobby168 <[email protected]>
…ay-project#61547) Adds a native ``DeltaDatasource`` that defers parquet URI resolution to execution time and applies pushed-down partition predicates against ``DeltaTable.file_uris(partition_filters=...)``. Mirrors Spark's ``TahoeFileIndex.matchingFiles(partitionFilters, dataFilters)`` shape using delta-rs Python primitives. Design (Option C, "thin wrapper"): - DeltaDatasource splits the pushed-down predicate using the existing ``_split_predicate_by_columns`` helper from parquet_datasource.py (no re-implementation). - A new ``_DeltaPartitionFilterTranslator`` converts the partition-only half into delta-rs DNF [(col, op, value), ...]. Supported ops: =, !=, in, not in. Anything else (OR, NOT, GT/LT, UDF, non-literal RHS) raises NotImplementedError and the datasource falls back gracefully -- the outer Filter operator handles correctness. - get_read_tasks builds a fresh ParquetDatasource each call (no inner caching, simplest lifetime), passing the surviving URIs and the Delta schema so PyArrow does not re-inspect parquet footers. The data half of the predicate is forwarded to the inner ParquetDatasource for PyArrow row-group / scanner-level pushdown. read_delta is rewritten to construct the datasource and route through read_datasource(...). Every existing public kwarg (version, filesystem, columns, partition_filter, partitioning, shuffle, include_paths, **arrow_parquet_args, all resource args) is preserved -- this is a behavior-additive change, not an API change. Stats-based / non-partition file skipping (delta-io/delta-rs#3014) is out of scope for this iteration and left to a phase-2 PR. Tests: the failing test suite from commit 3df71ad (test_delta_pushdown.py, 12 tests) now exercises this implementation; contract tests verified locally. Signed-off-by: tobby168 <[email protected]>
Addresses correctness, robustness, and performance gaps caught in bot review:
1. Silent-drop on unsplittable mixed predicates (correctness).
``_split_predicate_by_columns`` returns ``(None, None)`` for OR/NOT chains
spanning partition + data columns. The previous ``_split`` accepted that
verbatim, so the predicate vanished -- and because
``supports_predicate_pushdown=True`` had already removed the outer Filter,
the read returned unfiltered rows. Now we route the full predicate to the
inner ParquetDatasource for PyArrow scanner-level evaluation.
2. ``ParquetDatasource(**arrow_parquet_args)`` TypeError (crash).
ParquetDatasource takes a fixed set of named parameters (no ``**kwargs``),
so any user-supplied scanner option like ``batch_size`` blew up the
constructor, and an explicit ``schema=`` collided with our positional one.
Mirror ``read_parquet``'s pattern: pop the named kwargs (``dataset_kwargs``,
``_block_udf``, ``schema``) and pass the rest as ``to_batch_kwargs``.
3. Projection pushdown (perf parity with read_parquet).
``select_columns`` was previously a no-op above the (already-removed)
Filter, making read_delta strictly slower than read_parquet for projected
reads. Override ``supports_projection_pushdown`` and forward the resulting
``_projection_map`` into the inner ParquetDatasource via apply_projection.
4. Commutative literal-on-LHS in the partition translator (robustness).
Python's __eq__ overload normalises ``5 == col("p")`` for free, but a
hand-constructed BinaryExpr with a flipped LHS can still land here. Swap
for EQ/NE before the column-on-LHS check so we don't fall back unnecessarily.
Tests: three new regression tests in test_delta_pushdown.py cover the
silent-drop case (OR across part+data columns), arrow_parquet_args routing
(read_delta(path, batch_size=5) must not TypeError), and projection pushdown
end-to-end via ds.select_columns.
Signed-off-by: tobby168 <[email protected]>
65466b2 to
e60b5fb
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit e60b5fb. Configure here.
| dataset_kwargs=dataset_kwargs, | ||
| _block_udf=block_udf, | ||
| to_batch_kwargs=parquet_args, | ||
| ) |
There was a problem hiding this comment.
Cloud storage credentials lost when filesystem is None
High Severity
When filesystem=None (the common case for cloud storage), the old code derived a credential-bearing PyArrow filesystem from DeltaTable.to_pyarrow_dataset(filesystem=filesystem), which internally wired storage_options into the filesystem used by ParquetDatasource. The new code passes filesystem=self._filesystem (i.e. None) directly to ParquetDatasource, so storage_options credentials are only used by the DeltaTable for log reading and file_uris() but never reach the parquet reader. Cloud storage users authenticating via storage_options without a separate filesystem argument will get authentication failures when reading the actual data files.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit e60b5fb. Configure here.
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
|
This pull request has been automatically closed because there has been no more activity in the 14 days Please feel free to reopen or open a new pull request if you'd still like this to be addressed. Again, you can always ask for help on our discussion forum or Ray's public slack channel. Thanks again for your contribution! |
…he log (#67900) ## Summary `read_delta` gains `partition_filters`, which lists and reads only the matching partitions' files, and takes file sizes from the Delta log instead of one `get_file_info` call per file. ## Before `read_delta` had no way to read only some partitions: - `DeltaTable.to_pyarrow_dataset()` was called without a filter, so the dataset had a fragment for every file in the table. - `ParquetDatasource.from_pyarrow_dataset` called `get_file_info` on every fragment to size the read tasks: one request per file on object storage, although the sizes are in the Delta log. - A `filter` on a partition column became a PyArrow row filter, so every file was still opened. On a table with 26,085 files, a one-date read needs 60 of them; building the dataset took 26,085 `get_file_info` requests before the read started. ## After - `read_delta(partition_filters=...)` takes deltalake's tuple filters: `(column, op, value)` with `=`, `!=`, `<`, `<=`, `>`, `>=`, `in`, `not in`. A flat list is an AND, and a list of lists is an OR of ANDs. Only the matching partitions' files become fragments, so only they are sized and read. - deltalake 1.6.6 takes the filters as `file_pruning_predicate` (AND or OR of ANDs). Older versions take them as `partitions`, which only supports an AND list (deltalake 1.5.0 and 1.6.3 fail on an OR with `not enough values to unpack`), so an OR of groups raises a clear error asking for 1.6.6 there. - Every column must be a partition column. deltalake would accept others but prune them only by file statistics, so rows outside the filter would come back. Use `Dataset.filter` for those. - `read_unity_catalog` passes it through `reader_kwargs`. - File sizes come from the log's add actions. Their paths are URL-encoded once more than the fragment paths (`p=a%2520b` vs `p=a%20b`), so they're decoded once. `ParquetDatasource.from_pyarrow_dataset` takes them as `known_file_sizes` and calls `get_file_info` only for paths missing from it. ```mermaid flowchart TD subgraph Before subgraph BS[Subsystem: IO] subgraph BC["Component: read_delta → ParquetDatasource.from_pyarrow_dataset"] B1["DeltaTable.to_pyarrow_dataset()<br/>every file"] --> B2["get_file_info per fragment"] B2 --> B3["read tasks: every file"] end end end subgraph After subgraph AS[Subsystem: IO] subgraph AC["Component: read_delta → ParquetDatasource.from_pyarrow_dataset"] A0["partition_filters<br/>(validated: partition columns only)"] --> A1["to_pyarrow_dataset(file_pruning_predicate | partitions)<br/>matching files only"] A1 --> A2["sizes from the Delta log<br/>(get_file_info only for misses)"] A2 --> A3["read tasks: matching files"] end end end classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 classDef changed fill:#fff9c4,stroke:#f9a825,color:#000 class A0 added class A1,A2 changed ``` ## Subsystems API (`read_api.read_delta`, new `partition_filters` parameter) carries the change; IO for `ParquetDatasource.from_pyarrow_dataset`'s `known_file_sizes`. ## Not a duplicate #62959 ("Add DeltaDatasource with partition predicate pushdown") was closed by the stale bot in May 2026 without review. No open PR adds partition filters to `read_delta`. The DataSourceV2 Delta reader in review (#67888–#67890) prunes partitions from `filter(expr)`; it will send reads with `partition_filters` to this reader until it supports them natively. ## Testing macOS / Python 3.12, env pinned to the CI lock (pyarrow 23.0.1, deltalake 1.5.0): - `pytest python/ray/data/tests/datasource/test_delta.py`: 31 passed on deltalake 1.5.0, and 31 passed with deltalake 1.6.6 on the path. On a table with two files per date partition, `Dataset.input_files()` lists only the matching partitions' files, and the rows match, for: - `=`, `in`, a range, and an AND of two conditions; - an OR of AND groups, which reads on 1.6.6 and raises the clear error on 1.5.0; - invalid filters (a data column, an empty list, a short tuple, an empty group), which raise `ValueError`; - `read_unity_catalog(reader_kwargs={"partition_filters": ...})`. - With a filesystem that counts `info` calls and partition values with special characters (`a b`, `x/y`, `100%`), building the dataset makes 0 `get_file_info` lookups. With the log sizes disabled, it makes 4 (one per file). - `_delta_file_sizes` matches the real file sizes, keyed by the fragment paths deltalake builds, special characters and null partitions included. - `test_catalog.py`: 46 passed; `test_write_delta.py`: 101 passed; `tests/unit/datasource/`: 94 passed. - pre-commit, pyrefly (CI file set) and the API param coverage check pass. AI assistance was used (Claude Code); every line has been reviewed by the submitter. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Abhishek Verma <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>


Summary
Adds a native
DeltaDatasourcefor Ray Data that pushes partition predicatesdown to Delta Lake instead of resolving every parquet URI eagerly.
Previously
read_deltacalledDeltaTable(path).file_uris()with no filterand forwarded every URI to
read_parquet, so even metadata-only queriesfanned out across every file in the table. The new datasource defers URI
resolution to execution time and hands supported partition predicates to
DeltaTable.file_uris(partition_filters=...), letting Delta prune files atthe log level. Non-partition predicates continue to flow into the inner
ParquetDatasourcefor PyArrow row-group / scanner-level pushdown.Closes #61547.
Design notes
TahoeFileIndex.matchingFiles(partitionFilters, dataFilters)shape using delta-rs Python primitives.
_split_predicate_by_columnshelper fromparquet_datasource.pyto split a predicate into partition-only anddata-only halves -- no re-implementation.
_DeltaPartitionFilterTranslatorconverts the partition-only halfinto delta-rs DNF
[(col, op, value), ...]. Supported ops:=,!=,in,not in. Anything else (OR, NOT, GT/LT, UDF, non-literal RHS)raises
NotImplementedErrorand the datasource falls back gracefully --the outer Filter operator handles correctness.
DeltaDatasourceis a thin wrapper:get_read_tasksbuilds a freshParquetDatasourceeach call (no inner caching, simplest lifetime),passing the surviving URIs and the Delta schema so PyArrow does not
re-inspect parquet footers.
read_deltais rewritten to construct the datasource and route throughread_datasource(...). Every existing public kwarg (version,filesystem,columns,partition_filter,partitioning,shuffle,include_paths,**arrow_parquet_args, all resource args) is preserved -- this is abehavior-additive change, not an API change.
Out of scope (follow-ups)
DeltaTable.get_add_actions()min/max evaluation. The data-predicate plumbing is in place; the evaluator
is the only missing piece.
datetime=kwarg onread_delta).Test plan
python/ray/data/tests/datasource/test_delta_pushdown.py(12 tests):supports_predicate_pushdown,apply_predicateAND-combine.
after
LogicalOptimizer), end-to-end row counts for=,!=,is_in.DeltaTable.file_urisis called with the expectedpartition_filtersDNF (and not called with garbage filters when nopredicate is applied).
version=time travel andcolumns=projection over thenew code path.
python/ray/data/tests/datasource/test_delta.pysmoke test leftunchanged.