Repository navigation
Conversation
Review of ray-project#65142 found the V2 read path diverging from V1 in ways that were silent, plus a documented invariant the code did not actually hold. `count()` crashed: `PushdownCountFiles` asserted the indexer was a `NonSamplingFileIndexer`. It only needs one that can be pinned to whole-file listing, so it now checks for that and skips the optimization otherwise instead of failing the query. The PR's own test hid this by reading before counting, which populated the cached row count. `**arrow_parquet_args` was accepted and dropped, changing which rows came back. `catalog=` broke: its bucket-rooted filesystem was wrapped in a table-rooted `SubTreeFileSystem` for `to_pyarrow_dataset`, but the V2 path resolves absolute paths from the log. Both now decide V2 eligibility in one place, `_delta_table_supports_datasource_v2`, which fails closed -- anything V2 would answer *differently* rather than merely faster stays on V1. The claim that log-level pruning is only an optimization did not hold for typed partition columns: partition values parsed from a path are strings, so `col("year") == lit(2024)` raised inside PyArrow and was conservatively read as "keep the file", leaving pruning as the only thing enforcing the predicate. The partitioning now carries `field_types` from the Delta schema so the scanner can evaluate such predicates itself, and tables whose partition types that cannot express (date, decimal) stay on V1. `PathPartitionParser` also no longer coerces a `null_fallback`-derived `None`, which the two features together would otherwise hit. Also: the snapshot version is pinned on the driver, so deferred listing can't pick up a concurrent commit or disagree across task retries; `path` survives a column projection under `include_paths`; an empty table honors `columns` and `include_paths`; the rule declares `PredicatePushdown` as a dependency rather than relying on list position; the datasource caches its snapshot instead of reopening the log five times per read; and listing uses `ParquetFileChunker`, matching `read_parquet`. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: tobby168 <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a DataSourceV2 implementation for Delta Lake tables, enabling log-driven file listing and pruning (both partition pruning and statistics-based skipping) via DeltaFileIndexer and prune_add_actions. It also adds logical rules (PushdownDeltaFilePruning) to push down predicates settled by PredicatePushdown to the DeltaFileIndexer, and updates read_delta to route through the V2 path when use_datasource_v2 is enabled. The review feedback highlights several instances of redundant wrapping of PyArrow objects (such as pa.schema() and pa.table()) where the underlying methods already return the correct types.
| columns keep their declared position and type rather than being | ||
| appended as the strings the directory names encode. | ||
| """ | ||
| schema = pa.schema(self._open_table().schema().to_arrow()) |
There was a problem hiding this comment.
The call to pa.schema() is redundant here because self._open_table().schema().to_arrow() already returns a pyarrow.Schema object. Removing the redundant wrapping simplifies the code and avoids unnecessary object instantiation.
| schema = pa.schema(self._open_table().schema().to_arrow()) | |
| schema = self._open_table().schema().to_arrow() |
| version=self._version, | ||
| storage_options=self._storage_options, | ||
| ) | ||
| add_actions = pa.table(table.get_add_actions(flatten=True)) |
There was a problem hiding this comment.
The call to pa.table() is redundant here because table.get_add_actions(flatten=True) already returns a pyarrow.Table object. Removing the redundant wrapping simplifies the code and avoids unnecessary object instantiation.
| add_actions = pa.table(table.get_add_actions(flatten=True)) | |
| add_actions = table.get_add_actions(flatten=True) |
| if mode is not None and mode.lower() != "none": | ||
| return False | ||
|
|
||
| schema = pa.schema(dt.schema().to_arrow()) |
There was a problem hiding this comment.
The call to pa.schema() is redundant here because dt.schema().to_arrow() already returns a pyarrow.Schema object. Removing the redundant wrapping simplifies the code and avoids unnecessary object instantiation.
| schema = pa.schema(dt.schema().to_arrow()) | |
| schema = dt.schema().to_arrow() |
| if not partition_columns: | ||
| return {} | ||
|
|
||
| schema = pa.schema(dt.schema().to_arrow()) |
There was a problem hiding this comment.
The call to pa.schema() is redundant here because dt.schema().to_arrow() already returns a pyarrow.Schema object. Removing the redundant wrapping simplifies the code and avoids unnecessary object instantiation.
| schema = pa.schema(dt.schema().to_arrow()) | |
| schema = dt.schema().to_arrow() |
| INCLUDE_PATHS_COLUMN_NAME, | ||
| ) | ||
|
|
||
| schema = pyarrow.schema(dt.schema().to_arrow()) |
There was a problem hiding this comment.
The call to pyarrow.schema() is redundant here because dt.schema().to_arrow() already returns a pyarrow.Schema object. Removing the redundant wrapping simplifies the code and avoids unnecessary object instantiation.
| schema = pyarrow.schema(dt.schema().to_arrow()) | |
| schema = dt.schema().to_arrow() |
`_empty_delta_dataset` appended the synthesized `path` column and then projected to `columns`, which dropped it again. A real read adds `path` after the projection instead, so `read_delta(columns=["a"], include_paths=True)` returned `["a", "path"]` for a populated table and `["a"]` for an empty one -- a union of the two then failed on mismatched schemas. Both paths now derive their output columns from `_delta_output_columns`, so they can't drift apart again, and the test covers each combination of `columns` and `include_paths` rather than one option at a time. Reported by Cursor Bugbot on ray-project#65142. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: tobby168 <[email protected]>
|
Thanks both — responses below, plus one behavior change worth flagging that came out of digging into the second Bugbot finding. @gemini-code-assist: the five
|
|
Thanks for the detailed breakdown, @tobby168. Your analysis of the Regarding the behavior change for partition columns in |
|
Drive-by note, not a review — this PR touches the same loop I was about to send a separate fix for, and they're different defects, so flagging here rather than opening a competing PR. Your f = PathPartitionFilter.of(lambda d: True if d else False, style="hive",
base_dir="/tmp/part_probe", field_types={"year": int})
f(["/tmp/part_probe/year=2024/f.csv", "/tmp/part_probe/loose.csv"])
# KeyError: 'year'Either works for me: I can wait for this to land and send the missing-key fix on top, or you could fold it in here since it's the same two lines. Whichever you prefer. |
Groundwork for deferring Delta Lake file resolution to execution time (ray-project#61547). `prune_add_actions` answers, from a Delta snapshot's add actions alone, which data files a query could need. Partition values are matched exactly via Ray's own expression evaluator; data columns are bounded conservatively against the log's min/max statistics, so a file is dropped only when its interval proves no row can match. Every unprovable case keeps the file -- over-retention costs a read, but dropping a matching file loses data silently. `DeltaFileIndexer` lists a table from that log rather than walking the filesystem, applying the pruning before files are sized or chunked. Paths are reconstructed by decoding the log's URL-encoded relative path once before joining; the raw value names a path that does not exist when a partition value contains `=`, `/` or a space. `build_manifests` is extracted from `NonSamplingFileIndexer` unchanged so both indexers share manifest batching. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: tobby168 <[email protected]>
`read_delta` now builds a `DeltaDatasourceV2` when `use_datasource_v2` is set (the default), so listing is deferred to execution and driven by the Delta log rather than `to_pyarrow_dataset()`, which resolved every file on the driver before any predicate was known (ray-project#61547). `PushdownDeltaFilePruning` runs after `PredicatePushdown` and copies the predicates it settled onto the scanner into the upstream `ListFiles` indexer. Files that cannot match are then never listed, sized, or scheduled. Pruning is strictly an optimization: the scanner still enforces the predicates, so a plan the rule does not recognize reads more files but returns the same rows. Schema and partition columns come from the log, so no Parquet footers are sampled. The scanner pins a projection to keep the Delta column order -- the reader appends path-derived partition columns, which would otherwise move them to the end of every partitioned table. Also handled: - Deletion Vectors are rejected up front on both paths. Reading those files directly returns rows the table marks deleted; the previous error text suggested upgrading to deltalake>=0.10.0, which is not the issue under 1.5.0. - `Partitioning.null_fallback` parses a sentinel directory name back to `None`. Delta writes null partition values as `__HIVE_DEFAULT_PARTITION__`, which cannot be cast to the column's declared type. Opt-in, so `read_parquet` is unchanged. - An empty Delta table is answered from the log instead of tripping the V2 "no files found" guard, which exists to catch empty directories. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: tobby168 <[email protected]>
Under `delta.columnMapping.mode`, a table's Parquet files carry generated column names and the logical names live only in the transaction log. The V2 path opens those files directly with the logical schema, so it would ask for names the files don't have and hand back empty columns. Route such tables to the V1 path instead of guarding against them. Today `to_pyarrow_dataset` raises for them, so behavior is unchanged; if ray-project#64929 lands, they pick up its fix without this path needing to know about it. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: tobby168 <[email protected]>
Review of ray-project#65142 found the V2 read path diverging from V1 in ways that were silent, plus a documented invariant the code did not actually hold. `count()` crashed: `PushdownCountFiles` asserted the indexer was a `NonSamplingFileIndexer`. It only needs one that can be pinned to whole-file listing, so it now checks for that and skips the optimization otherwise instead of failing the query. The PR's own test hid this by reading before counting, which populated the cached row count. `**arrow_parquet_args` was accepted and dropped, changing which rows came back. `catalog=` broke: its bucket-rooted filesystem was wrapped in a table-rooted `SubTreeFileSystem` for `to_pyarrow_dataset`, but the V2 path resolves absolute paths from the log. Both now decide V2 eligibility in one place, `_delta_table_supports_datasource_v2`, which fails closed -- anything V2 would answer *differently* rather than merely faster stays on V1. The claim that log-level pruning is only an optimization did not hold for typed partition columns: partition values parsed from a path are strings, so `col("year") == lit(2024)` raised inside PyArrow and was conservatively read as "keep the file", leaving pruning as the only thing enforcing the predicate. The partitioning now carries `field_types` from the Delta schema so the scanner can evaluate such predicates itself, and tables whose partition types that cannot express (date, decimal) stay on V1. `PathPartitionParser` also no longer coerces a `null_fallback`-derived `None`, which the two features together would otherwise hit. Also: the snapshot version is pinned on the driver, so deferred listing can't pick up a concurrent commit or disagree across task retries; `path` survives a column projection under `include_paths`; an empty table honors `columns` and `include_paths`; the rule declares `PredicatePushdown` as a dependency rather than relying on list position; the datasource caches its snapshot instead of reopening the log five times per read; and listing uses `ParquetFileChunker`, matching `read_parquet`. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: tobby168 <[email protected]>
A second review found the V2 Delta path returning extra rows in its
default configuration, and failing outright for URI-addressed tables.
`PathPartitionParser.evaluate_predicate_on_partition` swallows any
evaluation error and keeps the file. That is sound only while something
else applies the predicate -- but `ReadFiles.apply_predicate` removes the
`Filter` as soon as a scanner accepts one, leaving path parsing as the
sole enforcement point. A path is a lossy view of what the Delta log
records: a null partition is the literal `__HIVE_DEFAULT_PARTITION__`
directory, and `pc.is_in` over the null-typed row the parser builds
raises. `col("p").is_in(["a"]) | (col("p") == lit("b"))` over a nullable
partition column therefore returned the NULL partition's rows as well.
Scanners can now decline to enforce a partition predicate
(`enforces_partition_predicate`), in which case the optimizer keeps it in
a `Filter` above the read, where it binds against the partition columns
the reader has already materialized -- exactly typed, with real nulls.
`DeltaScanner` declines. `PushdownDeltaFilePruning` still forwards the
same predicate to the log for file skipping, so pruning is unchanged and
only the correctness burden moves; a partition-pruned read still lists 1
of 2 files.
This also removes the reason to keep exotic partition types off V2: they
now simply prune less rather than risk a wrong answer.
`DeltaDatasourceV2` also never resolved its paths, so manifests carried
scheme-prefixed URIs and PyArrow rejected them at read time -- breaking
every `s3://`/`az://` table, including `read_delta`'s own docstring
examples, with V2 on by default. The log is now opened with the URI as
given while the reader gets filesystem-native paths. This was also the
remaining half of the `catalog=` breakage.
Tables with a column named `path` stay on V1; that name is how the reader
labels the synthesized file path, so the real column was being shadowed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: tobby168 <[email protected]>
`_empty_delta_dataset` appended the synthesized `path` column and then projected to `columns`, which dropped it again. A real read adds `path` after the projection instead, so `read_delta(columns=["a"], include_paths=True)` returned `["a", "path"]` for a populated table and `["a"]` for an empty one -- a union of the two then failed on mismatched schemas. Both paths now derive their output columns from `_delta_output_columns`, so they can't drift apart again, and the test covers each combination of `columns` and `include_paths` rather than one option at a time. Reported by Cursor Bugbot on ray-project#65142. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: tobby168 <[email protected]>
Master's DataSourceV2 listing split (ray-project#65167, ray-project#65214) changed the base class under this branch: - ``list_file_infos`` became an ``@abstractmethod``, so a ``FileIndexer`` that doesn't implement it can no longer be instantiated. - ``list_files`` gained ``predicate`` / ``limit`` / ``projected_columns``, the listing-time pushdown state that ``DeriveListFilesPushdown`` now derives from the ``ReadFiles`` scanner. - Zero-size skipping and pruner application moved out of manifest building and into ``list_file_infos``, so ``build_manifests`` no longer takes ``pruners``. Implement ``list_file_infos`` for the Delta indexer and route ``list_files`` through it, mirroring ``NonSamplingFileIndexer`` so both listing entry points share one filtering point. Log-level pruning still happens upstream of both, in ``_iter_file_infos``. The three new pushdown kwargs are accepted and ignored for now: this indexer prunes from the partition/data predicate split it was constructed with. Consuming the derived state instead would let this branch's ``PushdownDeltaFilePruning`` rule be dropped entirely in favor of the upstream one; that is a design question for the PR thread rather than a mechanical rebase. Signed-off-by: tobby168 <[email protected]>
``PathPartitionParser.__call__`` iterated ``field_types`` and indexed the
parsed partitions directly, so any path that didn't carry every typed key
raised ``KeyError`` instead of parsing.
That contradicts two documented contracts in this same module:
- ``Partitioning.base_dir``: "File paths either outside of, or at the
first level of, this directory will be considered unpartitioned."
- ``PathPartitionFilter``: "Unpartitioned files are denoted with an empty
input dictionary" -- and the docstring's own recipe for dropping
unpartitioned files raised instead of running whenever ``field_types``
was supplied.
An unpartitioned file directly under ``base_dir`` parses to ``{}``, so the
very first ``field_types`` key blew up. Skip keys a given path doesn't
carry; ``field_types`` describes the scheme, not any individual path.
Reported by @jackylee-ch on ray-project#65142. Distinct from the adjacent
``value is None`` guard, which handles a null value produced by
``null_fallback`` rather than an absent key.
Signed-off-by: tobby168 <[email protected]>
This branch shipped its own rule, ``PushdownDeltaFilePruning``, to copy settled predicates from the ``ReadFiles`` scanner onto the upstream ``DeltaFileIndexer``. Master has since landed the general mechanism for exactly that (ray-project#65214): ``DeriveListFilesPushdown`` derives each ``ListFiles``' listing constraints from its consuming scanner, once, after the rule loop. Keeping a second rule that does the same thing for one format is redundant and drifts. Delete the custom rule and make Delta a consumer of the upstream one. One piece was missing to do that. ``derive_list_files_pushdown`` reported only ``scanner.pushed_predicate()``, which is the *data* half of a predicate: ``ReadFiles.apply_predicate`` splits by column, routing partition columns to ``prune_partitions`` and data columns to ``push_filters``, so a partition predicate never appears there. Delta can answer both from its log, and partition pruning is the larger win, so report it: - ``SupportsPartitionPruning.pushed_partition_predicate()``, concrete and defaulting to ``None`` for the same reason as ``pushed_predicate`` -- an out-of-tree scanner keeps working, just without partition pruning at listing time. - ``derive_list_files_pushdown`` returns it as a fourth element, and ``ListFiles`` gains a matching field, forwarded through ``plan_list_files_op`` / ``list_files_for_each_block`` to ``FileIndexer.list_files``. ``DeltaFileIndexer`` now takes predicates per call rather than holding them, which makes the staleness the old ``with_predicates`` copy guarded against unrepresentable. It also reads the table schema off the snapshot it already opens instead of having it plumbed in -- that is the unprojected schema by construction, which is what casting the log's string partition values needs. ``_files_listed`` in the pushdown tests now forwards the operator's pushdown state, matching what ``plan_list_files_op`` does. Without that the indexer would list the whole snapshot and every pruning assertion would pass vacuously. Signed-off-by: tobby168 <[email protected]>
44ace4c to
8b129b8
Compare
|
Rebased onto master and restructured. The short version: this PR no longer carries its own optimizer rule. @jackylee-ch's report is folded in too. Re-founded on
|
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 8b129b8. Configure here.
``_resolve_file_uri`` always ``posixpath.join``ed the table URI with the
decoded add-action path. The Delta protocol permits that path to be an
absolute URI or an absolute filesystem path -- shallow clones and
externally managed files use that form -- and joining an absolute URI
onto a root produces a path that does not exist:
posixpath.join("/tmp/tbl", "s3://other/key/part-0.parquet")
-> "/tmp/tbl/s3://other/key/part-0.parquet"
Such a table listed files that could never be opened. Return absolute
paths unchanged instead.
(An absolute *filesystem* path already resolved correctly, since
``posixpath.join`` discards the left operand in that case. The explicit
check keeps both forms deliberate rather than incidental.)
The scheme test requires more than one character so a Windows drive
letter isn't mistaken for a scheme, and a colon inside a partition value
(``key=a:b/part-0.parquet``) is unaffected because the text before it is
not a valid scheme.
Reported by Cursor Bugbot on ray-project#65142.
Signed-off-by: tobby168 <[email protected]>
|
Bugbot's finding is real — fixed in the latest push.
Such a table would list files that never open. Absolute paths are now returned unchanged. One correction to the report, for the record: it says the join "either prefixes them incorrectly or discards the table root". The discarding case — an absolute filesystem path — was already correct, since The scheme test requires more than one character so a Windows drive letter isn't read as a scheme, and a colon inside a partition value ( This one I could verify — it's pure path arithmetic with no Ray import — and all seven pass. The rest of the suite is still unrun for the reason in my previous comment. |
## Why Footer IO for the footer-based Parquet chunking path (the rest of the split of #64985). Reading N Parquet footers serially on the driver doesn't scale — it's the step that decides which row groups a read even touches. `FooterReader` runs as a pool of Ray actors, each reading footers on its own thread pool and streaming results back in batches, so footer IO spreads across the cluster instead of bottlenecking on one process. **Nothing constructs it yet** — it's unused until the footer indexer lands in step 6. ## Flow Per file, it produces the row-group descriptors the bin packer (merged in #65210) consumes: ```mermaid flowchart LR B["(path, size) batch"] --> A["FooterReaderActor<br/>SPREAD across the cluster"] A --> R[read footer] R --> F["split_by_row_group(filter)<br/>prune by statistics"] F --> Q["split_by_row_group(~filter)<br/>classify fully_matched"] Q --> C["coalesce_row_groups<br/>(from #65210)"] C --> O["stream List[FileChunks]<br/>batched by result_batch_size"] ``` Three things it decides, each of which the packer and the limit push-down depend on: - **Predicate pruning.** `fragment.split_by_row_group(filter)` drops row groups whose Parquet statistics contradict the pushed filter, so they never reach the packer at all. - **`fully_matched` classification.** A surviving group is *fully* matched iff `~filter` prunes it entirely. Only fully-matched groups have an exact survivor count, and only exact counts may drive limit push-down. Any failure defaults to not-fully-matched, which is always the safe direction. **This is the correctness-critical bit**: nulls are the interesting case, since Parquet min/max stats are computed over non-null values only, so a group whose non-null values all satisfy the filter looks fully matched by bounds alone while its null rows don't survive. - **Projection-scoped sizing.** Byte sizes are accounted over only the projected leaf columns, so bins get sized for what the reader will actually fetch. Nested columns expand to all their leaves. ## What changed Two new files, 368 insertions, 0 deletions: | File | Change | | --- | --- | | `listing/footer_reader.py` | **new** — `FooterReader` plus `FooterReaderActor = ray.remote(FooterReader)`. Kept as a plain class with the actor built via the functional form, so callers can type handles as `ActorProxy[FooterReader]`. `read_footers` is a streaming `@ray.method` generator that yields `List[FileChunks]`, batched by `result_batch_size` — the driver pays one object-store fetch per yielded list, so batching cuts driver-side deserialization roughly proportionally. | | `tests/test_footer_reader.py` | **new** — 14 tests | ## Testing The tests drive the plain class directly against local Parquet fixtures — no actor, no cluster. Coverage is aimed at the decisions above rather than the plumbing: predicate pruning by statistics, the partial-match case (`id >= 30` splitting a row group, which must **not** count as exact), a predicate matching nothing, projection shrinking accounted size while leaving row counts alone, coalescing preserving total rows, nested columns expanding to all leaves, and result batching at several `result_batch_size` values. ``` $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/test_footer_reader.py 14 passed in 4.30s $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/ python/ray/data/tests/unit/datasource_v2/ 145 passed in 0.90s ``` ## Stack Step 5 of an 11-step split of #64985, which was 43 files / +3234 −719 and not reviewable as one unit. - #65167 `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - #65168 `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - #65214 `[3/11]` Derive `ListFiles` pushdown state from the scanner ✅ merged - #65210 `[4/11]` Parquet footer types + online bin packer ✅ merged - **this PR** `[5/11]` — depends on #65210 for `parquet_footer_types` and `parquet_row_group_coalescing` - #65169 `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) Step 6 wires this and the packer together behind an opt-in flag, and needs both this and #65214. --- Not a duplicate of any open PR (checked `gh pr list --state open` plus a file-level overlap check against #65142 / #63158 / #64404 — no overlap; only #64985, which this replaces). AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]>
## Why The last step of the split of #64985: flip Parquet V2 to the footer read path, delete the blind one, and tune the release tests so this can be validated by a real release run. Everything it depends on has landed — footer types and the bin packer (#65210), the `FooterReader` actor pool (#65273), the indexer plus `count()` fix and packer-as-partitioner (#65596), reader IO tuning (#65806), and test env pinning (#65169). The path has been reachable behind `RAY_DATA_PARQUET_ENABLE_FOOTER_INDEXER` since #65596; this makes it the only path. ## Flow ```mermaid flowchart LR RP[read_parquet] --> FF["FooterFileIndexer<br/>+ OnlineBinPacker"] RP -.->|deleted| PC["ParquetFileChunker<br/>size-estimated chunks<br/>+ parquet_chunker_target_chunk_size"] style PC stroke-dasharray: 4 4 ``` ## What changed **The flip** — `RAY_DATA_PARQUET_ENABLE_FOOTER_INDEXER` is gone from both call sites. `_get_file_indexer()` always returns `FooterFileIndexer`; `get_file_partitioner()` always returns `OnlineBinPacker`. **The deletions** — `ParquetFileChunker`, `ParquetFileChunkMetadata`, `_calculate_row_group_range`, `_fragments_from_chunk_metadata`, and the tests covering only that path. **The config it left behind** — `DataContext.parquet_chunker_target_chunk_size` and `DEFAULT_PARQUET_CHUNKER_TARGET_CHUNK_SIZE` were read *only* by `ParquetFileChunker.__init__`, so they would otherwise stay declared and documented while doing nothing. Verified dead by grep across `.py` / `.yaml` / `.rst` / `.md`. **Reader pool defaults** — `RAY_DATA_PARQUET_READER_IO_THREAD_COUNT` 128, `RAY_DATA_PARQUET_READER_CPU_COUNT` 32. ## Release tests tuned Budgets are per-test overrides of `RAY_DATA_PARQUET_BIN_PACKING_BYTES` (uncompressed bytes of row-group data per read task; default 128 MiB). The shape of the tuning: reads over few large groups want **large** bins, because small bins shatter the read into short tasks the executor cannot dispatch fast enough and the cluster idles; shuffle-bound reads over many groups want **small** bins. Rows whose variants all share the same tuning are collapsed and marked. | release test | bin budget | other tuning | | --- | --- | --- | | `aggregate_groups_fixed_size_hash_shuffle_column02 column14` | 32 MiB | — | | `aggregate_groups_fixed_size_hash_shuffle_column08 column13 column14` | 128 MiB | — | | `aggregate_groups_fixed_size_shuffle_v2_column02 column14` | 64 MiB | — | | `aggregate_groups_fixed_size_shuffle_v2_column08 column13 column14` | 512 MiB | — | | `aggregate_groups_fixed_size_sort_shuffle_pull_based_column02 column14` | 32 MiB | — | | `aggregate_groups_fixed_size_sort_shuffle_pull_based_column08 column13 column14` | 256 MiB | — | | `count_parquet_fixed_size` | 64 MiB | — | | `cross_az_map_batches_autoscaling_iptable_failure_injection` | 1 GiB | — | | `distributed_training` | — | footer actors `20` | | `flat_map` | 64 MiB | — | | `iceberg_benchmark_overwrite` | 64 MiB | — | | `iter_batches_pyarrow` | 64 MiB | — | | `iter_torch_batches` | 64 MiB | — | | `joins_{{dataset}}_{{join_type}} *(all 4 variants)*` | 1.25 GiB | — | | `map` | 64 MiB | — | | `map_batches_fixed_size_{{compute}}_{{format}}_{{repeat_map_batches}} *(all 7 variants)*` | 1 GiB | scale-up threshold `0.6` | | `map_groups_fixed_size_{{shuffle_strategy}}_{{columns}} *(all 6 variants)*` | 1.25 GiB | — | | `mix` | — | footer actors `4` | | `random_shuffle_fixed_size` | 64 MiB | — | | `read_large_parquet_fixed_size` | 1 GiB | — | | `read_parquet_fixed_size` | 64 MiB | — | | `read_tfrecords` | 64 MiB | — | | `streaming_split` | 64 MiB | footer batch `50`, result batch `50` | | `to_tf` | 64 MiB | — | | `tpch_q1_fixed_size_{{shuffle_strategy}} *(all 2 variants)*` | 192 MiB | — | | `training_ingest_benchmark` | 64 MiB | — | | `wide_schema_pipeline_nested_structs` | 2 MiB | footer batch `1`, footer actors `21`, io threads `5000` | | `wide_schema_pipeline_objects` | 4.2 MiB | footer batch `1`, footer actors `9`, io threads `5000` | | `wide_schema_pipeline_primitives` | 256 KiB | footer batch `1`, footer actors `27`, io threads `5000` | | `wide_schema_pipeline_tensors` | 39 MiB | footer batch `1`, footer actors `22`, io threads `5000` | | `write_parquet` | 1.25 GiB | — | **Three matrices are split**, because a matrix cannot vary `byod.runtime_env` per value and their variants want different budgets: `wide_schema_pipeline_{{data_type}}` into four entries, and one variant each out of `iceberg_benchmark_{{mode}}` and `iter_batches_{{format}}`. `aggregate_groups` keeps its matrix and carries the budget as a matrix dimension with explicit adjustments. **Rendered test names are unchanged — 121 before and after** — so release baselines still line up. **Not carried over** from the original branch: 7 previously-pinned entries no longer exist — the autoscaling variants removed in #65506, plus `tpch_q20` and `tpch_q22`. Any entry gaining its own `runtime_env` re-lists the four `DEFAULTS` guards verbatim: `deep_update` overwrites lists rather than merging them, so declaring one silently drops the OOM / dead-node / object-store checks. (17 entries on master are already missing guards for this reason; pre-existing, not touched here.) `map_benchmark.py` also drops its `use_datasource_v2 = False` pin, which existed because V2 was spilling. > Budgets originally measured against the pre-decoupling design and refined since. Packing moved between stages in #65596 but the packer and its inputs did not, so bins should be unchanged — a release run against this PR is what confirms that. The wide-schema tests are the first place to look. ## Behavior change worth reviewing **Read-task sizing no longer comes from `override_num_blocks` / `read_op_min_num_blocks` for Parquet.** Bins are sized by `RAY_DATA_PARQUET_BIN_PACKING_BYTES`, which is *also* not derived from `DataContext.target_max_block_size`. That decoupling is deliberate — read units are row-group-accurate rather than size-estimated — but it means the two knobs users reach for first no longer affect Parquet read parallelism. Deriving the budget from `target_max_block_size` is worth considering as a follow-up; the per-test overrides above are the evidence that a single global default does not fit every workload. ## Testing ``` $ python -m pytest -q python/ray/data/tests/datasource/test_parquet.py 286 passed, 6 skipped in 521.25s $ python -m pytest -q python/ray/data/tests/datasource/test_read_parquet_v2.py 32 passed $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/ python/ray/data/_internal/datasource_v2/tests/ 181 passed $ python -m pytest -q python/ray/data/tests/test_predicate_pushdown.py \ python/ray/data/tests/test_execution_optimizer_limit_pushdown.py 78 passed ``` The 286-test parquet suite is the one that matters — it runs the full read surface with the footer path as the default rather than behind a flag. The release YAML is additionally checked for parse validity, unresolved `{{...}}` in any pin, duplicate `byod:` keys, and rendered-name stability. ## Stack Final step of an 11-step split of #64985 (43 files / +3234 −719, not reviewable as one unit). - #65167 `[1]` · #65168 `[2]` · #65214 `[3]` · #65210 `[4]` · #65273 `[5]` · #65596 `[6]` · #65806 `[8]` · #65169 `[9]` — all merged - `[7]` (count push-down fix) was absorbed into #65596 - `[10]` (release tuning) is folded into this PR, so a release run exercises the flip and its tuning together - **this PR** `[11/11]` --- Not a duplicate. File-level overlap check: #63158 none; #65142 overlaps `file_indexer.py` / `context.py`; #65406 / #65407 (arrow-rs reader A/B) overlap broadly but are explicitly `[DO NOT MERGE]` benchmark branches carrying the footer work out-of-tree. AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]>
|
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! |
) ## Why Footer IO for the footer-based Parquet chunking path (the rest of the split of ray-project#64985). Reading N Parquet footers serially on the driver doesn't scale — it's the step that decides which row groups a read even touches. `FooterReader` runs as a pool of Ray actors, each reading footers on its own thread pool and streaming results back in batches, so footer IO spreads across the cluster instead of bottlenecking on one process. **Nothing constructs it yet** — it's unused until the footer indexer lands in step 6. ## Flow Per file, it produces the row-group descriptors the bin packer (merged in ray-project#65210) consumes: ```mermaid flowchart LR B["(path, size) batch"] --> A["FooterReaderActor<br/>SPREAD across the cluster"] A --> R[read footer] R --> F["split_by_row_group(filter)<br/>prune by statistics"] F --> Q["split_by_row_group(~filter)<br/>classify fully_matched"] Q --> C["coalesce_row_groups<br/>(from ray-project#65210)"] C --> O["stream List[FileChunks]<br/>batched by result_batch_size"] ``` Three things it decides, each of which the packer and the limit push-down depend on: - **Predicate pruning.** `fragment.split_by_row_group(filter)` drops row groups whose Parquet statistics contradict the pushed filter, so they never reach the packer at all. - **`fully_matched` classification.** A surviving group is *fully* matched iff `~filter` prunes it entirely. Only fully-matched groups have an exact survivor count, and only exact counts may drive limit push-down. Any failure defaults to not-fully-matched, which is always the safe direction. **This is the correctness-critical bit**: nulls are the interesting case, since Parquet min/max stats are computed over non-null values only, so a group whose non-null values all satisfy the filter looks fully matched by bounds alone while its null rows don't survive. - **Projection-scoped sizing.** Byte sizes are accounted over only the projected leaf columns, so bins get sized for what the reader will actually fetch. Nested columns expand to all their leaves. ## What changed Two new files, 368 insertions, 0 deletions: | File | Change | | --- | --- | | `listing/footer_reader.py` | **new** — `FooterReader` plus `FooterReaderActor = ray.remote(FooterReader)`. Kept as a plain class with the actor built via the functional form, so callers can type handles as `ActorProxy[FooterReader]`. `read_footers` is a streaming `@ray.method` generator that yields `List[FileChunks]`, batched by `result_batch_size` — the driver pays one object-store fetch per yielded list, so batching cuts driver-side deserialization roughly proportionally. | | `tests/test_footer_reader.py` | **new** — 14 tests | ## Testing The tests drive the plain class directly against local Parquet fixtures — no actor, no cluster. Coverage is aimed at the decisions above rather than the plumbing: predicate pruning by statistics, the partial-match case (`id >= 30` splitting a row group, which must **not** count as exact), a predicate matching nothing, projection shrinking accounted size while leaving row counts alone, coalescing preserving total rows, nested columns expanding to all leaves, and result batching at several `result_batch_size` values. ``` $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/test_footer_reader.py 14 passed in 4.30s $ python -m pytest -q python/ray/data/_internal/datasource_v2/tests/ python/ray/data/tests/unit/datasource_v2/ 145 passed in 0.90s ``` ## Stack Step 5 of an 11-step split of ray-project#64985, which was 43 files / +3234 −719 and not reviewable as one unit. - ray-project#65167 `[1/11]` Extract `FileIndexer.list_file_infos` ✅ merged - ray-project#65168 `[2/11]` Push limit into `ReadFiles` when `Limit` sits directly on it ✅ merged - ray-project#65214 `[3/11]` Derive `ListFiles` pushdown state from the scanner ✅ merged - ray-project#65210 `[4/11]` Parquet footer types + online bin packer ✅ merged - **this PR** `[5/11]` — depends on ray-project#65210 for `parquet_footer_types` and `parquet_row_group_coalescing` - ray-project#65169 `[9/11]` Pin the Parquet footer actor pool to 1 in tests (open, independent) Step 6 wires this and the packer together behind an opt-in flag, and needs both this and ray-project#65214. --- Not a duplicate of any open PR (checked `gh pr list --state open` plus a file-level overlap check against ray-project#65142 / ray-project#63158 / ray-project#64404 — no overlap; only ray-project#64985, which this replaces). AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]>
…ect#65821) ## Why The last step of the split of ray-project#64985: flip Parquet V2 to the footer read path, delete the blind one, and tune the release tests so this can be validated by a real release run. Everything it depends on has landed — footer types and the bin packer (ray-project#65210), the `FooterReader` actor pool (ray-project#65273), the indexer plus `count()` fix and packer-as-partitioner (ray-project#65596), reader IO tuning (ray-project#65806), and test env pinning (ray-project#65169). The path has been reachable behind `RAY_DATA_PARQUET_ENABLE_FOOTER_INDEXER` since ray-project#65596; this makes it the only path. ## Flow ```mermaid flowchart LR RP[read_parquet] --> FF["FooterFileIndexer<br/>+ OnlineBinPacker"] RP -.->|deleted| PC["ParquetFileChunker<br/>size-estimated chunks<br/>+ parquet_chunker_target_chunk_size"] style PC stroke-dasharray: 4 4 ``` ## What changed **The flip** — `RAY_DATA_PARQUET_ENABLE_FOOTER_INDEXER` is gone from both call sites. `_get_file_indexer()` always returns `FooterFileIndexer`; `get_file_partitioner()` always returns `OnlineBinPacker`. **The deletions** — `ParquetFileChunker`, `ParquetFileChunkMetadata`, `_calculate_row_group_range`, `_fragments_from_chunk_metadata`, and the tests covering only that path. **The config it left behind** — `DataContext.parquet_chunker_target_chunk_size` and `DEFAULT_PARQUET_CHUNKER_TARGET_CHUNK_SIZE` were read *only* by `ParquetFileChunker.__init__`, so they would otherwise stay declared and documented while doing nothing. Verified dead by grep across `.py` / `.yaml` / `.rst` / `.md`. **Reader pool defaults** — `RAY_DATA_PARQUET_READER_IO_THREAD_COUNT` 128, `RAY_DATA_PARQUET_READER_CPU_COUNT` 32. ## Release tests tuned Budgets are per-test overrides of `RAY_DATA_PARQUET_BIN_PACKING_BYTES` (uncompressed bytes of row-group data per read task; default 128 MiB). The shape of the tuning: reads over few large groups want **large** bins, because small bins shatter the read into short tasks the executor cannot dispatch fast enough and the cluster idles; shuffle-bound reads over many groups want **small** bins. Rows whose variants all share the same tuning are collapsed and marked. | release test | bin budget | other tuning | | --- | --- | --- | | `aggregate_groups_fixed_size_hash_shuffle_column02 column14` | 32 MiB | — | | `aggregate_groups_fixed_size_hash_shuffle_column08 column13 column14` | 128 MiB | — | | `aggregate_groups_fixed_size_shuffle_v2_column02 column14` | 64 MiB | — | | `aggregate_groups_fixed_size_shuffle_v2_column08 column13 column14` | 512 MiB | — | | `aggregate_groups_fixed_size_sort_shuffle_pull_based_column02 column14` | 32 MiB | — | | `aggregate_groups_fixed_size_sort_shuffle_pull_based_column08 column13 column14` | 256 MiB | — | | `count_parquet_fixed_size` | 64 MiB | — | | `cross_az_map_batches_autoscaling_iptable_failure_injection` | 1 GiB | — | | `distributed_training` | — | footer actors `20` | | `flat_map` | 64 MiB | — | | `iceberg_benchmark_overwrite` | 64 MiB | — | | `iter_batches_pyarrow` | 64 MiB | — | | `iter_torch_batches` | 64 MiB | — | | `joins_{{dataset}}_{{join_type}} *(all 4 variants)*` | 1.25 GiB | — | | `map` | 64 MiB | — | | `map_batches_fixed_size_{{compute}}_{{format}}_{{repeat_map_batches}} *(all 7 variants)*` | 1 GiB | scale-up threshold `0.6` | | `map_groups_fixed_size_{{shuffle_strategy}}_{{columns}} *(all 6 variants)*` | 1.25 GiB | — | | `mix` | — | footer actors `4` | | `random_shuffle_fixed_size` | 64 MiB | — | | `read_large_parquet_fixed_size` | 1 GiB | — | | `read_parquet_fixed_size` | 64 MiB | — | | `read_tfrecords` | 64 MiB | — | | `streaming_split` | 64 MiB | footer batch `50`, result batch `50` | | `to_tf` | 64 MiB | — | | `tpch_q1_fixed_size_{{shuffle_strategy}} *(all 2 variants)*` | 192 MiB | — | | `training_ingest_benchmark` | 64 MiB | — | | `wide_schema_pipeline_nested_structs` | 2 MiB | footer batch `1`, footer actors `21`, io threads `5000` | | `wide_schema_pipeline_objects` | 4.2 MiB | footer batch `1`, footer actors `9`, io threads `5000` | | `wide_schema_pipeline_primitives` | 256 KiB | footer batch `1`, footer actors `27`, io threads `5000` | | `wide_schema_pipeline_tensors` | 39 MiB | footer batch `1`, footer actors `22`, io threads `5000` | | `write_parquet` | 1.25 GiB | — | **Three matrices are split**, because a matrix cannot vary `byod.runtime_env` per value and their variants want different budgets: `wide_schema_pipeline_{{data_type}}` into four entries, and one variant each out of `iceberg_benchmark_{{mode}}` and `iter_batches_{{format}}`. `aggregate_groups` keeps its matrix and carries the budget as a matrix dimension with explicit adjustments. **Rendered test names are unchanged — 121 before and after** — so release baselines still line up. **Not carried over** from the original branch: 7 previously-pinned entries no longer exist — the autoscaling variants removed in ray-project#65506, plus `tpch_q20` and `tpch_q22`. Any entry gaining its own `runtime_env` re-lists the four `DEFAULTS` guards verbatim: `deep_update` overwrites lists rather than merging them, so declaring one silently drops the OOM / dead-node / object-store checks. (17 entries on master are already missing guards for this reason; pre-existing, not touched here.) `map_benchmark.py` also drops its `use_datasource_v2 = False` pin, which existed because V2 was spilling. > Budgets originally measured against the pre-decoupling design and refined since. Packing moved between stages in ray-project#65596 but the packer and its inputs did not, so bins should be unchanged — a release run against this PR is what confirms that. The wide-schema tests are the first place to look. ## Behavior change worth reviewing **Read-task sizing no longer comes from `override_num_blocks` / `read_op_min_num_blocks` for Parquet.** Bins are sized by `RAY_DATA_PARQUET_BIN_PACKING_BYTES`, which is *also* not derived from `DataContext.target_max_block_size`. That decoupling is deliberate — read units are row-group-accurate rather than size-estimated — but it means the two knobs users reach for first no longer affect Parquet read parallelism. Deriving the budget from `target_max_block_size` is worth considering as a follow-up; the per-test overrides above are the evidence that a single global default does not fit every workload. ## Testing ``` $ python -m pytest -q python/ray/data/tests/datasource/test_parquet.py 286 passed, 6 skipped in 521.25s $ python -m pytest -q python/ray/data/tests/datasource/test_read_parquet_v2.py 32 passed $ python -m pytest -q python/ray/data/tests/unit/datasource_v2/ python/ray/data/_internal/datasource_v2/tests/ 181 passed $ python -m pytest -q python/ray/data/tests/test_predicate_pushdown.py \ python/ray/data/tests/test_execution_optimizer_limit_pushdown.py 78 passed ``` The 286-test parquet suite is the one that matters — it runs the full read surface with the footer path as the default rather than behind a flag. The release YAML is additionally checked for parse validity, unresolved `{{...}}` in any pin, duplicate `byod:` keys, and rendered-name stability. ## Stack Final step of an 11-step split of ray-project#64985 (43 files / +3234 −719, not reviewable as one unit). - ray-project#65167 `[1]` · ray-project#65168 `[2]` · ray-project#65214 `[3]` · ray-project#65210 `[4]` · ray-project#65273 `[5]` · ray-project#65596 `[6]` · ray-project#65806 `[8]` · ray-project#65169 `[9]` — all merged - `[7]` (count push-down fix) was absorbed into ray-project#65596 - `[10]` (release tuning) is folded into this PR, so a release run exercises the flip and its tuning together - **this PR** `[11/11]` --- Not a duplicate. File-level overlap check: ray-project#63158 none; ray-project#65142 overlaps `file_indexer.py` / `context.py`; ray-project#65406 / ray-project#65407 (arrow-rs reader A/B) overlap broadly but are explicitly `[DO NOT MERGE]` benchmark branches carrying the footer work out-of-tree. AI assistance was used; every line reviewed by me and tests run locally. --------- Signed-off-by: Goutam <[email protected]>
|
this has gone stale - @ayushk7102 should we close and restart? |
|
Hi @richardliaw, @ayushk7102 and @tobby168 , I've restarted this on the current DSv2 layout as a stack of four PRs:
It keeps the core design from this PR: the snapshot version is pinned on the driver, files are listed from the Delta log, and files are pruned by partition values and min/max stats. Column mapping (#64854), deletion vectors, and reading partition values from the log (on top of #67037) will come as follow-ups. I think this PR can be closed in favor of the stack. |
) ## Summary Adds the file listing for the Delta Lake DataSourceV2 reader: indexers that list a table version's data files from its transaction log. Second part of the split of #67676. Builds on #67887 (merged). Nothing uses the indexers until #67889 and #67890. The review changes are in the second commit (443b3a1cdb). ## Before No DataSourceV2 listing for Delta. `read_delta` lists files on the driver with `DeltaTable.to_pyarrow_dataset()`. ## After New `_internal/datasource_v2/formats/delta/delta_file_indexer.py`: - `DeltaTableSnapshot`: a picklable reference to one table version (`deltalake.DeltaTable` can't be pickled). Listing tasks reopen the table from it at the version the driver pinned. - `DeltaFileIndexer(_DeltaLogListing, FooterFileIndexer)`: lists the version's `add` actions instead of walking the directory, which also holds removed and uncommitted files, then reads each file's Parquet footer. Listing rows are row-group runs, so predicate pruning, read units and resume work as for Parquet. - `DeltaWholeFileIndexer`: the log-based listing for metadata-only reads. `FooterFileIndexer.as_whole_file_indexer` would walk the directory. - Paths are relative to the table root and URL-decoded exactly once; an absolute path fails with a pointer to the V1 reader. - Partition values come from the log's `add` actions, not from the paths: the Delta protocol doesn't require partition directories, and Delta stores a null and the string `__HIVE_DEFAULT_PARTITION__` in the same one. `partition_values_as_strings` casts them to the table's types and back to strings with Arrow, the form the reader casts back exactly, as it does a value parsed from a path. `DeltaPartitionPruner` prunes files on them, and both indexers add them to each manifest in `__delta_partition_values`, which `OnlineBinPacker` carries to the read tasks. The reader that uses it comes in #67889. - The indexer carries the table's filesystem and the read's shuffle, because the framework passes neither to a metadata-backed source. ```mermaid flowchart LR subgraph IO["Subsystem: IO"] subgraph D["Component: datasource_v2/formats/delta"] S["DeltaTableSnapshot<br/>(uri, pinned version)"] --> L["ListFiles task: _DeltaLogListing<br/>add actions → relative paths, sizes,<br/>partition values (pruned, added to manifests)"] L --> F["FooterFileIndexer<br/>footer reads → row-group runs"] L --> W["DeltaWholeFileIndexer<br/>one row per file"] end end classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 class S,L,F,W added ``` ## Subsystems IO (`_internal/datasource_v2/formats/delta/`). ## Not a duplicate Split out of #67676, which takes over #65142 (tobby168, credited as co-author) on the current DSv2 layout. No other open PR reads Delta through DSv2. ## Testing Same env as #67887: - `pytest python/ray/data/tests/unit/datasource_v2/test_delta_file_indexer.py`: 18 passed. Covers what `read_delta` can't reach: absolute paths, partition values from the log (a null and the literal `__HIVE_DEFAULT_PARTITION__` told apart, a file outside partition directories), their string round trip for each type, pruning on them, path pruners, log sizes and the manifest column. Listing through `read_delta` (pinned version, path decoding, shuffle, resume) is tested in #67890's `test_delta_v2.py`. - `pytest python/ray/data/tests/unit/datasource_v2/`: 933 passed; `tests/unit/datasource/` (pickle gate scan): 110 passed. - pre-commit and pyrefly (CI file set) 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: tobby168 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…68282) ## Summary Adds `DeltaDatasourceV2` and `DeltaScanner`, the DataSourceV2 datasource for one version of a Delta Lake table. Third part of the split of #67676. `read_delta` starts using it in #68283. Replaces #67889, which was opened from a fork; earlier review is there. This PR is part of a GitHub stack, so its diff shows only this layer. ## Before No DataSourceV2 datasource for Delta. ## After - `DeltaDatasourceV2(DataSourceWithMetadata)`: the driver pins the version and takes the schema and partition columns from the log. The file list is built from the log in a Ray task, not on the driver; deltalake 1.6 and later load it when the table is opened anyway (`without_files` is ignored there). `_get_file_indexer()` returns the `DeltaFileIndexer` from #67888, and `get_file_partitioner()` the shared row-group bin packer from #67887. #68407 opens the table only once, in a Ray task. - `DeltaScanner(ParquetScanner)`: data files are Parquet, so filter, column and limit pushdown are inherited. Partition columns keep their place in the output; an `include_paths` `path` column comes last, as with the V1 reader. - Partition values come from the log, not the paths (#67888): `DeltaScanner` prunes partitions with `DeltaPartitionPruner`, which the listing applies to each file's values, and reads with `DeltaFileReader`, a `ParquetFileReader` that takes each file's values from the manifest's `__delta_partition_values` column. `ParquetScanner` gets a `reader_class` class attribute so the scanner can swap the reader without copying `create_reader`. - Everything is read through a filesystem rooted at the table directory, as `DeltaTable.to_pyarrow_dataset` does: the caller's, or `deltalake`'s `DeltaStorageHandler` built from `storage_options`. Credentials and `az://` behave as in V1. - Data files are opened with their sizes from the log, so S3 gets no HEAD request per open: - With `deltalake`'s filesystem, `DeltaTableFileSystemHandler` wraps `DeltaStorageHandler`. The listing gives it every file's size before the footer reads, and `DeltaFileReader` gives it each manifest's sizes. It builds the deltalake handler on first use. - With a caller's `SubTreeFileSystem` over S3 (what `read_unity_catalog` passes), `filesystem_for_sized_opens` now unwraps it, as it already did a plain `S3FileSystem`. - `count()` takes each file's row count from the log (`numRecords`), not from its Parquet footer: the whole-file listing that `count()` uses carries the counts in a `__delta_num_records` manifest column, and `DeltaFileReader.read_metadata` reads a footer only for a file whose writer recorded no stats. Tables with deletion vectors, whose counts include deleted rows, never reach this reader. - `delta_datasource_v2_unsupported_reason()` says when a table must stay on the V1 reader: reader features beyond `timestampNtz` (deletion vectors, ...), column mapping, a partition column type whose values don't round-trip through a string (binary, ...), PyArrow scan options, or a table `path` column with `include_paths`. It fails closed. V1 reads some of these tables; it rejects the others (column mapping, deletion vectors) with the same error as before. #68408 replaces this fallback with errors, before #68286 makes V2 the default. - `generated_id_column` rejects Delta reads for now (#68285 adds support). - The pickle gate scan allowlists `delta_datasource_v2.py`: its only match is a schema `.to_arrow()`; data files are read and gated in `ParquetFileReader`. ```mermaid flowchart LR subgraph IO["Subsystem: IO"] subgraph D["Component: datasource_v2/formats/delta"] DS["driver: DeltaDatasourceV2<br/>log schema, pinned version"] --> IX["DeltaFileIndexer (2/11)"] DS --> BP["make_row_group_bin_packer (1/11)"] DS --> SC["DeltaScanner → DeltaFileReader<br/>partition values from the manifest,<br/>table-rooted filesystem"] end end classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 class DS,SC added ``` ## Subsystems IO (`_internal/datasource_v2/formats/delta/`; `ParquetScanner.reader_class`; `filesystem_for_sized_opens` in `_internal/util.py`). Ripple: logical planning (`bind_generated_id_column.py` rejects Delta scanners). ## Not a duplicate Split out of #67676, which takes over #65142 (tobby168, credited as co-author). No other open PR reads Delta through DSv2. ## Testing Same env as #67887: - `pytest python/ray/data/tests/unit/datasource_v2/test_delta_datasource_v2.py`: 20 passed. It covers: - the schema and partitioning from the log, and version pinning; - column order and `path` placement, and unknown-column errors; - pickling the indexer and scanner, and reading through the unpickled reader: each row gets its file's partition values from the log, and every data file opens with its size from the log (fails if the reader doesn't pass the sizes, or if two files' partition values are swapped); - `count()`'s row counts: from the log with no file opened, and from the footers when the log has no counts (with the reader change reverted, the first case opens all 3 files and fails); - every fallback reason, and a real table passing the eligibility check; - the `generated_id_column` rejection. - `pytest python/ray/data/tests/unit/datasource_v2/`: 1546 passed (rerun after the review round in a fresh env with the Nov 18 Ray nightly and CI pins). At the top of the stack (#68287), after the `count()` change: unit 1740 passed, `test_delta.py` and `test_delta_v2.py` 138 passed, 1 skipped. I skipped `test_text_datasource_v2.py`, which master added this week and which needs `snappy`, not installed locally. - `tests/unit/datasource/` (pickle gate scan): 125 passed. - `pytest python/ray/data/tests/test_util.py`: 51 passed, including `filesystem_for_sized_opens` on a `SubTreeFileSystem` over S3. - The S3 request count is tested end to end in #68283. - pre-commit and pyrefly (CI file set) 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: tobby168 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
|
Thanks a lot @tobby168 for this PR and for the careful write-ups. They shaped the Delta reader that's now landing. As mentioned on Nov 2, this work continues as a stack on the current DataSource V2 layout. Merged so far: #67887, #67888 and #68282. Open: #68283, #68284, #68285, #68330, #68407, #68408, #68286 and #68287. The stack keeps the core ideas from this PR:
Some things work differently, based on what we found while testing:
The I'd also like to bring over your vectorized partition pruning (one evaluation over all add actions, instead of one per file). It's much faster on tables with many files, and I'll credit you there. Closing this one in favor of the stack. Thanks again! |
|
Thank you @abhishekverma-ray ! It's good to see this is landing! |
…(opt-in) (#68283) ## Summary Routes `ray.data.read_delta` through the Delta Lake DataSourceV2 reader behind the private, temporary `DataContext._use_delta_datasource_v2` (off by default). Last part of the split of #67676. #68284, #68285, #68330, #68407 and #68408 build on it. #68286 deletes the switch, so `use_datasource_v2` alone decides, as it does for `read_parquet` and `read_orc`. Replaces #67890, which was opened from a fork; earlier review is there. This PR is part of a GitHub stack, so its diff shows only this layer. ## Before `read_delta` opens the whole table on the driver (`DeltaTable.to_pyarrow_dataset()`), builds the full file list there, and reads it through the V1 `ParquetDatasource`, one read task per file. ## After With the switch on (and `use_datasource_v2`, already the default), `read_delta` reads through `DeltaDatasourceV2` (#68282): - The table on the driver is used only for its log metadata (`without_files=True` on deltalake before 1.6; later versions ignore it). - The file list is built in a Ray task from the log at the pinned version (#67888). - Files are split into row-group read units, and DSv2 pushdown and resume apply. - Files are listed in path order, so one version lists its files in one order however its log is checkpointed. `deltalake`'s own order follows the row layout of the latest checkpoint, which the protocol leaves to the writer. - `filesystem=`, `storage_options`, `catalog=` and `include_paths` behave as before. Some reads keep using the V1 reader, with an info log saying why: - Tables that `delta_datasource_v2_unsupported_reason()` rejects. V1 then reads the table that was checked, at the same version. On deltalake 1.6+ it reuses that table rather than loading it again; before 1.6 it reopens it with its file list. - Reads that pass `partition_filters` (added in #67900). The V2 reader doesn't apply them yet and would read every partition, so these reads go to V1 without opening the table for the V2 check, with their own info log. #68330 applies them in V2. `filter(expr)` on partition columns already prunes in V2. Later layers change this before #68286 makes V2 the default: - #68407 opens the table only once, in a Ray task, instead of on the driver and again in the listing. That task also rejects a log that names data files by absolute path (as a shallow clone's does), so `read_delta` fails right away. V1 can't read such tables either. - #68408 replaces the V1 fallback with errors. ### Changes from V1 - An empty table's `schema()` is the schema in the log. V1 returns `None`. - `input_files()` is empty until the read runs, because the files are listed in Ray tasks (as for `read_parquet` on DataSourceV2). - Read tasks hold row-group runs packed by size, not one file each. A large file can be split across tasks, and small files share one. - The log is read in Ray tasks (the listing here; from #68407 also the table open), so worker nodes, not only the driver, need read access to the table's `_delta_log`. Credentials in `storage_options` travel with the tasks. #68286 says so in the `read_delta` docstring. - A data file whose size is missing from the log is still read (its footer read finds the size); only files of size 0 are skipped. - With `preserve_order=True`, rows come back in path order. V1 reads files in `deltalake`'s order (newest commit first for JSON commits), which can change for one version when a checkpoint lays out its rows in another order. - Unchanged: the version is pinned when `read_delta` is called. ```mermaid flowchart TD subgraph Before subgraph BS[Subsystem: IO] subgraph BC["Component: read_delta (read_api.py)"] B1["driver: DeltaTable(...).to_pyarrow_dataset()<br/>(full file list)"] --> B2["V1 ParquetDatasource.from_pyarrow_dataset"] B2 --> B3["Read: one task per file"] end end end subgraph After subgraph AS[Subsystem: IO] subgraph AC["Component: read_delta → DataSourceV2 formats/delta"] A0{"_use_delta_datasource_v2, table supported<br/>and no partition_filters?"} -->|no| A5["V1 path (unchanged)"] A0 -->|yes| A1["driver: DeltaTable (log metadata)<br/>pin version, schema, partition cols"] A1 --> A2["ListFiles task: DeltaFileIndexer<br/>add actions at pinned version, sorted by path, footer reads"] A2 --> A3["OnlineBinPacker: row-group read units"] A3 --> A4["ReadFiles: DeltaScanner / ParquetFileReader"] end end end classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 classDef changed fill:#fff9c4,stroke:#f9a825,color:#000 class A0 changed class A1,A2,A3,A4 added ``` ## Subsystems API (`read_api.read_delta`, the private `DataContext._use_delta_datasource_v2`) carries the change; IO for the listing order, the README and the tests. ## Not a duplicate Split out of #67676, which takes over #65142 (tobby168, credited as co-author). richardliaw asked for a restart on the current DSv2 layout. No other open PR reads Delta through DSv2. ## Testing Same env as #67887 (deltalake 1.5.0, pyarrow 23). Each module runs in its own pytest process, as CI runs one `py_test` per file: - `test_delta.py`: 54 passed. `test_delta_v2.py`: 35 passed. `tests/datasource_v2/test_delta_footer_listing.py`: 2 passed. - `test_delta.py` runs under both readers through conftest's `datasource_v2` fixture. Tests that take the V1 path with either reader run once: the `partition_filters` tests (until #68330), the multiple-paths check, `_delta_file_sizes` and `use_datasource_v2 = False`. An empty table's schema from the log is a separate V2-only test. - The no-`get_file_info` check (`test_delta_read_takes_file_sizes_from_the_log`) runs under both readers. Its handler records each call in a file, so calls made inside Ray tasks count too. - What `test_delta_v2.py` checks, V2 only (`datasource_v2` fixture, `ray_start_regular_shared`), through `read_delta` and `Dataset` methods. It tells the readers apart by the read operator's name in `ds.stats()`. - V2 returns the same rows and schema as V1 for partitioned tables (special-character, null, int and date partitions). - Filters on partition and data columns, `columns=`, `include_paths` and a table-rooted `filesystem=`. - Count after overwrite, version pinning at call time, row-group splitting, the read order, a seeded shuffle, and each V1 fallback. - `test_delta_footer_listing.py` builds the indexer as `read_delta` does and lists the table: the row groups a resumed job skips, and those a filter prunes. Footer reads run in Ray actors, so these live in `tests/datasource_v2/`, not `tests/unit/`. - Tests that fail without this layer's fixes: - `test_a_version_reads_its_files_in_one_order` reads a table, rewrites its checkpoint with the rows in reverse order (as the protocol allows), and reads the same version again, through the same Dataset and a new `read_delta`. Without the path sort, the order changes; so does the listing-order check in `test_indexer_and_scanner_survive_worker_serialization`. - `test_snapshot_repr_leaves_out_storage_options` fails when `storage_options` is in the snapshot's `repr`. - `test_partition_filters_fall_back_to_v1` fails without the fallback (the read goes to V2). - `test_skips_only_empty_files` fails with the old size check, which also dropped files of unknown size. - `test_falls_back_to_v1_with_pyarrow_scan_options` appends to the table right after the check, with deltalake reporting 1.5 and 1.6. It checks that V1 reads the checked version and, on 1.6, opens the table once. Both cases fail with the old code, which reopened the latest version. - `test_partition_values_come_from_the_log` reads tables whose paths don't give their partition values: random file prefixes, timestamp partitions with a time zone, and the string `__HIVE_DEFAULT_PARTITION__` next to nulls. It reads them through V2 and matches V1, with and without a filter on the partition column. - `test_delta_read_does_not_unpickle_a_tampered_data_file`: a data file swapped for one with a pickled-object column reads as plain bytes under both readers, and its pickle never runs. The test also writes the swapped file's size into the log, because V2 opens data files with the log's sizes, as Delta readers do. - `test_s3_reads_send_no_head_requests` reads a table on moto S3, through deltalake's filesystem and through a caller's `SubTreeFileSystem` over S3. Using moto's request recorder, it checks that no data file gets a HEAD request. - `tests/unit/datasource_v2/` and `tests/unit/datasource/`: 1521 passed, 225 skipped. `test_write_delta.py`: 105 passed. - Each guard was removed one at a time, and a test failed each time: path decoding, the log-based whole-file indexer, version pinning, projection pinning, the protocol fallback, shuffle, the indexer's own filesystem, schema pinning against tampered files, the path order and the `repr`. - pre-commit and pyrefly (CI file set, with deltalake 1.5 and pyarrow 23 resolved) 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: tobby168 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>

Summary
read_deltaresolves the entire Delta table on the driver before any predicate is known:Every file is enumerated at call time. For tables that rely on Delta's Z-ordering and per-file statistics rather than Hive partitioning, a selective query still touches every file — at minimum for tail metadata.
This routes
read_deltathrough the DataSourceV2 pipeline (already the default) with a Delta-native file indexer that prunes files from the transaction log — by partition values and by per-file min/max statistics — before any file is listed, sized, or scheduled.On an unpartitioned table of 4 files holding disjoint
valranges (the shape the issue describes):val > 250val < 5val > 1000val >= 0val != 3Closes #61547.
Design
Log-level pruning is an optimization, never a correctness requirement.
Predicates reach the scanner through the existing
ReadFiles.apply_predicatepath and are enforced there while reading — data predicates through the PyArrow scanner filter, partition predicates by parsing the file path.PushdownDeltaFilePruningruns afterPredicatePushdownand additionally copies them onto the upstreamListFilesindexer, so files that cannot match are never listed. If that rule doesn't fire, the query reads more files but returns the same rows.Making that true rather than merely intended took two changes, both of which earlier revisions of this PR got wrong:
PathPartitionParser.evaluate_predicate_on_partitionswallows any evaluation error and keeps the file — sound only while something else applies the predicate, butapply_predicateremoves theFilteras soon as a scanner accepts one. A path is a lossy view of the log: a null partition is the literal__HIVE_DEFAULT_PARTITION__directory, andpc.is_inover the null-typed row the parser builds raises. Scanners can now decline enforcement viaenforces_partition_predicate;DeltaScannerdoes, so the predicate stays in aFilterthat binds against the partition columns the reader has already materialized — exactly typed, with real nulls. The rule still forwards it to the log for skipping, so a partition-pruned read still lists 1 of 2 files.PredicatePushdownindependencies().Rulesetonly honors declared edges; list position is a tiebreaker, so an ordering assumption left in a comment can be silently inverted by an unrelated rule.Statistics-based skipping is conservative: a file is dropped only when
[min, max]proves no row can match.!=,NOT, UDFs, missing stats, a null bound, an unknown column — every "don't know" keeps the file. Over-retention costs a read; dropping a matching file loses data silently.test_pruning_never_drops_a_matching_fileasserts that property over generated inputs (seeded per parameter, so each case is reproducible).DeltaScannersubclassesParquetScannerand adds exactly one thing — declining partition-predicate enforcement. Filter pushdown, column pruning and limit pushdown are inherited unchanged, and the reader isParquetFileReaderas-is, because a Delta table's data files are ordinary Parquet laid out Hive-style. Schema and partition columns come from the log, so no Parquet footers are sampled for inference.The snapshot version is resolved on the driver and pinned into the datasource. Listing is deferred to workers, so leaving it unresolved would let a concurrent commit be read against a schema inferred before it existed, and could make a retried task disagree with its first attempt.
When V2 is used
_delta_table_supports_datasource_v2is the single gate, and it fails closed — anything V2 would answer differently rather than merely faster stays on V1, so enabling V2 never changes a result:to_pyarrow_datasetcurrently raises for these, so behavior is unchanged — and if [data] Fix delta column mapping read #64929 lands they pick up its fix without this path needing to know about it.path. That is how the reader labels the synthesized file path, so a real column of that name would be shadowed rather than returned.**arrow_parquet_argspassed. V1 forwards these toiter_batches; V2 has nowhere to put them, so honoring them means staying on V1 rather than silently dropping them.Deletion Vectors are rejected up front on both paths. Those data files still physically contain the deleted rows, and the V2 path opens them directly. The previous error text suggested upgrading to
deltalake>=0.10.0, which is not the issue under 1.5.0.Incidental correctness fixes
Cases where the V2 path would otherwise have been silently wrong:
e=flives ingrp=e%3Dfbut is recorded asgrp=e%253Df. Joining the raw value yields a path that doesn't exist. Decoded once before joining, which reproducesDeltaTable.file_uris()without a second listing.pathadded back wheninclude_pathsis set so a column projection can't drop it.__HIVE_DEFAULT_PARTITION__, which cannot be cast to the column's declared type. Adds opt-inPartitioning.null_fallback, andPathPartitionParserno longer coerces the resultingNone.read_parquetbehavior is unchanged.deltalakeresolves its storage backend from the URI while PyArrow rejects a scheme-prefixed path, so the log is opened with the path as given and the reader gets filesystem-native paths. Without this everys3:///az://table —read_delta's own documented examples — failed at execution. This was also the remaining half of thecatalog=breakage.count().PushdownCountFilesasserted its indexer was aNonSamplingFileIndexer; it only needs one that can be pinned to whole-file listing. It now checks for that and skips the optimization otherwise, rather than failing the query.columnsandinclude_paths, so unioning it with a populated table doesn't fail on mismatched schemas — instead of tripping the V2 "no files found" guard, which exists to catch empty directories.Not a duplicate
No open PR addresses #61547 (
gh pr list --state open --search "61547 in:body"returns nothing). #62959 was an earlier attempt by the same author on a since-superseded architecture; it was closed by the stale bot without human review, and this is a fresh implementation against the current DataSourceV2 code.richardliawinvited work on the issue in this comment.The nearest open PR in this area, #64929 (Delta column mapping), touches
read_deltain the same function but solves a different problem; the column-mapping fallback above is written so the two compose rather than conflict.Testing
Run per file, matching how Bazel runs these targets. 270 passed, 0 failed.
pre-commit run --files $(git diff --name-only master...HEAD)— all hooks pass.Tests assert on files skipped, not only on rows: reading every file also produces the right answer, so a pruning optimization that silently stopped pruning would otherwise pass every correctness test. Likewise
test_count_matches_v1counts on a fresh dataset, because reading first populates the cached row count and hides the plan shapecount()actually takes.test_parquet.py,test_partitioning.pyandpython/ray/data/tests/unit/show pre-existing failures in the local environment used here (missingtorch, S3/moto fixtures, and Ray workers unable to import test modules outside Bazel). Each was verified identical on the base commit —test_parquet.py7 failed / 34 errors on both,test_partitioning.py32 failed / 6 errors on both,tests/unit/9 failed on both.AI assistance
This change was developed with AI assistance (Claude Code), including two adversarial review passes. The first found the
count(),**arrow_parquet_argsandcatalog=breakage; the second found that partition predicates still had a single, fail-open enforcement point — returning extra rows foris_inover a nullable partition column in the default configuration — and that URI-addressed tables did not work at all. Both are fixed and covered by tests above.