Skip to content

Commit 32e27d0

Browse files
committed
fix: Tell entity rows apart by a row id in local historical retrieval
Two entity rows can share their join keys and timestamp. The dedup node kept one of them and the aggregation node summed both into one row, and a feature view without entities had no key to join on, so the join raised. Number the entity rows when entity_df is joined, as the Flink engine does, and use that id to dedup, to group and to join already joined inputs. A view without entities is cross joined with entity_df. The id is dropped from the output. Signed-off-by: Edson <zhuoxi2000@gmail.com>
1 parent cc0fa4b commit 32e27d0

2 files changed

Lines changed: 141 additions & 23 deletions

File tree

‎sdk/python/feast/infra/compute_engines/local/nodes.py‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from feast.infra.compute_engines.local.arrow_table_value import ArrowTableValue
1515
from feast.infra.compute_engines.local.local_node import LocalNode
1616
from feast.infra.compute_engines.utils import (
17+
ENTITY_ROW_ID,
1718
ENTITY_TS_ALIAS,
1819
create_offline_store_retrieval_job,
1920
infer_entity_timestamp_column,
@@ -84,8 +85,12 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue:
8485
joined_df = self.backend.from_arrow(input_values[0].data)
8586
# Upstream views that were already joined with entity_df carry one
8687
# row per entity row; keep those rows apart and do not join again.
87-
already_joined = ENTITY_TS_ALIAS in self.backend.columns(joined_df)
88-
input_join_keys = [*join_keys, ENTITY_TS_ALIAS] if already_joined else join_keys
88+
columns = self.backend.columns(joined_df)
89+
already_joined = ENTITY_TS_ALIAS in columns
90+
input_join_keys = [
91+
*join_keys,
92+
*(key for key in (ENTITY_TS_ALIAS, ENTITY_ROW_ID) if key in columns),
93+
]
8994
for val in input_values[1:]:
9095
next_df = self.backend.from_arrow(val.data)
9196
joined_df = self.backend.join(
@@ -97,7 +102,15 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue:
97102

98103
# If entity_df is provided, join it in last
99104
if context.entity_df is not None and not already_joined:
100-
entity_df = self.backend.from_arrow(pa.Table.from_pandas(context.entity_df))
105+
# Number the entity rows. Two of them can share their join keys
106+
# and timestamp, and each is still a request of its own.
107+
entity_df = self.backend.from_arrow(
108+
pa.Table.from_pandas(
109+
context.entity_df.assign(
110+
**{ENTITY_ROW_ID: range(len(context.entity_df))}
111+
)
112+
)
113+
)
101114

102115
entity_schema = dict(zip(entity_df.columns, entity_df.dtypes))
103116
entity_ts_col = infer_entity_timestamp_column(entity_schema)
@@ -107,11 +120,14 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue:
107120
entity_df, {entity_ts_col: ENTITY_TS_ALIAS}
108121
)
109122

123+
# A view without entities has no join keys: every feature row is
124+
# a candidate for every entity row, and the filter node picks the
125+
# ones inside the point-in-time and TTL bounds.
110126
joined_df = self.backend.join(
111127
entity_df,
112128
joined_df,
113-
on=join_keys,
114-
how="left",
129+
on=join_keys or None,
130+
how="left" if join_keys else "cross",
115131
)
116132

117133
result = self.backend.to_arrow(joined_df)
@@ -182,10 +198,12 @@ def __init__(
182198
def execute(self, context: ExecutionContext) -> ArrowTableValue:
183199
input_table = self.get_single_table(context).data
184200
df = self.backend.from_arrow(input_table)
185-
group_keys = list(self.group_keys)
186201
# Aggregate per entity row after the entity_df join.
187-
if ENTITY_TS_ALIAS in self.backend.columns(df):
188-
group_keys.append(ENTITY_TS_ALIAS)
202+
columns = self.backend.columns(df)
203+
group_keys = [
204+
*self.group_keys,
205+
*(key for key in (ENTITY_TS_ALIAS, ENTITY_ROW_ID) if key in columns),
206+
]
189207
grouped_df = self.backend.groupby_agg(df, group_keys, self.agg_ops)
190208
result = self.backend.to_arrow(grouped_df)
191209
output = ArrowTableValue(result)
@@ -210,11 +228,14 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue:
210228
# names so we look up the columns that the source-read node has
211229
# already renamed (see issue #5942).
212230
dedup_keys = list(self.column_info.join_keys_columns)
231+
# Keep one row per entity row, not per entity key, after the
232+
# entity_df join.
233+
columns = self.backend.columns(df)
234+
if ENTITY_ROW_ID in columns:
235+
dedup_keys = [ENTITY_ROW_ID]
236+
elif dedup_keys and ENTITY_TS_ALIAS in columns:
237+
dedup_keys.append(ENTITY_TS_ALIAS)
213238
if dedup_keys:
214-
# Keep one row per entity row, not per entity key, after the
215-
# entity_df join.
216-
if ENTITY_TS_ALIAS in self.backend.columns(df):
217-
dedup_keys.append(ENTITY_TS_ALIAS)
218239
sort_keys = [self.column_info.timestamp_column]
219240
if (
220241
self.column_info.created_timestamp_column
@@ -380,6 +401,9 @@ def __init__(
380401

381402
def execute(self, context: ExecutionContext) -> ArrowTableValue:
382403
input_table = self.get_single_table(context).data
404+
# The row id only tells the entity rows apart while the plan runs.
405+
if ENTITY_ROW_ID in input_table.column_names:
406+
input_table = input_table.drop_columns([ENTITY_ROW_ID])
383407
output = ArrowTableValue(data=input_table)
384408
context.node_outputs[self.name] = output
385409

‎sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py‎

Lines changed: 105 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from unittest.mock import MagicMock
33

44
import pandas as pd
5+
import pytest
56

67
from feast import (
78
Aggregation,
@@ -12,12 +13,14 @@
1213
RepoConfig,
1314
ValueType,
1415
)
16+
from feast.feature_view import DUMMY_ENTITY
1517
from feast.infra.common.retrieval_task import HistoricalRetrievalTask
1618
from feast.infra.compute_engines.base import ComputeEngine
1719
from feast.infra.compute_engines.local.compute import (
1820
LocalComputeEngine,
1921
LocalComputeEngineConfig,
2022
)
23+
from feast.infra.compute_engines.utils import ENTITY_ROW_ID
2124
from feast.infra.offline_stores.dask import DaskOfflineStore, DaskOfflineStoreConfig
2225
from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig
2326
from feast.types import Float32, Int64
@@ -111,7 +114,11 @@ def _source_view(self, tmp_path):
111114
offline=False,
112115
)
113116

114-
def _get_historical_features(self, tmp_path, feature_view):
117+
def _get_historical_features(
118+
self, tmp_path, feature_view, entity_df=None, entity=None, backend="pandas"
119+
):
120+
if backend == "polars":
121+
pytest.importorskip("polars")
115122
repo_config = RepoConfig(
116123
project="test_local_engine",
117124
registry=str(tmp_path / "registry.db"),
@@ -124,21 +131,23 @@ def _get_historical_features(self, tmp_path, feature_view):
124131
repo_config=repo_config,
125132
offline_store=DaskOfflineStore(),
126133
online_store=MagicMock(),
134+
backend=backend,
127135
)
128136

129137
# Driver 1 is requested twice: before and after its second feature
130138
# row. Driver 2 is not requested at all.
131-
entity_df = pd.DataFrame(
132-
{
133-
"driver_id": [1, 1],
134-
"event_timestamp": [
135-
self.t0 + timedelta(hours=1),
136-
self.t0 + timedelta(hours=3),
137-
],
138-
}
139-
)
139+
if entity_df is None:
140+
entity_df = pd.DataFrame(
141+
{
142+
"driver_id": [1, 1],
143+
"event_timestamp": [
144+
self.t0 + timedelta(hours=1),
145+
self.t0 + timedelta(hours=3),
146+
],
147+
}
148+
)
140149
registry = MagicMock()
141-
registry.get_entity.return_value = self.driver
150+
registry.get_entity.return_value = entity or self.driver
142151
task = HistoricalRetrievalTask(
143152
project="test_local_engine",
144153
entity_df=entity_df,
@@ -153,6 +162,7 @@ def test_get_historical_features_is_point_in_time_per_entity_row(self, tmp_path)
153162

154163
assert sorted(df["driver_id"].to_list()) == [1, 1]
155164
assert sorted(round(v, 6) for v in df["conv_rate"].to_list()) == [0.1, 0.9]
165+
assert ENTITY_ROW_ID not in df.columns
156166

157167
def test_get_historical_features_for_derived_view(self, tmp_path):
158168
derived = BatchFeatureView(
@@ -196,3 +206,87 @@ def test_get_historical_features_aggregates_per_entity_row(self, tmp_path):
196206

197207
assert sorted(df["driver_id"].to_list()) == [1, 1]
198208
assert sorted(round(v, 6) for v in df["sum_conv_rate"].to_list()) == [0.1, 1.0]
209+
210+
def _same_request_twice(self):
211+
"""Two entity rows with the same driver and timestamp, told apart by a label."""
212+
return pd.DataFrame(
213+
{
214+
"driver_id": [1, 1],
215+
"event_timestamp": [self.t0 + timedelta(hours=1)] * 2,
216+
"label": ["a", "b"],
217+
}
218+
)
219+
220+
@pytest.mark.parametrize("backend", ["pandas", "polars"])
221+
def test_get_historical_features_keeps_entity_rows_with_the_same_key_and_time(
222+
self, tmp_path, backend
223+
):
224+
df = self._get_historical_features(
225+
tmp_path,
226+
self._source_view(tmp_path),
227+
self._same_request_twice(),
228+
backend=backend,
229+
)
230+
231+
assert sorted(df["label"].to_list()) == ["a", "b"]
232+
assert [round(v, 6) for v in df["conv_rate"].to_list()] == [0.1, 0.1]
233+
234+
@pytest.mark.parametrize("backend", ["pandas", "polars"])
235+
def test_get_historical_features_aggregates_entity_rows_with_the_same_key_and_time(
236+
self, tmp_path, backend
237+
):
238+
driver_id = Entity(
239+
name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64
240+
)
241+
aggregated = BatchFeatureView(
242+
name="driver_stats_sum",
243+
entities=[driver_id],
244+
mode="pandas",
245+
schema=self.schema,
246+
source=self._source_view(tmp_path).batch_source,
247+
aggregations=[Aggregation(column="conv_rate", function="sum")],
248+
ttl=timedelta(days=1),
249+
online=False,
250+
offline=False,
251+
)
252+
253+
df = self._get_historical_features(
254+
tmp_path, aggregated, self._same_request_twice(), backend=backend
255+
)
256+
257+
assert [round(v, 6) for v in df["sum_conv_rate"].to_list()] == [0.1, 0.1]
258+
assert ENTITY_ROW_ID not in df.columns
259+
260+
@pytest.mark.parametrize("backend", ["pandas", "polars"])
261+
def test_get_historical_features_for_view_without_entities(self, tmp_path, backend):
262+
source_path = str(tmp_path / "global_stats.parquet")
263+
pd.DataFrame(
264+
{
265+
"conv_rate": [0.1, 0.9],
266+
"event_timestamp": [self.t0, self.t0 + timedelta(hours=2)],
267+
}
268+
).to_parquet(source_path)
269+
global_view = BatchFeatureView(
270+
name="global_stats",
271+
entities=[],
272+
mode="pandas",
273+
schema=[Field(name="conv_rate", dtype=Float32)],
274+
source=FileSource(path=source_path, timestamp_field="event_timestamp"),
275+
ttl=timedelta(days=1),
276+
online=False,
277+
offline=False,
278+
)
279+
entity_df = pd.DataFrame(
280+
{
281+
"event_timestamp": [
282+
self.t0 + timedelta(hours=1),
283+
self.t0 + timedelta(hours=3),
284+
]
285+
}
286+
)
287+
288+
df = self._get_historical_features(
289+
tmp_path, global_view, entity_df, entity=DUMMY_ENTITY, backend=backend
290+
)
291+
292+
assert sorted(round(v, 6) for v in df["conv_rate"].to_list()) == [0.1, 0.9]

0 commit comments

Comments
 (0)