From 8b18e587cb2e574949588ed9a71f2bf84cb37e8f Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:17:38 +0530 Subject: [PATCH 1/3] feat: Retrieve historical features from SQL Server without an entity dataframe MsSqlServerOfflineStore.get_historical_features did not accept start_date or end_date, so calling FeatureStore.get_historical_features without an entity_df failed with "unexpected keyword argument 'start_date'" on SQL Server. When entity_df is None, build the entity dataframe from the data itself: the distinct join keys that each feature view source has between start_date and end_date, with every row stamped at end_date. Each entity then gets its latest feature values within the TTL, matching the BigQuery, Spark and Trino offline stores. start_date and end_date default through compute_non_entity_date_range like the other stores. The keys are collected by a new ibis helper, build_entity_df_for_date_range_ibis, in a single UNION query that runs in SQL Server. It applies the source field mapping and the projection's join key map the same way the point-in-time join does, fills the join keys a feature view does not have with typed NULLs, and casts keys that appear in several sources to one type. Feature views without entities join on the timestamp only, so when no feature view has entities the entity dataframe is a single row at end_date. The helper only relies on the data source reader, so other ibis-based offline stores can use it. The SQL Server data source reader took a single argument, while the ibis helpers call it with the data source and the repo path, so every get_historical_features call on SQL Server raised a TypeError. Accept the repo path in the reader and the writer, like the Oracle store does. Document entity-less retrieval for SQL Server in the offline store reference, the feature retrieval concepts page and the FAQ. Signed-off-by: NopeCharon <115794254+NopeCharon@users.noreply.github.com> --- .../concepts/feature-retrieval.md | 2 +- docs/getting-started/faq.md | 2 +- docs/reference/offline-stores/mssql.md | 1 + .../contrib/mssql_offline_store/mssql.py | 25 +- sdk/python/feast/infra/offline_stores/ibis.py | 90 ++++++ .../test_mssql_non_entity_mode.py | 260 ++++++++++++++++++ .../unit/infra/offline_stores/test_ibis.py | 206 ++++++++++++++ 7 files changed, 581 insertions(+), 5 deletions(-) create mode 100644 sdk/python/tests/unit/infra/offline_stores/contrib/mssql_offline_store/test_mssql_non_entity_mode.py diff --git a/docs/getting-started/concepts/feature-retrieval.md b/docs/getting-started/concepts/feature-retrieval.md index 0fd65222ebe..a514d722b5e 100644 --- a/docs/getting-started/concepts/feature-retrieval.md +++ b/docs/getting-started/concepts/feature-retrieval.md @@ -175,7 +175,7 @@ training_df = store.get_historical_features( If `start_date` is omitted, it defaults to `end_date` minus the feature view TTL. If `end_date` is omitted, it defaults to the current time. Point-in-time correctness is still preserved. {% hint style="warning" %} -Entity-less retrieval is currently supported for the **Postgres**, **Dask**, **Spark**, **Ray**, and **Trino** offline stores. You cannot mix `entity_df` with `start_date`/`end_date` in the same call. +Entity-less retrieval is currently supported for the **Postgres**, **Dask**, **Spark**, **Ray**, **Trino**, and **MsSQL** offline stores. You cannot mix `entity_df` with `start_date`/`end_date` in the same call. {% endhint %} For more details, see the [FAQ](../faq.md#how-do-i-run-get_historical_features-without-providing-an-entity-dataframe) and [this blog post on entity-less historical feature retrieval](https://feast.dev/blog/entity-less-historical-features-retrieval/). diff --git a/docs/getting-started/faq.md b/docs/getting-started/faq.md index 2d22106b87f..af77ac307c2 100644 --- a/docs/getting-started/faq.md +++ b/docs/getting-started/faq.md @@ -41,7 +41,7 @@ Yes, this is possible. For example, you can use BigQuery as an offline store and Feast does support fetching historical features without passing an entity dataframe with the request. -- **Supported offline stores:** Entity-less (entity dataframe–less) retrieval is supported for the **Postgres**, **Dask**, **Spark**, **Ray**, and **Trino** offline stores. Postgres was the first to support it; Dask, Spark, Ray, and Trino have followed. Other offline stores may be added based on priority and community demand. +- **Supported offline stores:** Entity-less (entity dataframe–less) retrieval is supported for the **Postgres**, **Dask**, **Spark**, **Ray**, **Trino**, and **MsSQL** offline stores. Postgres was the first to support it; Dask, Spark, Ray, Trino, and MsSQL have followed. Other offline stores may be added based on priority and community demand. - **Date range:** Retrieval is controlled by the `start_date` and `end_date` parameters. Supported combinations: - Both params given → data in the given start-to-end time range. - Only `start_date` given → data from the start date to now. diff --git a/docs/reference/offline-stores/mssql.md b/docs/reference/offline-stores/mssql.md index e352b3dd2aa..b24ee1ca742 100644 --- a/docs/reference/offline-stores/mssql.md +++ b/docs/reference/offline-stores/mssql.md @@ -5,6 +5,7 @@ The MsSQL offline store provides support for reading [MsSQL Sources](../data-sources/mssql.md). Specifically, it is developed to read from [Synapse SQL](https://docs.microsoft.com/en-us/azure/synapse-analytics/sql/overview-features) on Microsoft Azure * Entity dataframes can be provided as a SQL query or can be provided as a Pandas dataframe. +* Historical features can also be retrieved without an entity dataframe by passing `start_date` and/or `end_date` to `get_historical_features`. Every entity key with an event between `start_date` and `end_date` is joined as of `end_date`, so each entity gets its latest feature values within the feature view TTL. See [entity-less retrieval](../../getting-started/concepts/feature-retrieval.md) for details. ## Getting started In order to use this offline store, you'll need to run `pip install 'feast[azure]'`. You can get started by then following this [tutorial](https://github.com/feast-dev/feast/blob/master/docs/tutorials/azure/README.md). diff --git a/sdk/python/feast/infra/offline_stores/contrib/mssql_offline_store/mssql.py b/sdk/python/feast/infra/offline_stores/contrib/mssql_offline_store/mssql.py index fd3e2cb4a34..3cf5faea64e 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/mssql_offline_store/mssql.py +++ b/sdk/python/feast/infra/offline_stores/contrib/mssql_offline_store/mssql.py @@ -16,6 +16,7 @@ MsSqlServerSource, ) from feast.infra.offline_stores.ibis import ( + build_entity_df_for_date_range_ibis, get_historical_features_ibis, offline_write_batch_ibis, pull_all_from_table_or_query_ibis, @@ -25,6 +26,7 @@ from feast.infra.offline_stores.offline_store import OfflineStore, RetrievalJob from feast.infra.registry.base_registry import BaseRegistry from feast.repo_config import FeastConfigBaseModel, RepoConfig +from feast.utils import compute_non_entity_date_range def get_ibis_connection(config: RepoConfig): @@ -79,7 +81,7 @@ def get_table_column_names_and_types( def _build_data_source_reader(config: RepoConfig): con = get_ibis_connection(config) - def _read_data_source(data_source: DataSource) -> Table: + def _read_data_source(data_source: DataSource, repo_path: str = "") -> Table: assert isinstance(data_source, MsSqlServerSource) return con.table(data_source.table_ref) @@ -92,6 +94,7 @@ def _build_data_source_writer(config: RepoConfig): def _write_data_source( table: Table, data_source: DataSource, + repo_path: str = "", mode: str = "append", allow_overwrite: bool = False, ): @@ -149,14 +152,30 @@ def get_historical_features( config: RepoConfig, feature_views: List[FeatureView], feature_refs: List[str], - entity_df: Union[pd.DataFrame, str], + entity_df: Optional[Union[pd.DataFrame, str]], registry: BaseRegistry, project: str, full_feature_names: bool = False, filter_by_created_timestamp: bool = False, + **kwargs: Any, ) -> RetrievalJob: + if entity_df is None: + # Non-entity mode: join every entity key with an event in the time + # range as of end_date, so it gets its latest values within the TTL. + start_date, end_date = compute_non_entity_date_range( + feature_views, + start_date=kwargs.get("start_date"), + end_date=kwargs.get("end_date"), + ) + entity_df = build_entity_df_for_date_range_ibis( + config=config, + feature_views=feature_views, + start_date=start_date, + end_date=end_date, + data_source_reader=_build_data_source_reader(config), + ) # TODO avoid this conversion - if type(entity_df) == str: + elif type(entity_df) == str: con = get_ibis_connection(config) entity_df = con.sql(entity_df).execute() diff --git a/sdk/python/feast/infra/offline_stores/ibis.py b/sdk/python/feast/infra/offline_stores/ibis.py index 5f3bd686977..ba6741fa323 100644 --- a/sdk/python/feast/infra/offline_stores/ibis.py +++ b/sdk/python/feast/infra/offline_stores/ibis.py @@ -30,6 +30,7 @@ from feast.on_demand_feature_view import OnDemandFeatureView from feast.repo_config import RepoConfig from feast.saved_dataset import SavedDatasetStorage +from feast.utils import make_tzaware def read_mlflow_data_source(data_source: DataSource) -> Optional[Table]: @@ -198,6 +199,95 @@ def _generate_row_id( return entity_table +def build_entity_df_for_date_range_ibis( + config: RepoConfig, + feature_views: List[FeatureView], + start_date: datetime, + end_date: datetime, + data_source_reader: Callable[[DataSource, str], Table], + event_timestamp_col: str = offline_utils.DEFAULT_ENTITY_DF_EVENT_TIMESTAMP_COL, +) -> pd.DataFrame: + """Build the entity dataframe that stands in for entity_df in non-entity mode. + + It holds the distinct join keys of every feature view with entities whose source + has events between start_date and end_date, with NULL for the join keys a feature + view does not have, and end_date as the event timestamp of every row, so each + entity gets its latest feature values within the TTL. Feature views without + entities join on the timestamp alone, so they do not contribute rows. When no + feature view has entities, the dataframe is a single row holding end_date. + + The keys are collected in one query, so data_source_reader must read every + source from the same backend. + """ + start_date = make_tzaware(start_date).astimezone(tz=timezone.utc) + end_date = make_tzaware(end_date).astimezone(tz=timezone.utc) + start_literal = ibis.literal(start_date.replace(tzinfo=None)) + end_literal = ibis.literal(end_date.replace(tzinfo=None)) + + key_tables: List[Table] = [] + for feature_view in feature_views: + join_key_map = { + column.name: feature_view.projection.join_key_map.get( + column.name, column.name + ) + for column in feature_view.entity_columns + } + if not join_key_map: + continue + if feature_view.batch_source is None: + raise ValueError( + f"Feature view '{feature_view.name}' has no batch_source and cannot be queried." + ) + + table = data_source_reader(feature_view.batch_source, str(config.repo_path)) + for old_name, new_name in feature_view.batch_source.field_mapping.items(): + if old_name in table.columns: + table = table.rename({new_name: old_name}) + + timestamp = _comparable_timestamp( + table[feature_view.batch_source.timestamp_field] + ) + table = table.filter(timestamp >= start_literal, timestamp <= end_literal) + key_tables.append( + table.select( + **{ + entity_column: table[join_key] + for join_key, entity_column in join_key_map.items() + } + ) + ) + + if not key_tables: + return pd.DataFrame({event_timestamp_col: [pd.Timestamp(end_date)]}) + + # A union needs the same columns and types in every table, so each key table + # gets every join key, cast to the type of its first occurrence or NULL. + join_key_types: Dict[str, dt.DataType] = {} + for key_table in key_tables: + for column, column_type in key_table.schema().items(): + join_key_types.setdefault(column, column_type) + + entity_table = ibis.union( + *[ + key_table.select( + **{ + column: key_table[column].cast(column_type) + if column in key_table.columns + else ibis.null(column_type) + for column, column_type in join_key_types.items() + } + ) + for key_table in key_tables + ] + ).distinct() + + entity_df = entity_table.execute() + entity_df[event_timestamp_col] = pd.Series( + pd.Timestamp(end_date), index=entity_df.index, dtype="datetime64[ns, UTC]" + ) + return entity_df + + def get_historical_features_ibis( config: RepoConfig, feature_views: List[FeatureView], diff --git a/sdk/python/tests/unit/infra/offline_stores/contrib/mssql_offline_store/test_mssql_non_entity_mode.py b/sdk/python/tests/unit/infra/offline_stores/contrib/mssql_offline_store/test_mssql_non_entity_mode.py new file mode 100644 index 00000000000..ab1ab8d07be --- /dev/null +++ b/sdk/python/tests/unit/infra/offline_stores/contrib/mssql_offline_store/test_mssql_non_entity_mode.py @@ -0,0 +1,260 @@ +from datetime import datetime, timedelta, timezone +from unittest.mock import MagicMock, patch + +import ibis +import pandas as pd +import pytest + +from feast import Entity, FeatureView, Field, ValueType +from feast.infra.offline_stores.contrib.mssql_offline_store.mssql import ( + MsSqlServerOfflineStore, + MsSqlServerOfflineStoreConfig, +) +from feast.infra.offline_stores.contrib.mssql_offline_store.mssqlserver_source import ( + MsSqlServerSource, +) +from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig +from feast.repo_config import RepoConfig +from feast.types import Float32, Int64 + +START = datetime(2025, 7, 1, tzinfo=timezone.utc) +END = datetime(2025, 7, 10, 12, 0, tzinfo=timezone.utc) + +driver = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) +customer = Entity( + name="customer", join_keys=["customer_id"], value_type=ValueType.INT64 +) + +driver_fv = FeatureView( + name="driver_stats", + entities=[driver], + ttl=timedelta(days=2), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="conv_rate", dtype=Float32), + ], + source=MsSqlServerSource( + name="driver_source", + table_ref="driver_stats", + event_timestamp_column="event_timestamp", + created_timestamp_column="created", + ), +) + +customer_fv = FeatureView( + name="customer_stats", + entities=[customer], + ttl=timedelta(days=5), + schema=[ + Field(name="customer_id", dtype=Int64), + Field(name="spend", dtype=Float32), + ], + source=MsSqlServerSource( + name="customer_source", + table_ref="customer_stats", + event_timestamp_column="event_timestamp", + field_mapping={"cust": "customer_id"}, + ), +) + +global_fv = FeatureView( + name="global_stats", + entities=[], + ttl=timedelta(days=1), + schema=[Field(name="total", dtype=Int64)], + source=MsSqlServerSource( + name="global_source", + table_ref="global_stats", + event_timestamp_column="event_timestamp", + ), +) + + +def _utc(*timestamps): + return pd.to_datetime(list(timestamps), utc=True) + + +@pytest.fixture +def repo_config(): + return RepoConfig( + registry="file:///tmp/registry.db", + project="test_project", + provider="local", + online_store=SqliteOnlineStoreConfig(type="sqlite"), + offline_store=MsSqlServerOfflineStoreConfig(), + entity_key_serialization_version=3, + ) + + +@pytest.fixture +def connection(): + """Stands in for SQL Server with an in-memory DuckDB holding the sources.""" + con = ibis.duckdb.connect() + sources = { + "driver_stats": pd.DataFrame( + { + "driver_id": [1, 1, 1, 2, 3], + "event_timestamp": _utc( + "2025-07-02", "2025-07-09", "2025-07-10", "2025-07-05", "2025-06-01" + ), + # The 2025-07-10 row arrived after END. + "created": _utc( + "2025-07-02", "2025-07-09", "2025-07-11", "2025-07-05", "2025-06-01" + ), + "conv_rate": [0.1, 0.2, 0.25, 0.3, 0.4], + } + ), + "customer_stats": pd.DataFrame( + { + "cust": [10, 20], + "event_timestamp": _utc("2025-07-08", "2025-07-11"), + "spend": [100.0, 200.0], + } + ), + "global_stats": pd.DataFrame( + { + "event_timestamp": _utc("2025-07-01", "2025-07-10"), + "total": [5, 7], + } + ), + } + for table_ref, df in sources.items(): + con.con.register(table_ref, df) + + def duckdb_expire_timestamp(timestamp_field, ttl): + return f"{timestamp_field} + INTERVAL {int(ttl.total_seconds())} SECOND" + + module = "feast.infra.offline_stores.contrib.mssql_offline_store.mssql" + with ( + patch(f"{module}.get_ibis_connection", return_value=con), + patch( + f"{module}.mssql_event_expire_timestamp_fn", + side_effect=duckdb_expire_timestamp, + ), + ): + yield con + + +def _get_historical_features(repo_config, feature_views, feature_refs, **kwargs): + registry = MagicMock() + registry.list_on_demand_feature_views.return_value = [] + return MsSqlServerOfflineStore.get_historical_features( + config=repo_config, + feature_views=feature_views, + feature_refs=feature_refs, + entity_df=None, + registry=registry, + project="test_project", + **kwargs, + ) + + +def _rows(df, columns): + return sorted( + ( + tuple(None if pd.isna(row[c]) else row[c] for c in columns) + for _, row in df.iterrows() + ), + key=str, + ) + + +def test_returns_latest_values_of_entities_in_range(repo_config, connection): + df = _get_historical_features( + repo_config, + [driver_fv], + ["driver_stats:conv_rate"], + start_date=START, + end_date=END, + ).to_df() + + assert _rows(df, ["driver_id", "conv_rate"]) == [(1, 0.25), (2, None)] + assert (pd.to_datetime(df["event_timestamp"], utc=True) == END).all() + + +def test_fills_missing_join_keys_across_feature_views(repo_config, connection): + df = _get_historical_features( + repo_config, + [driver_fv, customer_fv], + ["driver_stats:conv_rate", "customer_stats:spend"], + start_date=START, + end_date=END, + full_feature_names=True, + ).to_df() + + assert _rows( + df, + [ + "driver_id", + "customer_id", + "driver_stats__conv_rate", + "customer_stats__spend", + ], + ) == [(1, None, 0.25, None), (2, None, None, None), (None, 10, None, 100.0)] + + +def test_feature_view_without_entities_returns_one_row(repo_config, connection): + df = _get_historical_features( + repo_config, + [global_fv], + ["global_stats:total"], + start_date=START, + end_date=END, + ).to_df() + + assert df["total"].tolist() == [7] + + +def test_defaults_start_date_to_ttl_window(repo_config, connection): + """Without start_date the window is end_date minus the largest TTL (2 days).""" + df = _get_historical_features( + repo_config, + [driver_fv], + ["driver_stats:conv_rate"], + end_date=END, + ).to_df() + + assert _rows(df, ["driver_id", "conv_rate"]) == [(1, 0.25)] + + +def test_filter_by_created_timestamp(repo_config, connection): + df = _get_historical_features( + repo_config, + [driver_fv], + ["driver_stats:conv_rate"], + start_date=START, + end_date=END, + filter_by_created_timestamp=True, + ).to_df() + + assert _rows(df, ["driver_id", "conv_rate"]) == [(1, 0.2), (2, None)] + + +def test_returns_no_rows_without_events_in_range(repo_config, connection): + df = _get_historical_features( + repo_config, + [driver_fv], + ["driver_stats:conv_rate"], + start_date=datetime(2025, 8, 1, tzinfo=timezone.utc), + end_date=datetime(2025, 8, 2, tzinfo=timezone.utc), + ).to_df() + + assert df.empty + assert {"driver_id", "event_timestamp", "conv_rate"} <= set(df.columns) + + +def test_entity_df_mode_is_unchanged(repo_config, connection): + entity_df = pd.DataFrame({"driver_id": [3], "event_timestamp": _utc("2025-06-02")}) + registry = MagicMock() + registry.list_on_demand_feature_views.return_value = [] + + df = MsSqlServerOfflineStore.get_historical_features( + config=repo_config, + feature_views=[driver_fv], + feature_refs=["driver_stats:conv_rate"], + entity_df=entity_df, + registry=registry, + project="test_project", + ).to_df() + + assert _rows(df, ["driver_id", "conv_rate"]) == [(3, 0.4)] diff --git a/sdk/python/tests/unit/infra/offline_stores/test_ibis.py b/sdk/python/tests/unit/infra/offline_stores/test_ibis.py index 20c10cd19e8..094b811e4ca 100644 --- a/sdk/python/tests/unit/infra/offline_stores/test_ibis.py +++ b/sdk/python/tests/unit/infra/offline_stores/test_ibis.py @@ -8,11 +8,18 @@ import pyarrow.compute as pc import pytest +from feast.entity import Entity +from feast.feature_view import FeatureView +from feast.field import Field +from feast.infra.offline_stores.file_source import FileSource from feast.infra.offline_stores.ibis import ( + build_entity_df_for_date_range_ibis, point_in_time_join, pull_all_from_table_or_query_ibis, pull_latest_from_table_or_query_ibis, ) +from feast.types import Float32, Int64 +from feast.value_type import ValueType def pa_datetime(year, month, day): @@ -278,3 +285,202 @@ def test_pull_filters_parquet_timestamps_of_any_precision(tmp_path, dtype, pull) ).to_arrow() assert sorted(table["driver_id"].to_pylist()) == [2, 3] + + +def _date_range_feature_view(name, entities, schema, field_mapping=None): + return FeatureView( + name=name, + entities=entities, + schema=schema, + source=FileSource( + name=name, + path=f"{name}.parquet", + timestamp_field="event_timestamp", + field_mapping=field_mapping, + ), + ) + + +def _build_entity_df_for_date_range(feature_views, tables, start_date, end_date): + return build_entity_df_for_date_range_ibis( + config=MagicMock(repo_path=None), + feature_views=feature_views, + start_date=start_date, + end_date=end_date, + data_source_reader=lambda source, repo_path: ibis.memtable(tables[source.name]), + ) + + +def test_build_entity_df_for_date_range_unions_keys_in_the_time_range(): + """Every join key with an event in the range gets one row at end_date, with NULL + for the keys its feature view does not have.""" + driver = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) + customer = Entity( + name="customer", join_keys=["customer_id"], value_type=ValueType.INT64 + ) + driver_fv = _date_range_feature_view( + "driver_stats", + [driver], + [Field(name="driver_id", dtype=Int64), Field(name="rating", dtype=Float32)], + ) + customer_fv = _date_range_feature_view( + "customer_stats", + [customer], + [Field(name="customer_id", dtype=Int64)], + field_mapping={"cust": "customer_id"}, + ) + tables = { + "driver_stats": pd.DataFrame( + { + "driver_id": [1, 1, 2, 3], + "event_timestamp": pd.to_datetime( + ["2024-01-02", "2024-01-03", "2024-01-04", "2023-12-01"], utc=True + ), + "rating": [1.0, 2.0, 3.0, 4.0], + } + ), + "customer_stats": pd.DataFrame( + { + "cust": [10, 20], + "event_timestamp": pd.to_datetime( + ["2024-01-02", "2024-02-01"], utc=True + ), + } + ), + } + end_date = datetime(2024, 1, 10, tzinfo=timezone.utc) + + entity_df = _build_entity_df_for_date_range( + [driver_fv, customer_fv], + tables, + start_date=datetime(2024, 1, 1, tzinfo=timezone.utc), + end_date=end_date, + ) + + assert list(entity_df.columns) == ["driver_id", "customer_id", "event_timestamp"] + rows = { + ( + None if pd.isna(row.driver_id) else int(row.driver_id), + None if pd.isna(row.customer_id) else int(row.customer_id), + ) + for row in entity_df.itertuples() + } + assert rows == {(1, None), (2, None), (None, 10)} + assert len(entity_df) == 3 + assert str(entity_df["event_timestamp"].dtype) == "datetime64[ns, UTC]" + assert (entity_df["event_timestamp"] == pd.Timestamp(end_date)).all() + + +def test_build_entity_df_for_date_range_uses_projected_join_keys(): + """Join keys renamed by the projection take the new name; the others keep theirs.""" + driver = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) + customer = Entity( + name="customer", join_keys=["customer_id"], value_type=ValueType.INT64 + ) + trips_fv = _date_range_feature_view( + "trips", + [driver, customer], + [Field(name="driver_id", dtype=Int64), Field(name="customer_id", dtype=Int64)], + ).with_join_key_map({"driver_id": "origin_id"}) + tables = { + "trips": pd.DataFrame( + { + "driver_id": [1, 1, 2], + "customer_id": [10, 10, 20], + "event_timestamp": pd.to_datetime( + ["2024-01-02", "2024-01-03", "2024-01-03"], utc=True + ), + } + ) + } + + entity_df = _build_entity_df_for_date_range( + [trips_fv], + tables, + start_date=datetime(2024, 1, 1, tzinfo=timezone.utc), + end_date=datetime(2024, 1, 10, tzinfo=timezone.utc), + ) + + assert list(entity_df.columns) == ["origin_id", "customer_id", "event_timestamp"] + assert sorted(zip(entity_df["origin_id"], entity_df["customer_id"])) == [ + (1, 10), + (2, 20), + ] + + +def test_build_entity_df_for_date_range_unions_join_keys_of_different_types(): + driver = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) + driver_fv = _date_range_feature_view( + "driver_stats", [driver], [Field(name="driver_id", dtype=Int64)] + ) + trips_fv = _date_range_feature_view( + "driver_trips", [driver], [Field(name="driver_id", dtype=Int64)] + ) + timestamps = pd.to_datetime(["2024-01-02", "2024-01-03"], utc=True) + tables = { + "driver_stats": pd.DataFrame( + { + "driver_id": pd.Series([1, 2], dtype="int64"), + "event_timestamp": timestamps, + } + ), + "driver_trips": pd.DataFrame( + { + "driver_id": pd.Series([2, 3], dtype="int32"), + "event_timestamp": timestamps, + } + ), + } + + entity_df = _build_entity_df_for_date_range( + [driver_fv, trips_fv], + tables, + start_date=datetime(2024, 1, 1, tzinfo=timezone.utc), + end_date=datetime(2024, 1, 10, tzinfo=timezone.utc), + ) + + assert sorted(entity_df["driver_id"]) == [1, 2, 3] + + +def test_build_entity_df_for_date_range_without_entities_is_one_row_at_end_date(): + """Feature views without entities join on the timestamp alone and add no rows.""" + global_fv = _date_range_feature_view( + "global_stats", [], [Field(name="total", dtype=Int64)] + ) + + entity_df = _build_entity_df_for_date_range( + [global_fv], + tables={}, + start_date=datetime(2024, 1, 1, tzinfo=timezone.utc), + end_date=datetime(2024, 1, 10), + ) + + assert entity_df.to_dict("list") == { + "event_timestamp": [pd.Timestamp("2024-01-10", tz="UTC")] + } + + +def test_build_entity_df_for_date_range_without_events_in_range_is_empty(): + driver = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) + driver_fv = _date_range_feature_view( + "driver_stats", [driver], [Field(name="driver_id", dtype=Int64)] + ) + tables = { + "driver_stats": pd.DataFrame( + { + "driver_id": [1], + "event_timestamp": pd.to_datetime(["2023-01-01"], utc=True), + } + ) + } + + entity_df = _build_entity_df_for_date_range( + [driver_fv], + tables, + start_date=datetime(2024, 1, 1, tzinfo=timezone.utc), + end_date=datetime(2024, 1, 10, tzinfo=timezone.utc), + ) + + assert entity_df.empty + assert list(entity_df.columns) == ["driver_id", "event_timestamp"] + assert str(entity_df["event_timestamp"].dtype) == "datetime64[ns, UTC]" From 6e4827bc5ae98c2265db4568c5ed406320a057fc Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:50:17 +0530 Subject: [PATCH 2/3] fix: Widen join key types across feature views in non-entity retrieval Casting every source to the type of the first feature view could overflow when a BIGINT key followed an INT one. Use the common type of all occurrences instead. Signed-off-by: NopeCharon <115794254+NopeCharon@users.noreply.github.com> --- sdk/python/feast/infra/offline_stores/ibis.py | 11 ++++-- .../unit/infra/offline_stores/test_ibis.py | 34 +++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/sdk/python/feast/infra/offline_stores/ibis.py b/sdk/python/feast/infra/offline_stores/ibis.py index ba6741fa323..ab31a84eee6 100644 --- a/sdk/python/feast/infra/offline_stores/ibis.py +++ b/sdk/python/feast/infra/offline_stores/ibis.py @@ -261,11 +261,16 @@ def build_entity_df_for_date_range_ibis( return pd.DataFrame({event_timestamp_col: [pd.Timestamp(end_date)]}) # A union needs the same columns and types in every table, so each key table - # gets every join key, cast to the type of its first occurrence or NULL. - join_key_types: Dict[str, dt.DataType] = {} + # gets every join key, cast to the common type of all its occurrences or NULL, + # so the result does not depend on the order of the feature views. + key_types: Dict[str, List[dt.DataType]] = {} for key_table in key_tables: for column, column_type in key_table.schema().items(): - join_key_types.setdefault(column, column_type) + key_types.setdefault(column, []).append(column_type) + join_key_types: Dict[str, dt.DataType] = { + column: dt.highest_precedence(column_types) + for column, column_types in key_types.items() + } entity_table = ibis.union( *[ diff --git a/sdk/python/tests/unit/infra/offline_stores/test_ibis.py b/sdk/python/tests/unit/infra/offline_stores/test_ibis.py index 094b811e4ca..01b63703901 100644 --- a/sdk/python/tests/unit/infra/offline_stores/test_ibis.py +++ b/sdk/python/tests/unit/infra/offline_stores/test_ibis.py @@ -442,6 +442,40 @@ def test_build_entity_df_for_date_range_unions_join_keys_of_different_types(): assert sorted(entity_df["driver_id"]) == [1, 2, 3] +def test_build_entity_df_for_date_range_widens_join_key_types_regardless_of_order(): + driver = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) + driver_fv = _date_range_feature_view( + "driver_stats", [driver], [Field(name="driver_id", dtype=Int64)] + ) + trips_fv = _date_range_feature_view( + "driver_trips", [driver], [Field(name="driver_id", dtype=Int64)] + ) + timestamps = pd.to_datetime(["2024-01-02", "2024-01-03"], utc=True) + tables = { + "driver_stats": pd.DataFrame( + { + "driver_id": pd.Series([1, 2], dtype="int32"), + "event_timestamp": timestamps, + } + ), + "driver_trips": pd.DataFrame( + { + "driver_id": pd.Series([2, 3_000_000_000], dtype="int64"), + "event_timestamp": timestamps, + } + ), + } + + entity_df = _build_entity_df_for_date_range( + [driver_fv, trips_fv], + tables, + start_date=datetime(2024, 1, 1, tzinfo=timezone.utc), + end_date=datetime(2024, 1, 10, tzinfo=timezone.utc), + ) + + assert sorted(entity_df["driver_id"]) == [1, 2, 3_000_000_000] + + def test_build_entity_df_for_date_range_without_entities_is_one_row_at_end_date(): """Feature views without entities join on the timestamp alone and add no rows.""" global_fv = _date_range_feature_view( From 16b98426076eaa8e57a0042f9a4ac5d273e5662e Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:11:17 +0530 Subject: [PATCH 3/3] test: Cover partial join key map in SQL Server non-entity retrieval Signed-off-by: NopeCharon <115794254+NopeCharon@users.noreply.github.com> --- sdk/python/feast/infra/offline_stores/ibis.py | 7 +--- .../test_mssql_non_entity_mode.py | 39 +++++++++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/sdk/python/feast/infra/offline_stores/ibis.py b/sdk/python/feast/infra/offline_stores/ibis.py index a43e2cea694..8a7ac95f71d 100644 --- a/sdk/python/feast/infra/offline_stores/ibis.py +++ b/sdk/python/feast/infra/offline_stores/ibis.py @@ -235,12 +235,7 @@ def build_entity_df_for_date_range_ibis( key_tables: List[Table] = [] for feature_view in feature_views: - join_key_map = { - column.name: feature_view.projection.join_key_map.get( - column.name, column.name - ) - for column in feature_view.entity_columns - } + join_key_map = _join_key_map(feature_view) if not join_key_map: continue if feature_view.batch_source is None: diff --git a/sdk/python/tests/unit/infra/offline_stores/contrib/mssql_offline_store/test_mssql_non_entity_mode.py b/sdk/python/tests/unit/infra/offline_stores/contrib/mssql_offline_store/test_mssql_non_entity_mode.py index ab1ab8d07be..f32ca21ca2c 100644 --- a/sdk/python/tests/unit/infra/offline_stores/contrib/mssql_offline_store/test_mssql_non_entity_mode.py +++ b/sdk/python/tests/unit/infra/offline_stores/contrib/mssql_offline_store/test_mssql_non_entity_mode.py @@ -69,6 +69,22 @@ ), ) +pair_fv = FeatureView( + name="pair_stats", + entities=[driver, customer], + ttl=timedelta(days=5), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="customer_id", dtype=Int64), + Field(name="rating", dtype=Float32), + ], + source=MsSqlServerSource( + name="pair_source", + table_ref="pair_stats", + event_timestamp_column="event_timestamp", + ), +) + def _utc(*timestamps): return pd.to_datetime(list(timestamps), utc=True) @@ -111,6 +127,14 @@ def connection(): "spend": [100.0, 200.0], } ), + "pair_stats": pd.DataFrame( + { + "driver_id": [1, 1], + "customer_id": [10, 20], + "event_timestamp": _utc("2025-07-08", "2025-07-09"), + "rating": [1.0, 2.0], + } + ), "global_stats": pd.DataFrame( { "event_timestamp": _utc("2025-07-01", "2025-07-10"), @@ -258,3 +282,18 @@ def test_entity_df_mode_is_unchanged(repo_config, connection): ).to_df() assert _rows(df, ["driver_id", "conv_rate"]) == [(3, 0.4)] + + +def test_partial_join_key_map_keeps_unmapped_keys(repo_config, connection): + df = _get_historical_features( + repo_config, + [pair_fv.with_join_key_map({"driver_id": "origin_id"})], + ["pair_stats:rating"], + start_date=START, + end_date=END, + ).to_df() + + assert _rows(df, ["origin_id", "customer_id", "rating"]) == [ + (1, 10, 1.0), + (1, 20, 2.0), + ]