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..9191bfd26b9 100644 --- a/sdk/python/feast/infra/compute_engines/local/feature_builder.py +++ b/sdk/python/feast/infra/compute_engines/local/feature_builder.py @@ -1,14 +1,18 @@ 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, LocalDedupNode, + LocalEntityRowsNode, LocalFilterNode, LocalJoinNode, LocalOutputNode, @@ -32,6 +36,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 @@ -129,6 +172,19 @@ 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]) + 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, + 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 71e78a8380e..f04f90f7cdf 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 @@ -14,6 +15,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, @@ -23,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, @@ -82,32 +103,35 @@ 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. + 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( 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: - entity_df = self.backend.from_arrow(pa.Table.from_pandas(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} - ) + if context.entity_df is not None and not already_joined: + 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 + # 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) @@ -178,7 +202,13 @@ 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) + # Aggregate per entity row after the entity_df join. + 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) return output @@ -201,7 +231,14 @@ 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) + # 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: sort_keys = [self.column_info.timestamp_column] if ( @@ -356,22 +393,72 @@ 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", + ) + # 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 + + class LocalOutputNode(LocalNode): def __init__( self, 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 + # 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 - 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 3396a45c995..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 @@ -1,10 +1,30 @@ +from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock +import pandas as pd +import pytest + +from feast import ( + Aggregation, + BatchFeatureView, + Entity, + Field, + FileSource, + RepoConfig, + 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 ( 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 class TestLocalComputeEngineConfig: @@ -65,3 +85,355 @@ 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 _engine(self, tmp_path, backend="pandas"): + if backend == "polars": + pytest.importorskip("polars") + 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, + ) + 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: + 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 = entity or 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] + assert ENTITY_ROW_ID not in df.columns + + 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] + + 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] + + 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) + 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()