Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 33 additions & 12 deletions sdk/python/feast/infra/offline_stores/dask.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the new universal case fails in Ray CI in both feature-name modes: expected [20, 20, 40], actual [30.0, nan, 40.0]. Ray uses the request's feature_timestamp as the cutoff when that column exists, so the first result comes from after event_timestamp. this exposes an existing Ray bug, but leaves the new suite red. we need to fix that path or narrowly mark this known Ray failure with a tracked issue while preserving the file-store assertions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! I checked it, and the Ray failure isn't caused by this PR. Running the new test on master without the Dask change, Ray gives the same [30.0, nan, 40.0] (Ray 2.58.0), and 0.68.0 does the same. I've opened #7190 for it.

In 796e6b1 I marked only the Ray case as a known failure (xfail(strict=True), linking #7190), so the file-store and DuckDB assertions are unchanged, and the test will turn red again once Ray is fixed, as a reminder to remove the mark. The Ray offline suite now gives 52 passed, 2 xfailed, 4 skipped (CI had 52 passed, 2 failed).

I'm happy to fix the Ray path in a follow-up PR.

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"])
Original file line number Diff line number Diff line change
@@ -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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these cases exercise the public API but hard-code the file store, so they do not check the retrieval contract across the universal store matrix. the component rule requires a universal integration regression when retrieval behavior changes. we need to add the timestamp-name collision to test_universal_historical_retrieval.py using its source/store fixtures, checking the latest eligible feature value and unchanged request columns with both feature-name modes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in bb0ca85: test_historical_features_with_request_column_named_like_timestamp_field in test_universal_historical_retrieval.py, using its source and store fixtures. The source's timestamp_field is feature_timestamp, and the entity dataframe has its own feature_timestamp request column (later than, earlier than and between the source rows). The test checks the latest eligible feature value for each request and that the request columns come back unchanged, with and without full feature names. Without the fix it fails on the file store (the request column is dropped and feature_timestamp__ is added); with it, it passes on the file and DuckDB stores.


@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)
Loading