Skip to content
Open
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
60 changes: 58 additions & 2 deletions sdk/python/feast/infra/compute_engines/local/feature_builder.py
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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])
Comment on lines +55 to +56

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Historical reads overwrite live features

When historical retrieval selects older rows for an online-enabled view, LocalOutputNode writes them to the online store. SQLite replaces newer serving values unconditionally. For offline-enabled Dask views, the added request timestamp makes the offline write reject the result.

Learn more

The local engine executes the historical plan when the caller reads the retrieval job’s result, as shown in LocalRetrievalJob. The builder still ends both historical and materialization plans with build_output_nodes, which calls stores through LocalOutputNode. Before the new join, source-backed retrieval deduplicated source values to the latest per entity; now it feeds historical values into an existing write path. SQLite’s upsert replaces the row without comparing timestamps. Dask’s offline writer requires exactly the source columns, which exclude the request timestamp.

Example: A driver has source values 0.1 at 10:00 and 0.9 at 12:00. SQLite is serving 0.9. Retrieving the driver at 11:00 returns and writes 0.1, so the next online lookup also serves 0.1. If the view also writes to Dask, the historical call raises after the online write.

Recommended fix: End historical plans with a read-only output node; reserve the store-writing node for materialization. Test an online-enabled view with a preloaded newer value and an offline-enabled view with a real source schema.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

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.

Fixed in 5b01404. LocalOutputNode now takes a write_to_stores flag, and LocalFeatureBuilder sets it only for a MaterializationTask, as FlinkFeatureBuilder does. Historical retrieval returns its rows and writes nothing.

The write was there before this PR: on master a historical read of an online view already makes one online_write_batch call with the latest row per key, and a read of an offline view raises in offline_write_batch. What this PR changed is which rows reached that write, so the overwrite described here was real.

Tests: test_get_historical_features_does_not_write_to_the_stores (an online and offline view read at an older timestamp, no online_write_batch call) and test_materialization_still_writes_to_the_online_store. It is a separate commit in case it should go in on its own.

Comment on lines +55 to +56

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Historical lookups fail for global features

For views without entities, LocalFeatureBuilder sends an empty key list to PandasBackend.join. The merge raises before the request timestamps can select any global feature values.

Learn more

FeatureView records a dummy entity for views without keys, and _get_column_names resolves their columns using the registry. The column resolver excludes the dummy key, so the new source join receives no keys. LocalJoinNode still requests a left equality join rather than handling that case explicitly, and pandas rejects on=[].

Example: Request global ride counts at 12:00 with an entity DataFrame containing only event_timestamp. A source row at 11:00 is eligible, but the merge raises an IndexError.

Recommended fix: Give keyless views a global point-in-time lookup instead of an empty-key left merge. Ensure LocalDedupNode selects one eligible value per request even when there are no entity keys.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

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.

Fixed in 32e27d0. A view without entities is cross joined with entity_df, and the filter node keeps the feature rows inside the point-in-time and TTL bounds of each entity row. LocalDedupNode then keeps one row per entity row through the row id, so it no longer needs a join key.

test_get_historical_features_for_view_without_entities requests a view with entities=[] at two timestamps and gets 0.1 and 0.9, on the pandas and the Polars backend. FeatureStore.get_historical_features with the Dask offline store returns the same for that input.

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 source-backed historical path joins each request to candidate feature rows and then LocalFilterNode removes rows outside PIT/TTL bounds, but LocalRetrievalJob returns that filtered table directly. a request with no matching key, only future features, or only expired features therefore disappears instead of returning its entity row and null features; this can silently remove training examples. we need to left-join the selected results back to the original entity rows by ENTITY_ROW_ID before dropping that id, and cover unmatched, future-only, and expired-only requests on both backends.

@Zhuoxi2000 Zhuoxi2000 Nov 25, 2026 •

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.

Agreed, those requests were dropped. Fixed in 0e1c766 and 962ca9c.

A new LocalEntityRowsNode runs just before the output node for a historical task and left-joins the selected rows back onto the numbered entity rows by ENTITY_ROW_ID, before LocalOutputNode drops the id. The entity columns are taken from entity_df, so a request with no surviving feature row comes back with its own columns and null features, and the result is sorted by the row id, so it is in entity_df order on both backends (962ca9c). LocalJoinNode and the new node share one helper for numbering the rows.

Tests, each on pandas and Polars and for an unmatched key, a future-only key and an expired-only key, always next to a request that does have a value: a source-backed view, a derived view, and the sum aggregation view. One more test covers a request set where no row has a feature. With the previous head's source files these are 20 failed / 18 passed; now 38 passed.

Side effect: the aggregation path now also returns the other entity_df columns (a label, for example), since they come from the join back. I updated the PR description to match.


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
Expand Down Expand Up @@ -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
119 changes: 103 additions & 16 deletions sdk/python/feast/infra/compute_engines/local/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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 (
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading