diff --git a/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py b/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py index b0626cd4fa1..110ac8c1533 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py +++ b/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py @@ -3,7 +3,7 @@ import uuid from datetime import datetime from pathlib import Path -from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union +from typing import Any, Callable, Dict, List, Literal, Optional, Set, Tuple, Union import dill import fsspec @@ -775,16 +775,10 @@ def join_batch_with_features(batch: pd.DataFrame) -> pd.DataFrame: ).reset_index(drop=True) try: + # Only the feature rows are deduplicated. Every entity row is + # a separate request, so rows that share an entity key and a + # timestamp are all kept (merge_asof matches each of them). if feature_join_keys: - batch_dedup_cols = [ - k for k in entity_join_keys if k in batch_sorted.columns - ] - if timestamp_field in batch_sorted.columns: - batch_dedup_cols.append(timestamp_field) - if batch_dedup_cols: - batch_sorted = batch_sorted.drop_duplicates( - subset=batch_dedup_cols, keep="last" - ) feature_dedup_cols = [ k for k in feature_join_keys if k in features_sorted.columns ] @@ -1244,6 +1238,14 @@ def schema(self) -> pa.Schema: return pa.Table.from_pandas(df).schema +def _unused_column_name(column: str, existing_columns: Set[str]) -> str: + """Return a temporary name for a source column that collides with request data.""" + name = f"__{column}" + while name in existing_columns: + name = f"_{name}" + return name + + def _make_filter_range(timestamp_field: str, start_date: datetime, end_date: datetime): # Why: factory function for time-range filtering in Ray map_batches def _filter_range(batch: pd.DataFrame) -> pd.Series: @@ -2355,6 +2357,8 @@ def get_historical_features( for k, v in mapping.items(): global_field_mappings[v] = k + # Request columns after any rename below, to keep internal names unused. + entity_columns = set(entity_df_sample.columns) if global_field_mappings: cols_to_rename = { v: k @@ -2363,7 +2367,12 @@ def get_historical_features( } if cols_to_rename: entity_ds = apply_field_mapping(entity_ds, cols_to_rename) + entity_columns = { + cols_to_rename.get(col, col) for col in entity_df_sample.columns + } + # Columns that earlier feature views add to the result. + added_columns: Set[str] = set() result_ds = entity_ds for fv in regular_feature_views: fv_feature_refs = [ @@ -2498,15 +2507,39 @@ def apply_transformation_with_serialized_func( # Also map requested_feats back to logical names after forward mapping requested_feats = [field_mapping.get(f, f) for f in requested_feats] + # The joins below use one timestamp column name for both sides. If + # the request has its own column named like the source timestamp + # field, join on an internal name instead, so the request's values + # are not used as the point-in-time cutoff. + join_timestamp_field = timestamp_field if ( timestamp_field != "event_timestamp" - and timestamp_field not in entity_df_sample.columns + and timestamp_field in entity_df_sample.columns + and "event_timestamp" in entity_df_sample.columns + ): + join_timestamp_field = _unused_column_name( + timestamp_field, + set(entity_df_sample.columns) + | entity_columns + | added_columns + | set(join_keys) + | set(original_join_keys) + | set(requested_feats) + | ({created_col} if created_col else set()), + ) + feature_ds = apply_field_mapping( + feature_ds, {timestamp_field: join_timestamp_field} + ) + + if ( + join_timestamp_field != "event_timestamp" + and join_timestamp_field not in entity_df_sample.columns and "event_timestamp" in entity_df_sample.columns ): def add_timestamp_field( batch: pd.DataFrame, - timestamp_field: str = timestamp_field, + timestamp_field: str = join_timestamp_field, ) -> pd.DataFrame: batch = batch.copy() batch[timestamp_field] = batch["event_timestamp"] @@ -2515,7 +2548,7 @@ def add_timestamp_field( result_ds = result_ds.map_batches( add_timestamp_field, batch_format="pandas" ) - result_ds = normalize_timestamp_columns(result_ds, timestamp_field) + result_ds = normalize_timestamp_columns(result_ds, join_timestamp_field) if store._resource_manager is None: raise ValueError("Resource manager not initialized") @@ -2531,7 +2564,7 @@ def add_timestamp_field( ) feature_df = feature_ds.to_pandas() feature_df = ensure_timestamp_compatibility( - feature_df, [timestamp_field] + feature_df, [join_timestamp_field] ) if store._data_processor is None: @@ -2540,7 +2573,7 @@ def add_timestamp_field( result_ds, feature_df, join_keys, - timestamp_field, + join_timestamp_field, requested_feats, full_feature_names, fv.projection.name_to_use(), @@ -2553,7 +2586,7 @@ def add_timestamp_field( f"Using distributed join for {fv.name} (size: {feature_size // 1024**2}MB)" ) feature_ds = ensure_timestamp_compatibility( - feature_ds, [timestamp_field] + feature_ds, [join_timestamp_field] ) if store._data_processor is None: @@ -2562,7 +2595,7 @@ def add_timestamp_field( result_ds, feature_ds, join_keys, - timestamp_field, + join_timestamp_field, requested_feats, window_size=config.offline_store.window_size_for_joins, full_feature_names=full_feature_names, @@ -2572,6 +2605,24 @@ def add_timestamp_field( else None, ) + if join_timestamp_field != timestamp_field: + + def drop_join_timestamp_field( + batch: pd.DataFrame, + join_timestamp_field: str = join_timestamp_field, + ) -> pd.DataFrame: + return batch.drop(columns=[join_timestamp_field], errors="ignore") + + result_ds = result_ds.map_batches( + drop_join_timestamp_field, batch_format="pandas" + ) + + added_columns.add(timestamp_field) + added_columns.update( + f"{fv.projection.name_to_use()}__{feat}" if full_feature_names else feat + for feat in requested_feats + ) + def finalize_result(batch: pd.DataFrame) -> pd.DataFrame: batch = batch.copy() diff --git a/sdk/python/tests/component/ray/test_ray_timestamp_field_collision.py b/sdk/python/tests/component/ray/test_ray_timestamp_field_collision.py new file mode 100644 index 00000000000..7d7a7385b03 --- /dev/null +++ b/sdk/python/tests/component/ray/test_ray_timestamp_field_collision.py @@ -0,0 +1,140 @@ +"""Ray offline store: request columns named like the source timestamp field. + +The entity dataframe can hold request data in a column that has the same name +as a feature view's source timestamp field. That column is not the event +timestamp, so retrieval must not use it as the point-in-time cutoff, and it +must come back unchanged, whatever its type. +""" + +from datetime import timedelta +from pathlib import Path + +import pandas as pd +import pytest + +from feast import Entity, FeatureStore, FeatureView, Field, FileSource, RepoConfig +from feast.infra.ray_initializer import shutdown_ray +from feast.types import Int64 +from feast.value_type import ValueType + + +@pytest.fixture(autouse=True) +def fresh_ray(): + shutdown_ray() + yield + shutdown_ray() + + +def _feature_store(repo: Path, with_driver_2: bool = True) -> FeatureStore: + # Driver 1 has 10, 20 and 30 on 1, 2 and 3 Jan; driver 2 has 40 on 1 Jan. + trips_df = pd.DataFrame( + { + "driver_id": [1, 1, 1, 2], + "ts": pd.to_datetime( + ["2024-01-01", "2024-01-02", "2024-01-03", "2024-01-01"], utc=True + ), + "trips": [10, 20, 30, 40], + } + ) + if not with_driver_2: + # With one driver the source timestamps stay sorted after sorting by + # driver, so the broadcast join uses merge_asof instead of falling + # back to its row-by-row join. + trips_df = trips_df[trips_df["driver_id"] == 1] + trips_df.to_parquet(repo / "trips.parquet") + driver = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) + trips = FeatureView( + name="driver_trips", + entities=[driver], + schema=[Field(name="trips", dtype=Int64)], + source=FileSource(path=str(repo / "trips.parquet"), timestamp_field="ts"), + ttl=timedelta(days=7), + ) + store = FeatureStore( + config=RepoConfig( + project="ray_timestamp_field_collision", + provider="local", + registry=str(repo / "registry.db"), + offline_store={"type": "ray", "storage_path": str(repo / "ray_storage")}, + online_store={"type": "sqlite", "path": str(repo / "online.db")}, + entity_key_serialization_version=3, + repo_path=str(repo), + ) + ) + store.apply([driver, trips]) + return store + + +@pytest.mark.parametrize( + "request_values", + [ + pd.to_datetime( + ["2024-01-10 00:00", "2023-12-25 00:00", "2024-01-02 06:00"], utc=True + ), + pd.Series([1, 2, 3], dtype="int64"), + pd.Series(["a", "2024-01-05", ""], dtype=object), + ], + ids=["datetime", "int", "string"], +) +@pytest.mark.parametrize("full_feature_names", [False, True], ids=lambda v: str(v)) +def test_request_column_named_like_timestamp_field( + tmp_path, request_values, full_feature_names +): + store = _feature_store(tmp_path) + entity_df = pd.DataFrame( + { + "driver_id": [1, 1, 2], + "event_timestamp": pd.to_datetime( + ["2024-01-02 12:00", "2024-01-02 13:00", "2024-01-02 12:00"], utc=True + ), + "ts": list(request_values), + "request_id": [1, 2, 3], + } + ) + + result = store.get_historical_features( + entity_df=entity_df, + features=["driver_trips:trips"], + full_feature_names=full_feature_names, + ).to_df() + + feature = "driver_trips__trips" if full_feature_names else "trips" + assert set(result.columns) == set(entity_df.columns) | {feature} + result = result.sort_values("request_id").reset_index(drop=True) + # The latest value at or before each event timestamp. + assert result[feature].tolist() == [20, 20, 40] + # The request column comes back unchanged. + assert result["ts"].tolist() == entity_df["ts"].tolist() + + +@pytest.mark.parametrize( + "with_colliding_column", [True, False], ids=["colliding-ts", "no-collision"] +) +def test_requests_sharing_entity_and_event_timestamp_are_all_kept( + tmp_path, with_colliding_column +): + store = _feature_store(tmp_path, with_driver_2=False) + entity_df = pd.DataFrame( + { + "driver_id": [1, 1], + "event_timestamp": pd.to_datetime( + ["2024-01-02 12:00", "2024-01-02 12:00"], utc=True + ), + "request_id": [101, 102], + } + ) + if with_colliding_column: + # Different request values in the column named like the source timestamp. + entity_df["ts"] = pd.to_datetime(["2024-01-02", "2024-01-04"], utc=True) + + result = store.get_historical_features( + entity_df=entity_df, features=["driver_trips:trips"] + ).to_df() + + result = result.sort_values("request_id").reset_index(drop=True) + # Each row is its own request, so both come back, each with the latest value + # at or before its event timestamp. + assert result["request_id"].tolist() == [101, 102] + assert result["trips"].tolist() == [20, 20] + if with_colliding_column: + assert result["ts"].tolist() == entity_df["ts"].tolist() diff --git a/sdk/python/tests/integration/offline_store/test_universal_historical_retrieval.py b/sdk/python/tests/integration/offline_store/test_universal_historical_retrieval.py index d4b8ef269d8..9695744a6e3 100644 --- a/sdk/python/tests/integration/offline_store/test_universal_historical_retrieval.py +++ b/sdk/python/tests/integration/offline_store/test_universal_historical_retrieval.py @@ -1146,15 +1146,8 @@ def test_historical_features_filter_by_created_timestamp(environment): @pytest.mark.universal_offline_stores @pytest.mark.parametrize("full_feature_names", [True, False], ids=lambda v: str(v)) def test_historical_features_with_request_column_named_like_timestamp_field( - request, environment, full_feature_names + environment, full_feature_names ): - if environment.data_source_creator.__class__.__name__ == "RayDataSourceCreator": - request.applymarker( - pytest.mark.xfail( - reason="Ray uses the request column as the cutoff: https://github.com/feast-dev/feast/issues/7190", - strict=True, - ) - ) store = environment.feature_store now = datetime.now().replace(microsecond=0, second=0, minute=0)