Skip to content

Commit daec722

Browse files
abhishekverma-raytobby168claude
committed
[Data] Add the Delta Lake DataSourceV2 datasource
Add `DeltaDatasourceV2`, a `DataSourceWithMetadata` for one version of a Delta Lake table, and `DeltaScanner`: - The driver opens the log without its file list, pins the version and takes the schema and partition columns from the log; listing goes through the `DeltaFileIndexer` from the previous PR. - Data files are Parquet: `DeltaScanner` is a `ParquetScanner`, so the filter, column and limit pushdown are inherited. Partition columns keep their place in the output, and an `include_paths` `path` column comes last, as with the V1 reader. - Partition values come from the log, not from the paths: `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. `ParquetScanner` gets a `reader_class` attribute for that. - Everything is read through a filesystem rooted at the table directory, as `DeltaTable.to_pyarrow_dataset` does: the caller's, or a `deltalake` `DeltaStorageHandler` built from `storage_options`. - `delta_datasource_v2_unsupported_reason` says why 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`. - `generated_id_column` rejects Delta reads for now. - The pickle gate scan allowlists `delta_datasource_v2.py`, whose only match is a schema `.to_arrow()`; data files are read and gated in `ParquetFileReader`. `read_delta` doesn't use the datasource yet; that wiring follows in a separate PR. Co-authored-by: tobby168 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
1 parent 443b3a1 commit daec722

6 files changed

Lines changed: 700 additions & 2 deletions

File tree

Lines changed: 271 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
1+
"""``DataSourceV2`` for Delta Lake tables.
2+
3+
The driver opens the table's log without its file list, pins the version and
4+
takes the schema from the log. Listing tasks read the file list from the log at
5+
that version (``DeltaFileIndexer``); the data files are Parquet and read by the
6+
Parquet reader (``DeltaScanner``).
7+
8+
Everything goes through a filesystem rooted at the table directory, with paths
9+
relative to it, as ``DeltaTable.to_pyarrow_dataset`` -- the V1 reader -- does.
10+
"""
11+
12+
from __future__ import annotations
13+
14+
import logging
15+
import time
16+
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union
17+
18+
import pyarrow as pa
19+
from typing_extensions import override
20+
21+
from ray._common.utils import env_integer
22+
from ray.data._internal.datasource_v2.common.synthesized_columns import PathColumn
23+
from ray.data._internal.datasource_v2.formats.delta.delta_file_indexer import (
24+
DeltaFileIndexer,
25+
DeltaTableSnapshot,
26+
is_supported_partition_type,
27+
make_partitioning,
28+
)
29+
from ray.data._internal.datasource_v2.formats.delta.delta_scanner import (
30+
DeltaScanner,
31+
)
32+
from ray.data._internal.datasource_v2.formats.parquet.parquet_datasource_v2 import (
33+
make_row_group_bin_packer,
34+
)
35+
from ray.data._internal.datasource_v2.interfaces.datasource_v2 import (
36+
DatasourceCategory,
37+
DataSourceWithMetadata,
38+
)
39+
from ray.data._internal.datasource_v2.interfaces.file_manifest import FileManifest
40+
from ray.data._internal.util import RetryingPyFileSystem
41+
from ray.data.context import DataContext
42+
from ray.data.datasource.file_based_datasource import (
43+
FileShuffleConfig,
44+
_validate_shuffle_arg,
45+
)
46+
from ray.util.annotations import DeveloperAPI
47+
48+
if TYPE_CHECKING:
49+
from deltalake import DeltaTable
50+
from pyarrow.fs import FileSystem
51+
52+
from ray.data._internal.datasource_v2.common.online_bin_packer import (
53+
OnlineBinPacker,
54+
)
55+
from ray.data._internal.datasource_v2.interfaces.file_partitioner import (
56+
PartitionHints,
57+
)
58+
59+
logger = logging.getLogger(__name__)
60+
61+
# Reader features the V2 reader handles. Tables that need others (deletion
62+
# vectors, column mapping, ...) are read with the V1 reader.
63+
_SUPPORTED_READER_FEATURES = frozenset({"timestampNtz"})
64+
65+
_INT32_MAX = 2**31 - 1
66+
67+
68+
def delta_datasource_v2_unsupported_reason(
69+
table: "DeltaTable",
70+
*,
71+
include_paths: bool,
72+
arrow_parquet_args: Dict[str, Any],
73+
) -> Optional[str]:
74+
"""Why ``table`` can't be read with :class:`DeltaDatasourceV2`, if it can't.
75+
76+
Args:
77+
table: The table, opened at the version to read.
78+
include_paths: The read's ``include_paths`` argument.
79+
arrow_parquet_args: The read's extra PyArrow scan options.
80+
81+
Returns:
82+
A short reason for the V1 fallback, or ``None`` if V2 can read it.
83+
"""
84+
if arrow_parquet_args:
85+
return f"PyArrow scan options were passed: {sorted(arrow_parquet_args)}"
86+
try:
87+
protocol = table.protocol()
88+
if protocol.min_reader_version not in (1, 3):
89+
return f"the table needs reader version {protocol.min_reader_version}"
90+
unsupported_features = (
91+
set(protocol.reader_features or []) - _SUPPORTED_READER_FEATURES
92+
)
93+
if unsupported_features:
94+
return f"the table needs the reader features {sorted(unsupported_features)}"
95+
metadata = table.metadata()
96+
configuration = metadata.configuration or {}
97+
if configuration.get("delta.columnMapping.mode", "none") != "none":
98+
return "the table uses column mapping"
99+
schema = pa.schema(table.schema().to_arrow())
100+
unsupported_partitions = {
101+
name: str(schema.field(name).type)
102+
for name in metadata.partition_columns
103+
if not is_supported_partition_type(schema.field(name).type)
104+
}
105+
if unsupported_partitions:
106+
return (
107+
"the partition columns have types the V2 reader doesn't "
108+
f"support: {unsupported_partitions}"
109+
)
110+
if include_paths and "path" in schema.names:
111+
return "the table has its own `path` column and include_paths is set"
112+
except Exception as e: # Fail closed: when in doubt, read with V1.
113+
return f"the table couldn't be inspected ({type(e).__name__}: {e})"
114+
return None
115+
116+
117+
def _make_table_filesystem(
118+
table_uri: str, storage_options: Optional[Dict[str, Any]]
119+
) -> "FileSystem":
120+
"""Filesystem rooted at the table directory that ``deltalake`` reads through.
121+
122+
The same one ``DeltaTable.to_pyarrow_dataset`` builds when no filesystem
123+
is given: it takes ``storage_options`` for credentials and every URI
124+
scheme ``deltalake`` does, including ``az://``, which PyArrow can't parse.
125+
It is picklable.
126+
"""
127+
import pyarrow.fs as pa_fs
128+
from deltalake.fs import DeltaStorageHandler
129+
130+
return pa_fs.PyFileSystem(DeltaStorageHandler(table_uri, options=storage_options))
131+
132+
133+
@DeveloperAPI
134+
class DeltaDatasourceV2(DataSourceWithMetadata[FileManifest]):
135+
"""V2 datasource for one version of a Delta Lake table."""
136+
137+
def __init__(
138+
self,
139+
table: "DeltaTable",
140+
*,
141+
storage_options: Optional[Dict[str, Any]] = None,
142+
filesystem: Optional["FileSystem"] = None,
143+
columns: Optional[List[str]] = None,
144+
include_paths: bool = False,
145+
shuffle: Optional[Union[Literal["files"], "FileShuffleConfig"]] = None,
146+
):
147+
"""Create the datasource.
148+
149+
Args:
150+
table: The table, opened at the version to read. Its file list
151+
isn't needed: open it with ``without_files=True``.
152+
storage_options: The ``deltalake`` storage options the table was
153+
opened with.
154+
filesystem: A filesystem rooted at the table directory. ``None``
155+
uses the one ``deltalake`` builds from ``storage_options``.
156+
columns: Columns to read, in this order. ``None`` reads every
157+
column, in the table's order.
158+
include_paths: Whether to add a ``path`` column with each row's
159+
data file path, relative to the table directory.
160+
shuffle: ``"files"`` or a ``FileShuffleConfig`` to shuffle the
161+
table's data files before reading them.
162+
"""
163+
super().__init__(name="DeltaV2", category=DatasourceCategory.DATA_LAKE)
164+
# Pinned here so every listing task, retry and re-execution reads the
165+
# same version, even if the table changes in the meantime.
166+
self._snapshot = DeltaTableSnapshot(
167+
table_uri=table.table_uri,
168+
version=table.version(),
169+
storage_options=storage_options,
170+
)
171+
self._table_schema = pa.schema(table.schema().to_arrow())
172+
self._partition_columns: List[str] = list(table.metadata().partition_columns)
173+
self._partition_schema = pa.schema(
174+
[self._table_schema.field(name) for name in self._partition_columns]
175+
)
176+
self._partitioning = make_partitioning(self._partition_columns)
177+
if filesystem is None:
178+
filesystem = _make_table_filesystem(table.table_uri, storage_options)
179+
self._filesystem = RetryingPyFileSystem.wrap(
180+
filesystem,
181+
retryable_errors=DataContext.get_current().retried_io_errors,
182+
)
183+
self._synthesized_columns = (PathColumn(),) if include_paths else ()
184+
if columns is not None:
185+
# ``columns`` may name the ``path`` column, as with the V1 reader.
186+
known = set(self._table_schema.names) | {
187+
column.name for column in self._synthesized_columns
188+
}
189+
unknown = [c for c in columns if c not in known]
190+
if unknown:
191+
raise ValueError(
192+
f"Columns {unknown} don't exist in the Delta table "
193+
f"{table.table_uri!r}, whose columns are "
194+
f"{self._table_schema.names}."
195+
)
196+
# Pinned on the scanner so the output keeps the table's (or the
197+
# caller's) column order: unprojected, the reader would append the
198+
# partition columns, which it takes from the listing, at the end. The
199+
# ``path`` column comes last even when ``columns`` names it, as with
200+
# the V1 reader.
201+
synthesized = [column.name for column in self._synthesized_columns]
202+
projected = list(columns) if columns is not None else self._table_schema.names
203+
self._projected_columns = tuple(
204+
[name for name in projected if name not in synthesized] + synthesized
205+
)
206+
_validate_shuffle_arg(shuffle)
207+
# ``_read_datasource_v2`` gives a metadata-backed source's listing no
208+
# file shuffle, so the indexer applies it. As for file sources, the seed
209+
# for ``"files"`` is drawn when the dataset is created.
210+
self._shuffle_config: Optional[FileShuffleConfig] = (
211+
FileShuffleConfig(seed=time.time_ns() % _INT32_MAX)
212+
if shuffle == "files"
213+
else shuffle
214+
)
215+
216+
@property
217+
def paths(self) -> List[str]:
218+
# DSv2 needs ``paths``, but the indexer lists files from the log, so
219+
# this is only a label for the table.
220+
return [self._snapshot.table_uri]
221+
222+
@property
223+
def version(self) -> int:
224+
"""The table version this datasource reads."""
225+
return self._snapshot.version
226+
227+
def _get_file_indexer(self) -> DeltaFileIndexer:
228+
return DeltaFileIndexer(
229+
snapshot=self._snapshot,
230+
filesystem=self._filesystem,
231+
partition_schema=self._partition_schema,
232+
shuffle_config=self._shuffle_config,
233+
coalesce_bytes=env_integer("RAY_DATA_PARQUET_FOOTER_COALESCE_BYTES", 0),
234+
small_shuffle_chunk_size=(
235+
DataContext.get_current().small_shuffle_chunk_size
236+
),
237+
)
238+
239+
def get_file_partitioner(
240+
self, *, hints: Optional["PartitionHints"] = None
241+
) -> "OnlineBinPacker":
242+
# The footer-read listing emits one row per row-group run with exact
243+
# sizes, as for Parquet.
244+
return make_row_group_bin_packer(self._shuffle_config)
245+
246+
@override
247+
def infer_schema(self, sample: Optional[FileManifest]) -> pa.Schema:
248+
"""The table schema from the log, plus the ``path`` column if asked."""
249+
schema = self._table_schema
250+
for column in self._synthesized_columns:
251+
schema = schema.append(pa.field(column.name, column.type))
252+
return schema
253+
254+
def create_scanner(
255+
self,
256+
schema: pa.Schema,
257+
filesystem: Optional["FileSystem"] = None,
258+
**options: Any,
259+
) -> DeltaScanner:
260+
# ``_read_datasource_v2`` passes ``filesystem=None`` and
261+
# ``partitioning=None`` for a metadata-backed source; both come from
262+
# the table.
263+
return DeltaScanner(
264+
schema=schema,
265+
columns=self._projected_columns,
266+
filesystem=self._filesystem,
267+
partitioning=self._partitioning,
268+
synthesized_columns=self._synthesized_columns,
269+
shuffle=self._shuffle_config,
270+
target_block_size=DataContext.get_current().target_max_block_size,
271+
)
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
from dataclasses import dataclass
2+
from typing import ClassVar, Dict, Iterator, Optional, Type
3+
4+
import pyarrow as pa
5+
from typing_extensions import override
6+
7+
from ray.data._internal.datasource_v2.formats.delta.delta_file_indexer import (
8+
PARTITION_VALUES_COLUMN,
9+
DeltaPartitionPruner,
10+
PartitionValues,
11+
)
12+
from ray.data._internal.datasource_v2.formats.parquet.parquet_file_reader import (
13+
ParquetFileReader,
14+
)
15+
from ray.data._internal.datasource_v2.formats.parquet.parquet_scanner import (
16+
ParquetScanner,
17+
)
18+
from ray.data._internal.datasource_v2.interfaces.file_manifest import FileManifest
19+
from ray.data._internal.datasource_v2.interfaces.file_pruner import FilePruner
20+
from ray.util.annotations import DeveloperAPI
21+
22+
23+
class DeltaFileReader(ParquetFileReader):
24+
"""Parquet reader that takes partition values from the listing.
25+
26+
A Delta file's path needn't hold its partition values, so the listing puts
27+
the ones the log records in each manifest (``PARTITION_VALUES_COLUMN``).
28+
The reader casts them to the columns' types as it does a value parsed from
29+
a path.
30+
"""
31+
32+
# Replaced, never changed in place, by each ``read``.
33+
_partition_values_by_path: Dict[str, PartitionValues] = {}
34+
35+
@override
36+
def read(self, input_split: FileManifest) -> Iterator[pa.Table]:
37+
# A read task reads its manifests one after another.
38+
extra_columns = input_split.extra_columns
39+
self._partition_values_by_path = (
40+
dict(
41+
zip(
42+
input_split.paths.tolist(),
43+
extra_columns[PARTITION_VALUES_COLUMN].to_pylist(),
44+
)
45+
)
46+
if extra_columns is not None
47+
and PARTITION_VALUES_COLUMN in extra_columns.column_names
48+
else {}
49+
)
50+
yield from super().read(input_split)
51+
52+
@override
53+
def _get_partition_values(self, path: str) -> Dict[str, Optional[str]]:
54+
# ``ParquetFileReader`` keeps its partitioning here, not in the base
55+
# class's parser; ``None`` for an unpartitioned table.
56+
if self._partition_value_parser is None:
57+
return {}
58+
values = self._partition_values_by_path.get(path)
59+
if values is None:
60+
raise ValueError(
61+
f"The listing gave no partition values for the Delta data file {path!r}."
62+
)
63+
return values
64+
65+
66+
@DeveloperAPI
67+
@dataclass(frozen=True)
68+
class DeltaScanner(ParquetScanner):
69+
"""Scanner for a Delta Lake table.
70+
71+
A Delta table's data files are Parquet files, so filter, column and limit
72+
pushdown are inherited from :class:`ParquetScanner`. Partition values come
73+
from the log: the listing prunes files by them and carries them to
74+
:class:`DeltaFileReader`. ``partitioning`` only names the partition
75+
columns.
76+
"""
77+
78+
reader_class: ClassVar[Type[ParquetFileReader]] = DeltaFileReader
79+
80+
@override
81+
def _create_partition_pruner(self) -> Optional[FilePruner]:
82+
if self.partitioning is None or self.partition_predicate is None:
83+
return None
84+
return DeltaPartitionPruner(self.partition_predicate, self.schema)
85+
86+
@override
87+
def prune_input_split(self, input_split: FileManifest) -> FileManifest:
88+
# The listing already left out the files whose partition values in the
89+
# log fail the predicate, and the reader filters rows by it.
90+
return input_split

