From 129280e79c7e2ed29c8b66f92bc43d625c3c1a62 Mon Sep 17 00:00:00 2001 From: Benson LUO Date: Tue, 24 Nov 2026 22:33:11 +0800 Subject: [PATCH 1/3] fix: Read Delta Lake tables through the current snapshot in the Dask offline store The Dask offline store read every FileSource through dd.read_parquet on the source directory, ignoring file_format=DeltaFormat(). After a Delta overwrite or compaction, data files removed by the transaction log can remain on disk until they are vacuumed, so historical retrieval, materialization pulls, and monitoring reads could return stale or duplicated rows instead of the current snapshot. - Read the Delta snapshot's Arrow dataset: partition values and their types come from the transaction log, an empty snapshot still exposes its columns, and reader features the installed delta-rs reader does not support are rejected instead of being bypassed with a raw Parquet read. Data is read only inside Dask tasks, one fragment per task, and nullable integers keep their pandas dtypes when fragments are assembled. - Treat timezone-naive Delta timestamps and time bounds as UTC when comparing times, in retrieval and monitoring. - compute_monitoring_metrics and get_monitoring_max_timestamp read the current snapshot. A missing Delta table yields no metrics and no max timestamp, while an existing empty snapshot yields zero-row metric summaries and a None max timestamp. - offline_write_batch raises NotImplementedError for DeltaFormat before invoking the Parquet writer, which cannot commit to the Delta transaction log. - Reads reject formats other than Parquet and Delta with NotImplementedError, mirroring the DuckDB offline store. Explicit and default Parquet sources keep their existing paths. - Document the Parquet/Delta read support, the write restriction, and the absolute-path requirement in the Dask offline store reference. Fixes #7221 Signed-off-by: Benson LUO --- docs/reference/offline-stores/dask.md | 9 +- sdk/python/feast/infra/offline_stores/dask.py | 345 +++++-- .../offline_stores/test_dask_delta_source.py | 894 ++++++++++++++++++ 3 files changed, 1188 insertions(+), 60 deletions(-) create mode 100644 sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py diff --git a/docs/reference/offline-stores/dask.md b/docs/reference/offline-stores/dask.md index 3bcac5abd7b..ef611d1d856 100644 --- a/docs/reference/offline-stores/dask.md +++ b/docs/reference/offline-stores/dask.md @@ -2,7 +2,12 @@ ## Description -The Dask offline store provides support for reading [FileSources](../data-sources/file.md). +The Dask offline store reads Parquet and Delta [FileSources](../data-sources/file.md). +Delta reads require the `feast[delta]` extra and a table protocol supported by its +Delta Lake reader. Reads use the current snapshot in the transaction log, so +data files removed by an overwrite or compaction are not included. Use an absolute +local Delta path when Feast needs to infer the source schema, because `FileSource` +schema discovery does not resolve that path relative to the repository. When an entity dataframe is supplied to `get_historical_features`, entity rows and their additional columns (such as training labels) are retained even if all matching @@ -41,7 +46,7 @@ Below is a matrix indicating which functionality is supported by the dask offlin | `get_historical_features` (point-in-time correct join) | yes | | `pull_latest_from_table_or_query` (retrieve latest feature values) | yes | | `pull_all_from_table_or_query` (retrieve a saved dataset) | yes | -| `offline_write_batch` (persist dataframes to offline store) | yes | +| `offline_write_batch` (persist dataframes to offline store) | yes (Parquet only; Delta sources are rejected) | | `write_logged_features` (persist logged features to offline store) | yes | Below is a matrix indicating which functionality is supported by `DaskRetrievalJob`. diff --git a/sdk/python/feast/infra/offline_stores/dask.py b/sdk/python/feast/infra/offline_stores/dask.py index 8ee65de9729..f29756f4258 100644 --- a/sdk/python/feast/infra/offline_stores/dask.py +++ b/sdk/python/feast/infra/offline_stores/dask.py @@ -3,7 +3,19 @@ import uuid from datetime import date, datetime, timezone from pathlib import Path -from typing import Any, Callable, Dict, List, Literal, Optional, Set, Tuple, Union +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + Literal, + Optional, + Set, + Tuple, + Union, + cast, +) import dask import dask.dataframe as dd @@ -16,6 +28,7 @@ import pytz from pandas.api.types import is_integer_dtype, is_unsigned_integer_dtype +from feast.data_format import DeltaFormat, ParquetFormat from feast.data_source import DataSource from feast.errors import ( FeastJoinKeysDuringMaterialization, @@ -55,6 +68,9 @@ compute_non_entity_date_range, ) +if TYPE_CHECKING: + from deltalake import DeltaTable + # DaskRetrievalJob will cast string objects to string[pyarrow] from dask version 2023.7.1 # This is not the desired behavior for our use case, so we set the convert-string option to False # See (https://github.com/dask/dask/issues/10881#issuecomment-1923327936) @@ -264,10 +280,10 @@ def evaluate_historical_retrieval(): # Load feature view data from sources and join them incrementally for feature_view, features in feature_views_to_features.items(): - timestamp_field = feature_view.batch_source.timestamp_field - created_timestamp_column = ( - feature_view.batch_source.created_timestamp_column - ) + source = cast(FileSource, feature_view.batch_source) + delta_source = isinstance(source.file_format, DeltaFormat) + timestamp_field = source.timestamp_field + created_timestamp_column = source.created_timestamp_column # Build a list of entity columns to join on (from the right table) join_keys = [] @@ -286,18 +302,18 @@ def evaluate_historical_retrieval(): all_join_keys = list(set(all_join_keys + join_keys)) - df_to_join = _read_datasource( - feature_view.batch_source, config.repo_path - ) + df_to_join = _read_datasource(source, config.repo_path) - df_to_join, timestamp_field = _field_mapping( + df_to_join, timestamp_field, created_timestamp_column = _field_mapping( df_to_join, feature_view, features, right_entity_key_columns, entity_df_event_timestamp_col, timestamp_field, + created_timestamp_column, full_feature_names, + delta_source=delta_source, ) # Keep the source timestamps separate from request data. @@ -329,6 +345,11 @@ def evaluate_historical_retrieval(): ) created_timestamp_column = source_created_timestamp_column + if delta_source: + # A source row without an event time cannot match a point-in-time + # request. Keep genuine unmatched rows from the later left join. + df_to_join = df_to_join[~df_to_join[timestamp_field].isna()] + # In non-entity mode, if the synthetic entity_df lacks join keys, cross join to build a snapshot # of all entities as-of the requested timestamp, then rely on TTL and deduplication to select # the appropriate latest rows per entity. @@ -344,7 +365,10 @@ def evaluate_historical_retrieval(): ) df_to_join = _normalize_timestamp( - df_to_join, timestamp_field, created_timestamp_column + df_to_join, + timestamp_field, + created_timestamp_column, + delta_source=delta_source, ) df_to_join = _filter_ttl( @@ -362,6 +386,7 @@ def evaluate_historical_retrieval(): if not non_entity_mode else None ), + delta_source=delta_source, ) if filter_by_created_timestamp and created_timestamp_column: @@ -381,6 +406,7 @@ def evaluate_historical_retrieval(): timestamp_field, created_timestamp_column, entity_df_event_timestamp_col, + delta_source=delta_source, ) entity_df_with_features = _drop_columns( @@ -479,16 +505,23 @@ def evaluate_offline_job( # FeastJoinKeysDuringMaterialization), Python's atexit handler calls # ThreadPoolExecutor.shutdown(wait=True) which can block indefinitely, hanging # the subprocess and preventing the parent from reading its output. - # df.columns is derived from the Parquet schema metadata — no computation needed. + # df.columns is derived from schema metadata — no row reads needed. source_columns = set(source_df.columns) if not set(join_key_columns).issubset(source_columns): raise FeastJoinKeysDuringMaterialization( data_source.path, set(join_key_columns), source_columns ) + delta_source = isinstance(data_source.file_format, DeltaFormat) source_df = _normalize_timestamp( - source_df, timestamp_field, created_timestamp_column + source_df, + timestamp_field, + created_timestamp_column, + delta_source=delta_source, ) + if delta_source: + start_date = _utc_if_naive(start_date) + end_date = _utc_if_naive(end_date) # try-catch block is added to deal with this issue https://github.com/dask/dask/issues/8939. # TODO(kevjumba): remove try catch when fix is merged upstream in Dask. @@ -498,13 +531,16 @@ def evaluate_offline_job( if created_timestamp_column: sort_columns.append(created_timestamp_column) - try: - source_df = source_df.sort_values(by=sort_columns) - - except ZeroDivisionError: - # Use 1 partition to get around case where everything in timestamp column is the same so the partition algorithm doesn't - # try to divide by zero. - source_df = source_df.sort_values(by=sort_columns, npartitions=1) + if delta_source: + source_df = _sort_delta_timestamps( + source_df, sort_columns, na_position="last" + ) + else: + try: + source_df = source_df.sort_values(by=sort_columns) + except ZeroDivisionError: + # Use 1 partition when every row has the same timestamp. + source_df = source_df.sort_values(by=sort_columns, npartitions=1) # TODO: The old implementation is inclusive of start_date and exclusive of end_date. # Which is inconsistent with other offline stores. @@ -619,6 +655,14 @@ def offline_write_batch( assert isinstance(config.offline_store, DaskOfflineStoreConfig) assert isinstance(feature_view.batch_source, FileSource) + if isinstance(feature_view.batch_source.file_format, DeltaFormat): + raise NotImplementedError( + f"The Dask offline store cannot write to file source " + f"'{feature_view.batch_source.name}' with file format " + "DeltaFormat; only Parquet writes are supported. The Parquet " + "writer does not commit to the Delta transaction log." + ) + pa_schema, column_names = get_pyarrow_schema_from_batch_source( config, feature_view.batch_source ) @@ -664,8 +708,15 @@ def compute_monitoring_metrics( assert isinstance(data_source, FileSource) table = _dask_read_batch_arrow(data_source, config.repo_path) + if table is None: + # Nothing written to the source yet: no metrics to compute. + return [] table = _dask_filter_arrow_by_timestamp( - table, timestamp_field, start_date, end_date + table, + timestamp_field, + start_date, + end_date, + delta_source=isinstance(data_source.file_format, DeltaFormat), ) results: List[Dict[str, Any]] = [] @@ -696,16 +747,28 @@ def get_monitoring_max_timestamp( repo_path=config.repo_path, uri=data_source.file_options.uri, ) - filesystem, path = FileSource.create_filesystem_and_path( - str(absolute_path), - data_source.file_options.s3_endpoint_override, - resolved_credentials=data_source.resolve_credentials(), - ) - try: - t = pq.read_table(path, filesystem=filesystem, columns=[timestamp_field]) - except FileNotFoundError: - # Nothing written to the source yet: no data to monitor. - return None + if _is_delta_source(data_source): + from deltalake.exceptions import TableNotFoundError + + try: + delta_table = _read_delta_table(data_source, absolute_path) + except TableNotFoundError: + # Nothing written to the source yet: no data to monitor. + return None + t = delta_table.to_pyarrow_table(columns=[timestamp_field]) + else: + filesystem, path = FileSource.create_filesystem_and_path( + str(absolute_path), + data_source.file_options.s3_endpoint_override, + resolved_credentials=data_source.resolve_credentials(), + ) + try: + t = pq.read_table( + path, filesystem=filesystem, columns=[timestamp_field] + ) + except FileNotFoundError: + # Nothing written to the source yet: no data to monitor. + return None if t.num_rows == 0: return None arr = t[timestamp_field] @@ -815,11 +878,20 @@ def _dask_read_parquet_if_exists(path: str) -> Optional[pyarrow.Table]: def _dask_read_batch_arrow( data_source: FileSource, repo_path: Optional[Path] -) -> pyarrow.Table: +) -> Optional[pyarrow.Table]: absolute_path = FileSource.get_uri_for_file_path( repo_path=repo_path, uri=data_source.file_options.uri, ) + if _is_delta_source(data_source): + from deltalake.exceptions import TableNotFoundError + + try: + delta_table = _read_delta_table(data_source, absolute_path) + except TableNotFoundError: + # Nothing written to the source yet: no data to monitor. + return None + return delta_table.to_pyarrow_table() filesystem, path = FileSource.create_filesystem_and_path( str(absolute_path), data_source.file_options.s3_endpoint_override, @@ -828,15 +900,29 @@ def _dask_read_batch_arrow( return pq.read_table(path, filesystem=filesystem) +def _utc_if_naive(value: Optional[datetime]) -> Optional[datetime]: + if value is not None and value.tzinfo is None: + return value.replace(tzinfo=timezone.utc) + return value + + def _dask_filter_arrow_by_timestamp( table: pyarrow.Table, timestamp_field: str, start_date: Optional[datetime], end_date: Optional[datetime], + *, + delta_source: bool = False, ) -> pyarrow.Table: if start_date is None and end_date is None: return table arr = table[timestamp_field] + if delta_source and pyarrow.types.is_timestamp(arr.type): + # Match retrieval and max-timestamp semantics: naive timestamps are UTC. + if arr.type.tz is None: + arr = pc.assume_timezone(arr, "UTC") # type: ignore[attr-defined] + start_date = _utc_if_naive(start_date) + end_date = _utc_if_naive(end_date) mask = None if start_date is not None: mask = pc.greater_equal(arr, pyarrow.scalar(start_date)) # type: ignore[attr-defined] @@ -1043,7 +1129,83 @@ def _get_entity_df_event_timestamp_range( ) -def _read_datasource(data_source, repo_path) -> dd.DataFrame: +def _is_delta_source(data_source: FileSource) -> bool: + file_format = data_source.file_format + if isinstance(file_format, DeltaFormat): + return True + if file_format is None or isinstance(file_format, ParquetFormat): + return False + raise NotImplementedError( + f"The Dask offline store cannot read file source '{data_source.name}' " + f"with file format {type(file_format).__name__}; only Parquet and Delta " + "are supported." + ) + + +def _read_delta_table(data_source: FileSource, path: str) -> "DeltaTable": + from deltalake import DeltaTable + + credentials = data_source.resolve_credentials() or {} + storage_options = { + key: credentials[key] + for key in ( + "AWS_ACCESS_KEY_ID", + "AWS_SECRET_ACCESS_KEY", + "AWS_SESSION_TOKEN", + "AWS_DEFAULT_REGION", + ) + if credentials.get(key) + } + endpoint = data_source.file_options.s3_endpoint_override + if endpoint: + storage_options["AWS_ENDPOINT_URL"] = str(endpoint) + if str(endpoint).startswith("http://"): + storage_options["AWS_ALLOW_HTTP"] = "true" + return DeltaTable(path, storage_options=storage_options or None) + + +def _delta_pandas_dtype( + data_type: pyarrow.DataType, +) -> Optional[pd.api.extensions.ExtensionDtype]: + # NumPy promotes a nullable integer column to float64, which rounds large + # values and gives it a different dtype from a null-free fragment. + if pyarrow.types.is_integer(data_type): + prefix = "UInt" if pyarrow.types.is_unsigned_integer(data_type) else "Int" + return pd.api.types.pandas_dtype(f"{prefix}{data_type.bit_width}") + if pyarrow.types.is_boolean(data_type): + return pd.BooleanDtype() + return None + + +def _read_delta_fragment( + fragment: pyarrow.dataset.Fragment, + schema: pyarrow.Schema, + columns: Optional[List[str]] = None, +) -> pd.DataFrame: + return fragment.to_table(schema=schema, columns=columns).to_pandas( + types_mapper=_delta_pandas_dtype + ) + + +def _read_datasource( + data_source: FileSource, repo_path: Optional[Path] +) -> dd.DataFrame: + path = FileSource.get_uri_for_file_path( + repo_path=repo_path, + uri=data_source.file_options.uri, + ) + if _is_delta_source(data_source): + # Delta supplies the snapshot schema and partition expressions and + # rejects reader features it cannot honor. Read data only in Dask tasks. + dataset = _read_delta_table(data_source, path).to_pyarrow_dataset() + fragments = list(dataset.get_fragments()) + meta = dataset.schema.empty_table().to_pandas(types_mapper=_delta_pandas_dtype) + if not fragments: + return dd.from_pandas(meta, npartitions=1) + return dd.from_map( + _read_delta_fragment, fragments, schema=dataset.schema, meta=meta + ) + storage_options: Optional[dict] = None resolved_creds = data_source.resolve_credentials() @@ -1065,15 +1227,7 @@ def _read_datasource(data_source, repo_path) -> dd.DataFrame: } } - path = FileSource.get_uri_for_file_path( - repo_path=repo_path, - uri=data_source.file_options.uri, - ) - - return dd.read_parquet( - path, - storage_options=storage_options, - ) + return dd.read_parquet(path, storage_options=storage_options) def _run_dask_field_mapping( @@ -1095,8 +1249,11 @@ def _field_mapping( right_entity_key_columns: List[str], entity_df_event_timestamp_col: str, timestamp_field: str, + created_timestamp_column: str, full_feature_names: bool, -) -> Tuple[dd.DataFrame, str]: + *, + delta_source: bool, +) -> Tuple[dd.DataFrame, str, str]: # Rename columns by the field mapping dictionary if it exists if ( feature_view.batch_source is not None @@ -1128,22 +1285,44 @@ def _field_mapping( feature_names.append(formatted_feature_name) columns_map[feature] = formatted_feature_name + if delta_source: + # Keep an independent copy for time filtering when a source timestamp + # is also requested as a feature, whether or not it is prefixed. + aliases = {} + for column in dict.fromkeys((timestamp_field, created_timestamp_column)): + if column and column in columns_map: + alias = _unused_column_name( + column, df_to_join, df_to_join, feature_names + ) + df_to_join = df_to_join.assign(**{alias: df_to_join[column]}) + aliases[column] = alias + timestamp_field = aliases.get(timestamp_field, timestamp_field) + created_timestamp_column = aliases.get( + created_timestamp_column, created_timestamp_column + ) + right_entity_key_columns = [ + aliases.get(column, column) for column in right_entity_key_columns + ] + # Ensure that the source dataframe feature column includes the feature view name as a prefix df_to_join = _run_dask_field_mapping(df_to_join, columns_map) # Select only the columns we need to join from the feature dataframe - df_to_join = df_to_join[right_entity_key_columns + feature_names] + columns_to_join = right_entity_key_columns + feature_names + if delta_source: + columns_to_join = list(dict.fromkeys(columns_to_join)) + df_to_join = df_to_join[columns_to_join] df_to_join = df_to_join.persist() # Make sure to not have duplicated columns - if entity_df_event_timestamp_col == timestamp_field: + if not delta_source and entity_df_event_timestamp_col == timestamp_field: df_to_join = _run_dask_field_mapping( df_to_join, {timestamp_field: f"__{timestamp_field}"}, ) timestamp_field = f"__{timestamp_field}" - return df_to_join.persist(), timestamp_field + return df_to_join.persist(), timestamp_field, created_timestamp_column def _unused_column_name( @@ -1196,7 +1375,19 @@ def _normalize_timestamp( df_to_join: dd.DataFrame, timestamp_field: str, created_timestamp_column: Optional[str] = None, + *, + delta_source: bool = False, ) -> dd.DataFrame: + if delta_source: + # Unlike element-wise apply, this also normalizes empty partitions. + return df_to_join.assign( + **{ + column: dd.to_datetime(df_to_join[column], utc=True) + for column in dict.fromkeys((timestamp_field, created_timestamp_column)) + if column + } + ).persist() + df_to_join_types = df_to_join.dtypes timestamp_field_type = df_to_join_types[timestamp_field] @@ -1243,8 +1434,9 @@ def _filter_ttl( timestamp_field: str, preserved_columns: Optional[Set[str]] = None, request_columns: Optional[List[str]] = None, + *, + delta_source: bool = False, ) -> dd.DataFrame: - # A missing source row is already a valid left-join result. within_time_range = ( df_to_join[timestamp_field] <= df_to_join[entity_df_event_timestamp_col] ) @@ -1253,7 +1445,11 @@ def _filter_ttl( df_to_join[timestamp_field] >= df_to_join[entity_df_event_timestamp_col] - feature_view.ttl ) - valid = df_to_join[timestamp_field].isna() | within_time_range + valid = within_time_range + if not delta_source or preserved_columns is not None: + # A missing source row is already a valid left-join result, unless + # it came from the synthetic request for a Delta snapshot. + valid = df_to_join[timestamp_field].isna() | valid if preserved_columns is None: # Non-entity snapshots only contain entities with an eligible source row. @@ -1297,6 +1493,12 @@ def _filter_ttl( ) .mask(ttl_missing, other=pd.NA) if is_integer_dtype(marked[column].dtype) + and not ( + delta_source + and isinstance( + marked[column].dtype, pd.api.extensions.ExtensionDtype + ) + ) else marked[column].mask(ttl_missing, other=pd.NA) for column in marked.columns if column not in preserved_columns @@ -1334,12 +1536,36 @@ def _apply_created_timestamp_cutoff( ) +def _sort_delta_timestamps( + frame: dd.DataFrame, + sort_columns: List[str], + *, + na_position: Literal["first", "last"], +) -> dd.DataFrame: + # Dask uses the first sort column to calculate partition boundaries. A + # partition of only NaTs can make that calculation fail or lose rows. Use + # a non-null numeric key for partitioning, then the original timestamps + # to order any ties (including timestamps rounded to the same float). + event_time = frame[sort_columns[0]] + order = event_time.astype("int64").astype("float64") + if na_position == "last": + order = order.mask(event_time.isna(), float(2**63)) + key = _unused_column_name("delta_timestamp_sort", frame, frame, []) + return ( + frame.assign(**{key: order}) + .sort_values(by=[key, *sort_columns], na_position=na_position) + .drop(columns=key) + ) + + def _drop_duplicates( df_to_join: dd.DataFrame, all_join_keys: List[str], timestamp_field: str, created_timestamp_column: str, entity_df_event_timestamp_col: str, + *, + delta_source: bool = False, ) -> dd.DataFrame: column_order = df_to_join.columns @@ -1351,17 +1577,20 @@ def _drop_duplicates( if created_timestamp_column: sort_columns.append(created_timestamp_column) - try: - df_to_join = df_to_join.sort_values(by=sort_columns, na_position="first") - df_to_join = df_to_join.persist() - - except ZeroDivisionError: - # Use 1 partition to get around case where everything in timestamp column is the same so the partition algorithm doesn't - # try to divide by zero. - df_to_join = df_to_join[column_order].sort_values( - by=sort_columns, na_position="first", npartitions=1 - ) - df_to_join = df_to_join.persist() + if delta_source: + df_to_join = _sort_delta_timestamps( + df_to_join, sort_columns, na_position="first" + ).persist() + else: + try: + df_to_join = df_to_join.sort_values(by=sort_columns, na_position="first") + df_to_join = df_to_join.persist() + except ZeroDivisionError: + # Use 1 partition when every row has the same timestamp. + df_to_join = df_to_join[column_order].sort_values( + by=sort_columns, na_position="first", npartitions=1 + ) + df_to_join = df_to_join.persist() df_to_join = df_to_join.drop_duplicates( all_join_keys + [entity_df_event_timestamp_col], diff --git a/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py b/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py new file mode 100644 index 00000000000..374b99f4c4a --- /dev/null +++ b/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py @@ -0,0 +1,894 @@ +"""Unit tests for DeltaFormat FileSource support in the Dask offline store. + +The Dask offline store previously read every FileSource through +``dd.read_parquet`` on the source directory, ignoring ``file_format``. For +Delta Lake tables this returns stale or duplicated rows after overwrites or +compaction, because tombstoned ``part-*.parquet`` files of earlier Delta +versions stay on disk until they are vacuumed. These tests pin the +snapshot-correct behavior for reads (historical retrieval, materialization +pulls, monitoring) and the explicit failure for writes. +""" + +import glob +import json +import os +from collections.abc import Callable +from datetime import datetime, timezone +from pathlib import Path +from unittest.mock import MagicMock + +import pandas as pd +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +from feast.data_format import DeltaFormat, FileFormat, ParquetFormat +from feast.entity import Entity +from feast.feature_view import FeatureView, Field +from feast.infra.offline_stores import dask as dask_mod +from feast.infra.offline_stores.dask import DaskOfflineStore, DaskOfflineStoreConfig +from feast.infra.offline_stores.file_source import FileSource +from feast.infra.offline_stores.offline_store import RetrievalJob +from feast.repo_config import RepoConfig +from feast.types import Float32, Int32, Int64, UnixTimestamp, ValueType + +DeltaTable = pytest.importorskip("deltalake").DeltaTable +write_deltalake = pytest.importorskip("deltalake.writer").write_deltalake + + +class _UnsupportedFileFormat(FileFormat): + """A FileFormat outside the formats the Dask offline store can read.""" + + def to_proto(self) -> None: + raise NotImplementedError + + def __str__(self) -> str: + return "unsupported" + + +# Values in the initial and replacement snapshots. +STALE_CONV_RATES = [0.10, 0.20] +CURRENT_CONV_RATES = [0.90, 0.80] + + +def _write_snapshot( + path: str, day: int, conv_rates: list[float], partition_by: list[str] | None = None +) -> None: + df = pd.DataFrame( + { + "driver_id": [1001, 1002], + "conv_rate": conv_rates, + "event_timestamp": pd.to_datetime( + [datetime(2026, 1, day, tzinfo=timezone.utc)] * 2 + ), + } + ) + write_deltalake(path, df, mode="overwrite", partition_by=partition_by) + + +def _make_overwritten_delta_table( + tmp_path: Path, partition_by: list[str] | None = None +) -> str: + """Create a Delta table whose first version was fully overwritten. + + The tombstoned files of version 0 remain on disk, so reading the + directory with a plain Parquet reader returns both versions. + """ + delta_path = str(tmp_path / "driver_stats_delta") + os.makedirs(delta_path) + _write_snapshot( + delta_path, day=1, conv_rates=STALE_CONV_RATES, partition_by=partition_by + ) + _write_snapshot( + delta_path, day=2, conv_rates=CURRENT_CONV_RATES, partition_by=partition_by + ) + return delta_path + + +def _delta_file_source(delta_path: str) -> FileSource: + return FileSource( + name="driver_stats_source", + path=delta_path, + file_format=DeltaFormat(), + timestamp_field="event_timestamp", + ) + + +def _mock_repo_config(repo_path: Path | None = None) -> RepoConfig: + return RepoConfig( + project="test_project", + registry="test_registry", + provider="local", + repo_path=repo_path, + offline_store=DaskOfflineStoreConfig(type="dask"), + ) + + +def _mock_entity() -> list[Entity]: + return [ + Entity( + name="driver_id", + join_keys=["driver_id"], + description="Driver ID", + value_type=ValueType.INT64, + ) + ] + + +def _mock_feature_view(source: FileSource) -> FeatureView: + return FeatureView( + name="driver_stats", + entities=_mock_entity(), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="conv_rate", dtype=Float32), + ], + source=source, + ttl=None, + ) + + +def _physical_part_files(delta_path: str) -> list[str]: + return glob.glob(os.path.join(delta_path, "**", "part-*.parquet"), recursive=True) + + +# ------------------------------------------------------------------ # +# Read path: _read_datasource (historical retrieval + materialization) +# ------------------------------------------------------------------ # + + +def test_read_datasource_returns_current_delta_snapshot_only(tmp_path: Path) -> None: + delta_path = _make_overwritten_delta_table(tmp_path) + + # Sanity: the tombstoned files of the overwritten version are still on + # disk, so a directory-level Parquet read would see both versions. + assert len(_physical_part_files(delta_path)) == 2 + assert DeltaTable(delta_path).version() == 1 + assert len(DeltaTable(delta_path).file_uris()) == 1 + + source = _delta_file_source(delta_path) + result = dask_mod._read_datasource(source, None).compute() + + assert len(result) == 2 + assert sorted(float(v) for v in result["conv_rate"]) == sorted(CURRENT_CONV_RATES) + + +def test_read_datasource_delta_partitioned_restores_partition_column( + tmp_path: Path, +) -> None: + delta_path = _make_overwritten_delta_table(tmp_path, partition_by=["driver_id"]) + + source = _delta_file_source(delta_path) + result = dask_mod._read_datasource(source, None).compute() + + assert len(result) == 2 + # Partition values live in the Delta log and the directory layout, not in + # the Parquet files themselves; the reader must still surface them. + assert sorted(int(v) for v in result["driver_id"]) == [1001, 1002] + assert sorted(float(v) for v in result["conv_rate"]) == sorted(CURRENT_CONV_RATES) + + +@pytest.mark.parametrize("segments", [["001"], ["001", "002", "east/west", None]]) +def test_delta_partition_values_come_from_the_log( + tmp_path: Path, segments: list[str | None] +) -> None: + path = str(tmp_path / "delta") + table = pa.table( + {"row_id": range(len(segments)), "segment": pa.array(segments, pa.string())} + ) + write_deltalake(path, table, partition_by=["segment"]) + + # A relative source path uses the repo root, and projecting the partition + # column must retain the declared type and values (not path-inferred ints). + frame = dask_mod._read_datasource(_delta_file_source("delta"), tmp_path) + assert frame.npartitions == len(segments) + rows = frame[["row_id", "segment"]].compute().sort_values("row_id") + assert [None if pd.isna(value) else value for value in rows["segment"]] == segments + + +def test_delta_rejects_an_unsupported_reader_protocol(tmp_path: Path) -> None: + from deltalake.exceptions import DeltaProtocolError + + path = Path(_make_overwritten_delta_table(tmp_path)) + # The pinned reader cannot apply deletion vectors. A raw Parquet scan + # would silently return results from a table it cannot interpret. + action = { + "protocol": { + "minReaderVersion": 3, + "minWriterVersion": 7, + "readerFeatures": ["deletionVectors"], + "writerFeatures": ["deletionVectors"], + } + } + (path / "_delta_log" / "00000000000000000002.json").write_text( + json.dumps(action) + "\n", encoding="utf-8" + ) + source = _delta_file_source(str(path)) + with pytest.raises(DeltaProtocolError, match="deletionVectors"): + dask_mod._read_datasource(source, None).compute() + with pytest.raises(DeltaProtocolError, match="deletionVectors"): + DaskOfflineStore.get_monitoring_max_timestamp( + _mock_repo_config(tmp_path), source, "event_timestamp" + ) + with pytest.raises(DeltaProtocolError, match="deletionVectors"): + DaskOfflineStore.compute_monitoring_metrics( + _mock_repo_config(tmp_path), + source, + [("conv_rate", "numeric")], + "event_timestamp", + ) + + +def test_read_datasource_delta_empty_snapshot_keeps_schema(tmp_path: Path) -> None: + delta_path = _make_overwritten_delta_table(tmp_path) + delta_table = DeltaTable(delta_path) + # Delete every row without vacuuming: an empty snapshot that still knows + # its schema through the Delta log. + delta_table.delete() + + source = _delta_file_source(delta_path) + result = dask_mod._read_datasource(source, None).compute() + + assert len(result) == 0 + assert set(result.columns) == {"driver_id", "conv_rate", "event_timestamp"} + + +@pytest.mark.parametrize("empty", [False, True]) +@pytest.mark.parametrize("tz", [None, timezone.utc], ids=["naive", "aware"]) +@pytest.mark.parametrize("bounds", ["start", "end", "both"]) +def test_delta_timestamp_bounds_respect_utc( + tmp_path: Path, empty: bool, tz: timezone | None, bounds: str +) -> None: + path = str(tmp_path / "delta") + write_deltalake( + path, + pa.table( + { + "driver_id": [1001, 1002], + "conv_rate": [0.25, 0.75], + "event_timestamp": pa.array( + [datetime(2026, 1, 1, tzinfo=tz), datetime(2026, 1, 2, tzinfo=tz)], + pa.timestamp("us", "UTC" if tz else None), + ), + } + ), + ) + if empty: + DeltaTable(path).delete() + source = _delta_file_source(path) + config = _mock_repo_config(tmp_path) + bounds_tz = None if tz else timezone.utc + start = datetime(2026, 1, 2, tzinfo=bounds_tz) if bounds != "end" else None + end = ( + datetime(2026, 1, 1 if bounds == "end" else 2, tzinfo=bounds_tz) + if bounds != "start" + else None + ) + expected = 0.25 if bounds == "end" else 0.75 + job = DaskOfflineStore.pull_all_from_table_or_query( + config, + source, + ["driver_id"], + ["conv_rate"], + "event_timestamp", + start_date=start, + end_date=end, + ) + assert job.to_df()["conv_rate"].tolist() == ([] if empty else [expected]) + metrics = DaskOfflineStore.compute_monitoring_metrics( + config, + source, + [("conv_rate", "numeric")], + "event_timestamp", + start_date=start, + end_date=end, + ) + assert metrics[0]["row_count"] == (0 if empty else 1) + assert metrics[0]["mean"] == (None if empty else expected) + + +def test_delta_nullable_integers_keep_precision_and_arrow_type(tmp_path: Path) -> None: + path = str(tmp_path / "delta") + large = 2**53 + 1 + timestamp = datetime(2026, 1, 1, tzinfo=timezone.utc) + for ids, flags in (([large, None], [True, None]), ([large + 2], [False])): + write_deltalake( + path, + pa.table( + { + "driver_id": pa.array(ids, pa.int64()), + "is_active": pa.array(flags, pa.bool_()), + "event_timestamp": [timestamp] * len(ids), + } + ), + mode="append", + ) + source = _delta_file_source(path) + table = DaskOfflineStore.pull_all_from_table_or_query( + _mock_repo_config(tmp_path), source, ["driver_id"], [], "event_timestamp" + ).to_arrow() + ids = table["driver_id"] + assert ids.type == pa.int64() + assert ids.null_count == 1 + assert sorted(v for v in ids.to_pylist() if v is not None) == [large, large + 2] + assert table["is_active"].type == pa.bool_() + assert dict(zip(ids.to_pylist(), table["is_active"].to_pylist())) == { + large: True, + large + 2: False, + None: None, + } + + +def test_read_datasource_unknown_file_format_raises(tmp_path: Path) -> None: + parquet_path = str(tmp_path / "data.parquet") + pq.write_table(pa.table({"event_timestamp": [datetime(2026, 1, 1)]}), parquet_path) + source = FileSource( + name="unsupported_source", + path=parquet_path, + file_format=_UnsupportedFileFormat(), + timestamp_field="event_timestamp", + ) + + with pytest.raises(NotImplementedError, match="only Parquet and Delta"): + dask_mod._read_datasource(source, None) + with pytest.raises(NotImplementedError, match="only Parquet and Delta"): + DaskOfflineStore.get_monitoring_max_timestamp( + _mock_repo_config(tmp_path), source, "event_timestamp" + ) + with pytest.raises(NotImplementedError, match="only Parquet and Delta"): + DaskOfflineStore.compute_monitoring_metrics( + _mock_repo_config(tmp_path), source, [], "event_timestamp" + ) + + +@pytest.mark.parametrize("file_format", [None, ParquetFormat()]) +def test_parquet_file_source_is_unchanged( + tmp_path: Path, file_format: FileFormat | None +) -> None: + table = pa.table( + { + "driver_id": [1001], + "conv_rate": [0.5], + "event_timestamp": [datetime(2026, 1, 1, tzinfo=timezone.utc)], + } + ) + pq.write_table(table, tmp_path / "data.parquet") + source = FileSource( + path="data.parquet", file_format=file_format, timestamp_field="event_timestamp" + ) + config = _mock_repo_config(tmp_path) + + assert dask_mod._read_datasource(source, tmp_path).compute()[ + "conv_rate" + ].tolist() == [0.5] + assert DaskOfflineStore.get_monitoring_max_timestamp( + config, source, "event_timestamp" + ) == datetime(2026, 1, 1, tzinfo=timezone.utc) + metrics = DaskOfflineStore.compute_monitoring_metrics( + config, source, [("conv_rate", "numeric")], "event_timestamp" + ) + assert metrics[0]["row_count"] == 1 + assert metrics[0]["mean"] == 0.5 + DaskOfflineStore.offline_write_batch( + config, _mock_feature_view(source), table, None + ) + assert pq.read_table(tmp_path / "data.parquet").num_rows == 2 + + +# ------------------------------------------------------------------ # +# End-to-end: historical retrieval and materialization pulls +# ------------------------------------------------------------------ # + + +def test_historical_retrieval_reads_delta_snapshot(tmp_path: Path) -> None: + # The tombstoned version has a later event time, so PIT deduplication + # would select stale values if the reader included its rows. + delta_path = str(tmp_path / "driver_stats_delta") + _write_snapshot(delta_path, day=2, conv_rates=STALE_CONV_RATES) + _write_snapshot(delta_path, day=1, conv_rates=CURRENT_CONV_RATES) + + source = _delta_file_source(delta_path) + repo_config = _mock_repo_config(repo_path=tmp_path) + fv = _mock_feature_view(source) + entity_df = pd.DataFrame( + { + "driver_id": [1001, 1002], + "event_timestamp": pd.to_datetime( + [datetime(2026, 1, 3, tzinfo=timezone.utc)] * 2 + ), + } + ) + + job = DaskOfflineStore.get_historical_features( + config=repo_config, + feature_views=[fv], + feature_refs=["driver_stats:conv_rate"], + entity_df=entity_df, + registry=MagicMock(), + project="test_project", + full_feature_names=False, + ) + result = job.to_df() + + assert len(result) == 2 + assert sorted(float(v) for v in result["conv_rate"]) == sorted(CURRENT_CONV_RATES) + + +@pytest.mark.parametrize("full_feature_names", [False, True]) +def test_delta_historical_requested_timestamp_keeps_pit_filter( + tmp_path: Path, full_feature_names: bool +) -> None: + path = str(tmp_path / "delta") + past = datetime(2026, 1, 1, tzinfo=timezone.utc) + cutoff = datetime(2026, 1, 2, tzinfo=timezone.utc) + future = datetime(2026, 1, 3, tzinfo=timezone.utc) + write_deltalake( + path, + pa.table( + { + "driver_id": [1001, 1001, 1001], + "event_timestamp": [past, past, future], + "created": [cutoff, future, cutoff], + } + ), + ) + source = FileSource( + path=path, + file_format=DeltaFormat(), + timestamp_field="event_timestamp", + created_timestamp_column="created", + ) + fv = FeatureView( + name="driver_stats", + entities=_mock_entity(), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="event_timestamp", dtype=UnixTimestamp), + Field(name="created", dtype=UnixTimestamp), + ], + source=source, + ) + entity_df = pd.DataFrame({"driver_id": [1001], "request_time": [cutoff]}) + result = DaskOfflineStore.get_historical_features( + _mock_repo_config(tmp_path), + [fv], + ["driver_stats:event_timestamp", "driver_stats:created"], + entity_df, + MagicMock(), + "test_project", + full_feature_names=full_feature_names, + filter_by_created_timestamp=True, + ).to_df() + prefix = "driver_stats__" if full_feature_names else "" + assert result[f"{prefix}event_timestamp"].tolist() == [past] + assert result[f"{prefix}created"].tolist() == [cutoff] + assert result["request_time"].tolist() == [cutoff] + + +@pytest.mark.parametrize("all_unmatched", [False, True]) +def test_delta_historical_retains_requests_without_eligible_rows( + tmp_path: Path, all_unmatched: bool +) -> None: + path = str(tmp_path / "delta") + cutoff = datetime(2026, 1, 2, tzinfo=timezone.utc) + past = datetime(2026, 1, 1, tzinfo=timezone.utc) + future = datetime(2026, 1, 3, tzinfo=timezone.utc) + for ids, times, scores in ( + ([1001, 1002], [past, None], [10, 20]), + ([1001, 1003], [future, future], [30, 40]), + ): + write_deltalake( + path, + pa.table( + { + "driver_id": ids, + "event_timestamp": pa.array(times, pa.timestamp("us", "UTC")), + "score": pa.array(scores, pa.int32()), + } + ), + mode="append", + ) + fv = FeatureView( + name="driver_stats", + entities=_mock_entity(), + schema=[Field(name="driver_id", dtype=Int64), Field(name="score", dtype=Int32)], + source=_delta_file_source(path), + ) + # One missing entity, one null source timestamp, and one future-only entity. + ids = [1001, 1002, 1003, 1004] if not all_unmatched else [1004, 1005] + requests = pd.DataFrame( + {"driver_id": ids, "event_timestamp": [cutoff] * len(ids), "label": ids} + ) + table = ( + DaskOfflineStore.get_historical_features( + _mock_repo_config(tmp_path), + [fv], + ["driver_stats:score"], + requests, + MagicMock(), + "test_project", + ) + .to_arrow() + .sort_by("driver_id") + ) + assert table["driver_id"].to_pylist() == ids + assert table["label"].to_pylist() == ids + assert table["event_timestamp"].to_pylist() == [cutoff] * len(ids) + assert table["score"].type == pa.int32() + assert table["score"].to_pylist() == ( + [None, None] if all_unmatched else [10, None, None, None] + ) + + +@pytest.mark.parametrize("full_feature_names", [False, True]) +def test_delta_historical_timestamp_alias_does_not_shadow_feature( + tmp_path: Path, full_feature_names: bool +) -> None: + path = str(tmp_path / "delta") + past = datetime(2026, 1, 1, tzinfo=timezone.utc) + cutoff = datetime(2026, 1, 2, tzinfo=timezone.utc) + future = datetime(2026, 1, 3, tzinfo=timezone.utc) + write_deltalake( + path, + pa.table( + { + "driver_id": [1001, 1001, 9999], + "event_timestamp": [past, future, cutoff], + "__event_timestamp": [10, 20, 30], + } + ), + ) + fv = FeatureView( + name="driver_stats", + entities=_mock_entity(), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="__event_timestamp", dtype=Int64), + ], + source=FileSource( + path=path, + file_format=DeltaFormat(), + timestamp_field="event_timestamp", + ), + ) + result = DaskOfflineStore.get_historical_features( + _mock_repo_config(tmp_path), + [fv], + ["driver_stats:__event_timestamp"], + pd.DataFrame({"driver_id": [1001], "event_timestamp": [cutoff]}), + MagicMock(), + "test_project", + full_feature_names=full_feature_names, + ).to_df() + assert result.columns.is_unique + output = ( + "driver_stats____event_timestamp" if full_feature_names else "__event_timestamp" + ) + assert result[output].tolist() == [10] + assert result["event_timestamp"].tolist() == [cutoff] + + +@pytest.mark.parametrize("has_entity_df", [False, True]) +def test_delta_empty_historical_snapshot(tmp_path: Path, has_entity_df: bool) -> None: + path = _make_overwritten_delta_table(tmp_path) + DeltaTable(path).delete() + cutoff = datetime(2026, 1, 3, tzinfo=timezone.utc) + entity_df = pd.DataFrame({"driver_id": [1001], "event_timestamp": [cutoff]}) + result = DaskOfflineStore.get_historical_features( + _mock_repo_config(tmp_path), + [_mock_feature_view(_delta_file_source(path))], + ["driver_stats:conv_rate"], + entity_df if has_entity_df else None, + MagicMock(), + "test_project", + end_date=cutoff, + ).to_df() + assert list(result["driver_id"]) == ([1001] if has_entity_df else []) + assert result["conv_rate"].isna().all() + + +def test_delta_non_entity_snapshot_requires_a_timestamp(tmp_path: Path) -> None: + path = str(tmp_path / "delta") + event_time = datetime(2026, 1, 1, tzinfo=timezone.utc) + write_deltalake( + path, + pa.table( + { + "driver_id": [1001, 1002], + "conv_rate": [0.25, 0.75], + "event_timestamp": [event_time, None], + } + ), + ) + result = DaskOfflineStore.get_historical_features( + _mock_repo_config(tmp_path), + [_mock_feature_view(_delta_file_source(path))], + ["driver_stats:conv_rate"], + None, + MagicMock(), + "test_project", + end_date=event_time, + ).to_df() + assert result["driver_id"].tolist() == [1001] + assert result["conv_rate"].tolist() == [0.25] + + +@pytest.mark.parametrize( + "pull", + [ + DaskOfflineStore.pull_latest_from_table_or_query, + DaskOfflineStore.pull_all_from_table_or_query, + ], + ids=["latest", "all"], +) +def test_materialization_pulls_read_delta_snapshot( + tmp_path: Path, pull: Callable[..., RetrievalJob] +) -> None: + delta_path = str(tmp_path / "driver_stats_delta") + _write_snapshot(delta_path, day=2, conv_rates=STALE_CONV_RATES) + _write_snapshot(delta_path, day=1, conv_rates=CURRENT_CONV_RATES) + + source = _delta_file_source(delta_path) + repo_config = _mock_repo_config(repo_path=tmp_path) + + job = pull( + config=repo_config, + data_source=source, + join_key_columns=["driver_id"], + feature_name_columns=["conv_rate"], + timestamp_field="event_timestamp", + created_timestamp_column=None, + start_date=datetime(2026, 1, 1, tzinfo=timezone.utc), + end_date=datetime(2026, 1, 3, tzinfo=timezone.utc), + ) + result = job.to_df() + + assert len(result) == 2 + assert sorted(float(v) for v in result["conv_rate"]) == sorted(CURRENT_CONV_RATES) + + +@pytest.mark.parametrize("all_null", [False, True]) +@pytest.mark.parametrize("bounded", [False, True]) +def test_delta_pulls_handle_null_timestamp_fragments( + tmp_path: Path, all_null: bool, bounded: bool +) -> None: + path = str(tmp_path / "delta") + start = datetime(2026, 1, 1, tzinfo=timezone.utc) + end = datetime(2026, 1, 2, tzinfo=timezone.utc) + for ids, times, values in ( + ([1001, 1001], [None, None] if all_null else [start, end], [10, 20]), + ([1002], [None], [30]), + ): + write_deltalake( + path, + pa.table( + { + "driver_id": ids, + "event_timestamp": pa.array(times, pa.timestamp("us", "UTC")), + "conv_rate": values, + } + ), + mode="append", + ) + args = ( + _mock_repo_config(tmp_path), + _delta_file_source(path), + ["driver_id"], + ["conv_rate"], + "event_timestamp", + None, + ) + bounds = {"start_date": start, "end_date": end} if bounded else {} + rows = DaskOfflineStore.pull_all_from_table_or_query(*args, **bounds).to_df() + latest = DaskOfflineStore.pull_latest_from_table_or_query(*args, **bounds).to_df() + if all_null: + assert rows["event_timestamp"].isna().all() + assert sorted(rows["conv_rate"]) == ([] if bounded else [10, 20, 30]) + assert sorted(latest["driver_id"]) == ([] if bounded else [1001, 1002]) + else: + assert rows["conv_rate"].tolist() == ([10, 20] if bounded else [10, 20, 30]) + assert sorted(latest["conv_rate"]) == ([20] if bounded else [20, 30]) + + +# ------------------------------------------------------------------ # +# Monitoring +# ------------------------------------------------------------------ # + + +def test_monitoring_max_timestamp_ignores_tombstoned_files(tmp_path: Path) -> None: + # The overwritten version carries a NEWER timestamp than the current + # snapshot, so a directory-level read would report the wrong max. + delta_path = str(tmp_path / "driver_stats_delta") + os.makedirs(delta_path) + _write_snapshot( + delta_path, day=20, conv_rates=STALE_CONV_RATES + ) # tombstoned, ts 2026-01-20 + _write_snapshot( + delta_path, day=2, conv_rates=CURRENT_CONV_RATES + ) # current, ts 2026-01-02 + + source = _delta_file_source(delta_path) + repo_config = _mock_repo_config(repo_path=tmp_path) + + max_ts = DaskOfflineStore.get_monitoring_max_timestamp( + config=repo_config, + data_source=source, + timestamp_field="event_timestamp", + ) + + assert max_ts == datetime(2026, 1, 2, tzinfo=timezone.utc) + + +def test_monitoring_max_timestamp_empty_delta_snapshot_returns_none( + tmp_path: Path, +) -> None: + delta_path = _make_overwritten_delta_table(tmp_path) + DeltaTable(delta_path).delete() + + source = _delta_file_source(delta_path) + repo_config = _mock_repo_config(repo_path=tmp_path) + + assert ( + DaskOfflineStore.get_monitoring_max_timestamp( + config=repo_config, + data_source=source, + timestamp_field="event_timestamp", + ) + is None + ) + + +def test_monitoring_missing_delta_table_returns_no_data( + tmp_path: Path, +) -> None: + source = _delta_file_source(str(tmp_path / "not_written_yet_delta")) + repo_config = _mock_repo_config(repo_path=tmp_path) + + assert ( + DaskOfflineStore.get_monitoring_max_timestamp( + config=repo_config, + data_source=source, + timestamp_field="event_timestamp", + ) + is None + ) + assert ( + DaskOfflineStore.compute_monitoring_metrics( + config=repo_config, + data_source=source, + feature_columns=[("conv_rate", "numeric")], + timestamp_field="event_timestamp", + ) + == [] + ) + + +def test_missing_delta_table_raises_for_retrieval(tmp_path: Path) -> None: + from deltalake.exceptions import TableNotFoundError + + job = DaskOfflineStore.pull_all_from_table_or_query( + _mock_repo_config(tmp_path), + _delta_file_source(str(tmp_path / "not_written_yet_delta")), + ["driver_id"], + [], + "event_timestamp", + ) + with pytest.raises(TableNotFoundError): + job.to_arrow() + + +def test_delta_monitoring_max_invalid_timestamp_column_raises(tmp_path: Path) -> None: + source = _delta_file_source(_make_overwritten_delta_table(tmp_path)) + with pytest.raises(pa.ArrowInvalid, match="missing_timestamp"): + DaskOfflineStore.get_monitoring_max_timestamp( + _mock_repo_config(tmp_path), source, "missing_timestamp" + ) + + +@pytest.mark.parametrize( + "credentials, endpoint, expected", + [ + (None, None, None), + ( + None, + "https://s3.example.invalid", + {"AWS_ENDPOINT_URL": "https://s3.example.invalid"}, + ), + ( + { + "AWS_ACCESS_KEY_ID": "test-key", + "AWS_SECRET_ACCESS_KEY": "test-secret", + "AWS_SESSION_TOKEN": "test-token", + "AWS_DEFAULT_REGION": "us-west-2", + }, + "http://s3.example.invalid", + { + "AWS_ACCESS_KEY_ID": "test-key", + "AWS_SECRET_ACCESS_KEY": "test-secret", + "AWS_SESSION_TOKEN": "test-token", + "AWS_DEFAULT_REGION": "us-west-2", + "AWS_ENDPOINT_URL": "http://s3.example.invalid", + "AWS_ALLOW_HTTP": "true", + }, + ), + ], +) +def test_delta_s3_reader_options( + monkeypatch: pytest.MonkeyPatch, + credentials: dict[str, str] | None, + endpoint: str | None, + expected: dict[str, str] | None, +) -> None: + path = "s3://bucket/table" + source = FileSource( + path=path, file_format=DeltaFormat(), s3_endpoint_override=endpoint + ) + credentials_resolver = MagicMock(return_value=credentials) + monkeypatch.setattr(source, "resolve_credentials", credentials_resolver) + constructor = MagicMock() + constructor.return_value.to_pyarrow_dataset.return_value = pa.dataset.dataset( + pa.table({"event_timestamp": pa.array([], pa.timestamp("us", "UTC"))}) + ) + monkeypatch.setattr("deltalake.DeltaTable", constructor) + + dask_mod._read_datasource(source, None) + + credentials_resolver.assert_called_once_with() + constructor.assert_called_once_with(path, storage_options=expected) + + +def test_compute_monitoring_metrics_reads_delta_snapshot(tmp_path: Path) -> None: + delta_path = _make_overwritten_delta_table(tmp_path) + + source = _delta_file_source(delta_path) + repo_config = _mock_repo_config(repo_path=tmp_path) + + metrics = DaskOfflineStore.compute_monitoring_metrics( + config=repo_config, + data_source=source, + feature_columns=[("conv_rate", "numeric")], + timestamp_field="event_timestamp", + ) + + assert len(metrics) == 1 + conv_metrics = metrics[0] + assert conv_metrics["feature_name"] == "conv_rate" + assert conv_metrics["row_count"] == 2 + assert conv_metrics["mean"] == pytest.approx(sum(CURRENT_CONV_RATES) / 2) + + +# ------------------------------------------------------------------ # +# Write guard +# ------------------------------------------------------------------ # + + +def test_offline_write_batch_delta_raises_not_implemented(tmp_path: Path) -> None: + delta_path = _make_overwritten_delta_table(tmp_path) + + source = _delta_file_source(delta_path) + repo_config = _mock_repo_config(repo_path=tmp_path) + fv = _mock_feature_view(source) + + table = pa.Table.from_pandas( + pd.DataFrame( + { + "driver_id": pd.array([1001], dtype="int64"), + "conv_rate": pd.array([0.5], dtype="float32"), + "event_timestamp": pd.to_datetime( + [datetime(2026, 1, 3, tzinfo=timezone.utc)] + ), + } + ) + ) + + old_version = DeltaTable(delta_path).version() + old_files = set(_physical_part_files(delta_path)) + with pytest.raises(NotImplementedError, match="DeltaFormat"): + DaskOfflineStore.offline_write_batch( + config=repo_config, + feature_view=fv, + table=table, + progress=None, + ) + assert DeltaTable(delta_path).version() == old_version + assert set(_physical_part_files(delta_path)) == old_files From 2c1dd259faafcf7f50916ceb5a281f186bc41ed6 Mon Sep 17 00:00:00 2001 From: Benson LUO Date: Wed, 25 Nov 2026 01:41:18 +0800 Subject: [PATCH 2/3] test: Mark mock Delta credentials as detect-secrets false positives Signed-off-by: Benson LUO --- .../tests/unit/infra/offline_stores/test_dask_delta_source.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py b/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py index 374b99f4c4a..e8fec0f38a3 100644 --- a/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py +++ b/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py @@ -797,14 +797,14 @@ def test_delta_monitoring_max_invalid_timestamp_column_raises(tmp_path: Path) -> ( { "AWS_ACCESS_KEY_ID": "test-key", - "AWS_SECRET_ACCESS_KEY": "test-secret", + "AWS_SECRET_ACCESS_KEY": "test-secret", # pragma: allowlist secret "AWS_SESSION_TOKEN": "test-token", "AWS_DEFAULT_REGION": "us-west-2", }, "http://s3.example.invalid", { "AWS_ACCESS_KEY_ID": "test-key", - "AWS_SECRET_ACCESS_KEY": "test-secret", + "AWS_SECRET_ACCESS_KEY": "test-secret", # pragma: allowlist secret "AWS_SESSION_TOKEN": "test-token", "AWS_DEFAULT_REGION": "us-west-2", "AWS_ENDPOINT_URL": "http://s3.example.invalid", From e61ae61444d7202378e07b9eaee5a75ab9185f7f Mon Sep 17 00:00:00 2001 From: Benson LUO Date: Wed, 25 Nov 2026 19:45:50 +0800 Subject: [PATCH 3/3] fix: Reject DeltaFormat saved-dataset storage in the Dask offline store DaskRetrievalJob.persist wrote plain Parquet files even when the saved dataset storage declared DeltaFormat, so creation succeeded while retrieval failed: the Dask Delta reader requires a transaction log. Reject DeltaFormat saved-dataset storage before writing anything, and raise a recovery-guidance error when a DeltaFormat source has no Delta transaction log, covering saved datasets that earlier Feast versions wrote as plain Parquet under a Delta declaration. Signed-off-by: Benson LUO --- docs/reference/offline-stores/dask.md | 9 ++ sdk/python/feast/infra/offline_stores/dask.py | 35 +++++++- .../offline_stores/test_dask_delta_source.py | 83 ++++++++++++++++++- 3 files changed, 124 insertions(+), 3 deletions(-) diff --git a/docs/reference/offline-stores/dask.md b/docs/reference/offline-stores/dask.md index ef611d1d856..f1058c0e56a 100644 --- a/docs/reference/offline-stores/dask.md +++ b/docs/reference/offline-stores/dask.md @@ -9,6 +9,15 @@ data files removed by an overwrite or compaction are not included. Use an absolu local Delta path when Feast needs to infer the source schema, because `FileSource` schema discovery does not resolve that path relative to the repository. +Saved datasets are written as Parquet. `DaskRetrievalJob.persist` rejects +`SavedDatasetFileStorage(file_format=DeltaFormat())` instead of writing Parquet +files under a Delta declaration, because such a directory has no Delta transaction +log and cannot be read back as a Delta table. Saved datasets that an earlier Feast +version wrote as plain Parquet under a DeltaFormat declaration are also not valid +Delta tables: re-create them with `ParquetFormat` storage, or register the +directory as a ParquetFormat `FileSource` to keep reading the existing Parquet +files. + When an entity dataframe is supplied to `get_historical_features`, entity rows and their additional columns (such as training labels) are retained even if all matching feature records are outside the feature view's TTL window or after the entity diff --git a/sdk/python/feast/infra/offline_stores/dask.py b/sdk/python/feast/infra/offline_stores/dask.py index f29756f4258..363c800d589 100644 --- a/sdk/python/feast/infra/offline_stores/dask.py +++ b/sdk/python/feast/infra/offline_stores/dask.py @@ -129,6 +129,20 @@ def persist( ): assert isinstance(storage, SavedDatasetFileStorage) + if isinstance(storage.file_options.file_format, DeltaFormat): + raise NotImplementedError( + f"The Dask offline store cannot persist a saved dataset to " + f"'{storage.file_options.uri}' with file format DeltaFormat; " + "only Parquet saved datasets are supported. Writing Parquet " + "files under a DeltaFormat declaration would create a " + "directory without a Delta transaction log, which the Dask " + "reader rejects on retrieval. Persist with ParquetFormat " + "storage instead. To serve a saved dataset from a Delta " + "table, write the retrieval result with a Delta writer and " + "register a FileSource with file_format=DeltaFormat pointing " + "at it." + ) + # Check if the specified location already exists. if not allow_overwrite and os.path.exists(storage.file_options.uri): raise SavedDatasetLocationAlreadyExists(location=storage.file_options.uri) @@ -1197,7 +1211,26 @@ def _read_datasource( if _is_delta_source(data_source): # Delta supplies the snapshot schema and partition expressions and # rejects reader features it cannot honor. Read data only in Dask tasks. - dataset = _read_delta_table(data_source, path).to_pyarrow_dataset() + from deltalake.exceptions import TableNotFoundError + + try: + delta_table = _read_delta_table(data_source, path) + except TableNotFoundError as exc: + # Covers both genuinely missing tables and the legacy + # saved-dataset directories written as plain Parquet while + # declaring DeltaFormat, which older Feast versions accepted. + raise TableNotFoundError( + f"Delta source '{path}' has no Delta transaction log " + "(_delta_log), so it cannot be read as a Delta table: " + "directories that only contain Parquet files are not Delta " + "tables. If this is a saved dataset written by an earlier " + "Feast version that ignored the DeltaFormat declaration and " + "wrote plain Parquet, re-create the saved dataset with " + "ParquetFormat storage, or register the directory as a " + "ParquetFormat FileSource to read the existing Parquet files " + "directly." + ) from exc + dataset = delta_table.to_pyarrow_dataset() fragments = list(dataset.get_fragments()) meta = dataset.schema.empty_table().to_pandas(types_mapper=_delta_pandas_dtype) if not fragments: diff --git a/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py b/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py index e8fec0f38a3..365fc42f806 100644 --- a/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py +++ b/sdk/python/tests/unit/infra/offline_stores/test_dask_delta_source.py @@ -17,6 +17,7 @@ from pathlib import Path from unittest.mock import MagicMock +import dask.dataframe as dd import pandas as pd import pyarrow as pa import pyarrow.parquet as pq @@ -26,8 +27,12 @@ from feast.entity import Entity from feast.feature_view import FeatureView, Field from feast.infra.offline_stores import dask as dask_mod -from feast.infra.offline_stores.dask import DaskOfflineStore, DaskOfflineStoreConfig -from feast.infra.offline_stores.file_source import FileSource +from feast.infra.offline_stores.dask import ( + DaskOfflineStore, + DaskOfflineStoreConfig, + DaskRetrievalJob, +) +from feast.infra.offline_stores.file_source import FileSource, SavedDatasetFileStorage from feast.infra.offline_stores.offline_store import RetrievalJob from feast.repo_config import RepoConfig from feast.types import Float32, Int32, Int64, UnixTimestamp, ValueType @@ -892,3 +897,77 @@ def test_offline_write_batch_delta_raises_not_implemented(tmp_path: Path) -> Non ) assert DeltaTable(delta_path).version() == old_version assert set(_physical_part_files(delta_path)) == old_files + + +# ------------------------------------------------------------------ # +# Saved datasets: persist guard and create/retrieve roundtrip +# ------------------------------------------------------------------ # + + +def _retrieval_df() -> pd.DataFrame: + return pd.DataFrame( + { + "driver_id": pd.array([1001, 1002], dtype="int64"), + "conv_rate": pd.array([0.5, 0.6], dtype="float32"), + "event_timestamp": pd.to_datetime( + [datetime(2026, 1, 4, tzinfo=timezone.utc)] * 2 + ), + } + ) + + +def _retrieval_job(repo_path: Path) -> DaskRetrievalJob: + return DaskRetrievalJob( + evaluation_function=lambda: dd.from_pandas(_retrieval_df(), npartitions=1), + full_feature_names=False, + repo_path=str(repo_path), + ) + + +def test_persist_rejects_delta_saved_dataset_storage(tmp_path: Path) -> None: + job = _retrieval_job(tmp_path) + storage = SavedDatasetFileStorage( + path=str(tmp_path / "saved_dataset"), file_format=DeltaFormat() + ) + + with pytest.raises(NotImplementedError, match="DeltaFormat"): + job.persist(storage) + + # The mismatch is rejected before anything is written. + assert not os.path.exists(str(tmp_path / "saved_dataset")) + + +def test_saved_dataset_parquet_roundtrip(tmp_path: Path) -> None: + job = _retrieval_job(tmp_path) + storage = SavedDatasetFileStorage(path=str(tmp_path / "saved_dataset")) + + job.persist(storage) + + # Retrieval reads the persisted dataset back through the reader the + # offline store uses for historical retrieval. + persisted_source = storage.to_data_source() + assert isinstance(persisted_source, FileSource) + retrieved = dask_mod._read_datasource(persisted_source, tmp_path) + retrieved = retrieved.compute().sort_values("driver_id").reset_index(drop=True) + original = _retrieval_df().sort_values("driver_id").reset_index(drop=True) + assert retrieved["driver_id"].tolist() == original["driver_id"].tolist() + assert retrieved["conv_rate"].tolist() == original["conv_rate"].tolist() + assert len(retrieved) == len(original) + + +def test_delta_labelled_parquet_directory_read_error_gives_recovery_guidance( + tmp_path: Path, +) -> None: + from deltalake.exceptions import TableNotFoundError + + # A saved-dataset directory as written by DaskRetrievalJob.persist before + # this change: plain Parquet files saved under a DeltaFormat declaration. + parquet_dir = str(tmp_path / "legacy_saved_dataset") + os.makedirs(parquet_dir) + pq.write_table( + pa.table({"driver_id": pa.array([1001], type=pa.int64())}), + os.path.join(parquet_dir, "part-0.parquet"), + ) + + with pytest.raises(TableNotFoundError, match="earlier Feast version"): + dask_mod._read_datasource(_delta_file_source(parquet_dir), tmp_path)