Skip to content

Commit a03167a

Browse files
abhishekverma-raytobby168claude
committed
[Data] Read Delta Lake tables through DataSourceV2 behind a flag
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]>
1 parent daec722 commit a03167a

6 files changed

Lines changed: 584 additions & 8 deletions

File tree

‎python/ray/data/BUILD.bazel‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2737,7 +2737,7 @@ py_test(
27372737

27382738
py_test(
27392739
name = "test_delta",
2740-
size = "small",
2740+
size = "medium",
27412741
srcs = ["tests/datasource/test_delta.py"],
27422742
tags = [
27432743
"exclusive",
@@ -2749,6 +2749,20 @@ py_test(
27492749
],
27502750
)
27512751

2752+
py_test(
2753+
name = "test_delta_v2",
2754+
size = "medium",
2755+
srcs = ["tests/datasource/test_delta_v2.py"],
2756+
tags = [
2757+
"exclusive",
2758+
"team:data",
2759+
],
2760+
deps = [
2761+
":conftest",
2762+
"//:ray_lib",
2763+
],
2764+
)
2765+
27522766
py_test(
27532767
name = "test_write_delta",
27542768
size = "medium",

‎python/ray/data/_internal/datasource_v2/README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ The read path behind `ray.data.read_*` when
55
and *how* to decode it; the framework does listing, planning, pushdown, task
66
grouping and execution. Parquet is the file-based reference implementation.
77
Hive uses the metadata-backed path to stream one HiveServer2 query per execution.
8+
Delta Lake uses it to list the data files a table version's log names.
89

910
## Layout
1011

@@ -160,3 +161,11 @@ Every hook's docstring says when to override it and what you gain.
160161
`infer_schema(None)` resolves the table schema on the driver through HiveServer2 (HS2) metadata, or returns the explicit Arrow schema for a query. `_HiveScanner.read_schema()` reports that schema. The scanner carries the read specification, including a connection factory that Ray can serialize, and schema to the worker, where it creates a `_HiveReader`. The factory creates separate connections for driver metadata lookup and worker data reads. The reader executes at most one HS2 data query and uses `fetchmany()` to yield Arrow tables incrementally.
161162

162163
Once the data connection is open, `read_hs2_batches()` attempts to cancel the operation and close any cursor and the connection in `finally`. This covers completion, errors, and early generator closure. Cleanup is best effort. Closing a Dataset iterator can force the streaming executor to stop the read worker while it's fetching rows. That forced stop can bypass the reader's `finally`, even when the caller closes the iterator normally. Abrupt worker termination can also prevent `finally` from running, so immediate server cancellation or explicit cursor and connection cleanup isn't guaranteed.
164+
165+
## How does Delta Lake fit?
166+
167+
`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 `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, ...).
168+
169+
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.
170+
171+
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`.

‎python/ray/data/context.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,8 @@ def _missing_(cls, value):
116116

117117
DEFAULT_USE_DATASOURCE_V2 = env_bool("RAY_DATA_USE_DATASOURCE_V2", True)
118118

119+
DEFAULT_USE_DELTA_DATASOURCE_V2 = env_bool("RAY_DATA_USE_DELTA_DATASOURCE_V2", False)
120+
119121
DEFAULT_SMALL_SHUFFLE_CHUNK_SIZE = 64 * 1024 * 1024
120122

121123
DEFAULT_ACTOR_PREFETCHER_ENABLED = False
@@ -722,6 +724,12 @@ class DataContext:
722724
``ray.data.read_orc()`` and ``ray.data.read_mcap()`` route through
723725
the DataSourceV2 pipeline. Defaults to True; override with
724726
``RAY_DATA_USE_DATASOURCE_V2`` (``0`` for V1, ``1`` for V2).
727+
use_delta_datasource_v2: When True, and ``use_datasource_v2`` is also
728+
True, ``ray.data.read_delta()`` routes through the DataSourceV2
729+
pipeline. Tables that pipeline can't read yet (for example ones
730+
with deletion vectors) still use the V1 reader.
731+
Defaults to False; override with
732+
``RAY_DATA_USE_DELTA_DATASOURCE_V2``.
725733
small_shuffle_chunk_size: Target uncompressed size in bytes of the row-group
726734
runs that ``FileShuffleConfig(small_chunks_shuffle=True)`` shuffles.
727735
Contiguous row groups are coalesced up to this size; a single row group
@@ -1131,6 +1139,7 @@ class DataContext:
11311139
min_parallelism: int = DEFAULT_MIN_PARALLELISM
11321140
read_op_min_num_blocks: int = DEFAULT_READ_OP_MIN_NUM_BLOCKS
11331141
use_datasource_v2: bool = DEFAULT_USE_DATASOURCE_V2
1142+
use_delta_datasource_v2: bool = DEFAULT_USE_DELTA_DATASOURCE_V2
11341143
small_shuffle_chunk_size: int = DEFAULT_SMALL_SHUFFLE_CHUNK_SIZE
11351144
enable_tensor_extension_casting: bool = DEFAULT_ENABLE_TENSOR_EXTENSION_CASTING
11361145
arrow_fixed_shape_tensor_format: "FixedShapeTensorFormat" = field(

‎python/ray/data/read_api.py‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2993,7 +2993,8 @@ def read_orc(
29932993
If you encounter a DataSourceV2 limitation, use the V1 reader by
29942994
setting ``ray.data.DataContext.get_current().use_datasource_v2 = False``,
29952995
or ``RAY_DATA_USE_DATASOURCE_V2=0`` in the environment before importing
2996-
Ray. This shared setting also affects ``read_parquet()``.
2996+
Ray. This shared setting also affects ``read_parquet()`` and
2997+
``read_delta()``.
29972998
29982999
Examples:
29993000
Read an ORC file in remote storage or local storage.
@@ -6567,6 +6568,16 @@ def read_delta(
65676568
``name`` or ``id``) aren't supported yet, and ``read_delta`` raises
65686569
``NotImplementedError`` for them.
65696570
6571+
.. note::
6572+
6573+
Set ``ray.data.DataContext.get_current().use_delta_datasource_v2 = True``
6574+
(or ``RAY_DATA_USE_DELTA_DATASOURCE_V2=1``) to read through the
6575+
DataSourceV2 pipeline, which also needs ``use_datasource_v2``. It pins
6576+
the table version when ``read_delta`` is called, lists the data files
6577+
in Ray tasks rather than on the driver, and splits files into row-group
6578+
read units. Tables it can't read yet, such as ones with deletion
6579+
vectors, are read with the V1 reader.
6580+
65706581
Examples:
65716582
65726583
Read a local Delta table:
@@ -6635,6 +6646,8 @@ def read_delta(
66356646
of the inner ANDs (this form needs ``deltalake`` 1.6.6 or later).
66366647
Every column must be a partition column, so the result is exact. To
66376648
filter on other columns, use :meth:`~ray.data.Dataset.filter`.
6649+
The DataSourceV2 reader doesn't apply these yet, so a read that
6650+
passes them uses the V1 reader.
66386651
parallelism: This argument is deprecated. Use ``override_num_blocks`` argument.
66396652
num_cpus: The number of CPUs to reserve for each parallel read worker.
66406653
num_gpus: The number of GPUs to reserve for each parallel read worker. For
@@ -6718,6 +6731,60 @@ def read_delta(
67186731
_, normalized_path = pafs.FileSystem.from_uri(path)
67196732
filesystem = pafs.SubTreeFileSystem(normalized_path, resolved.filesystem)
67206733

6734+
ctx = DataContext.get_current()
6735+
if ctx.use_datasource_v2 and ctx.use_delta_datasource_v2:
6736+
from ray.data._internal.datasource_v2.formats.delta.delta_datasource_v2 import (
6737+
DeltaDatasourceV2,
6738+
delta_datasource_v2_unsupported_reason,
6739+
)
6740+
6741+
# The V2 reader lists the data files in its listing tasks, so the driver
6742+
# only needs the log's metadata.
6743+
log_only_table = DeltaTable(
6744+
path,
6745+
version=version,
6746+
storage_options=storage_options,
6747+
without_files=True,
6748+
)
6749+
unsupported_reason = (
6750+
# The V2 reader doesn't turn ``partition_filters`` into partition
6751+
# pruning yet, so it would read every partition.
6752+
"`partition_filters` was passed"
6753+
if partition_filters is not None
6754+
else delta_datasource_v2_unsupported_reason(
6755+
log_only_table,
6756+
include_paths=include_paths,
6757+
arrow_parquet_args=arrow_parquet_args,
6758+
)
6759+
)
6760+
if unsupported_reason is None:
6761+
datasource_v2 = DeltaDatasourceV2(
6762+
log_only_table,
6763+
storage_options=storage_options,
6764+
filesystem=filesystem,
6765+
columns=columns,
6766+
include_paths=include_paths,
6767+
shuffle=shuffle,
6768+
)
6769+
return _read_datasource_v2(
6770+
datasource_v2,
6771+
parallelism=_get_num_output_blocks(parallelism, override_num_blocks),
6772+
num_cpus=num_cpus,
6773+
num_gpus=num_gpus,
6774+
memory=memory,
6775+
ray_remote_args=ray_remote_args,
6776+
label_selector=label_selector,
6777+
fallback_strategy=fallback_strategy,
6778+
max_calls=max_calls,
6779+
resources=resources,
6780+
accelerator_type=accelerator_type,
6781+
runtime_env=runtime_env,
6782+
concurrency=concurrency,
6783+
)
6784+
logger.info(
6785+
"Reading Delta table %r with the V1 reader: %s.", path, unsupported_reason
6786+
)
6787+
67216788
dt = DeltaTable(path, version=version, storage_options=storage_options)
67226789
# The data files of a column-mapped table name their columns with physical
67236790
# names (such as ``col-<uuid>``) that only the log maps to the table's

‎python/ray/data/tests/datasource/test_delta.py‎

Lines changed: 69 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,31 @@
33

44
import pandas as pd
55
import pyarrow as pa
6+
import pyarrow.parquet as pq
67
import pytest
78

89
import ray
9-
from ray.data import Schema
10+
from ray.data import DataContext, Schema
11+
from ray.data._internal.object_extensions.arrow import (
12+
ArrowPythonObjectArray,
13+
_contains_pickle_object_type,
14+
)
1015
from ray.data._internal.util import rows_same
1116
from ray.data.tests.conftest import * # noqa
1217
from ray.data.tests.delta_test_utils import write_column_mapped_table
1318
from ray.data.tests.mock_http_server import * # noqa
1419
from ray.tests.conftest import * # noqa
1520

1621

22+
@pytest.fixture(params=["v1", "v2"], autouse=True)
23+
def delta_reader(request, restore_data_context):
24+
"""Run every test with both the V1 and the DataSourceV2 reader."""
25+
ctx = DataContext.get_current()
26+
ctx.use_datasource_v2 = True
27+
ctx.use_delta_datasource_v2 = request.param == "v2"
28+
return request.param
29+
30+
1731
@pytest.mark.parametrize(
1832
"batch_size",
1933
[1, 100],
@@ -141,14 +155,53 @@ def test_delta_read_storage_options(tmp_path, storage_options):
141155
assert rows_same(ds.to_pandas(), df)
142156

143157

144-
def test_delta_read_empty_table(tmp_path):
158+
def test_delta_read_empty_table(tmp_path, delta_reader):
145159
from deltalake import write_deltalake
146160

147161
path = os.path.join(tmp_path, "tmp_test_delta_empty")
148-
write_deltalake(path, pa.table({"x": pa.array([], type=pa.int64())}))
162+
write_deltalake(
163+
path, pa.schema([("x", pa.int64()), ("y", pa.string())]).empty_table()
164+
)
149165

150166
ds = ray.data.read_delta(path)
151167
assert ds.count() == 0
168+
assert ds.take_all() == []
169+
if delta_reader == "v2":
170+
# The V2 reader takes the schema from the log. The V1 reader takes it
171+
# from the data files, and an empty table has none.
172+
assert ds.schema().names == ["x", "y"]
173+
174+
175+
def test_delta_read_does_not_unpickle_a_tampered_data_file(tmp_path):
176+
"""A data file swapped for one with a pickled-object column must not run
177+
its pickle. Both readers read data files with the log's schema, so the
178+
column comes back as plain bytes."""
179+
from deltalake import DeltaTable, write_deltalake
180+
181+
marker = tmp_path / "exploit_marker"
182+
183+
class Exploit:
184+
def __reduce__(self):
185+
return (os.system, (f"touch {marker}",))
186+
187+
path = os.path.join(tmp_path, "tmp_test_delta_tampered")
188+
write_deltalake(path, pa.table({"id": [1, 2], "obj": [b"a", b"b"]}))
189+
(data_file,) = pa.table(DeltaTable(path).get_add_actions(flatten=True))[
190+
"path"
191+
].to_pylist()
192+
pq.write_table(
193+
pa.table(
194+
{"id": [1, 2], "obj": ArrowPythonObjectArray.from_objects([Exploit()] * 2)}
195+
),
196+
os.path.join(path, data_file),
197+
)
198+
199+
batches = list(ray.data.read_delta(path).iter_batches(batch_format="pyarrow"))
200+
201+
assert sum(batch.num_rows for batch in batches) == 2
202+
for batch in batches:
203+
assert not _contains_pickle_object_type(batch.schema.field("obj").type)
204+
assert not marker.exists(), "pickle.load executed attacker code"
152205

153206

154207
def test_delta_read_rejects_multiple_paths():
@@ -165,11 +218,13 @@ def test_delta_read_deletion_vectors_message_is_actionable(tmp_path):
165218
has to point at the table property, not at a library upgrade.
166219
167220
deltalake cannot *write* a table declaring the feature either, so the
168-
protocol error is injected rather than provoked; what is under test is
169-
Ray's translation of it.
221+
feature and the protocol error are injected rather than provoked; what is
222+
under test is Ray's translation of it. The DataSourceV2 reader leaves such
223+
a table to the V1 reader, so both readers fail the same way.
170224
"""
171225
from deltalake import write_deltalake
172226
from deltalake.exceptions import DeltaProtocolError
227+
from deltalake.table import ProtocolVersions
173228

174229
path = os.path.join(tmp_path, "tmp_test_delta_dv_message")
175230
write_deltalake(path, pa.table({"id": [1, 2, 3]}))
@@ -178,8 +233,11 @@ def test_delta_read_deletion_vectors_message_is_actionable(tmp_path):
178233
"The table has set these reader features: {'deletionVectors'} but these "
179234
"are not yet supported by the deltalake reader."
180235
)
236+
dv_protocol = ProtocolVersions(3, 7, ["deletionVectors"], ["deletionVectors"])
181237

182238
with mock.patch(
239+
"deltalake.DeltaTable.protocol", return_value=dv_protocol
240+
), mock.patch(
183241
"deltalake.DeltaTable.to_pyarrow_dataset", side_effect=protocol_error
184242
):
185243
with pytest.raises(RuntimeError) as excinfo:
@@ -347,12 +405,17 @@ def test_read_unity_catalog_partition_filters(tmp_path):
347405
assert _input_dates(ds) == ["2026-01-02"] * 2
348406

349407

350-
def test_delta_read_takes_file_sizes_from_the_log(tmp_path):
408+
def test_delta_read_takes_file_sizes_from_the_log(tmp_path, delta_reader):
351409
"""Listing makes no per-file ``get_file_info`` call; sizes come from the log.
352410
353411
Partition values with special characters check that the log's paths, which
354412
are URL-encoded once more than the fragment paths, are decoded exactly once.
355413
"""
414+
if delta_reader == "v2":
415+
pytest.skip(
416+
"The V2 reader lists files in Ray tasks when the read runs; "
417+
"test_delta_file_indexer.py checks its paths and log sizes."
418+
)
356419
import fsspec.implementations.local
357420
import pyarrow.fs as pafs
358421
from deltalake import write_deltalake

0 commit comments

Comments
 (0)