‎python/ray/data/_internal/datasource_v2/formats/parquet/parquet_scanner.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import dataclass, field, replace
2-
from typing import Any, Dict, Optional, Tuple
2+
from typing import Any, ClassVar, Dict, Optional, Tuple, Type
33

44
import pyarrow as pa
55
from typing_extensions import override
@@ -45,6 +45,9 @@ class ParquetScanner(ArrowFileScanner):
4545
# ``pre_buffer``, ``dictionary_columns``). Carries the deprecated
4646
# ``dataset_kwargs`` payload from ``read_parquet`` to the worker.
4747
parquet_format_kwargs: Dict[str, Any] = field(default_factory=dict)
48+
# The reader ``create_reader`` builds; a format whose files are Parquet
49+
# can substitute a subclass.
50+
reader_class: ClassVar[Type[ParquetFileReader]] = ParquetFileReader
4851

4952
@override
5053
def prune_partitions(self, predicate: Expr) -> "ParquetScanner":
@@ -91,7 +94,7 @@ def create_reader(self) -> ParquetFileReader:
9194
Returns:
9295
ParquetFileReader with all pushdowns and adaptive batch sizing.
9396
"""
94-
return ParquetFileReader(
97+
return self.reader_class(
9598
batch_size=self.batch_size,
9699
columns=list(self.columns) if self.columns is not None else None,
97100
predicate=combine_predicates(self.predicate, self.partition_predicate),

0 commit comments

Comments
 (0)