|
| 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 | + ) |
0 commit comments