Skip to content

Commit 42ed604

Browse files
authored
fix: Keep the source event timestamp separate from request data in Dask retrieval (#7177)
* fix: Keep the source event timestamp separate from request data in Dask retrieval When the entity dataframe had a column named like a feature view's source timestamp_field, the merge suffixed the source column, so the TTL filter, the created-timestamp cutoff, deduplication and the column drop read the request's column instead. Features came back missing or from after the event timestamp, the request column was dropped, non-timestamp values raised, and a request with both ts and ts__ failed or kept allocating memory. Keep the source timestamp under an unused temporary name, as #7071 does for the created timestamp column. Signed-off-by: Manoj Kumar Thapa <iammanoj807@gmail.com> * test: Cover request columns named like the source timestamp field in universal retrieval Signed-off-by: Manoj Kumar Thapa <iammanoj807@gmail.com> * test: Mark the Ray case of the timestamp field collision test as a known failure The Ray offline store uses an entity dataframe column named like the source timestamp field as the point-in-time cutoff (#7190). Mark only the Ray case as a strict xfail so the file and DuckDB assertions still run. Signed-off-by: Manoj Kumar Thapa <iammanoj807@gmail.com> --------- Signed-off-by: Manoj Kumar Thapa <iammanoj807@gmail.com>
1 parent 439b131 commit 42ed604

3 files changed

Lines changed: 295 additions & 12 deletions

File tree

‎sdk/python/feast/infra/offline_stores/dask.py‎

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -300,23 +300,28 @@ def evaluate_historical_retrieval():
300300
full_feature_names,
301301
)
302302

