From cc0fa4bbe5e1472c7e3dd08ff602621467d9f70b Mon Sep 17 00:00:00 2001 From: Edson Date: Sun, 15 Nov 2026 02:59:15 -0500 Subject: [PATCH 1/5] fix: Join entity_df in local compute engine historical retrieval LocalFeatureBuilder used the base _build, which never joins entity_df for a source-backed view. get_historical_features therefore returned the latest row per join key across the whole source: unrequested entities came back and the point-in-time/TTL filter never ran. Override _build like the Trino and Flink builders and join entity_df after the source (and transformation). Dedup and aggregate on the entity timestamp as well as the entity keys, so an entity requested at several timestamps keeps one row per entity row. LocalJoinNode no longer joins entity_df a second time for a derived view whose inputs already carry it. Signed-off-by: Edson --- .../compute_engines/local/feature_builder.py | 44 +++++- .../infra/compute_engines/local/nodes.py | 20 ++- .../test_local_compute_engine.py | 131 ++++++++++++++++++ 3 files changed, 190 insertions(+), 5 deletions(-) diff --git a/sdk/python/feast/infra/compute_engines/local/feature_builder.py b/sdk/python/feast/infra/compute_engines/local/feature_builder.py index 754a00db76f..210ff4b25dd 100644 --- a/sdk/python/feast/infra/compute_engines/local/feature_builder.py +++ b/sdk/python/feast/infra/compute_engines/local/feature_builder.py @@ -1,10 +1,13 @@ import logging -from typing import Union +from typing import List, Optional, Union + +import pandas as pd from feast.aggregation import aggregation_specs_to_agg_ops from feast.infra.common.materialization_job import MaterializationTask from feast.infra.common.retrieval_task import HistoricalRetrievalTask from feast.infra.compute_engines.backends.base import DataFrameBackend +from feast.infra.compute_engines.dag.node import DAGNode from feast.infra.compute_engines.feature_builder import FeatureBuilder from feast.infra.compute_engines.local.nodes import ( LocalAggregationNode, @@ -32,6 +35,45 @@ def __init__( super().__init__(registry, task.feature_view, task) self.backend = backend + def _should_join_entity_df(self) -> bool: + # LocalJoinNode converts entity_df with pa.Table.from_pandas. + return isinstance(self.task, HistoricalRetrievalTask) and isinstance( + self.task.entity_df, pd.DataFrame + ) + + def _build(self, view, input_nodes: Optional[List[DAGNode]]) -> DAGNode: + # Same steps as FeatureBuilder._build, but a source-backed view is + # joined with entity_df so the filter node can apply the point-in-time + # and TTL bounds per entity row. + if view.data_source: + last_node = self.build_source_node(view) + + if self._should_transform(view): + last_node = self.build_transformation_node(view, [last_node]) + + if self._should_join_entity_df(): + last_node = self.build_join_node(view, [last_node]) + + elif input_nodes: + if self._should_transform(view): + last_node = self.build_transformation_node(view, input_nodes) + else: + last_node = self.build_join_node(view, input_nodes) + else: + raise ValueError(f"FeatureView {view.name} has no valid source or inputs") + + last_node = self.build_filter_node(view, last_node) + + if self._should_aggregate(view): + last_node = self.build_aggregation_node(view, last_node) + elif self._should_dedupe(view): + last_node = self.build_dedup_node(view, last_node) + + if self._should_validate(view): + last_node = self.build_validation_node(view, last_node) + + return last_node + def build_source_node(self, view): start_time = self.task.start_time end_time = self.task.end_time diff --git a/sdk/python/feast/infra/compute_engines/local/nodes.py b/sdk/python/feast/infra/compute_engines/local/nodes.py index 71e78a8380e..7dc601dd499 100644 --- a/sdk/python/feast/infra/compute_engines/local/nodes.py +++ b/sdk/python/feast/infra/compute_engines/local/nodes.py @@ -82,17 +82,21 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue: # Convert all upstream ArrowTables to backend DataFrames joined_df = self.backend.from_arrow(input_values[0].data) + # Upstream views that were already joined with entity_df carry one + # row per entity row; keep those rows apart and do not join again. + already_joined = ENTITY_TS_ALIAS in self.backend.columns(joined_df) + input_join_keys = [*join_keys, ENTITY_TS_ALIAS] if already_joined else join_keys for val in input_values[1:]: next_df = self.backend.from_arrow(val.data) joined_df = self.backend.join( joined_df, next_df, - on=join_keys, + on=input_join_keys, how=self.how, ) # If entity_df is provided, join it in last - if context.entity_df is not None: + if context.entity_df is not None and not already_joined: entity_df = self.backend.from_arrow(pa.Table.from_pandas(context.entity_df)) entity_schema = dict(zip(entity_df.columns, entity_df.dtypes)) @@ -178,7 +182,11 @@ def __init__( def execute(self, context: ExecutionContext) -> ArrowTableValue: input_table = self.get_single_table(context).data df = self.backend.from_arrow(input_table) - grouped_df = self.backend.groupby_agg(df, self.group_keys, self.agg_ops) + group_keys = list(self.group_keys) + # Aggregate per entity row after the entity_df join. + if ENTITY_TS_ALIAS in self.backend.columns(df): + group_keys.append(ENTITY_TS_ALIAS) + grouped_df = self.backend.groupby_agg(df, group_keys, self.agg_ops) result = self.backend.to_arrow(grouped_df) output = ArrowTableValue(result) return output @@ -201,8 +209,12 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue: # Dedup strategy: sort and drop_duplicates. Use the mapped join key # names so we look up the columns that the source-read node has # already renamed (see issue #5942). - dedup_keys = self.column_info.join_keys_columns + dedup_keys = list(self.column_info.join_keys_columns) if dedup_keys: + # Keep one row per entity row, not per entity key, after the + # entity_df join. + if ENTITY_TS_ALIAS in self.backend.columns(df): + dedup_keys.append(ENTITY_TS_ALIAS) sort_keys = [self.column_info.timestamp_column] if ( self.column_info.created_timestamp_column diff --git a/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py b/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py index 3396a45c995..f7ae4662475 100644 --- a/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py +++ b/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py @@ -1,10 +1,26 @@ +from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock +import pandas as pd + +from feast import ( + Aggregation, + BatchFeatureView, + Entity, + Field, + FileSource, + RepoConfig, + ValueType, +) +from feast.infra.common.retrieval_task import HistoricalRetrievalTask from feast.infra.compute_engines.base import ComputeEngine from feast.infra.compute_engines.local.compute import ( LocalComputeEngine, LocalComputeEngineConfig, ) +from feast.infra.offline_stores.dask import DaskOfflineStore, DaskOfflineStoreConfig +from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig +from feast.types import Float32, Int64 class TestLocalComputeEngineConfig: @@ -65,3 +81,118 @@ def test_stores_config(self): assert engine.repo_config is repo_config assert engine.offline_store is offline assert engine.online_store is online + + +class TestLocalComputeEngineHistoricalRetrieval: + t0 = datetime(2026, 1, 1, tzinfo=timezone.utc) + driver = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) + schema = [ + Field(name="driver_id", dtype=Int64), + Field(name="conv_rate", dtype=Float32), + ] + + def _source_view(self, tmp_path): + source_path = str(tmp_path / "driver_stats.parquet") + pd.DataFrame( + { + "driver_id": [1, 1, 2], + "conv_rate": [0.1, 0.9, 0.5], + "event_timestamp": [self.t0, self.t0 + timedelta(hours=2), self.t0], + } + ).to_parquet(source_path) + return BatchFeatureView( + name="driver_stats", + entities=[self.driver], + mode="pandas", + schema=self.schema, + source=FileSource(path=source_path, timestamp_field="event_timestamp"), + ttl=timedelta(days=1), + online=False, + offline=False, + ) + + def _get_historical_features(self, tmp_path, feature_view): + repo_config = RepoConfig( + project="test_local_engine", + registry=str(tmp_path / "registry.db"), + provider="local", + online_store=SqliteOnlineStoreConfig(path=str(tmp_path / "online.db")), + offline_store=DaskOfflineStoreConfig(), + entity_key_serialization_version=3, + ) + engine = LocalComputeEngine( + repo_config=repo_config, + offline_store=DaskOfflineStore(), + online_store=MagicMock(), + ) + + # Driver 1 is requested twice: before and after its second feature + # row. Driver 2 is not requested at all. + entity_df = pd.DataFrame( + { + "driver_id": [1, 1], + "event_timestamp": [ + self.t0 + timedelta(hours=1), + self.t0 + timedelta(hours=3), + ], + } + ) + registry = MagicMock() + registry.get_entity.return_value = self.driver + task = HistoricalRetrievalTask( + project="test_local_engine", + entity_df=entity_df, + feature_view=feature_view, + full_feature_name=False, + registry=registry, + ) + return engine.get_historical_features(registry, task).to_df() + + def test_get_historical_features_is_point_in_time_per_entity_row(self, tmp_path): + df = self._get_historical_features(tmp_path, self._source_view(tmp_path)) + + assert sorted(df["driver_id"].to_list()) == [1, 1] + assert sorted(round(v, 6) for v in df["conv_rate"].to_list()) == [0.1, 0.9] + + def test_get_historical_features_for_derived_view(self, tmp_path): + derived = BatchFeatureView( + name="derived_driver_stats", + entities=[self.driver], + mode="pandas", + schema=self.schema, + source=self._source_view(tmp_path), + sink_source=FileSource( + path=str(tmp_path / "derived.parquet"), + timestamp_field="event_timestamp", + ), + ttl=timedelta(days=1), + online=False, + offline=False, + ) + + df = self._get_historical_features(tmp_path, derived) + + assert sorted(df["driver_id"].to_list()) == [1, 1] + assert sorted(round(v, 6) for v in df["conv_rate"].to_list()) == [0.1, 0.9] + + def test_get_historical_features_aggregates_per_entity_row(self, tmp_path): + source_view = self._source_view(tmp_path) + driver_id = Entity( + name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64 + ) + aggregated = BatchFeatureView( + name="driver_stats_sum", + entities=[driver_id], + mode="pandas", + schema=self.schema, + source=source_view.batch_source, + aggregations=[Aggregation(column="conv_rate", function="sum")], + ttl=timedelta(days=1), + online=False, + offline=False, + ) + + df = self._get_historical_features(tmp_path, aggregated) + + assert sorted(df["driver_id"].to_list()) == [1, 1] + assert sorted(round(v, 6) for v in df["sum_conv_rate"].to_list()) == [0.1, 1.0] From 32e27d05ae4e4f7a9df173e9ea8ebeba02597165 Mon Sep 17 00:00:00 2001 From: Edson Date: Tue, 24 Nov 2026 17:57:35 -0500 Subject: [PATCH 2/5] 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 --- .../infra/compute_engines/local/nodes.py | 48 ++++++-- .../test_local_compute_engine.py | 116 ++++++++++++++++-- 2 files changed, 141 insertions(+), 23 deletions(-) diff --git a/sdk/python/feast/infra/compute_engines/local/nodes.py b/sdk/python/feast/infra/compute_engines/local/nodes.py index 7dc601dd499..508922497bc 100644 --- a/sdk/python/feast/infra/compute_engines/local/nodes.py +++ b/sdk/python/feast/infra/compute_engines/local/nodes.py @@ -14,6 +14,7 @@ from feast.infra.compute_engines.local.arrow_table_value import ArrowTableValue from feast.infra.compute_engines.local.local_node import LocalNode from feast.infra.compute_engines.utils import ( + ENTITY_ROW_ID, ENTITY_TS_ALIAS, create_offline_store_retrieval_job, infer_entity_timestamp_column, @@ -84,8 +85,12 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue: joined_df = self.backend.from_arrow(input_values[0].data) # Upstream views that were already joined with entity_df carry one # row per entity row; keep those rows apart and do not join again. - already_joined = ENTITY_TS_ALIAS in self.backend.columns(joined_df) - input_join_keys = [*join_keys, ENTITY_TS_ALIAS] if already_joined else join_keys + columns = self.backend.columns(joined_df) + already_joined = ENTITY_TS_ALIAS in columns + input_join_keys = [ + *join_keys, + *(key for key in (ENTITY_TS_ALIAS, ENTITY_ROW_ID) if key in columns), + ] for val in input_values[1:]: next_df = self.backend.from_arrow(val.data) joined_df = self.backend.join( @@ -97,7 +102,15 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue: # If entity_df is provided, join it in last if context.entity_df is not None and not already_joined: - entity_df = self.backend.from_arrow(pa.Table.from_pandas(context.entity_df)) + # Number the entity rows. Two of them can share their join keys + # and timestamp, and each is still a request of its own. + entity_df = self.backend.from_arrow( + pa.Table.from_pandas( + context.entity_df.assign( + **{ENTITY_ROW_ID: range(len(context.entity_df))} + ) + ) + ) entity_schema = dict(zip(entity_df.columns, entity_df.dtypes)) entity_ts_col = infer_entity_timestamp_column(entity_schema) @@ -107,11 +120,14 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue: entity_df, {entity_ts_col: ENTITY_TS_ALIAS} ) + # A view without entities has no join keys: every feature row is + # a candidate for every entity row, and the filter node picks the + # ones inside the point-in-time and TTL bounds. joined_df = self.backend.join( entity_df, joined_df, - on=join_keys, - how="left", + on=join_keys or None, + how="left" if join_keys else "cross", ) result = self.backend.to_arrow(joined_df) @@ -182,10 +198,12 @@ def __init__( def execute(self, context: ExecutionContext) -> ArrowTableValue: input_table = self.get_single_table(context).data df = self.backend.from_arrow(input_table) - group_keys = list(self.group_keys) # Aggregate per entity row after the entity_df join. - if ENTITY_TS_ALIAS in self.backend.columns(df): - group_keys.append(ENTITY_TS_ALIAS) + columns = self.backend.columns(df) + group_keys = [ + *self.group_keys, + *(key for key in (ENTITY_TS_ALIAS, ENTITY_ROW_ID) if key in columns), + ] grouped_df = self.backend.groupby_agg(df, group_keys, self.agg_ops) result = self.backend.to_arrow(grouped_df) output = ArrowTableValue(result) @@ -210,11 +228,14 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue: # names so we look up the columns that the source-read node has # already renamed (see issue #5942). dedup_keys = list(self.column_info.join_keys_columns) + # Keep one row per entity row, not per entity key, after the + # entity_df join. + columns = self.backend.columns(df) + if ENTITY_ROW_ID in columns: + dedup_keys = [ENTITY_ROW_ID] + elif dedup_keys and ENTITY_TS_ALIAS in columns: + dedup_keys.append(ENTITY_TS_ALIAS) if dedup_keys: - # Keep one row per entity row, not per entity key, after the - # entity_df join. - if ENTITY_TS_ALIAS in self.backend.columns(df): - dedup_keys.append(ENTITY_TS_ALIAS) sort_keys = [self.column_info.timestamp_column] if ( self.column_info.created_timestamp_column @@ -380,6 +401,9 @@ def __init__( def execute(self, context: ExecutionContext) -> ArrowTableValue: input_table = self.get_single_table(context).data + # The row id only tells the entity rows apart while the plan runs. + if ENTITY_ROW_ID in input_table.column_names: + input_table = input_table.drop_columns([ENTITY_ROW_ID]) output = ArrowTableValue(data=input_table) context.node_outputs[self.name] = output diff --git a/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py b/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py index f7ae4662475..d033926271a 100644 --- a/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py +++ b/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py @@ -2,6 +2,7 @@ from unittest.mock import MagicMock import pandas as pd +import pytest from feast import ( Aggregation, @@ -12,12 +13,14 @@ RepoConfig, ValueType, ) +from feast.feature_view import DUMMY_ENTITY from feast.infra.common.retrieval_task import HistoricalRetrievalTask from feast.infra.compute_engines.base import ComputeEngine from feast.infra.compute_engines.local.compute import ( LocalComputeEngine, LocalComputeEngineConfig, ) +from feast.infra.compute_engines.utils import ENTITY_ROW_ID from feast.infra.offline_stores.dask import DaskOfflineStore, DaskOfflineStoreConfig from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig from feast.types import Float32, Int64 @@ -111,7 +114,11 @@ def _source_view(self, tmp_path): offline=False, ) - def _get_historical_features(self, tmp_path, feature_view): + def _get_historical_features( + self, tmp_path, feature_view, entity_df=None, entity=None, backend="pandas" + ): + if backend == "polars": + pytest.importorskip("polars") repo_config = RepoConfig( project="test_local_engine", registry=str(tmp_path / "registry.db"), @@ -124,21 +131,23 @@ def _get_historical_features(self, tmp_path, feature_view): repo_config=repo_config, offline_store=DaskOfflineStore(), online_store=MagicMock(), + backend=backend, ) # Driver 1 is requested twice: before and after its second feature # row. Driver 2 is not requested at all. - entity_df = pd.DataFrame( - { - "driver_id": [1, 1], - "event_timestamp": [ - self.t0 + timedelta(hours=1), - self.t0 + timedelta(hours=3), - ], - } - ) + if entity_df is None: + entity_df = pd.DataFrame( + { + "driver_id": [1, 1], + "event_timestamp": [ + self.t0 + timedelta(hours=1), + self.t0 + timedelta(hours=3), + ], + } + ) registry = MagicMock() - registry.get_entity.return_value = self.driver + registry.get_entity.return_value = entity or self.driver task = HistoricalRetrievalTask( project="test_local_engine", entity_df=entity_df, @@ -153,6 +162,7 @@ def test_get_historical_features_is_point_in_time_per_entity_row(self, tmp_path) assert sorted(df["driver_id"].to_list()) == [1, 1] assert sorted(round(v, 6) for v in df["conv_rate"].to_list()) == [0.1, 0.9] + assert ENTITY_ROW_ID not in df.columns def test_get_historical_features_for_derived_view(self, tmp_path): derived = BatchFeatureView( @@ -196,3 +206,87 @@ def test_get_historical_features_aggregates_per_entity_row(self, tmp_path): assert sorted(df["driver_id"].to_list()) == [1, 1] assert sorted(round(v, 6) for v in df["sum_conv_rate"].to_list()) == [0.1, 1.0] + + def _same_request_twice(self): + """Two entity rows with the same driver and timestamp, told apart by a label.""" + return pd.DataFrame( + { + "driver_id": [1, 1], + "event_timestamp": [self.t0 + timedelta(hours=1)] * 2, + "label": ["a", "b"], + } + ) + + @pytest.mark.parametrize("backend", ["pandas", "polars"]) + def test_get_historical_features_keeps_entity_rows_with_the_same_key_and_time( + self, tmp_path, backend + ): + df = self._get_historical_features( + tmp_path, + self._source_view(tmp_path), + self._same_request_twice(), + backend=backend, + ) + + assert sorted(df["label"].to_list()) == ["a", "b"] + assert [round(v, 6) for v in df["conv_rate"].to_list()] == [0.1, 0.1] + + @pytest.mark.parametrize("backend", ["pandas", "polars"]) + def test_get_historical_features_aggregates_entity_rows_with_the_same_key_and_time( + self, tmp_path, backend + ): + driver_id = Entity( + name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64 + ) + aggregated = BatchFeatureView( + name="driver_stats_sum", + entities=[driver_id], + mode="pandas", + schema=self.schema, + source=self._source_view(tmp_path).batch_source, + aggregations=[Aggregation(column="conv_rate", function="sum")], + ttl=timedelta(days=1), + online=False, + offline=False, + ) + + df = self._get_historical_features( + tmp_path, aggregated, self._same_request_twice(), backend=backend + ) + + assert [round(v, 6) for v in df["sum_conv_rate"].to_list()] == [0.1, 0.1] + assert ENTITY_ROW_ID not in df.columns + + @pytest.mark.parametrize("backend", ["pandas", "polars"]) + def test_get_historical_features_for_view_without_entities(self, tmp_path, backend): + source_path = str(tmp_path / "global_stats.parquet") + pd.DataFrame( + { + "conv_rate": [0.1, 0.9], + "event_timestamp": [self.t0, self.t0 + timedelta(hours=2)], + } + ).to_parquet(source_path) + global_view = BatchFeatureView( + name="global_stats", + entities=[], + mode="pandas", + schema=[Field(name="conv_rate", dtype=Float32)], + source=FileSource(path=source_path, timestamp_field="event_timestamp"), + ttl=timedelta(days=1), + online=False, + offline=False, + ) + entity_df = pd.DataFrame( + { + "event_timestamp": [ + self.t0 + timedelta(hours=1), + self.t0 + timedelta(hours=3), + ] + } + ) + + df = self._get_historical_features( + tmp_path, global_view, entity_df, entity=DUMMY_ENTITY, backend=backend + ) + + assert sorted(round(v, 6) for v in df["conv_rate"].to_list()) == [0.1, 0.9] From 5b014045303f404355e31913a9f1646258ecbc4e Mon Sep 17 00:00:00 2001 From: Edson Date: Tue, 24 Nov 2026 17:59:19 -0500 Subject: [PATCH 3/5] fix: Do not write to the stores from local historical retrieval The local engine ended every plan with a node that writes its rows to the online and offline stores of the feature view. For historical retrieval those rows are now as of the entity timestamps, so reading an older value would replace the newer one the online store serves. Write only for materialization, as the Flink engine does. Signed-off-by: Edson --- .../compute_engines/local/feature_builder.py | 7 ++- .../infra/compute_engines/local/nodes.py | 6 ++- .../test_local_compute_engine.py | 44 +++++++++++++++++-- 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/sdk/python/feast/infra/compute_engines/local/feature_builder.py b/sdk/python/feast/infra/compute_engines/local/feature_builder.py index 210ff4b25dd..4de7df144c8 100644 --- a/sdk/python/feast/infra/compute_engines/local/feature_builder.py +++ b/sdk/python/feast/infra/compute_engines/local/feature_builder.py @@ -171,6 +171,11 @@ def build_validation_node(self, view, input_node): return node def build_output_nodes(self, view, input_node): - node = LocalOutputNode("output", self.dag_root.view, inputs=[input_node]) + node = LocalOutputNode( + "output", + self.dag_root.view, + inputs=[input_node], + write_to_stores=isinstance(self.task, MaterializationTask), + ) self.nodes.append(node) return node diff --git a/sdk/python/feast/infra/compute_engines/local/nodes.py b/sdk/python/feast/infra/compute_engines/local/nodes.py index 508922497bc..37cdf61fbca 100644 --- a/sdk/python/feast/infra/compute_engines/local/nodes.py +++ b/sdk/python/feast/infra/compute_engines/local/nodes.py @@ -395,9 +395,13 @@ def __init__( name: str, feature_view: Union[BatchFeatureView, StreamFeatureView], inputs=None, + write_to_stores: bool = True, ): super().__init__(name, inputs=inputs) self.feature_view = feature_view + # False for historical retrieval, which only reads: its rows are as of + # the entity timestamps and must not replace what the stores serve. + self.write_to_stores = write_to_stores def execute(self, context: ExecutionContext) -> ArrowTableValue: input_table = self.get_single_table(context).data @@ -407,7 +411,7 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue: output = ArrowTableValue(data=input_table) context.node_outputs[self.name] = output - if input_table.num_rows == 0: + if input_table.num_rows == 0 or not self.write_to_stores: return output if self.feature_view.online: diff --git a/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py b/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py index d033926271a..8c3fe6ebc84 100644 --- a/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py +++ b/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py @@ -14,6 +14,7 @@ ValueType, ) from feast.feature_view import DUMMY_ENTITY +from feast.infra.common.materialization_job import MaterializationTask from feast.infra.common.retrieval_task import HistoricalRetrievalTask from feast.infra.compute_engines.base import ComputeEngine from feast.infra.compute_engines.local.compute import ( @@ -114,9 +115,7 @@ def _source_view(self, tmp_path): offline=False, ) - def _get_historical_features( - self, tmp_path, feature_view, entity_df=None, entity=None, backend="pandas" - ): + def _engine(self, tmp_path, backend="pandas"): if backend == "polars": pytest.importorskip("polars") repo_config = RepoConfig( @@ -127,13 +126,18 @@ def _get_historical_features( offline_store=DaskOfflineStoreConfig(), entity_key_serialization_version=3, ) - engine = LocalComputeEngine( + return LocalComputeEngine( repo_config=repo_config, offline_store=DaskOfflineStore(), online_store=MagicMock(), backend=backend, ) + def _get_historical_features( + self, tmp_path, feature_view, entity_df=None, entity=None, backend="pandas" + ): + engine = self.engine = self._engine(tmp_path, backend) + # Driver 1 is requested twice: before and after its second feature # row. Driver 2 is not requested at all. if entity_df is None: @@ -290,3 +294,35 @@ def test_get_historical_features_for_view_without_entities(self, tmp_path, backe ) assert sorted(round(v, 6) for v in df["conv_rate"].to_list()) == [0.1, 0.9] + + def test_get_historical_features_does_not_write_to_the_stores(self, tmp_path): + """The view is online and offline, and the retrieval reads an older value.""" + view = self._source_view(tmp_path) + view.online = True + view.offline = True + entity_df = pd.DataFrame( + {"driver_id": [1], "event_timestamp": [self.t0 + timedelta(hours=1)]} + ) + + df = self._get_historical_features(tmp_path, view, entity_df) + + assert [round(v, 6) for v in df["conv_rate"].to_list()] == [0.1] + self.engine.online_store.online_write_batch.assert_not_called() + + def test_materialization_still_writes_to_the_online_store(self, tmp_path): + view = self._source_view(tmp_path) + view.online = True + engine = self._engine(tmp_path) + registry = MagicMock() + registry.get_entity.return_value = self.driver + task = MaterializationTask( + project="test_local_engine", + feature_view=view, + start_time=self.t0 - timedelta(hours=1), + end_time=self.t0 + timedelta(hours=3), + ) + + job = engine._materialize_one(registry, task) + + assert job.error() is None + engine.online_store.online_write_batch.assert_called_once() From 0e1c766922f69b1f3f87d92cc45b91ace2cc85a5 Mon Sep 17 00:00:00 2001 From: Edson Date: Wed, 25 Nov 2026 09:19:21 -0500 Subject: [PATCH 4/5] fix: Keep entity rows without features in local historical retrieval The filter node drops an entity row when its key has no feature row, or only rows after the entity timestamp or older than the TTL, and the retrieval job returned the filtered table. Left-join the selected rows back onto the entity rows by the entity row id before it is dropped, so that every requested row is returned, with null features when nothing was selected. Signed-off-by: Edson --- .../compute_engines/local/feature_builder.py | 9 ++ .../infra/compute_engines/local/nodes.py | 78 +++++++++--- .../test_local_compute_engine.py | 111 ++++++++++++++++++ 3 files changed, 181 insertions(+), 17 deletions(-) diff --git a/sdk/python/feast/infra/compute_engines/local/feature_builder.py b/sdk/python/feast/infra/compute_engines/local/feature_builder.py index 4de7df144c8..9191bfd26b9 100644 --- a/sdk/python/feast/infra/compute_engines/local/feature_builder.py +++ b/sdk/python/feast/infra/compute_engines/local/feature_builder.py @@ -12,6 +12,7 @@ from feast.infra.compute_engines.local.nodes import ( LocalAggregationNode, LocalDedupNode, + LocalEntityRowsNode, LocalFilterNode, LocalJoinNode, LocalOutputNode, @@ -171,6 +172,14 @@ def build_validation_node(self, view, input_node): return node def build_output_nodes(self, view, input_node): + if self._should_join_entity_df(): + # The filter node dropped the entity rows that no feature row + # matched; return them with null features. + input_node = LocalEntityRowsNode( + "entity_rows", self.backend, inputs=[input_node] + ) + self.nodes.append(input_node) + node = LocalOutputNode( "output", self.dag_root.view, diff --git a/sdk/python/feast/infra/compute_engines/local/nodes.py b/sdk/python/feast/infra/compute_engines/local/nodes.py index 37cdf61fbca..4ecd7f6020d 100644 --- a/sdk/python/feast/infra/compute_engines/local/nodes.py +++ b/sdk/python/feast/infra/compute_engines/local/nodes.py @@ -3,6 +3,7 @@ from datetime import datetime, timedelta from typing import List, Optional, Set, Union +import pandas as pd import pyarrow as pa from feast import BatchFeatureView, StreamFeatureView @@ -24,6 +25,25 @@ logger = logging.getLogger(__name__) +def _entity_rows(entity_df: pd.DataFrame, backend: DataFrameBackend): + """entity_df as a backend DataFrame, numbered and with its timestamp aliased. + + Two entity rows can share their join keys and timestamp, and each is still + a request of its own, so every row gets an ``ENTITY_ROW_ID``. + """ + entity_df = backend.from_arrow( + pa.Table.from_pandas( + entity_df.assign(**{ENTITY_ROW_ID: range(len(entity_df))}), + preserve_index=False, + ) + ) + entity_schema = dict(zip(entity_df.columns, entity_df.dtypes)) + entity_ts_col = infer_entity_timestamp_column(entity_schema) + if entity_ts_col != ENTITY_TS_ALIAS: + entity_df = backend.rename_columns(entity_df, {entity_ts_col: ENTITY_TS_ALIAS}) + return entity_df + + class LocalSourceReadNode(LocalNode): def __init__( self, @@ -102,23 +122,7 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue: # If entity_df is provided, join it in last if context.entity_df is not None and not already_joined: - # Number the entity rows. Two of them can share their join keys - # and timestamp, and each is still a request of its own. - entity_df = self.backend.from_arrow( - pa.Table.from_pandas( - context.entity_df.assign( - **{ENTITY_ROW_ID: range(len(context.entity_df))} - ) - ) - ) - - entity_schema = dict(zip(entity_df.columns, entity_df.dtypes)) - entity_ts_col = infer_entity_timestamp_column(entity_schema) - - if entity_ts_col != ENTITY_TS_ALIAS: - entity_df = self.backend.rename_columns( - entity_df, {entity_ts_col: ENTITY_TS_ALIAS} - ) + entity_df = _entity_rows(context.entity_df, self.backend) # A view without entities has no join keys: every feature row is # a candidate for every entity row, and the filter node picks the @@ -389,6 +393,46 @@ def _validate_schema(self, table: pa.Table): logger.debug("[Validation: %s] Schema validation passed.", self.name) +class LocalEntityRowsNode(LocalNode): + """Returns one row per entity row, with nulls where no feature row was selected. + + The filter node drops an entity row when its key has no feature row, or + only rows after its timestamp or older than the TTL. Historical retrieval + still has to answer that request, so the selected rows are left-joined + back onto the entity rows by ``ENTITY_ROW_ID``. + """ + + def __init__(self, name: str, backend: DataFrameBackend, inputs=None): + super().__init__(name, inputs=inputs) + self.backend = backend + + def execute(self, context: ExecutionContext) -> ArrowTableValue: + input_table = self.get_single_table(context).data + if context.entity_df is None or ENTITY_ROW_ID not in input_table.column_names: + return ArrowTableValue(input_table) + + entity_df = _entity_rows(context.entity_df, self.backend) + # The entity columns come from entity_df, so that they are filled in + # for the rows that were dropped too. + entity_columns = set(self.backend.columns(entity_df)) + selected = input_table.select( + [ + column + for column in input_table.column_names + if column == ENTITY_ROW_ID or column not in entity_columns + ] + ) + joined_df = self.backend.join( + entity_df, + self.backend.from_arrow(selected), + on=[ENTITY_ROW_ID], + how="left", + ) + output = ArrowTableValue(self.backend.to_arrow(joined_df)) + context.node_outputs[self.name] = output + return output + + class LocalOutputNode(LocalNode): def __init__( self, diff --git a/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py b/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py index 8c3fe6ebc84..1e6efce4c43 100644 --- a/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py +++ b/sdk/python/tests/unit/infra/compute_engines/test_local_compute_engine.py @@ -295,6 +295,117 @@ def test_get_historical_features_for_view_without_entities(self, tmp_path, backe assert sorted(round(v, 6) for v in df["conv_rate"].to_list()) == [0.1, 0.9] + def _hit_and_miss(self, miss): + """Driver 1 at t0+1h has a feature row; the second entity row has none.""" + driver_id, timestamp = { + # Driver 3 has no feature rows at all. + "unmatched": (3, self.t0 + timedelta(hours=1)), + # Driver 2's only feature row is at t0. + "future_only": (2, self.t0 - timedelta(hours=1)), + # ... and is older than the one-day TTL two days later. + "expired_only": (2, self.t0 + timedelta(days=2)), + }[miss] + return pd.DataFrame( + { + "driver_id": [1, driver_id], + "event_timestamp": [self.t0 + timedelta(hours=1), timestamp], + "label": ["hit", "miss"], + } + ) + + @pytest.mark.parametrize("backend", ["pandas", "polars"]) + @pytest.mark.parametrize("miss", ["unmatched", "future_only", "expired_only"]) + def test_get_historical_features_keeps_entity_rows_without_features( + self, tmp_path, backend, miss + ): + entity_df = self._hit_and_miss(miss) + + df = self._get_historical_features( + tmp_path, self._source_view(tmp_path), entity_df, backend=backend + ) + + assert df["label"].to_list() == ["hit", "miss"] + assert df["driver_id"].to_list() == entity_df["driver_id"].to_list() + assert round(df["conv_rate"][0], 6) == 0.1 + assert pd.isna(df["conv_rate"][1]) + assert ENTITY_ROW_ID not in df.columns + + @pytest.mark.parametrize("backend", ["pandas", "polars"]) + def test_get_historical_features_keeps_entity_rows_when_none_has_features( + self, tmp_path, backend + ): + entity_df = pd.DataFrame( + { + "driver_id": [3, 2], + "event_timestamp": [self.t0, self.t0 - timedelta(hours=1)], + "label": ["a", "b"], + } + ) + + df = self._get_historical_features( + tmp_path, self._source_view(tmp_path), entity_df, backend=backend + ) + + assert df["label"].to_list() == ["a", "b"] + assert df["driver_id"].to_list() == [3, 2] + assert df["conv_rate"].isna().all() + + @pytest.mark.parametrize("backend", ["pandas", "polars"]) + @pytest.mark.parametrize("miss", ["unmatched", "future_only", "expired_only"]) + def test_get_historical_features_for_derived_view_keeps_entity_rows( + self, tmp_path, backend, miss + ): + derived = BatchFeatureView( + name="derived_driver_stats", + entities=[self.driver], + mode="pandas", + schema=self.schema, + source=self._source_view(tmp_path), + sink_source=FileSource( + path=str(tmp_path / "derived.parquet"), + timestamp_field="event_timestamp", + ), + ttl=timedelta(days=1), + online=False, + offline=False, + ) + + df = self._get_historical_features( + tmp_path, derived, self._hit_and_miss(miss), backend=backend + ) + + assert df["label"].to_list() == ["hit", "miss"] + assert round(df["conv_rate"][0], 6) == 0.1 + assert pd.isna(df["conv_rate"][1]) + + @pytest.mark.parametrize("backend", ["pandas", "polars"]) + @pytest.mark.parametrize("miss", ["unmatched", "future_only", "expired_only"]) + def test_get_historical_features_aggregation_keeps_entity_rows( + self, tmp_path, backend, miss + ): + driver_id = Entity( + name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64 + ) + aggregated = BatchFeatureView( + name="driver_stats_sum", + entities=[driver_id], + mode="pandas", + schema=self.schema, + source=self._source_view(tmp_path).batch_source, + aggregations=[Aggregation(column="conv_rate", function="sum")], + ttl=timedelta(days=1), + online=False, + offline=False, + ) + + df = self._get_historical_features( + tmp_path, aggregated, self._hit_and_miss(miss), backend=backend + ) + + assert df["label"].to_list() == ["hit", "miss"] + assert round(df["sum_conv_rate"][0], 6) == 0.1 + assert pd.isna(df["sum_conv_rate"][1]) + def test_get_historical_features_does_not_write_to_the_stores(self, tmp_path): """The view is online and offline, and the retrieval reads an older value.""" view = self._source_view(tmp_path) From 962ca9cf11c5600bf2d970035f08f835eb68cd4b Mon Sep 17 00:00:00 2001 From: Edson Date: Wed, 25 Nov 2026 09:25:49 -0500 Subject: [PATCH 5/5] fix: Return local historical retrieval rows in entity_df order A backend's left join does not have to keep the order of the left frame, so sort the joined rows by the entity row id. Signed-off-by: Edson --- sdk/python/feast/infra/compute_engines/local/nodes.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sdk/python/feast/infra/compute_engines/local/nodes.py b/sdk/python/feast/infra/compute_engines/local/nodes.py index 4ecd7f6020d..f04f90f7cdf 100644 --- a/sdk/python/feast/infra/compute_engines/local/nodes.py +++ b/sdk/python/feast/infra/compute_engines/local/nodes.py @@ -428,7 +428,10 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue: on=[ENTITY_ROW_ID], how="left", ) - output = ArrowTableValue(self.backend.to_arrow(joined_df)) + # A backend's left join need not keep the left order; return the rows + # in entity_df order. + result = self.backend.to_arrow(joined_df).sort_by(ENTITY_ROW_ID) + output = ArrowTableValue(result) context.node_outputs[self.name] = output return output