diff --git a/docs/getting-started/concepts/feature-retrieval.md b/docs/getting-started/concepts/feature-retrieval.md index 0fd65222ebe..4a00fb1c34c 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 **Couchbase Columnar** 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..6d2d987e193 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 **Couchbase Columnar** offline stores. Postgres was the first to support it; Dask, Spark, Ray, Trino, and Couchbase Columnar 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/couchbase.md b/docs/reference/offline-stores/couchbase.md index 3ae0f68d4c2..0391352ba21 100644 --- a/docs/reference/offline-stores/couchbase.md +++ b/docs/reference/offline-stores/couchbase.md @@ -4,6 +4,7 @@ The Couchbase Columnar offline store provides support for reading [CouchbaseColumnarSources](../data-sources/couchbase.md). **Note that Couchbase Columnar is available through [Couchbase Capella](https://cloud.couchbase.com/).** * Entity dataframes can be provided as a SQL++ query or can be provided as a Pandas dataframe. A Pandas dataframe will be uploaded to Couchbase Capella Columnar as a collection. +* 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. No collection is created in this mode. See [entity-less retrieval](../../getting-started/concepts/feature-retrieval.md) for details. ## Disclaimer diff --git a/sdk/python/feast/infra/offline_stores/contrib/couchbase_offline_store/couchbase.py b/sdk/python/feast/infra/offline_stores/contrib/couchbase_offline_store/couchbase.py index bb239048a90..465332f1f19 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/couchbase_offline_store/couchbase.py +++ b/sdk/python/feast/infra/offline_stores/contrib/couchbase_offline_store/couchbase.py @@ -40,6 +40,7 @@ from feast.on_demand_feature_view import OnDemandFeatureView from feast.repo_config import FeastConfigBaseModel, RepoConfig from feast.saved_dataset import SavedDatasetStorage +from feast.utils import compute_non_entity_date_range from ... import offline_utils from ...offline_utils import get_timestamp_filter_sql @@ -134,11 +135,12 @@ 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: """ Retrieve historical features using point-in-time joins. @@ -152,6 +154,19 @@ def get_historical_features( for fv in feature_views: assert isinstance(fv.batch_source, CouchbaseColumnarSource) + if entity_df is None: + return _get_historical_features_without_entity_df( + config=config, + feature_views=feature_views, + feature_refs=feature_refs, + registry=registry, + project=project, + full_feature_names=full_feature_names, + filter_by_created_timestamp=filter_by_created_timestamp, + start_date=kwargs.get("start_date"), + end_date=kwargs.get("end_date"), + ) + entity_schema = _get_entity_schema(entity_df, config) entity_df_event_timestamp_col = ( @@ -468,6 +483,125 @@ def _get_entity_df_event_timestamp_range( return entity_df_event_timestamp_range +def _get_historical_features_without_entity_df( + config: RepoConfig, + feature_views: List[FeatureView], + feature_refs: List[str], + registry: BaseRegistry, + project: str, + full_feature_names: bool, + filter_by_created_timestamp: bool, + start_date: Optional[datetime], + end_date: Optional[datetime], +) -> RetrievalJob: + """ + Retrieves historical features for a time range instead of an entity dataframe. + + The left side of the point-in-time join is built from the entity keys observed + in the feature view sources between start_date and end_date, each joined as of + end_date, so every entity gets its latest feature values within the TTL. + """ + start_date, end_date = compute_non_entity_date_range( + feature_views, + start_date=start_date, + end_date=end_date, + ) + + query_context = offline_utils.get_feature_view_query_context( + feature_refs, + feature_views, + registry, + project, + (start_date, end_date), + ) + + entity_df_event_timestamp_col = offline_utils.DEFAULT_ENTITY_DF_EVENT_TIMESTAMP_COL + join_keys = offline_utils.gather_all_entities(query_context) + entity_df_columns = { + column: None for column in join_keys + [entity_df_event_timestamp_col] + }.keys() + + query = build_point_in_time_query( + [asdict(context) for context in query_context], + left_table_query_string=_build_non_entity_left_table_query( + query_context=query_context, + join_keys=join_keys, + start_date=start_date, + end_date=end_date, + entity_df_event_timestamp_col=entity_df_event_timestamp_col, + ), + entity_df_event_timestamp_col=entity_df_event_timestamp_col, + entity_df_columns=entity_df_columns, + query_template=MULTIPLE_FEATURE_VIEW_POINT_IN_TIME_JOIN, + full_feature_names=full_feature_names, + filter_by_created_timestamp=filter_by_created_timestamp, + ) + + return CouchbaseColumnarRetrievalJob( + query=query, + config=config, + full_feature_names=full_feature_names, + on_demand_feature_views=OnDemandFeatureView.get_requested_odfvs( + feature_refs, project, registry + ), + metadata=RetrievalMetadata( + features=feature_refs, + keys=join_keys, + min_event_timestamp=start_date, + max_event_timestamp=end_date, + ), + timestamp_field=entity_df_event_timestamp_col, + ) + + +def _build_non_entity_left_table_query( + query_context: List[offline_utils.FeatureViewQueryContext], + join_keys: List[str], + start_date: datetime, + end_date: datetime, + entity_df_event_timestamp_col: str, +) -> str: + """ + Builds a subquery that stands in for the entity dataframe in non-entity mode. + + It selects the distinct join keys of every feature view with entities whose + source has events between start_date and end_date, fills the join keys a + feature view does not have with null, and sets the event timestamp of every + row to end_date. Feature views without entities join on the timestamp alone, + so they do not contribute rows. When no feature view has entities, the + subquery is a single row holding end_date. + """ + start_timestamp = normalize_timestamp(start_date) + end_timestamp = normalize_timestamp(end_date) + event_timestamp_col = _escape_column(entity_df_event_timestamp_col) + + entity_selects = [] + for context in query_context: + if not context.entities: + continue + selections = dict(zip(context.entities, context.entity_selections)) + columns = ", ".join( + selections.get(join_key, f"null AS {join_key}") for join_key in join_keys + ) + entity_selects.append( + f"SELECT {columns} " + f"FROM {context.table_subquery} AS sub " + f"WHERE sub.{_escape_column(context.timestamp_field)} " + f"BETWEEN '{start_timestamp}' AND '{end_timestamp}'" + ) + + if not entity_selects: + return f"(SELECT '{end_timestamp}' AS {event_timestamp_col})" + + entity_union = "\n UNION ALL\n ".join(entity_selects) + return f"""( + SELECT DISTINCT entity_keys.*, '{end_timestamp}' AS {event_timestamp_col} + FROM ( + {entity_union} + ) AS entity_keys +)""" + + def _escape_column(column: str) -> str: """Wrap column names in backticks to handle reserved words.""" return f"`{column}`" diff --git a/sdk/python/tests/unit/infra/offline_stores/contrib/couchbase_offline_store/test_couchbase_non_entity_mode.py b/sdk/python/tests/unit/infra/offline_stores/contrib/couchbase_offline_store/test_couchbase_non_entity_mode.py new file mode 100644 index 00000000000..66c2de4b720 --- /dev/null +++ b/sdk/python/tests/unit/infra/offline_stores/contrib/couchbase_offline_store/test_couchbase_non_entity_mode.py @@ -0,0 +1,375 @@ +from datetime import datetime, timedelta, timezone +from unittest.mock import MagicMock, patch + +import pandas as pd +import pytest + +from feast import Entity, FeatureView, Field, ValueType +from feast.infra.offline_stores.contrib.couchbase_offline_store.couchbase import ( + CouchbaseColumnarOfflineStore, + CouchbaseColumnarOfflineStoreConfig, + _build_non_entity_left_table_query, +) +from feast.infra.offline_stores.contrib.couchbase_offline_store.couchbase_source import ( + CouchbaseColumnarSource, +) +from feast.infra.offline_stores.offline_utils import ( + gather_all_entities, + get_feature_view_query_context, +) +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) +START_LITERAL = "'2025-07-01T00:00:00+0000'" +END_LITERAL = "'2025-07-10T12:00:00+0000'" + +COUCHBASE_MODULE = ( + "feast.infra.offline_stores.contrib.couchbase_offline_store.couchbase" +) + +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=CouchbaseColumnarSource( + name="driver_source", + database="Default", + scope="Default", + collection="driver_stats", + timestamp_field="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=CouchbaseColumnarSource( + name="customer_source", + database="Default", + scope="Default", + collection="customer_stats", + timestamp_field="event_ts", + field_mapping={"cust": "customer_id", "ts": "event_ts"}, + ), +) + +global_fv = FeatureView( + name="global_stats", + entities=[], + ttl=timedelta(days=1), + schema=[Field(name="total", dtype=Int64)], + source=CouchbaseColumnarSource( + name="global_source", + database="Default", + scope="Default", + collection="global_stats", + timestamp_field="event_timestamp", + ), +) + + +@pytest.fixture +def repo_config(): + return RepoConfig( + registry="file:///tmp/registry.db", + project="test_project", + provider="local", + online_store=SqliteOnlineStoreConfig(type="sqlite"), + offline_store=CouchbaseColumnarOfflineStoreConfig( + connection_string="couchbases://localhost", + user="feast", + password="feast", # pragma: allowlist secret + ), + entity_key_serialization_version=3, + ) + + +@pytest.fixture +def execute_query(): + with patch(f"{COUCHBASE_MODULE}._execute_query") as execute_query: + yield execute_query + + +def _get_historical_features(repo_config, feature_views, feature_refs, **kwargs): + registry = MagicMock() + registry.list_on_demand_feature_views.return_value = [] + return CouchbaseColumnarOfflineStore.get_historical_features( + config=repo_config, + feature_views=feature_views, + feature_refs=feature_refs, + entity_df=None, + registry=registry, + project="test_project", + **kwargs, + ) + + +def _left_table_query(feature_views, feature_refs): + query_context = get_feature_view_query_context( + feature_refs=feature_refs, + feature_views=feature_views, + registry=MagicMock(), + project="test_project", + entity_df_timestamp_range=(START, END), + ) + join_keys = gather_all_entities(query_context) + return _build_non_entity_left_table_query( + query_context=query_context, + join_keys=join_keys, + start_date=START, + end_date=END, + entity_df_event_timestamp_col="event_timestamp", + ) + + +def _normalize(sql: str) -> str: + return " ".join(sql.split()) + + +def test_left_table_selects_entities_observed_in_range(): + query = _normalize(_left_table_query([driver_fv], ["driver_stats:conv_rate"])) + + assert ( + "SELECT driver_id AS driver_id " + "FROM `Default`.`Default`.`driver_stats` AS sub " + f"WHERE sub.`event_timestamp` BETWEEN {START_LITERAL} AND {END_LITERAL}" + ) in query + assert f"SELECT DISTINCT entity_keys.*, {END_LITERAL} AS `event_timestamp`" in query + assert "UNION ALL" not in query + + +def test_left_table_uses_source_column_names_from_field_mapping(): + query = _normalize(_left_table_query([customer_fv], ["customer_stats:spend"])) + + assert "SELECT cust AS customer_id" in query + assert f"WHERE sub.`ts` BETWEEN {START_LITERAL} AND {END_LITERAL}" in query + + +def test_left_table_unions_feature_views_and_fills_missing_join_keys(): + query = _normalize( + _left_table_query( + [driver_fv, customer_fv], + ["driver_stats:conv_rate", "customer_stats:spend"], + ) + ) + + assert ( + "SELECT driver_id AS driver_id, null AS customer_id " + "FROM `Default`.`Default`.`driver_stats` AS sub" + ) in query + assert ( + "SELECT null AS driver_id, cust AS customer_id " + "FROM `Default`.`Default`.`customer_stats` AS sub" + ) in query + assert query.count(" UNION ALL ") == 1 + assert query.count("SELECT DISTINCT") == 1 + + +def test_left_table_wraps_query_sources_in_parentheses(): + query_fv = FeatureView( + name="driver_query_stats", + entities=[driver], + ttl=timedelta(days=2), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="conv_rate", dtype=Float32), + ], + source=CouchbaseColumnarSource( + name="driver_query_source", + query="SELECT d.* FROM `Default`.`Default`.`drivers` d WHERE d.active", + timestamp_field="event_timestamp", + ), + ) + + query = _normalize(_left_table_query([query_fv], ["driver_query_stats:conv_rate"])) + + assert ( + "FROM (SELECT d.* FROM `Default`.`Default`.`drivers` d WHERE d.active) " + f"AS sub WHERE sub.`event_timestamp` BETWEEN {START_LITERAL} AND {END_LITERAL}" + ) in query + + +def test_left_table_skips_feature_views_without_entities(): + query = _normalize( + _left_table_query( + [driver_fv, global_fv], + ["driver_stats:conv_rate", "global_stats:total"], + ) + ) + + assert "global_stats" not in query + assert "FROM `Default`.`Default`.`driver_stats` AS sub" in query + + +def test_left_table_is_single_row_without_entities(): + query = _normalize(_left_table_query([global_fv], ["global_stats:total"])) + + assert query == f"(SELECT {END_LITERAL} AS `event_timestamp`)" + + +def test_left_table_converts_dates_to_utc(): + query_context = get_feature_view_query_context( + feature_refs=["driver_stats:conv_rate"], + feature_views=[driver_fv], + registry=MagicMock(), + project="test_project", + entity_df_timestamp_range=(START, END), + ) + tz = timezone(timedelta(hours=2)) + + query = _build_non_entity_left_table_query( + query_context=query_context, + join_keys=["driver_id"], + start_date=START.astimezone(tz), + end_date=END.astimezone(tz), + entity_df_event_timestamp_col="event_timestamp", + ) + + assert START_LITERAL in query + assert END_LITERAL in query + + +def test_non_entity_mode_does_not_upload_entity_df(repo_config, execute_query): + with patch(f"{COUCHBASE_MODULE}._upload_entity_df") as upload_entity_df: + job = _get_historical_features( + repo_config, + [driver_fv], + ["driver_stats:conv_rate"], + start_date=START, + end_date=END, + ) + job.to_sql() + + upload_entity_df.assert_not_called() + execute_query.assert_not_called() + + +def test_non_entity_mode_builds_point_in_time_query(repo_config, execute_query): + job = _get_historical_features( + repo_config, + [driver_fv, customer_fv], + ["driver_stats:conv_rate", "customer_stats:spend"], + full_feature_names=True, + start_date=START, + end_date=END, + ) + query = _normalize(job.to_sql()) + + assert "SELECT driver_id AS driver_id, null AS customer_id" in query + assert "SELECT null AS driver_id, cust AS customer_id" in query + assert "FROM ( SELECT DISTINCT entity_keys.*" in query + assert ( + "IFMISSINGORNULL(`driver_stats_final`.`driver_stats__conv_rate`, null) " + "AS `driver_stats__conv_rate`" + ) in query + assert ( + "IFMISSINGORNULL(`customer_stats_final`.`customer_stats__spend`, null) " + "AS `customer_stats__spend`" + ) in query + assert "main_entity.`driver_id`" in query + assert "main_entity.`customer_id`" in query + assert "main_entity.`event_timestamp`" in query + assert job.full_feature_names is True + + +def test_non_entity_mode_parses_event_timestamp_column(repo_config, execute_query): + execute_query.return_value.get_all_rows.return_value = [ + { + "driver_id": 1, + "event_timestamp": "2025-07-10T12:00:00+0000", + "conv_rate": 0.3, + } + ] + job = _get_historical_features( + repo_config, + [driver_fv], + ["driver_stats:conv_rate"], + start_date=START, + end_date=END, + ) + + df = job.to_df() + + assert df["event_timestamp"].tolist() == [pd.Timestamp(END)] + + +def test_non_entity_mode_metadata(repo_config, execute_query): + job = _get_historical_features( + repo_config, + [driver_fv, customer_fv], + ["driver_stats:conv_rate", "customer_stats:spend"], + start_date=START, + end_date=END, + ) + + assert job.metadata is not None + assert job.metadata.features == ["driver_stats:conv_rate", "customer_stats:spend"] + assert job.metadata.keys == ["driver_id", "customer_id"] + assert job.metadata.min_event_timestamp == START + assert job.metadata.max_event_timestamp == END + + +def test_non_entity_mode_defaults_start_date_to_max_ttl(repo_config, execute_query): + job = _get_historical_features( + repo_config, + [driver_fv, customer_fv], + ["driver_stats:conv_rate", "customer_stats:spend"], + end_date=END, + ) + + assert job.metadata is not None + assert job.metadata.min_event_timestamp == END - timedelta(days=5) + assert job.metadata.max_event_timestamp == END + + +def test_non_entity_mode_filters_by_created_timestamp(repo_config, execute_query): + job = _get_historical_features( + repo_config, + [driver_fv], + ["driver_stats:conv_rate"], + filter_by_created_timestamp=True, + start_date=START, + end_date=END, + ) + + assert "AND subquery.created_timestamp <= entity_dataframe.entity_timestamp" in ( + _normalize(job.to_sql()) + ) + + +def test_entity_df_mode_still_uploads_entity_df(repo_config, execute_query): + entity_df = pd.DataFrame({"driver_id": [1], "event_timestamp": [END]}) + registry = MagicMock() + registry.list_on_demand_feature_views.return_value = [] + + with patch(f"{COUCHBASE_MODULE}._upload_entity_df") as upload_entity_df: + job = CouchbaseColumnarOfflineStore.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", + ) + query = job.to_sql() + + upload_entity_df.assert_called_once() + assert "entity_keys" not in query