303-
# Keep the source created timestamp separate from request data.
304-
# Otherwise the merge suffixes the source column, so the cutoff
305-
# and deduplication read the entity column instead.
303+
# Keep the source timestamps separate from request data.
304+
# Otherwise the merge suffixes the source columns, so the TTL
305+
# filter, the cutoff and deduplication read the entity columns
306+
# instead.
307+
if timestamp_field in entity_df_with_features.columns:
308+
source_timestamp_field = _unused_column_name(
309+
timestamp_field, entity_df_with_features, df_to_join, features
310+
)
311+
df_to_join = df_to_join.rename(
312+
columns={timestamp_field: source_timestamp_field}
313+
)
314+
timestamp_field = source_timestamp_field
306315
if (
307316
created_timestamp_column
308317
and created_timestamp_column in entity_df_with_features.columns
309318
):
310-
source_created_timestamp_column = f"__{created_timestamp_column}"
311-
existing_columns = (
312-
set(entity_df_with_features.columns)
313-
| set(df_to_join.columns)
314-
| set(features)
319+
source_created_timestamp_column = _unused_column_name(
320+
created_timestamp_column,
321+
entity_df_with_features,
322+
df_to_join,
323+
features,
315324
)
316-
while source_created_timestamp_column in existing_columns:
317-
source_created_timestamp_column = (
318-
f"_{source_created_timestamp_column}"
319-
)
320325
df_to_join = df_to_join.rename(
321326
columns={
322327
created_timestamp_column: source_created_timestamp_column
@@ -1141,6 +1146,22 @@ def _field_mapping(
11411146
return df_to_join.persist(), timestamp_field
11421147

11431148

1149+
def _unused_column_name(
1150+
column: str,
1151+
entity_df_with_features: dd.DataFrame,
1152+
df_to_join: dd.DataFrame,
1153+
features: List[str],
1154+
) -> str:
1155+
"""Return a temporary name for a source column that collides with request data."""
1156+
existing_columns = (
1157+
set(entity_df_with_features.columns) | set(df_to_join.columns) | set(features)
1158+
)
1159+
name = f"__{column}"
1160+
while name in existing_columns:
1161+
name = f"_{name}"
1162+
return name
1163+
1164+
11441165
def _merge(
11451166
entity_df_with_features: dd.DataFrame,
11461167
df_to_join: dd.DataFrame,

‎sdk/python/tests/integration/offline_store/test_universal_historical_retrieval.py‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1140,3 +1140,117 @@ def test_historical_features_filter_by_created_timestamp(environment):
11401140
]
11411141
)
11421142
validate_dataframes(expected_df, actual_df, sort_by=["driver_id"])
1143+
1144+
1145+
@pytest.mark.integration
1146+
@pytest.mark.universal_offline_stores
1147+
@pytest.mark.parametrize("full_feature_names", [True, False], ids=lambda v: str(v))
1148+
def test_historical_features_with_request_column_named_like_timestamp_field(
1149+
request, environment, full_feature_names
1150+
):
1151+
if environment.data_source_creator.__class__.__name__ == "RayDataSourceCreator":
1152+
request.applymarker(
1153+
pytest.mark.xfail(
1154+
reason="Ray uses the request column as the cutoff: https://github.com/feast-dev/feast/issues/7190",
1155+
strict=True,
1156+
)
1157+
)
1158+
store = environment.feature_store
1159+
1160+
now = datetime.now().replace(microsecond=0, second=0, minute=0)
1161+
yesterday = now - timedelta(days=1)
1162+
tomorrow = now + timedelta(days=1)
1163+
1164+
# The source's timestamp field is "feature_timestamp". The entity
1165+
# dataframe has its own column with that name, which is request data and
1166+
# not its event timestamp.
1167+
trips_df = pd.DataFrame(
1168+
data=[
1169+
{
1170+
"driver_id": 1001,
1171+
"trips": 10,
1172+
"feature_timestamp": now - timedelta(days=2),
1173+
},
1174+
{"driver_id": 1001, "trips": 20, "feature_timestamp": yesterday},
1175+
{"driver_id": 1001, "trips": 30, "feature_timestamp": tomorrow},
1176+
{"driver_id": 1002, "trips": 40, "feature_timestamp": yesterday},
1177+
]
1178+
)
1179+
trips_df["created"] = trips_df["feature_timestamp"]
1180+
entity_df = pd.DataFrame(
1181+
data=[
1182+
{
1183+
"driver_id": 1001,
1184+
"event_timestamp": now,
1185+
# Later than every source row.
1186+
"feature_timestamp": now + timedelta(days=3),
1187+
"request_id": 1,
1188+
},
1189+
{
1190+
"driver_id": 1001,
1191+
"event_timestamp": now - timedelta(hours=1),
1192+
# Earlier than every source row.
1193+
"feature_timestamp": now - timedelta(days=5),
1194+
"request_id": 2,
1195+
},
1196+
{
1197+
"driver_id": 1002,
1198+
"event_timestamp": now,
1199+
# Between the source rows.
1200+
"feature_timestamp": now - timedelta(hours=12),
1201+
"request_id": 3,
1202+
},
1203+
]
1204+
)
1205+
1206+
trips_source = environment.data_source_creator.create_data_source(
1207+
df=trips_df,
1208+
destination_name=f"test_driver_trips_{int(time.time_ns())}_{random.randint(1000, 9999)}",
1209+
timestamp_field="feature_timestamp",
1210+
created_timestamp_column="created",
1211+
)
1212+
driver = Entity(name="driver", join_keys=["driver_id"])
1213+
trips_fv = FeatureView(
1214+
name="driver_trips",
1215+
entities=[driver],
1216+
schema=[Field(name="trips", dtype=Int32)],
1217+
source=trips_source,
1218+
)
1219+
store.apply([driver, trips_fv])
1220+
1221+
actual_df = store.get_historical_features(
1222+
entity_df=entity_df,
1223+
features=["driver_trips:trips"],
1224+
full_feature_names=full_feature_names,
1225+
).to_df()
1226+
1227+
feature_name = "driver_trips__trips" if full_feature_names else "trips"
1228+
# The request column comes back unchanged and nothing else is added.
1229+
assert set(actual_df.columns) == set(entity_df.columns) | {feature_name}
1230+
actual_df["feature_timestamp"] = pd.to_datetime(
1231+
actual_df["feature_timestamp"], utc=True
1232+
)
1233+
expected_df = pd.DataFrame(
1234+
data=[
1235+
{
1236+
"request_id": 1,
1237+
"feature_timestamp": now + timedelta(days=3),
1238+
feature_name: 20,
1239+
},
1240+
{
1241+
"request_id": 2,
1242+
"feature_timestamp": now - timedelta(days=5),
1243+
feature_name: 20,
1244+
},
1245+
{
1246+
"request_id": 3,
1247+
"feature_timestamp": now - timedelta(hours=12),
1248+
feature_name: 40,
1249+
},
1250+
]
1251+
)
1252+
expected_df["feature_timestamp"] = pd.to_datetime(
1253+
expected_df["feature_timestamp"], utc=True
1254+
)
1255+
1256+
validate_dataframes(expected_df, actual_df, sort_by=["request_id"])
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
from __future__ import annotations
2+
3+
from datetime import timedelta
4+
from pathlib import Path
5+
6+
import pandas as pd
7+
import pytest
8+
from pandas.testing import assert_frame_equal
9+
10+
from feast import Entity, FeatureStore, FeatureView, Field, FileSource, RepoConfig
11+
from feast.types import Int64, ValueType
12+
13+
14+
def _store(tmp_path: Path, timestamp_fields: dict[str, str]) -> FeatureStore:
15+
entity = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64)
16+
feature_views = []
17+
for name, timestamp_field in timestamp_fields.items():
18+
source_path = tmp_path / f"{name}.parquet"
19+
pd.DataFrame(
20+
{
21+
"driver_id": [1, 1, 1],
22+
timestamp_field: pd.to_datetime(
23+
[
24+
"2025-01-01T00:00:00Z",
25+
"2025-01-02T00:00:00Z",
26+
"2025-01-03T00:00:00Z",
27+
]
28+
),
29+
name: [10, 20, 30],
30+
}
31+
).to_parquet(source_path, index=False)
32+
feature_views.append(
33+
FeatureView(
34+
name=f"{name}_view",
35+
entities=[entity],
36+
schema=[
37+
Field(name="driver_id", dtype=Int64),
38+
Field(name=name, dtype=Int64),
39+
],
40+
source=FileSource(
41+
path=str(source_path), timestamp_field=timestamp_field
42+
),
43+
ttl=timedelta(days=7),
44+
)
45+
)
46+
store = FeatureStore(
47+
config=RepoConfig(
48+
project="timestamp_collision",
49+
provider="local",
50+
registry=str(tmp_path / "registry.db"),
51+
online_store={"type": "sqlite", "path": str(tmp_path / "online.db")},
52+
offline_store={"type": "file"},
53+
repo_path=tmp_path,
54+
)
55+
)
56+
store.apply([entity, *feature_views])
57+
return store
58+
59+
60+
@pytest.mark.parametrize("full_feature_names", [False, True])
61+
@pytest.mark.parametrize("filter_by_created_timestamp", [False, True])
62+
@pytest.mark.parametrize(
63+
"request_value",
64+
[
65+
pd.Timestamp("2025-01-10T00:00:00Z"),
66+
pd.Timestamp("2024-12-25T00:00:00Z"),
67+
pd.Timestamp("2025-01-02T01:00:00Z"),
68+
"not a timestamp",
69+
7,
70+
],
71+
ids=["later", "earlier", "between-rows", "string", "integer"],
72+
)
73+
def test_request_column_named_like_source_timestamp_field(
74+
tmp_path: Path,
75+
request_value: object,
76+
filter_by_created_timestamp: bool,
77+
full_feature_names: bool,
78+
) -> None:
79+
store = _store(tmp_path, {"trips": "feature_timestamp"})
80+
requests = pd.DataFrame(
81+
{
82+
"driver_id": [1],
83+
"event_timestamp": pd.to_datetime(["2025-01-02T12:00:00Z"]),
84+
# Request data that shares the source timestamp name, plus the
85+
# names a temporary alias would take.
86+
"feature_timestamp": [request_value],
87+
"__feature_timestamp": ["request label"],
88+
"___feature_timestamp": ["another label"],
89+
}
90+
)
91+
original = requests.copy(deep=True)
92+
93+
result = store.get_historical_features(
94+
entity_df=requests,
95+
features=["trips_view:trips"],
96+
filter_by_created_timestamp=filter_by_created_timestamp,
97+
full_feature_names=full_feature_names,
98+
).to_df()
99+
100+
feature_column = "trips_view__trips" if full_feature_names else "trips"
101+
assert result[feature_column].astype("float64").tolist() == [20]
102+
assert set(result.columns) == set(requests.columns) | {feature_column}
103+
assert_frame_equal(result[requests.columns], original)
104+
assert_frame_equal(requests, original)
105+
106+
107+
def test_request_timestamp_alias_does_not_collide_with_request_data(
108+
tmp_path: Path,
109+
) -> None:
110+
store = _store(tmp_path, {"trips": "event_timestamp"})
111+
requests = pd.DataFrame(
112+
{
113+
"driver_id": [1],
114+
"event_timestamp": pd.to_datetime(["2025-01-02T12:00:00Z"]),
115+
"__event_timestamp": pd.to_datetime(["2025-01-10T00:00:00Z"]),
116+
}
117+
)
118+
original = requests.copy(deep=True)
119+
120+
result = store.get_historical_features(
121+
entity_df=requests, features=["trips_view:trips"]
122+
).to_df()
123+
124+
assert result["trips"].astype("float64").tolist() == [20]
125+
assert set(result.columns) == set(requests.columns) | {"trips"}
126+
assert_frame_equal(result[requests.columns], original)
127+
128+
129+
def test_feature_views_sharing_a_colliding_timestamp_field(tmp_path: Path) -> None:
130+
store = _store(tmp_path, {"trips": "ts", "rating": "ts"})
131+
requests = pd.DataFrame(
132+
{
133+
"driver_id": [1],
134+
"event_timestamp": pd.to_datetime(["2025-01-02T12:00:00Z"]),
135+
"ts": pd.to_datetime(["2025-01-10T00:00:00Z"]),
136+
"ts__": pd.to_datetime(["2024-12-25T00:00:00Z"]),
137+
}
138+
)
139+
original = requests.copy(deep=True)
140+
141+
result = store.get_historical_features(
142+
entity_df=requests, features=["trips_view:trips", "rating_view:rating"]
143+
).to_df()
144+
145+
assert result["trips"].astype("float64").tolist() == [20]
146+
assert result["rating"].astype("float64").tolist() == [20]
147+
assert set(result.columns) == set(requests.columns) | {"trips", "rating"}
148+
assert_frame_equal(result[requests.columns], original)

0 commit comments

Comments
 (0)