Repository navigation
[Data][Delta DSv2][4/11] Read Delta Lake tables through DataSourceV2 (opt-in) - #68283
Conversation
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
a92e84e to
535399f
Compare
|
|
||
| DEFAULT_USE_DATASOURCE_V2 = env_bool("RAY_DATA_USE_DATASOURCE_V2", True) | ||
|
|
||
| DEFAULT_USE_DELTA_DATASOURCE_V2 = env_bool("RAY_DATA_USE_DELTA_DATASOURCE_V2", False) |
There was a problem hiding this comment.
We dont need a per Datasource switch
There was a problem hiding this comment.
Agreed for the end state. While the stack lands, Delta has to stay off by default, and use_datasource_v2 is already on by default, so this layer still needs its own off switch. I made it private (_use_delta_datasource_v2, like _use_iceberg_datasource_v2 in #68436), with no env var or docs. #68286 [10/11] deletes it, so use_datasource_v2 alone decides, as for the other formats.
| unsupported_reason = ( | ||
| # The V2 reader doesn't turn ``partition_filters`` into partition | ||
| # pruning yet, so it would read every partition. | ||
| "`partition_filters` was passed" |
There was a problem hiding this comment.
With V1 being deprecated, why fall back to it for partition_filters?
| filesystem = pafs.SubTreeFileSystem(normalized_path, resolved.filesystem) | ||
|
|
||
| ctx = DataContext.get_current() | ||
| if ctx.use_datasource_v2 and ctx.use_delta_datasource_v2: |
There was a problem hiding this comment.
Can the description list what changes from V1? With preserve_order=True:
for i in range(6):
write_deltalake(path, pa.table({"x": [i]}), mode="append")
[r["x"] for r in ray.data.read_delta(path).take_all()]
# V1: [5, 4, 3, 2, 1, 0]
# V2: [3, 1, 4, 0, 2, 5]An empty table's schema() also goes from None to the log schema.
There was a problem hiding this comment.
Good catch. V2 sorted the files by path, so its order was stable but unrelated to commits. V1 reads in the log's order (newest commit first), which stays the same after a checkpoint (checked on deltalake 1.5 and 1.6.6). V2 now keeps the log's order, so preserve_order=True matches V1. test_preserve_order_matches_v1 fails with the old sort.
The description now has a "Changes from V1" section:
- an empty table's
schema()is the log schema instead ofNone; input_files()is empty until the read runs;- files are split into row-group read tasks.
There was a problem hiding this comment.
The tests are ~5x the code. Ones to cut or merge:
test_unknown_columns_are_rejected: same as [Data][Delta DSv2][3/11] Add the Delta Lake DataSourceV2 datasource #68282'stest_datasource_rejects_unknown_columns.test_null_partition_values_read_as_null:test_partitioned_table_matches_v1already compares those null partitions with V1.test_literal_null_partition_string_is_not_null: covered by theliteral_null_stringcases oftest_partition_values_come_from_the_log.test_shuffle_files_reads_every_row:test_seeded_shuffle_permutes_the_filescovers Delta's part of shuffling.test_filters_match_v1: several of the 12 predicates take the same path (grp == "a b"/grp == "e=f",num == 1/num > 2, the null checks).test_columns_match_v1,test_include_paths_matches_v1: one case each is enough next to [Data][Delta DSv2][3/11] Add the Delta Lake DataSourceV2 datasource #68282'stest_datasource_projects_columns_in_order.test_lists_one_row_per_row_group_run: its assert fits intest_listing_skips_finished_row_groups, which lists the same table first.- The pyarrow < 15 skip is dead (Ray needs 23+).
There was a problem hiding this comment.
Thanks, all done:
- removed the four duplicate tests;
- cut
test_filters_match_v1to 8 predicates (one per pruning path); - kept one case each for
columns=andinclude_paths; - moved the row-group listing assert into
test_listing_skips_finished_row_groups; - dropped the pyarrow skip (
setup.pyneeds 23+).
The file is 45 lines shorter.
535399f to
40a7cac
Compare
86bbccf to
de5c0a9
Compare
9e712f3 to
4d9f5d8
Compare
…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]>
Route `read_delta` through `DeltaDatasourceV2` when the new `DataContext.use_delta_datasource_v2` (env `RAY_DATA_USE_DELTA_DATASOURCE_V2`, default off) and `use_datasource_v2` are both set. The driver then opens only the log (`without_files=True`), and tables `delta_datasource_v2_unsupported_reason` rejects keep using the V1 reader, with an info log saying why. Reads that pass `partition_filters` also use the V1 reader: the V2 reader doesn't apply them yet, so it would read every partition. Every `test_delta.py` test now runs under both readers (except the V1 listing's no-`get_file_info` check: V2 lists in Ray tasks, and `test_delta_file_indexer.py` covers its log sizes), and `test_delta_v2.py` checks that V2 returns the same rows and schema as V1 for partitioned tables, filters, `columns=`, `include_paths` and a table-rooted `filesystem=`, plus count after overwrite, version pinning, row-group read units, resume, shuffle and the V1 fallbacks. Tables whose paths don't give their partition values (random file prefixes, timestamp partitions with a time zone, the string `__HIVE_DEFAULT_PARTITION__` next to nulls) read the same through V2, with and without a filter on the partition column. Co-authored-by: tobby168 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
…before deltalake 1.6 deltalake 1.6 ignores without_files, with a DeprecationWarning on every read_delta call, and loads the file list anyway. Pass it only to older versions. Also test that V2 reads of an S3 table send no HEAD request for a data file's size, through deltalake's filesystem and through a caller's SubTreeFileSystem over S3 (what read_unity_catalog passes). The tampered-data-file test now also writes the swapped file's size into the log: V2 opens data files with the log's sizes, as Delta readers do, so a swap that leaves the old size fails at the footer instead of reaching the pickle gate. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
…ck to V1 When the DataSourceV2 reader can't read a table, read_delta opened it again for the V1 reader. deltalake 1.6 and later load the whole file list with the log, so that was two full loads on the driver where V1 alone does one. On 1.6+, hand V1 the table that was checked. Below 1.6, reopen it at the checked version. Either way V1 reads the version that was checked, even if the table changes in between. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
4d9f5d8 to
6c238e0
Compare
…r tests
- Make the opt-in switch private and temporary:
`DataContext._use_delta_datasource_v2`, with no environment variable and no
public docs. It keeps Delta on V1 while the rest of the stack lands, since
`use_datasource_v2` is already on by default. The layer that makes V2 the
default deletes it, so `use_datasource_v2` alone decides, as for the other
formats. Error messages now point to `use_datasource_v2 = False`.
- List the data files in the order deltalake gives the add actions, not
sorted by path. `to_pyarrow_dataset` uses the same order (newest commit
first, unchanged by checkpoints on deltalake 1.5 and 1.6.6), so
`preserve_order=True` returns rows in V1's order. New
`test_preserve_order_matches_v1`; the listing unit test now checks the
log's order. Both fail with the path sort.
- Trim test_delta_v2.py:
- Drop tests that duplicate others: unknown columns, null partitions,
the literal `__HIVE_DEFAULT_PARTITION__` string, and `shuffle="files"`.
- Cut `test_filters_match_v1` to 8 predicates.
- One case each for `columns=` and `include_paths`.
- Fold the row-group listing check into
`test_listing_skips_finished_row_groups`.
- Drop the dead pyarrow < 15 skip (setup.py needs pyarrow 23 or newer).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
| file_infos = [ | ||
| FileInfo(path=path, size=size) | ||
| for path, size in zip( | ||
| file_paths, add_actions[ADD_ACTION_SIZE_COLUMN].to_pylist() |
There was a problem hiding this comment.
why convert to python here?
There was a problem hiding this comment.
The shared listing code (_filter_file_infos, the shuffle, the footer batches) takes FileInfo objects, and each path needs decoding on its own (resolve_data_file_path, a URL-decode). It's one pass over columns already in memory. The row counts are now built only by the whole-file indexer (see the _num_records_by_path thread).
|
|
||
| `DeltaDatasourceV2` extends `DataSourceWithMetadata`, because a Delta table's data files are the ones its transaction log names at a version, not whatever the table directory holds. `read_delta` uses it when `use_datasource_v2` and the temporary, private `DataContext._use_delta_datasource_v2` are both set and `delta_datasource_v2_unsupported_reason()` finds nothing the V1 reader would handle differently (deletion vectors, column mapping, PyArrow scan options, ...). | ||
|
|
||
| On the driver, `read_delta` opens the log without its file list, pins the version and takes the schema and partition columns from the log. `DeltaFileIndexer` gets a picklable `DeltaTableSnapshot`, reopens the table at that version in the `ListFiles` task and lists the `add` actions. It extends `FooterFileIndexer`, which reads each file's footer, so listing rows are row-group runs and `OnlineBinPacker` groups them as for Parquet; `as_whole_file_indexer()` returns a log-based `DeltaWholeFileIndexer` for metadata-only reads. |
There was a problem hiding this comment.
why reopen the log twice? Why not list and pin the version in the same read/
There was a problem hiding this comment.
Fixed in #68407 (8/11): read_delta opens the table once, in a Ray task. The task pins the version, returns the schema to the driver and keeps the add actions in the object store, where the listing reads them. This layer still opens twice, but its switch is private and stays off until #68286, which sits on top of #68407.
|
|
||
| On the driver, `read_delta` opens the log without its file list, pins the version and takes the schema and partition columns from the log. `DeltaFileIndexer` gets a picklable `DeltaTableSnapshot`, reopens the table at that version in the `ListFiles` task and lists the `add` actions. It extends `FooterFileIndexer`, which reads each file's footer, so listing rows are row-group runs and `OnlineBinPacker` groups them as for Parquet; `as_whole_file_indexer()` returns a log-based `DeltaWholeFileIndexer` for metadata-only reads. | ||
|
|
||
| The data files are Parquet: `DeltaScanner` is a `ParquetScanner`. Partition values come from the `add` actions, not from the paths: the Delta protocol doesn't require partition directories, and a null and the string `__HIVE_DEFAULT_PARTITION__` share one. The listing prunes files on those values (`DeltaPartitionPruner`) and puts them in each manifest's `__delta_partition_values` column, which `OnlineBinPacker` carries to `DeltaFileReader`. Everything is read through a filesystem rooted at the table directory with paths relative to it, as `DeltaTable.to_pyarrow_dataset` does: the `filesystem` argument, or the one `deltalake` builds from `storage_options`. |
There was a problem hiding this comment.
Description here doesn't make sense.
- What does it mean the protocol doesn't require null and the hive partition string share one?
- If the data files are just parquet files, what extra functionality is
DeltaScanneradding on top ofParquetScanner?
There was a problem hiding this comment.
Rewrote the paragraph. In short:
- A Hive-style path writes a null and the string
__HIVE_DEFAULT_PARTITION__the same way (grp=__HIVE_DEFAULT_PARTITION__). The path can't tell them apart; the log can. And Delta doesn't requirekey=valuedirectories at all. DeltaScannerreusesParquetScanner's row-group reads, projection and filter pushdown. It changes one thing: partition values come from the log.DeltaPartitionPrunerprunes on them, andDeltaFileReaderadds them to the rows.
| # ``without_files`` (with a DeprecationWarning) and load the file list: | ||
| # they have no metadata-only load yet | ||
| # (https://github.com/delta-io/delta-rs/issues/5034). | ||
| loads_files = parse_version(deltalake.__version__) >= parse_version("1.6") |
There was a problem hiding this comment.
let's make this a const
There was a problem hiding this comment.
This version check is gone in #68407, which opens the table the same way on every deltalake version, so there's nothing left to name.
goutamvenkat-anyscale
left a comment
There was a problem hiding this comment.
Review of the V2 opt-in path (xhigh effort: 10 finder angles over the 8-file diff plus the enclosing functions read_delta, _DeltaLogListing.list_file_infos, delta_datasource_v2_unsupported_reason and FooterFileIndexer, then dedup and a gap sweep).
One early candidate was discarded during the sweep: dropping sorted() from list_file_infos looked like it broke seeded-shuffle reproducibility (the deleted docstring said so), but _shuffle_file_infos already re-sorts by path whenever a seed is set and DeltaDatasourceV2 always sets one — so the removal only affects unseeded/preserve_order order, which is the stated intent.
Comments inline, roughly most- to least-severe. Two are anchored a few lines off their real subject because the subject itself isn't in the diff; each says so.
AI assistance was used for this review.
| file_infos = [ | ||
| FileInfo(path=path, size=size) | ||
| for path, size in zip( | ||
| file_paths, add_actions[ADD_ACTION_SIZE_COLUMN].to_pylist() | ||
| ) | ||
| ] |
There was a problem hiding this comment.
Unknown-size data files are silently dropped, losing rows. (The anchor is this comprehension; the drop happens at the _filter_file_infos zero-size check further down, which isn't in the diff.)
FileInfo.size is declared Optional[int] and this comprehension passes the log's size_bytes straight through. _filter_file_infos then does if not info.size: logger.warning("Skipping zero-size file"); continue, so both None and 0 get dropped.
V1 does the opposite: _delta_file_sizes (read_api.py:7330) filters size is not None out of its known-sizes map but still reads the file, falling back to get_file_info. FooterFileIndexer._batches documents the same intent — "A file of unknown size stays in ... instead of silently dropping the file's rows".
So a table whose log has one add action with a null or zero size_bytes reads N rows under V1 and N minus that file's rows under V2, with only a WARNING line, and the "zero-size file" wording is misleading for the unknown-size case.
There was a problem hiding this comment.
Fixed: only files of size 0 are skipped now. A file with no size in the log stays in, and its footer read finds the size, as FooterFileIndexer does. The Delta protocol requires size, so this should be rare. test_skips_only_empty_files covers it.
| ) | ||
| ) | ||
| if unsupported_reason is None: | ||
| datasource_v2 = DeltaDatasourceV2( |
There was a problem hiding this comment.
The V2 path moves the transaction-log read into a Ray listing task, so read workers now need access to _delta_log/ that read_delta never required of them.
V1 only ever opened the log on the driver (DeltaTable(path, ...) + to_pyarrow_dataset); workers received serialized fragments and only did GETs on data files. Under the flag, DeltaTableSnapshot.open() runs inside the ListFiles task and replays the log from storage_options alone.
A cluster whose read-task IAM role is scoped to s3:GetObject on the data prefix (no s3:ListBucket / GET on _delta_log/), or whose workers lack the ambient credential the driver used, planned fine and read fine under V1 and now fails inside the listing task. Worth at least calling out in the flag's docs, since it's a deployment-visible change in required permissions, not just a performance change.
There was a problem hiding this comment.
| storage_options=storage_options, | ||
| **({} if loads_files else {"without_files": True}), | ||
| ) | ||
| unsupported_reason = ( |
There was a problem hiding this comment.
delta_datasource_v2_unsupported_reason() doesn't screen for absolute paths in the log, so a table the V2 reader provably can't read isn't routed to V1 — it fails mid-execution instead.
resolve_data_file_path (delta_file_indexer.py:135) raises ValueError for any add action with an absolute path or a URI scheme — shallow clones, cross-location tables. That check only runs inside the ListFiles Ray task, long after read_delta has returned a Dataset, so the documented "tables delta_datasource_v2_unsupported_reason() rejects fall back to V1" contract never fires for this class.
The user gets a task-level failure during take_all()/materialize(), and the error's own remedy (DataContext.use_datasource_v2 = False) can only be applied by re-creating the dataset. Checking the first add action's path here would move it back into the fallback.
There was a problem hiding this comment.
I checked V1 on deltalake 1.5: a log entry with an absolute path (plain or file://) fails V1 too, with FileNotFoundError when the read runs. So falling back wouldn't help. #68407 now checks the paths in its open task, so read_delta() raises right away, and the message no longer suggests the V1 reader. Test: test_read_delta_rejects_data_files_outside_the_table.
| # ``without_files`` (with a DeprecationWarning) and load the file list: | ||
| # they have no metadata-only load yet | ||
| # (https://github.com/delta-io/delta-rs/issues/5034). | ||
| loads_files = parse_version(deltalake.__version__) >= parse_version("1.6") |
There was a problem hiding this comment.
On deltalake 1.6+ — the current release line — the driver still loads the entire file list and the listing task loads it again, so the stated driver-side saving doesn't exist and each read replays the log twice.
loads_files is True for 1.6+, so without_files isn't passed and checked_table eagerly materializes every add action on the driver; the V2 path then discards it and DeltaTableSnapshot.open() replays the log a second time in the ListFiles task. For a 100k-file table on 1.6.6 the flag makes planning no cheaper than V1 and adds one extra full log replay.
I see this is deferred to #68407, but inverting the order (decide first, then open only what's needed) is the deeper fix and would avoid shipping a layer that's a net regression on the version most users have.
| # they have no metadata-only load yet | ||
| # (https://github.com/delta-io/delta-rs/issues/5034). | ||
| loads_files = parse_version(deltalake.__version__) >= parse_version("1.6") | ||
| checked_table = DeltaTable( |
There was a problem hiding this comment.
checked_table is opened before the partition_filters short-circuit, so a read known up front to go to V1 pays an extra full table open.
partition_filters is not None needs no table at all, but this DeltaTable(path, version=..., storage_options=...) open happens first. On deltalake < 1.6 the fallback then reopens with DeltaTable(path, version=checked_table.version(), ...) — two complete log replays (object-store round trips scaling with log size) for every read_delta(..., partition_filters=[...]) call with the flag on.
Hoisting the partition_filters test above the open removes both.
There was a problem hiding this comment.
Fixed: a read with partition_filters now goes to V1 before the table is opened. #68330 then applies them in V2.
| @pytest.fixture(params=["v1", "v2"], autouse=True) | ||
| def delta_reader(request, restore_data_context): | ||
| """Run every test with both the V1 and the DataSourceV2 reader.""" | ||
| ctx = DataContext.get_current() | ||
| ctx.use_datasource_v2 = True | ||
| ctx._use_delta_datasource_v2 = request.param == "v2" | ||
| return request.param |
There was a problem hiding this comment.
This autouse fixture re-implements conftest's existing datasource_v2 fixture and doubles every test in the module, including ~14 cases whose V2 run is identical to V1.
python/ray/data/tests/conftest.py:278 already defines @pytest.fixture(params=[False, True], ids=["v1", "v2"]) def datasource_v2(request, restore_data_context) with a documented usage pattern (pytestmark = pytest.mark.usefixtures(...), indirect=True to pin one value). delta_reader duplicates it with a string param instead of a bool, plus autouse=True.
The consequence: test_delta_read_rejects_multiple_paths, test_delta_file_sizes_match_the_files, test_read_unity_catalog_partition_filters and all 10 partition_filters cases run twice even though they take the V1 code path both times — and each V2 run that does read provisions an 8-actor FooterReaderActor pool. That's the whole reason size had to go small → medium; the doubled suite plus actor churn makes the 300s medium budget tight for zero added coverage.
There was a problem hiding this comment.
Fixed: test_delta.py uses conftest's datasource_v2 fixture, plus one line that turns on the private switch (removed in #68286). Tests that take the V1 path with either reader run once: multiple paths, _delta_file_sizes, and the 10 partition_filters cases (#68330 runs those under both readers again, since it applies them in V2). The module is 52 cases, about 20 s locally; I kept medium for CI headroom.
| @@ -330,15 +331,12 @@ def list_file_infos( | |||
| else [None] * add_actions.num_rows, | |||
There was a problem hiding this comment.
_num_records_by_path is built on every listing, but only DeltaWholeFileIndexer ever reads it — the footer path pays a full to_pylist() plus dict build for nothing. (Anchored at the tail of the construction; the assignment itself is just above the hunk.)
_num_records_by_path is consumed solely in DeltaWholeFileIndexer.list_files (line 511). DeltaFileIndexer — the normal read path — inherits the same list_file_infos, so each listing converts the num_records Arrow column to a Python list and builds an N-entry dict that's then discarded. On a table with hundreds of thousands of add actions that's a measurable chunk of listing-task time and memory.
Building it lazily, or only in the whole-file subclass, costs nothing.
There was a problem hiding this comment.
Fixed: only DeltaWholeFileIndexer builds it now, through a _remember_add_actions hook.
| # Footer reads finish in any order; keep the listing's. | ||
| return [row["__path"] for row in _list_files(ds, preserve_order=True)] |
There was a problem hiding this comment.
preserve_order=True is accepted and then silently discarded, so this comment credits the ordering guarantee to a no-op argument.
FooterFileIndexer.list_files_from_file_infos declares preserve_order: bool = False but never forwards it to _process_file_infos (footer_file_indexer.py:248-285). The determinism this test relies on actually comes from FooterReader.read_footers — "Results are always yielded in files order, never completion order" (footer_reader.py:504).
Not flaky today, but the comment documents a mechanism that isn't there: anyone who later removes the read_footers ordering guarantee will see these assertions pass locally and break in CI. (The dropped parameter in list_files_from_file_infos is arguably the real bug.)
There was a problem hiding this comment.
Fixed the comment: the order comes from read_footers yielding results in file order. Dropped the unused argument from the test. FooterFileIndexer ignoring preserve_order is harmless today, since its output always follows its input, and it's shared Parquet code, so I left it out of this PR.
| @pytest.mark.parametrize("deltalake_version", ["1.5.0", "1.6.6"]) | ||
| def test_falls_back_to_v1_with_pyarrow_scan_options( | ||
| tmp_path, monkeypatch, deltalake_version | ||
| ): |
There was a problem hiding this comment.
This test fakes deltalake.__version__ while running against whatever deltalake is actually installed, so it exercises a kwarg combination the real library may reject.
With deltalake_version="1.5.0" monkeypatched onto a real 1.6.x install, read_delta passes without_files=True to a constructor that deprecated it; when deltalake eventually removes the kwarg this fails with TypeError instead of testing the fallback.
The _AppendAfterFirstOpen subclass also assumes write_deltalake never constructs a deltalake.DeltaTable internally — if any deltalake release changes that, the nested open appends to opened, the len(opened) == 1 recursion guard misfires, and both the opened == [0] and opened == [0, 0] assertions break for reasons unrelated to Ray.
There was a problem hiding this comment.
This test is gone in #68407; there's no version-dependent open left to test.
| if delta_reader == "v2": | ||
| pytest.skip( | ||
| "The V2 reader lists files in Ray tasks when the read runs; " | ||
| "test_delta_file_indexer.py checks its paths and log sizes." | ||
| ) |
There was a problem hiding this comment.
Skipping this under V2 drops the only end-to-end assertion that listing makes zero get_file_info calls on a non-S3 / caller-supplied filesystem.
The skip points at test_delta_file_indexer.py (a unit test over log sizes) and test_delta_v2.py::test_s3_reads_send_no_head_requests (moto HEAD counting). Neither reproduces this test's counting fsspec LocalFileSystem wrapped in a caller SubTreeFileSystem, so a future change that reintroduces a per-file info()/get_file_info on a PyFileSystem-backed filesystem during V2 listing would pass CI.
Parameterizing this assertion over both readers instead of skipping it would keep the coverage.
There was a problem hiding this comment.
Fixed: the test runs under both readers. Its handler writes each get_file_info call to a file, so calls made inside Ray tasks count too, and both readers make none. (The info() calls either reader does make are FSSpecHandler.open_input_file's isfile check when it opens a file, not size lookups.)
…, shared test fixture - The Delta listing skipped every file whose logged size was missing or 0. It now skips only empty files; a file of unknown size stays in, and its footer read finds the size. - Only `DeltaWholeFileIndexer` (count()) uses the log's per-file row counts, so only it builds the path -> row count map. - `read_delta` sends a read with `partition_filters` to the V1 reader before opening the table for the V2 checks. - README: say what `DeltaScanner` changes from `ParquetScanner` and why the partition values come from the log. - test_delta.py runs through conftest's `datasource_v2` fixture. Tests that take the V1 path with either reader (`partition_filters`, multiple paths, `_delta_file_sizes`) run once. - The file-size test runs for both readers: a handler records `get_file_info` calls in a file, so calls in Ray tasks count too. - Fix a test comment that credited `preserve_order` with the listing order. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
goutamvenkat-anyscale
left a comment
There was a problem hiding this comment.
Second pass, at b47ebfd. Thanks for the fixes from the first round; this covers what is new or still open.
Each comment has the same parts: Scenario, How it breaks, Benchmark where one applies, and Suggestion. The first is the only one that can change what a read returns. The rest are small.
Not repeated here: the deltalake version gate and the second log replay on the driver. Both were answered in the earlier threads (#68407 removes them).
Checked and found fine: test_s3_reads_send_no_head_requests does record requests. Moto's recorder captures them when started through /moto-api/recorder/start-recording, without MOTO_ENABLE_RECORDING (moto 5.1.18: a HEAD and a GET on a .parquet key were both recorded).
AI assistance was used for this review. The repro and benchmark numbers below were run locally against this PR's code.
| file_infos = [ | ||
| FileInfo(path=path, size=size) | ||
| for path, size in zip( | ||
| file_paths, add_actions[ADD_ACTION_SIZE_COLUMN].to_pylist() | ||
| ) | ||
| ) | ||
| file_infos = sorted( | ||
| ( | ||
| FileInfo(path=path, size=size) | ||
| for path, size in zip( | ||
| file_paths, add_actions[ADD_ACTION_SIZE_COLUMN].to_pylist() | ||
| ) | ||
| ), | ||
| key=lambda info: info.path, | ||
| ) | ||
| ] |
There was a problem hiding this comment.
The listing order of a pinned version changes if a checkpoint with a different row order appears
Scenario
list_file_infos now yields files in get_add_actions() order, and this layer replays the log in every ListFiles task: once per execution of a Dataset, and again on each retry of a listing task. The earlier ordering thread says the order "stays the same after a checkpoint". That holds for a checkpoint deltalake writes. It doesn't hold for a checkpoint whose rows are in another order, which the protocol allows and another engine's writer may produce.
How it breaks
This PR's DeltaFileIndexer.list_file_infos, on one table (6 appends of one row each, x = the commit number), pinned at version 5, deltalake 1.5.0:
A JSON commits only -> [5, 4, 3, 2, 1, 0]
B + deltalake's create_checkpoint() -> [5, 4, 3, 2, 1, 0]
C same checkpoint, rows sorted by path -> [4, 2, 5, 0, 3, 1]
Same version, same files, another order. Two consequences:
preserve_order=True.ds.take_all()run twice on one Dataset returns rows in two orders if such a checkpoint lands in between. V1 can't do that: it takes the file list once, inread_delta.- Retries. A re-executed streaming generator is matched to its first attempt by output index (
ObjectRefStream::InsertToStreamintask_manager.ccskips an index that is already used). If aListFilestask fails after some of its manifests were consumed and the retry lists in another order, the remaining indexes can repeat files already delivered and leave others out. This needs the listing to span more than one output block and the checkpoint to appear between the attempt and its retry, so the window is narrow. When it's hit, rows are duplicated or missing with no error.
A seeded FileShuffleConfig isn't affected: _shuffle_file_infos sorts by path before it permutes.
Benchmark
If a deterministic order is part of the fix, a path sort is cheap next to the listing it sits in. Same function, synthetic add actions, median of 5 runs, Apple M4 Pro, Python 3.12:
| Files | list_file_infos |
+ sort by path |
|---|---|---|
| 10,000 | 21 ms | 1.3 ms (+6%) |
| 100,000 | 229 ms | 17 ms (+7%) |
| 1,000,000 | 2,328 ms | 241 ms (+10%) |
Suggestion
#68407 looks like it closes most of this: it loads the add actions once and the listing reads that copy from the object store, so one Dataset has one order, as in V1. Two things would finish it:
- [Data][Delta DSv2][8/11] Open the Delta table once, in a Ray task #68407's listing falls back to
load_add_actions(self.open(), ...)when the stored copy is lost. That is the replay path above. Give the fallback's result a deterministic order, or fail instead of relisting whenpreserve_orderis set. - Add case C as a test, so the guarantee is "one Dataset, one order" and doesn't rest on how a writer lays out its checkpoints. The docstring here could then say the order is
deltalake's for one listing, not a property of the version.
If this layer can be turned on before #68407 lands, sorting by path here unless preserve_order is set restores a stable order for the default case, at the cost in the table.
There was a problem hiding this comment.
All fixes are in ab39068 on #68283 and rebased up the stack (#68284 … #68287, #68504 … #68508).
Fixed by sorting by path, in both places the add actions are loaded:
- here,
DeltaTableSnapshot.add_actions(); - in [Data][Delta DSv2][8/11] Open the Delta table once, in a Ray task #68407,
load_add_actions, which both the open task and the fallback in your point 1 call.
So one version always lists its files in one order. That holds within one Dataset, across Datasets, and when the stored copy is lost and the listing reloads it, so a retried listing task can't pair its output indexes with other files.
Why path order and not deltalake's order kept stable some other way:
deltalake's order is a property of how the latest checkpoint lays out its rows, as your case C shows. Pinning it per Dataset still lets two reads of the same version disagree.- Failing instead of relisting when
preserve_orderis set would turn a lost object into a failed job. - The cost is an Arrow
sort_byon the path column, once per load. Your table measured a Python sort ofFileInfos; this is cheaper.
What we give up: with preserve_order=True, V2's row order is no longer V1's. I moved to V1's order in the first round, after Aarrya pointed out the difference. Your case C shows V1's order isn't stable either. The description now lists it under "Changes from V1", and the docstrings say the order is path order.
Test: test_a_version_reads_its_files_in_one_order is your case C. It reads a table, rewrites its checkpoint with the rows reversed, then reads the same version through the same Dataset and through a new read_delta. Both fail without the sort, on this layer and on #68407.
| datasource_v2 = DeltaDatasourceV2( | ||
| checked_table, | ||
| storage_options=storage_options, |
There was a problem hiding this comment.
DeltaTableSnapshot's repr prints storage_options, and this is the first call that puts a caller's credentials in one
Scenario
DeltaTableSnapshot is a plain frozen dataclass, so its generated repr prints every field. Until this PR nothing in read_delta built one. Here read_delta passes the caller's storage_options to DeltaDatasourceV2, which puts them in the snapshot that is pickled into the ListFiles tasks.
How it breaks
>>> DeltaTableSnapshot("s3://bucket/table", 3,
... {"AWS_ACCESS_KEY_ID": "AKIA-EXAMPLE", "AWS_SECRET_ACCESS_KEY": "example-secret"})
DeltaTableSnapshot(table_uri='s3://bucket/table', version=3, storage_options={'AWS_ACCESS_KEY_ID': 'AKIA-EXAMPLE', 'AWS_SECRET_ACCESS_KEY': 'example-secret'})I found no code path that prints it today. The exposure is anything that later reprs the object: a debug log of the indexer's fields, an assertion message, or a serialization-failure dump. _internal/datasource_v2/REVIEW.md asks that objects pickled into tasks "carry no secret in their repr".
Suggestion
One line in delta_file_indexer.py:
storage_options: Optional[Dict[str, Any]] = field(default=None, repr=False)plus a unit test that a secret passed in storage_options isn't in repr(snapshot).
There was a problem hiding this comment.
Fixed: storage_options is dataclasses.field(default=None, repr=False).
I checked the other objects that carry the options into tasks:
DeltaTableFileSystemHandlerhas no generatedrepr.- The
partition_filtersandloaded_add_actionsfields [Data][Delta DSv2][7/11] Apply partition_filters in the Delta DataSourceV2 reader #68330 and [Data][Delta DSv2][8/11] Open the Delta table once, in a Ray task #68407 add hold no secrets.
Test: test_snapshot_repr_leaves_out_storage_options fails without repr=False.
| "table directory. Set `DataContext.use_datasource_v2 = False` to " | ||
| "read this table with the V1 reader." |
There was a problem hiding this comment.
The absolute-path error points at a switch that doesn't help
Scenario
This message now tells the user to set DataContext.use_datasource_v2 = False to read the table with the V1 reader.
How it breaks
A user reads a shallow-cloned table and gets this ValueError from the ListFiles task, at execution time. They follow the advice:
use_datasource_v2 = Falseturns V2 off forread_parquetand every other format in the session, not only for Delta.- The read still fails. Per the reply in the earlier thread, V1 on
deltalake1.5 fails on an absolute path too, withFileNotFoundErrorwhen the read runs.
Suggestion
Say what isn't supported and drop the switch, for example:
raise ValueError(
f"The Delta log names a data file by absolute path ({logged_path!r}). "
"`read_delta` only reads data files under the table directory, so tables "
"that reference files elsewhere (for example shallow clones) aren't supported."
)There was a problem hiding this comment.
Fixed: this layer now has the message #68407 already had. It says the log names a file by absolute path, as a shallow clone's does, and that read_delta only reads data files under the table directory. It no longer mentions use_datasource_v2.
| @pytest.fixture(autouse=True) | ||
| def use_delta_datasource_v2(restore_data_context): | ||
| ctx = DataContext.get_current() | ||
| ctx.use_datasource_v2 = True | ||
| ctx._use_delta_datasource_v2 = True |
There was a problem hiding this comment.
The module sets use_datasource_v2 by hand and takes no cluster fixture
Scenario
This autouse fixture sets ctx.use_datasource_v2 = True, and test_falls_back_to_v1_without_datasource_v2 (line 435) sets it to False. No test in the module takes ray_start_regular_shared or another cluster fixture. test_delta.py moved to conftest's datasource_v2 fixture in this round, so the two modules now do it differently.
How it breaks
python/ray/data/tests/AGENTS.md:
For a V2-only test, write
@pytest.mark.parametrize("datasource_v2", [True], indirect=True). Don't setuse_datasource_v2yourself.
Use
ray_start_regular_shared, orray_start_2_cpus_shared/ray_start_10_cpus_sharedwhen the CPU count matters.
Without a cluster fixture, the first read_delta auto-initialises Ray with the machine's defaults, or reuses whatever cluster an earlier module left running. The CPU count then depends on the host and on test order, and so does the number of read tasks and blocks these tests produce.
Suggestion
pytestmark = pytest.mark.parametrize("datasource_v2", [True], indirect=True)
@pytest.fixture(autouse=True)
def use_delta_datasource_v2(ray_start_regular_shared, datasource_v2):
DataContext.get_current()._use_delta_datasource_v2 = Truetest_falls_back_to_v1_without_datasource_v2 needs [False], and pytest rejects a second parametrization of the same argument, so it can't stay under that module mark. test_delta.py already runs both readers and is a natural home for it.
There was a problem hiding this comment.
Fixed as you suggested:
pytestmark = pytest.mark.parametrize("datasource_v2", [True], indirect=True);- the autouse fixture takes
ray_start_regular_sharedanddatasource_v2, and sets only the private Delta switch. [Data][Delta DSv2][10/11] Read Delta Lake tables through DataSourceV2 by default #68286 drops that line with the switch. test_falls_back_to_v1_without_datasource_v2moved totest_delta.py, under_V1_ONLY, astest_delta_read_uses_v1_without_datasource_v2. In [Data][Delta DSv2][10/11] Read Delta Lake tables through DataSourceV2 by default #68286,test_reads_with_v1_without_datasource_v2is gone, since this test covers it.
One place still sets use_datasource_v2 by hand: _read(..., v2=False) in #68286. Once the private switch is gone, that is the only way to get a V1 read inside a V2-only test, for the _assert_matches_v1 comparisons. It's a comparison read, not the test's own setup, and restore_data_context (pulled in by datasource_v2) restores it.
| if datasource_v2: | ||
| # The V2 reader takes the schema from the log. The V1 reader takes it | ||
| # from the data files, and an empty table has none. | ||
| assert ds.schema().names == ["x", "y"] |
There was a problem hiding this comment.
test_delta_read_empty_table picks its assert by branching on the parameter
Scenario
The schema assert runs only under if datasource_v2:.
How it breaks
python/ray/data/tests/AGENTS.md:
Don't branch on a parameter inside a test (
if param: ... else: ...) to pick different setup or asserts. Write two tests.
In practice: the test id test_delta_read_empty_table[v1] passes without checking a schema at all, and nothing in the test's name says that V2 is the reader with the extra guarantee. A reader of a CI report can't tell which behaviour is covered.
Suggestion
Split it. The shared test keeps the two asserts both readers satisfy, and the schema gets its own V2-only test:
def test_delta_read_empty_table(tmp_path, datasource_v2):
...
assert ds.count() == 0
assert ds.take_all() == []
@pytest.mark.parametrize("datasource_v2", [True], indirect=True)
def test_delta_read_empty_table_takes_its_schema_from_the_log(tmp_path, datasource_v2):
...
assert ds.schema().names == ["x", "y"]There was a problem hiding this comment.
Fixed: split as you suggested.
test_delta_read_empty_tablekeeps the count and rows asserts, under both readers.test_delta_read_empty_table_takes_its_schema_from_the_logruns on V2 only and checks the schema.
| def _uses_v2(ds: ray.data.Dataset) -> bool: | ||
| dag = ds._logical_plan.dag | ||
| return isinstance(dag, ReadFiles) and dag.datasource_name == "DeltaV2" |
There was a problem hiding this comment.
These end-to-end tests drive and assert on Ray Data internals
Scenario
_uses_v2 reads ds._logical_plan.dag. _list_files (lines 283-294) takes the ListFiles operator out of the plan and calls file_indexer.list_files(...) itself, with unit ids built by the private _row_group_unit_id.
How it breaks
python/ray/data/tests/AGENTS.md:
Don't patch Ray [...] or Ray Data internals to drive a test, and don't assert on private attributes. Test through
ray.data.read_*andDatasetmethods.
Two concrete costs:
_assert_matches_v1calls_uses_v2, so almost every test in the module depends on the shape of the logical plan. A refactor that keeps behaviour (the read wrapped in another operator,datasource_namerenamed) fails the whole module.- The tests that go through
_list_filesnever execute the plan, so they pass even if the executor stops honouring what the indexer returns. The earlier round had an instance of this:preserve_order=Truewas passed to a directlist_filescall and silently ignored, and the test couldn't notice.
Suggestion
- For
_uses_v2, assert on something public, such as the operator name inds.stats()after the read. - Move the tests built on
_list_files(row-group pruning, resume, the seeded shuffle order) totests/unit/datasource_v2/test_delta_file_indexer.py, which already builds the indexer directly. Keep here the checks aDatasetread can make: rows, schema and order.
There was a problem hiding this comment.
Fixed:
_uses_v2now checks the read operator's name inds.materialize().stats()(ReadFilesDeltaV2; V1 showsReadParquet)._assert_matches_v1materializes the V2 read once and checks the name, schema and rows on it. Nothing in the module reads_logical_planany more.- The seeded-shuffle test now reads through
read_deltawithpreserve_order=Trueand compares row orders. It executes the plan, so it would catch the executor reordering what the indexer lists.
One deviation from your suggestion: the tests built on _list_files (resume skipping row groups, filter pruning row groups, and from #68505 the column-mapped statistics) didn't go to tests/unit/datasource_v2/test_delta_file_indexer.py.
DeltaFileIndexer.list_filesreads footers throughFooterReaderactors, so it needs a Ray cluster, andtests/unit/must not start one.- They're in a new
tests/datasource_v2/test_delta_footer_listing.py, next totest_footer_chunking.py, withray_start_regular_shared. - They build the indexer the way
read_deltadoes (DeltaDatasourceV2(DeltaTable(path))._get_file_indexer()) and no longer take it out of a logical plan. test_delta_v2.pykeeps what a read can show:test_row_groups_are_split_into_read_taskschecks blocks and rows.
|
|
||
| ## How does Delta Lake fit? | ||
|
|
||
| `DeltaDatasourceV2` extends `DataSourceWithMetadata`, because a Delta table's data files are the ones its transaction log names at a version, not whatever the table directory holds. `read_delta` uses it when `use_datasource_v2` and the temporary, private `DataContext._use_delta_datasource_v2` are both set and `delta_datasource_v2_unsupported_reason()` finds nothing the V1 reader would handle differently (deletion vectors, column mapping, PyArrow scan options, ...). |
There was a problem hiding this comment.
This sentence leaves out the partition_filters case
Scenario
The README says read_delta uses DeltaDatasourceV2 when both flags are set and delta_datasource_v2_unsupported_reason() finds nothing. read_api.py (lines 6815-6819) also sends every read that passes partition_filters to V1, before that check runs.
How it breaks
Someone reads this, turns both flags on and runs read_delta(path, partition_filters=[...]), expecting V2. They get the V1 reader with no sign of it: the "Reading Delta table ... with the V1 reader" info log is only emitted after the unsupported-reason check, which this path skips. A comparison of the two readers on a filtered read would measure V1 twice.
Suggestion
Add the condition to the sentence, for example "... are both set, no partition_filters are passed (until #68330), and delta_datasource_v2_unsupported_reason() finds nothing ...". Logging the same info line for this fallback would make it visible at run time too.
There was a problem hiding this comment.
Fixed:
- The sentence now says V2 is used when both switches are set, the read passes no
partition_filters(which the V2 reader doesn't apply yet), anddelta_datasource_v2_unsupported_reason()finds nothing. read_deltanow logs "Reading Delta table … with the V1 reader: the DataSourceV2 reader doesn't applypartition_filtersyet." for that path.- [Data][Delta DSv2][7/11] Apply partition_filters in the Delta DataSourceV2 reader #68330, which applies them in V2, removes both the condition and the log line.
…ls out of repr - DeltaTableSnapshot.add_actions sorts the add actions by path. deltalake lists them in the order of the latest checkpoint's rows, so one version could list its files in another order after a checkpoint is rewritten, which changes preserve_order reads and can mismatch a retried listing task. - DeltaTableSnapshot leaves storage_options out of its repr. - The absolute-path error no longer suggests the V1 reader, which fails on such tables too. - read_delta logs when partition_filters send a read to the V1 reader; the README names that case. - test_delta_v2.py runs under the datasource_v2 fixture with ray_start_regular_shared, checks the reader by the operator name in ds.stats(), and reads through Dataset only. The listing tests move to tests/datasource_v2/test_delta_footer_listing.py, which builds the indexer directly. test_delta_read_empty_table is split; the use_datasource_v2=False test moves to test_delta.py. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
Summary
Routes
ray.data.read_deltathrough the Delta Lake DataSourceV2 reader behind the private, temporaryDataContext._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, souse_datasource_v2alone decides, as it does forread_parquetandread_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_deltaopens the whole table on the driver (DeltaTable.to_pyarrow_dataset()), builds the full file list there, and reads it through the V1ParquetDatasource, one read task per file.After
With the switch on (and
use_datasource_v2, already the default),read_deltareads throughDeltaDatasourceV2(#68282):without_files=Trueon deltalake before 1.6; later versions ignore it).deltalake's own order follows the row layout of the latest checkpoint, which the protocol leaves to the writer.filesystem=,storage_options,catalog=andinclude_pathsbehave as before.Some reads keep using the V1 reader, with an info log saying why:
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.partition_filters(added in [Data] Add partition_filters to read_delta and take file sizes from the log #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. [Data][Delta DSv2][7/11] Apply partition_filters in the Delta DataSourceV2 reader #68330 applies them in V2.filter(expr)on partition columns already prunes in V2.Later layers change this before #68286 makes V2 the default:
read_deltafails right away. V1 can't read such tables either.Changes from V1
schema()is the schema in the log. V1 returnsNone.input_files()is empty until the read runs, because the files are listed in Ray tasks (as forread_parqueton DataSourceV2)._delta_log. Credentials instorage_optionstravel with the tasks. [Data][Delta DSv2][10/11] Read Delta Lake tables through DataSourceV2 by default #68286 says so in theread_deltadocstring.preserve_order=True, rows come back in path order. V1 reads files indeltalake's order (newest commit first for JSON commits), which can change for one version when a checkpoint lays out its rows in another order.read_deltais called.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 addedSubsystems
API (
read_api.read_delta, the privateDataContext._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_testper file:test_delta.py: 54 passed.test_delta_v2.py: 35 passed.tests/datasource_v2/test_delta_footer_listing.py: 2 passed.test_delta.pyruns under both readers through conftest'sdatasource_v2fixture. Tests that take the V1 path with either reader run once: thepartition_filterstests (until [Data][Delta DSv2][7/11] Apply partition_filters in the Delta DataSourceV2 reader #68330), the multiple-paths check,_delta_file_sizesanduse_datasource_v2 = False. An empty table's schema from the log is a separate V2-only test.get_file_infocheck (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.test_delta_v2.pychecks, V2 only (datasource_v2fixture,ray_start_regular_shared), throughread_deltaandDatasetmethods. It tells the readers apart by the read operator's name inds.stats().columns=,include_pathsand a table-rootedfilesystem=.test_delta_footer_listing.pybuilds the indexer asread_deltadoes 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 intests/datasource_v2/, nottests/unit/.test_a_version_reads_its_files_in_one_orderreads 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 newread_delta. Without the path sort, the order changes; so does the listing-order check intest_indexer_and_scanner_survive_worker_serialization.test_snapshot_repr_leaves_out_storage_optionsfails whenstorage_optionsis in the snapshot'srepr.test_partition_filters_fall_back_to_v1fails without the fallback (the read goes to V2).test_skips_only_empty_filesfails with the old size check, which also dropped files of unknown size.test_falls_back_to_v1_with_pyarrow_scan_optionsappends 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_logreads 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_requestsreads a table on moto S3, through deltalake's filesystem and through a caller'sSubTreeFileSystemover S3. Using moto's request recorder, it checks that no data file gets a HEAD request.tests/unit/datasource_v2/andtests/unit/datasource/: 1521 passed, 225 skipped.test_write_delta.py: 105 passed.repr.AI assistance was used (Claude Code); every line has been reviewed by the submitter.
🤖 Generated with Claude Code