diff --git a/sdk/python/feast/infra/offline_stores/dask.py b/sdk/python/feast/infra/offline_stores/dask.py index 670eab3d737..8ee65de9729 100644 --- a/sdk/python/feast/infra/offline_stores/dask.py +++ b/sdk/python/feast/infra/offline_stores/dask.py @@ -300,23 +300,28 @@ def evaluate_historical_retrieval(): full_feature_names, ) - # Keep the source created timestamp separate from request data. - # Otherwise the merge suffixes the source column, so the cutoff - # and deduplication read the entity column instead. + # Keep the source timestamps separate from request data. + # Otherwise the merge suffixes the source columns, so the TTL + # filter, the cutoff and deduplication read the entity columns + # instead. + if timestamp_field in entity_df_with_features.columns: + source_timestamp_field = _unused_column_name( + timestamp_field, entity_df_with_features, df_to_join, features + ) + df_to_join = df_to_join.rename( + columns={timestamp_field: source_timestamp_field} + ) + timestamp_field = source_timestamp_field if ( created_timestamp_column and created_timestamp_column in entity_df_with_features.columns ): - source_created_timestamp_column = f"__{created_timestamp_column}" - existing_columns = ( - set(entity_df_with_features.columns) - | set(df_to_join.columns) - | set(features) + source_created_timestamp_column = _unused_column_name( + created_timestamp_column, + entity_df_with_features, + df_to_join, + features, ) - while source_created_timestamp_column in existing_columns: - source_created_timestamp_column = ( - f"_{source_created_timestamp_column}" - ) df_to_join = df_to_join.rename( columns={ created_timestamp_column: source_created_timestamp_column @@ -1141,6 +1146,22 @@ def _field_mapping( return df_to_join.persist(), timestamp_field +def _unused_column_name( + column: str, + entity_df_with_features: dd.DataFrame, + df_to_join: dd.DataFrame, + features: List[str], +) -> str: + """Return a temporary name for a source column that collides with request data.""" + existing_columns = ( + set(entity_df_with_features.columns) | set(df_to_join.columns) | set(features) + ) + name = f"__{column}" + while name in existing_columns: + name = f"_{name}" + return name + + def _merge( entity_df_with_features: dd.DataFrame, df_to_join: dd.DataFrame, 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 90e9e6d4ac8..d4b8ef269d8 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 @@ -1140,3 +1140,117 @@ def test_historical_features_filter_by_created_timestamp(environment): ] ) validate_dataframes(expected_df, actual_df, sort_by=["driver_id"]) + + +@pytest.mark.integration +@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 +): + 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) + yesterday = now - timedelta(days=1) + tomorrow = now + timedelta(days=1) + + # The source's timestamp field is "feature_timestamp". The entity + # dataframe has its own column with that name, which is request data and + # not its event timestamp. + trips_df = pd.DataFrame( + data=[ + { + "driver_id": 1001, + "trips": 10, + "feature_timestamp": now - timedelta(days=2), + }, + {"driver_id": 1001, "trips": 20, "feature_timestamp": yesterday}, + {"driver_id": 1001, "trips": 30, "feature_timestamp": tomorrow}, + {"driver_id": 1002, "trips": 40, "feature_timestamp": yesterday}, + ] + ) + trips_df["created"] = trips_df["feature_timestamp"] + entity_df = pd.DataFrame( + data=[ + { + "driver_id": 1001, + "event_timestamp": now, + # Later than every source row. + "feature_timestamp": now + timedelta(days=3), + "request_id": 1, + }, + { + "driver_id": 1001, + "event_timestamp": now - timedelta(hours=1), + # Earlier than every source row. + "feature_timestamp": now - timedelta(days=5), + "request_id": 2, + }, + { + "driver_id": 1002, + "event_timestamp": now, + # Between the source rows. + "feature_timestamp": now - timedelta(hours=12), + "request_id": 3, + }, + ] + ) + + trips_source = environment.data_source_creator.create_data_source( + df=trips_df, + destination_name=f"test_driver_trips_{int(time.time_ns())}_{random.randint(1000, 9999)}", + timestamp_field="feature_timestamp", + created_timestamp_column="created", + ) + driver = Entity(name="driver", join_keys=["driver_id"]) + trips_fv = FeatureView( + name="driver_trips", + entities=[driver], + schema=[Field(name="trips", dtype=Int32)], + source=trips_source, + ) + store.apply([driver, trips_fv]) + + actual_df = store.get_historical_features( + entity_df=entity_df, + features=["driver_trips:trips"], + full_feature_names=full_feature_names, + ).to_df() + + feature_name = "driver_trips__trips" if full_feature_names else "trips" + # The request column comes back unchanged and nothing else is added. + assert set(actual_df.columns) == set(entity_df.columns) | {feature_name} + actual_df["feature_timestamp"] = pd.to_datetime( + actual_df["feature_timestamp"], utc=True + ) + expected_df = pd.DataFrame( + data=[ + { + "request_id": 1, + "feature_timestamp": now + timedelta(days=3), + feature_name: 20, + }, + { + "request_id": 2, + "feature_timestamp": now - timedelta(days=5), + feature_name: 20, + }, + { + "request_id": 3, + "feature_timestamp": now - timedelta(hours=12), + feature_name: 40, + }, + ] + ) + expected_df["feature_timestamp"] = pd.to_datetime( + expected_df["feature_timestamp"], utc=True + ) + + validate_dataframes(expected_df, actual_df, sort_by=["request_id"]) diff --git a/sdk/python/tests/unit/infra/offline_stores/test_dask_timestamp_field_collision.py b/sdk/python/tests/unit/infra/offline_stores/test_dask_timestamp_field_collision.py new file mode 100644 index 00000000000..309a650c52e --- /dev/null +++ b/sdk/python/tests/unit/infra/offline_stores/test_dask_timestamp_field_collision.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +from datetime import timedelta +from pathlib import Path + +import pandas as pd +import pytest +from pandas.testing import assert_frame_equal + +from feast import Entity, FeatureStore, FeatureView, Field, FileSource, RepoConfig +from feast.types import Int64, ValueType + + +def _store(tmp_path: Path, timestamp_fields: dict[str, str]) -> FeatureStore: + entity = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) + feature_views = [] + for name, timestamp_field in timestamp_fields.items(): + source_path = tmp_path / f"{name}.parquet" + pd.DataFrame( + { + "driver_id": [1, 1, 1], + timestamp_field: pd.to_datetime( + [ + "2025-01-01T00:00:00Z", + "2025-01-02T00:00:00Z", + "2025-01-03T00:00:00Z", + ] + ), + name: [10, 20, 30], + } + ).to_parquet(source_path, index=False) + feature_views.append( + FeatureView( + name=f"{name}_view", + entities=[entity], + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name=name, dtype=Int64), + ], + source=FileSource( + path=str(source_path), timestamp_field=timestamp_field + ), + ttl=timedelta(days=7), + ) + ) + store = FeatureStore( + config=RepoConfig( + project="timestamp_collision", + provider="local", + registry=str(tmp_path / "registry.db"), + online_store={"type": "sqlite", "path": str(tmp_path / "online.db")}, + offline_store={"type": "file"}, + repo_path=tmp_path, + ) + ) + store.apply([entity, *feature_views]) + return store + + +@pytest.mark.parametrize("full_feature_names", [False, True]) +@pytest.mark.parametrize("filter_by_created_timestamp", [False, True]) +@pytest.mark.parametrize( + "request_value", + [ + pd.Timestamp("2025-01-10T00:00:00Z"), + pd.Timestamp("2024-12-25T00:00:00Z"), + pd.Timestamp("2025-01-02T01:00:00Z"), + "not a timestamp", + 7, + ], + ids=["later", "earlier", "between-rows", "string", "integer"], +) +def test_request_column_named_like_source_timestamp_field( + tmp_path: Path, + request_value: object, + filter_by_created_timestamp: bool, + full_feature_names: bool, +) -> None: + store = _store(tmp_path, {"trips": "feature_timestamp"}) + requests = pd.DataFrame( + { + "driver_id": [1], + "event_timestamp": pd.to_datetime(["2025-01-02T12:00:00Z"]), + # Request data that shares the source timestamp name, plus the + # names a temporary alias would take. + "feature_timestamp": [request_value], + "__feature_timestamp": ["request label"], + "___feature_timestamp": ["another label"], + } + ) + original = requests.copy(deep=True) + + result = store.get_historical_features( + entity_df=requests, + features=["trips_view:trips"], + filter_by_created_timestamp=filter_by_created_timestamp, + full_feature_names=full_feature_names, + ).to_df() + + feature_column = "trips_view__trips" if full_feature_names else "trips" + assert result[feature_column].astype("float64").tolist() == [20] + assert set(result.columns) == set(requests.columns) | {feature_column} + assert_frame_equal(result[requests.columns], original) + assert_frame_equal(requests, original) + + +def test_request_timestamp_alias_does_not_collide_with_request_data( + tmp_path: Path, +) -> None: + store = _store(tmp_path, {"trips": "event_timestamp"}) + requests = pd.DataFrame( + { + "driver_id": [1], + "event_timestamp": pd.to_datetime(["2025-01-02T12:00:00Z"]), + "__event_timestamp": pd.to_datetime(["2025-01-10T00:00:00Z"]), + } + ) + original = requests.copy(deep=True) + + result = store.get_historical_features( + entity_df=requests, features=["trips_view:trips"] + ).to_df() + + assert result["trips"].astype("float64").tolist() == [20] + assert set(result.columns) == set(requests.columns) | {"trips"} + assert_frame_equal(result[requests.columns], original) + + +def test_feature_views_sharing_a_colliding_timestamp_field(tmp_path: Path) -> None: + store = _store(tmp_path, {"trips": "ts", "rating": "ts"}) + requests = pd.DataFrame( + { + "driver_id": [1], + "event_timestamp": pd.to_datetime(["2025-01-02T12:00:00Z"]), + "ts": pd.to_datetime(["2025-01-10T00:00:00Z"]), + "ts__": pd.to_datetime(["2024-12-25T00:00:00Z"]), + } + ) + original = requests.copy(deep=True) + + result = store.get_historical_features( + entity_df=requests, features=["trips_view:trips", "rating_view:rating"] + ).to_df() + + assert result["trips"].astype("float64").tolist() == [20] + assert result["rating"].astype("float64").tolist() == [20] + assert set(result.columns) == set(requests.columns) | {"trips", "rating"} + assert_frame_equal(result[requests.columns], original)