diff --git a/sdk/python/feast/infra/offline_stores/bigquery.py b/sdk/python/feast/infra/offline_stores/bigquery.py index 77c9a17de87..dc5eaf40cac 100644 --- a/sdk/python/feast/infra/offline_stores/bigquery.py +++ b/sdk/python/feast/infra/offline_stores/bigquery.py @@ -10,11 +10,13 @@ ContextManager, Dict, Iterator, + KeysView, List, Literal, Optional, Tuple, Union, + cast, ) import numpy as np @@ -57,7 +59,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 _utc_now, get_user_agent +from feast.utils import _utc_now, compute_non_entity_date_range, get_user_agent from .bigquery_source import ( BigQueryLoggingDestination, @@ -267,10 +269,11 @@ 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, + **kwargs: Any, ) -> RetrievalJob: # TODO: Add entity_df validation in order to fail before interacting with BigQuery assert isinstance(config.offline_store, BigQueryOfflineStoreConfig) @@ -297,39 +300,52 @@ def get_historical_features( config.offline_store.table_create_disposition, ) - entity_schema = _get_entity_schema( - client=client, - entity_df=entity_df, - ) + # Non-entity mode: create a left temporary table from entity keys - any entity key having an event in the time window - entity_df_event_timestamp_col = ( - offline_utils.infer_event_timestamp_from_entity_df(entity_schema) - ) + non_entity_mode = entity_df is None - entity_df_event_timestamp_range = _get_entity_df_event_timestamp_range( - entity_df, - entity_df_event_timestamp_col, - client, - ) + if non_entity_mode: + 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_event_timestamp_range = (start_date, end_date) - @contextlib.contextmanager - def query_generator() -> Iterator[str]: - _upload_entity_df( + # Pre-compute query contexts to collect entity column names per feature view. + fv_query_contexts_pre = offline_utils.get_feature_view_query_context( + feature_refs, + feature_views, + registry, + project, + entity_df_event_timestamp_range, + ) + all_entities = offline_utils.gather_all_entities(fv_query_contexts_pre) + event_timestamp_col = "entity_ts" + entity_schema_keys: KeysView[str] = cast( + KeysView[str], + {k: None for k in (all_entities + [event_timestamp_col])}.keys(), + ) + + entity_schema = None + else: + entity_schema = _get_entity_schema( client=client, - table_name=table_reference, entity_df=entity_df, ) - - expected_join_keys = offline_utils.get_expected_join_keys( - project, feature_views, registry + event_timestamp_col = offline_utils.infer_event_timestamp_from_entity_df( + entity_schema ) - - offline_utils.assert_expected_columns_in_entity_df( - entity_schema, expected_join_keys, entity_df_event_timestamp_col + entity_df_event_timestamp_range = _get_entity_df_event_timestamp_range( + entity_df, + event_timestamp_col, + client, ) - - # Build a query context containing all information required to template the BigQuery SQL query - query_context = offline_utils.get_feature_view_query_context( + entity_schema_keys = entity_schema.keys() + all_entities = [] + start_date = entity_df_event_timestamp_range[0] + end_date = entity_df_event_timestamp_range[1] + fv_query_contexts_pre = offline_utils.get_feature_view_query_context( feature_refs, feature_views, registry, @@ -337,12 +353,39 @@ def query_generator() -> Iterator[str]: entity_df_event_timestamp_range, ) + @contextlib.contextmanager + def query_generator() -> Iterator[str]: + if non_entity_mode: + _bq_create_entity_union_table( + client=client, + table_name=table_reference, + feature_views=feature_views, + fv_query_contexts=fv_query_contexts_pre, + start_date=start_date, + end_date=end_date, + all_entities=all_entities, + event_timestamp_col=event_timestamp_col, + ) + else: + _upload_entity_df( + client=client, + table_name=table_reference, + entity_df=entity_df, + ) + expected_join_keys = offline_utils.get_expected_join_keys( + project, feature_views, registry + ) + assert entity_schema is not None + offline_utils.assert_expected_columns_in_entity_df( + entity_schema, expected_join_keys, event_timestamp_col + ) + # Generate the BigQuery SQL query from the query context query = offline_utils.build_point_in_time_query( - query_context, + feature_view_query_contexts=fv_query_contexts_pre, left_table_query_string=table_reference, - entity_df_event_timestamp_col=entity_df_event_timestamp_col, - entity_df_columns=entity_schema.keys(), + entity_df_event_timestamp_col=event_timestamp_col, + entity_df_columns=entity_schema_keys, query_template=MULTIPLE_FEATURE_VIEW_POINT_IN_TIME_JOIN, full_feature_names=full_feature_names, ) @@ -350,7 +393,7 @@ def query_generator() -> Iterator[str]: try: yield query finally: - # Asynchronously clean up the uploaded Bigquery table, which will expire + # Asynchronously clean up the uploaded BigQuery table, which will expire # if cleanup fails client.delete_table(table=table_reference, not_found_ok=True) @@ -364,7 +407,7 @@ def query_generator() -> Iterator[str]: ), metadata=RetrievalMetadata( features=feature_refs, - keys=list(entity_schema.keys() - {entity_df_event_timestamp_col}), + keys=list(set(entity_schema_keys) - {event_timestamp_col}), min_event_timestamp=entity_df_event_timestamp_range[0], max_event_timestamp=entity_df_event_timestamp_range[1], ), @@ -567,6 +610,62 @@ def clear_monitoring_baseline( ) +def _bq_create_entity_union_table( + client: "Client", + table_name: str, + feature_views: List[FeatureView], + fv_query_contexts: List[offline_utils.FeatureViewQueryContext], + start_date: datetime, + end_date: datetime, + all_entities: List[str], + event_timestamp_col: str, +) -> None: + """ + Creates a BigQuery temp table containing the UNION DISTINCT of entity keys observed + across all feature views in [start_date, end_date], plus a stable as-of timestamp + column set to end_date. Used as the left table for PIT joins in non-entity mode. + """ + start_str = start_date.strftime("%Y-%m-%dT%H:%M:%S") + end_str = end_date.strftime("%Y-%m-%dT%H:%M:%S") + + per_view_selects: List[str] = [] + for fv, ctx in zip(feature_views, fv_query_contexts): + assert isinstance(fv.batch_source, BigQuerySource) + from_expression = fv.batch_source.get_table_query_string() + timestamp_field = ctx.timestamp_field + + ctx_entities_set = set(ctx.entities) + select_entities: List[str] = [] + for col in all_entities: + if col in ctx_entities_set: + select_entities.append(f"`{col}`") + else: + select_entities.append(f"CAST(NULL AS STRING) AS `{col}`") + + per_view_selects.append( + f"SELECT DISTINCT {', '.join(select_entities)} " + f"FROM {from_expression} " + f"WHERE `{timestamp_field}` BETWEEN TIMESTAMP('{start_str}') AND TIMESTAMP('{end_str}')" + ) + + union_query = "\nUNION DISTINCT\n".join(per_view_selects) + entity_cols = ( + ", ".join(f"`{e}`" for e in all_entities) if all_entities else "TRUE AS _dummy" + ) + + create_sql = ( + f"CREATE TABLE `{table_name}` AS " + f"SELECT {entity_cols}, TIMESTAMP('{end_str}') AS `{event_timestamp_col}` " + f"FROM ({union_query}) AS _entity_union" + ) + + block_until_done(client, client.query(create_sql)) + + table = client.get_table(table_name) + table.expires = _utc_now() + timedelta(minutes=30) + client.update_table(table, ["expires"]) + + # ------------------------------------------------------------------ # # BigQuery monitoring metrics (native) # ------------------------------------------------------------------ # diff --git a/sdk/python/feast/infra/offline_stores/offline_utils.py b/sdk/python/feast/infra/offline_stores/offline_utils.py index fee87dde595..cd2b05a9a60 100644 --- a/sdk/python/feast/infra/offline_stores/offline_utils.py +++ b/sdk/python/feast/infra/offline_stores/offline_utils.py @@ -429,3 +429,12 @@ def format_date(val: Union[str, datetime]) -> str: filters.append(f"{dp_field} <= '{format_date(end_date)}'") return " AND ".join(filters) if filters else "" + + +def gather_all_entities(fv_query_contexts: List[FeatureViewQueryContext]): + all_entities: List[str] = [] + for ctx in fv_query_contexts: + for e in ctx.entities: + if e not in all_entities: + all_entities.append(e) + return all_entities diff --git a/sdk/python/tests/unit/infra/offline_stores/test_bigquery_non_entity_mode.py b/sdk/python/tests/unit/infra/offline_stores/test_bigquery_non_entity_mode.py new file mode 100644 index 00000000000..6bad310041b --- /dev/null +++ b/sdk/python/tests/unit/infra/offline_stores/test_bigquery_non_entity_mode.py @@ -0,0 +1,758 @@ +""" +Unit tests for BigQuery offline store non-entity mode (entity_df=None). + +Covers: +- _gather_all_entities helper +- _bq_create_entity_union_table SQL generation +- get_historical_features non-entity mode flow +- Regression: normal entity_df mode still works +""" + +from datetime import datetime, timedelta, timezone +from unittest.mock import MagicMock, patch + +import pytest + +from feast.infra.offline_stores.bigquery import ( + BigQueryOfflineStore, + BigQueryOfflineStoreConfig, + BigQueryRetrievalJob, + _bq_create_entity_union_table, +) +from feast.infra.offline_stores.bigquery_source import BigQuerySource +from feast.infra.offline_stores.offline_utils import ( + FeatureViewQueryContext, + gather_all_entities, +) +from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig +from feast.repo_config import RepoConfig + +# --------------------------------------------------------------------------- +# Constants +# --------------------------------------------------------------------------- + +START = datetime(2023, 1, 1, tzinfo=timezone.utc) +END = datetime(2024, 1, 1, tzinfo=timezone.utc) +TABLE_NAME = "project.dataset.feast_tmp_abc123" + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _make_repo_config(project_id: str = "my-project") -> RepoConfig: + return RepoConfig( + registry="gs://test/registry.db", + project="feast_test", + provider="gcp", + online_store=SqliteOnlineStoreConfig(type="sqlite"), + offline_store=BigQueryOfflineStoreConfig( + type="bigquery", + project_id=project_id, + dataset="feast", + ), + ) + + +def _make_fv_context( + name: str, + entities: list, + timestamp_field: str = "event_timestamp", + table_subquery: str = "`project.dataset.table`", +) -> FeatureViewQueryContext: + return FeatureViewQueryContext( + name=name, + ttl=86400, + entities=entities, + features=["feature_a"], + field_mapping={}, + timestamp_field=timestamp_field, + created_timestamp_column=None, + table_subquery=table_subquery, + entity_selections=[f"{e} AS {e}" for e in entities], + min_event_timestamp="2023-01-01T00:00:00", + max_event_timestamp="2024-01-01T00:00:00", + date_partition_column=None, + timestamp_field_type=None, + ) + + +def _make_bq_source(table: str = "project.dataset.table") -> BigQuerySource: + return BigQuerySource( + name="test_source", + table=table, + timestamp_field="event_timestamp", + ) + + +def _make_feature_view_mock( + name: str, entities: list, table: str = "project.dataset.table" +) -> MagicMock: + fv = MagicMock() + fv.name = name + fv.batch_source = _make_bq_source(table) + fv.entities = entities + return fv + + +# --------------------------------------------------------------------------- +# Tests: _gather_all_entities +# --------------------------------------------------------------------------- + + +class TestGatherAllEntities: + def test_single_feature_view(self): + ctx = _make_fv_context("fv1", ["customer_id", "item_id"]) + assert gather_all_entities([ctx]) == ["customer_id", "item_id"] + + def test_multiple_views_overlapping_entities(self): + ctx1 = _make_fv_context("fv1", ["customer_id", "item_id"]) + ctx2 = _make_fv_context("fv2", ["customer_id", "store_id"]) + result = gather_all_entities([ctx1, ctx2]) + # customer_id should appear only once; order is first-seen + assert result == ["customer_id", "item_id", "store_id"] + + def test_multiple_views_disjoint_entities(self): + ctx1 = _make_fv_context("fv1", ["driver_id"]) + ctx2 = _make_fv_context("fv2", ["customer_id"]) + result = gather_all_entities([ctx1, ctx2]) + assert result == ["driver_id", "customer_id"] + + def test_entityless_feature_view(self): + ctx = _make_fv_context("fv1", []) + assert gather_all_entities([ctx]) == [] + + def test_empty_list(self): + assert gather_all_entities([]) == [] + + def test_preserves_insertion_order(self): + ctx1 = _make_fv_context("fv1", ["z_entity", "a_entity"]) + ctx2 = _make_fv_context("fv2", ["a_entity", "m_entity"]) + result = gather_all_entities([ctx1, ctx2]) + assert result == ["z_entity", "a_entity", "m_entity"] + + +# --------------------------------------------------------------------------- +# Tests: _bq_create_entity_union_table — SQL generation +# --------------------------------------------------------------------------- + + +class TestBqCreateEntityUnionTable: + def _make_client(self) -> MagicMock: + client = MagicMock() + client.query.return_value = MagicMock() + client.get_table.return_value = MagicMock() + return client + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + def test_single_view_creates_table_with_correct_sql(self, mock_utc_now, mock_block): + mock_utc_now.return_value = END + client = self._make_client() + fv = _make_feature_view_mock("fv1", ["customer_id"]) + ctx = _make_fv_context( + "fv1", ["customer_id"], table_subquery="`project.dataset.orders`" + ) + + _bq_create_entity_union_table( + client=client, + table_name=TABLE_NAME, + feature_views=[fv], + fv_query_contexts=[ctx], + start_date=START, + end_date=END, + all_entities=["customer_id"], + event_timestamp_col="entity_ts", + ) + + sql = client.query.call_args[0][0] + assert f"CREATE TABLE `{TABLE_NAME}` AS" in sql + assert "SELECT DISTINCT `customer_id`" in sql + assert "UNION DISTINCT" not in sql # single view → no union + assert "entity_ts" in sql + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + def test_entity_column_not_cast_to_string(self, mock_utc_now, mock_block): + """INT64 entity columns must NOT be cast to STRING — that breaks the PIT join.""" + mock_utc_now.return_value = END + client = self._make_client() + fv = _make_feature_view_mock("fv1", ["user_id"]) + ctx = _make_fv_context("fv1", ["user_id"]) + + _bq_create_entity_union_table( + client=client, + table_name=TABLE_NAME, + feature_views=[fv], + fv_query_contexts=[ctx], + start_date=START, + end_date=END, + all_entities=["user_id"], + event_timestamp_col="entity_ts", + ) + + sql = client.query.call_args[0][0] + assert "CAST(`user_id` AS STRING)" not in sql + assert "`user_id`" in sql + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + def test_missing_entity_filled_with_null_not_cast_string( + self, mock_utc_now, mock_block + ): + """When a feature view doesn't have an entity column, fill it with NULL.""" + mock_utc_now.return_value = END + client = self._make_client() + fv1 = _make_feature_view_mock("fv1", ["customer_id", "item_id"]) + fv2 = _make_feature_view_mock("fv2", ["customer_id"]) + ctx1 = _make_fv_context("fv1", ["customer_id", "item_id"]) + ctx2 = _make_fv_context("fv2", ["customer_id"]) + + _bq_create_entity_union_table( + client=client, + table_name=TABLE_NAME, + feature_views=[fv1, fv2], + fv_query_contexts=[ctx1, ctx2], + start_date=START, + end_date=END, + all_entities=["customer_id", "item_id"], + event_timestamp_col="entity_ts", + ) + + sql = client.query.call_args[0][0] + # fv2 does not have item_id → must appear as NULL for item_id + assert "`item_id`" in sql + assert "NULL" in sql + # fv2's item_id fill must not appear as a regular column reference + assert "SELECT DISTINCT `customer_id`" in sql + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + def test_multiple_views_produce_union_distinct(self, mock_utc_now, mock_block): + mock_utc_now.return_value = END + client = self._make_client() + fv1 = _make_feature_view_mock("fv1", ["driver_id"]) + fv2 = _make_feature_view_mock("fv2", ["driver_id"]) + ctx1 = _make_fv_context("fv1", ["driver_id"]) + ctx2 = _make_fv_context("fv2", ["driver_id"]) + + _bq_create_entity_union_table( + client=client, + table_name=TABLE_NAME, + feature_views=[fv1, fv2], + fv_query_contexts=[ctx1, ctx2], + start_date=START, + end_date=END, + all_entities=["driver_id"], + event_timestamp_col="entity_ts", + ) + + sql = client.query.call_args[0][0] + assert "UNION DISTINCT" in sql + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + def test_timestamp_filter_uses_start_and_end(self, mock_utc_now, mock_block): + mock_utc_now.return_value = END + client = self._make_client() + fv = _make_feature_view_mock("fv1", ["entity_id"]) + ctx = _make_fv_context("fv1", ["entity_id"]) + + _bq_create_entity_union_table( + client=client, + table_name=TABLE_NAME, + feature_views=[fv], + fv_query_contexts=[ctx], + start_date=START, + end_date=END, + all_entities=["entity_id"], + event_timestamp_col="entity_ts", + ) + + sql = client.query.call_args[0][0] + assert "2023-01-01T00:00:00" in sql # start_date + assert ( + "2024-01-01T00:00:00" in sql + ) # end_date (appears twice: WHERE + entity_ts value) + assert "BETWEEN TIMESTAMP(" in sql + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + def test_entity_ts_column_set_to_end_date(self, mock_utc_now, mock_block): + """The as-of timestamp in the synthetic left table must equal end_date.""" + mock_utc_now.return_value = END + client = self._make_client() + fv = _make_feature_view_mock("fv1", ["entity_id"]) + ctx = _make_fv_context("fv1", ["entity_id"]) + + _bq_create_entity_union_table( + client=client, + table_name=TABLE_NAME, + feature_views=[fv], + fv_query_contexts=[ctx], + start_date=START, + end_date=END, + all_entities=["entity_id"], + event_timestamp_col="entity_ts", + ) + + sql = client.query.call_args[0][0] + assert "TIMESTAMP('2024-01-01T00:00:00') AS `entity_ts`" in sql + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + def test_sets_table_expiry(self, mock_utc_now, mock_block): + mock_utc_now.return_value = datetime(2024, 1, 1, tzinfo=timezone.utc) + client = self._make_client() + fv = _make_feature_view_mock("fv1", ["entity_id"]) + ctx = _make_fv_context("fv1", ["entity_id"]) + + _bq_create_entity_union_table( + client=client, + table_name=TABLE_NAME, + feature_views=[fv], + fv_query_contexts=[ctx], + start_date=START, + end_date=END, + all_entities=["entity_id"], + event_timestamp_col="entity_ts", + ) + + client.update_table.assert_called_once() + updated_table = client.update_table.call_args[0][0] + # expiry should be 30 minutes after _utc_now() + assert updated_table.expires == datetime( + 2024, 1, 1, tzinfo=timezone.utc + ) + timedelta(minutes=30) + + +# --------------------------------------------------------------------------- +# Tests: get_historical_features — non-entity mode flow +# --------------------------------------------------------------------------- + + +@pytest.fixture +def repo_config(): + return _make_repo_config() + + +@pytest.fixture +def mock_bq_client(): + client = MagicMock() + client.project = "my-project" + client.query.return_value = MagicMock( + state="DONE", exception=lambda timeout=None: None + ) + client.get_table.return_value = MagicMock() + return client + + +class TestGetHistoricalFeaturesNonEntityMode: + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + @patch("feast.infra.offline_stores.bigquery._bq_create_entity_union_table") + @patch("feast.infra.offline_stores.bigquery._upload_entity_df") + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.get_feature_view_query_context" + ) + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.build_point_in_time_query" + ) + @patch("feast.infra.offline_stores.bigquery._get_table_reference_for_new_entity") + @patch("feast.infra.offline_stores.bigquery._get_bigquery_client") + def test_non_entity_mode_calls_union_table_not_upload( + self, + mock_get_client, + mock_get_table_ref, + mock_build_pit, + mock_get_ctx, + mock_upload, + mock_union_table, + mock_utc_now, + mock_block, + repo_config, + mock_bq_client, + ): + mock_get_client.return_value = mock_bq_client + mock_get_table_ref.return_value = TABLE_NAME + mock_build_pit.return_value = "SELECT 1" + mock_utc_now.return_value = END + + fv = MagicMock() + fv.batch_source = _make_bq_source() + fv.ttl = timedelta(days=30) + + ctx = _make_fv_context("fv1", ["customer_id"]) + mock_get_ctx.return_value = [ctx] + + registry = MagicMock() + registry.list_entities.return_value = [] + + job = BigQueryOfflineStore.get_historical_features( + config=repo_config, + feature_views=[fv], + feature_refs=["fv1:feature_a"], + entity_df=None, + registry=registry, + project="feast_test", + full_feature_names=False, + start_date=START, + end_date=END, + ) + + # Trigger query_generator + with job._query_generator(): + pass + + mock_union_table.assert_called_once() + mock_upload.assert_not_called() + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + @patch("feast.infra.offline_stores.bigquery._bq_create_entity_union_table") + @patch("feast.infra.offline_stores.bigquery._upload_entity_df") + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.get_feature_view_query_context" + ) + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.build_point_in_time_query" + ) + @patch("feast.infra.offline_stores.bigquery._get_table_reference_for_new_entity") + @patch("feast.infra.offline_stores.bigquery._get_bigquery_client") + def test_non_entity_mode_uses_entity_ts_as_timestamp_col( + self, + mock_get_client, + mock_get_table_ref, + mock_build_pit, + mock_get_ctx, + mock_upload, + mock_union_table, + mock_utc_now, + mock_block, + repo_config, + mock_bq_client, + ): + mock_get_client.return_value = mock_bq_client + mock_get_table_ref.return_value = TABLE_NAME + mock_build_pit.return_value = "SELECT 1" + mock_utc_now.return_value = END + + fv = MagicMock() + fv.batch_source = _make_bq_source() + fv.ttl = timedelta(days=30) + + ctx = _make_fv_context("fv1", ["customer_id"]) + mock_get_ctx.return_value = [ctx] + + registry = MagicMock() + + job = BigQueryOfflineStore.get_historical_features( + config=repo_config, + feature_views=[fv], + feature_refs=["fv1:feature_a"], + entity_df=None, + registry=registry, + project="feast_test", + start_date=START, + end_date=END, + ) + + with job._query_generator(): + pass + + build_call_kwargs = mock_build_pit.call_args[1] + assert build_call_kwargs["entity_df_event_timestamp_col"] == "entity_ts" + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + @patch("feast.infra.offline_stores.bigquery._bq_create_entity_union_table") + @patch("feast.infra.offline_stores.bigquery._upload_entity_df") + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.get_feature_view_query_context" + ) + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.build_point_in_time_query" + ) + @patch("feast.infra.offline_stores.bigquery._get_table_reference_for_new_entity") + @patch("feast.infra.offline_stores.bigquery._get_bigquery_client") + def test_non_entity_mode_passes_start_and_end_to_union_table( + self, + mock_get_client, + mock_get_table_ref, + mock_build_pit, + mock_get_ctx, + mock_upload, + mock_union_table, + mock_utc_now, + mock_block, + repo_config, + mock_bq_client, + ): + mock_get_client.return_value = mock_bq_client + mock_get_table_ref.return_value = TABLE_NAME + mock_build_pit.return_value = "SELECT 1" + mock_utc_now.return_value = END + + fv = MagicMock() + fv.batch_source = _make_bq_source() + fv.ttl = timedelta(days=30) + + ctx = _make_fv_context("fv1", ["customer_id"]) + mock_get_ctx.return_value = [ctx] + + registry = MagicMock() + + job = BigQueryOfflineStore.get_historical_features( + config=repo_config, + feature_views=[fv], + feature_refs=["fv1:feature_a"], + entity_df=None, + registry=registry, + project="feast_test", + start_date=START, + end_date=END, + ) + + with job._query_generator(): + pass + + call_kwargs = mock_union_table.call_args[1] + assert call_kwargs["start_date"].replace(tzinfo=timezone.utc) == START + assert call_kwargs["end_date"].replace(tzinfo=timezone.utc) == END + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + @patch("feast.infra.offline_stores.bigquery._bq_create_entity_union_table") + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.get_feature_view_query_context" + ) + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.build_point_in_time_query" + ) + @patch("feast.infra.offline_stores.bigquery._get_table_reference_for_new_entity") + @patch("feast.infra.offline_stores.bigquery._get_bigquery_client") + def test_non_entity_mode_returns_retrieval_job( + self, + mock_get_client, + mock_get_table_ref, + mock_build_pit, + mock_get_ctx, + mock_union_table, + mock_utc_now, + mock_block, + repo_config, + mock_bq_client, + ): + mock_get_client.return_value = mock_bq_client + mock_get_table_ref.return_value = TABLE_NAME + mock_build_pit.return_value = "SELECT 1" + mock_utc_now.return_value = END + + fv = MagicMock() + fv.batch_source = _make_bq_source() + fv.ttl = timedelta(days=30) + + ctx = _make_fv_context("fv1", ["customer_id"]) + mock_get_ctx.return_value = [ctx] + + registry = MagicMock() + + job = BigQueryOfflineStore.get_historical_features( + config=repo_config, + feature_views=[fv], + feature_refs=["fv1:feature_a"], + entity_df=None, + registry=registry, + project="feast_test", + start_date=START, + end_date=END, + ) + + assert isinstance(job, BigQueryRetrievalJob) + + @patch("feast.infra.offline_stores.bigquery.block_until_done") + @patch("feast.infra.offline_stores.bigquery._utc_now") + @patch("feast.infra.offline_stores.bigquery._bq_create_entity_union_table") + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.get_feature_view_query_context" + ) + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.build_point_in_time_query" + ) + @patch("feast.infra.offline_stores.bigquery._get_table_reference_for_new_entity") + @patch("feast.infra.offline_stores.bigquery._get_bigquery_client") + def test_non_entity_mode_metadata_excludes_timestamp_col_from_keys( + self, + mock_get_client, + mock_get_table_ref, + mock_build_pit, + mock_get_ctx, + mock_union_table, + mock_utc_now, + mock_block, + repo_config, + mock_bq_client, + ): + mock_get_client.return_value = mock_bq_client + mock_get_table_ref.return_value = TABLE_NAME + mock_build_pit.return_value = "SELECT 1" + mock_utc_now.return_value = END + + fv = MagicMock() + fv.batch_source = _make_bq_source() + fv.ttl = timedelta(days=30) + + ctx = _make_fv_context("fv1", ["customer_id"]) + mock_get_ctx.return_value = [ctx] + + registry = MagicMock() + + job = BigQueryOfflineStore.get_historical_features( + config=repo_config, + feature_views=[fv], + feature_refs=["fv1:feature_a"], + entity_df=None, + registry=registry, + project="feast_test", + start_date=START, + end_date=END, + ) + + # entity_ts (the as-of timestamp) must NOT appear in the returned keys + assert "entity_ts" not in job.metadata.keys + assert "customer_id" in job.metadata.keys + + +# --------------------------------------------------------------------------- +# Tests: get_historical_features — entity_df mode regression +# --------------------------------------------------------------------------- + + +class TestGetHistoricalFeaturesEntityDfMode: + @patch("feast.infra.offline_stores.bigquery._bq_create_entity_union_table") + @patch("feast.infra.offline_stores.bigquery._upload_entity_df") + @patch("feast.infra.offline_stores.bigquery._get_entity_df_event_timestamp_range") + @patch("feast.infra.offline_stores.bigquery._get_entity_schema") + @patch("feast.infra.offline_stores.bigquery.offline_utils.get_expected_join_keys") + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.assert_expected_columns_in_entity_df" + ) + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.get_feature_view_query_context" + ) + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.build_point_in_time_query" + ) + @patch("feast.infra.offline_stores.bigquery._get_table_reference_for_new_entity") + @patch("feast.infra.offline_stores.bigquery._get_bigquery_client") + def test_entity_df_mode_calls_upload_not_union_table( + self, + mock_get_client, + mock_get_table_ref, + mock_build_pit, + mock_get_ctx, + mock_assert_cols, + mock_join_keys, + mock_entity_schema, + mock_ts_range, + mock_upload, + mock_union_table, + ): + import pandas as pd + + mock_bq_client = MagicMock() + mock_bq_client.project = "my-project" + mock_get_client.return_value = mock_bq_client + mock_get_table_ref.return_value = TABLE_NAME + mock_build_pit.return_value = "SELECT 1" + mock_entity_schema.return_value = { + "customer_id": "int64", + "event_timestamp": "datetime64[ns, UTC]", + } + mock_ts_range.return_value = (START, END) + mock_get_ctx.return_value = [_make_fv_context("fv1", ["customer_id"])] + mock_join_keys.return_value = ["customer_id"] + + entity_df = pd.DataFrame( + {"customer_id": [1, 2], "event_timestamp": [START, END]} + ) + + repo_config = _make_repo_config() + fv = MagicMock() + fv.batch_source = _make_bq_source() + + job = BigQueryOfflineStore.get_historical_features( + config=repo_config, + feature_views=[fv], + feature_refs=["fv1:feature_a"], + entity_df=entity_df, + registry=MagicMock(), + project="feast_test", + ) + + with job._query_generator(): + pass + + mock_upload.assert_called_once() + mock_union_table.assert_not_called() + + @patch("feast.infra.offline_stores.bigquery._bq_create_entity_union_table") + @patch("feast.infra.offline_stores.bigquery._upload_entity_df") + @patch("feast.infra.offline_stores.bigquery._get_entity_df_event_timestamp_range") + @patch("feast.infra.offline_stores.bigquery._get_entity_schema") + @patch("feast.infra.offline_stores.bigquery.offline_utils.get_expected_join_keys") + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.assert_expected_columns_in_entity_df" + ) + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.get_feature_view_query_context" + ) + @patch( + "feast.infra.offline_stores.bigquery.offline_utils.build_point_in_time_query" + ) + @patch("feast.infra.offline_stores.bigquery._get_table_reference_for_new_entity") + @patch("feast.infra.offline_stores.bigquery._get_bigquery_client") + def test_entity_df_sql_string_mode_works( + self, + mock_get_client, + mock_get_table_ref, + mock_build_pit, + mock_get_ctx, + mock_assert_cols, + mock_join_keys, + mock_entity_schema, + mock_ts_range, + mock_upload, + mock_union_table, + ): + mock_bq_client = MagicMock() + mock_bq_client.project = "my-project" + mock_get_client.return_value = mock_bq_client + mock_get_table_ref.return_value = TABLE_NAME + mock_build_pit.return_value = "SELECT 1" + mock_entity_schema.return_value = { + "customer_id": "int64", + "event_timestamp": "datetime64[ns, UTC]", + } + mock_ts_range.return_value = (START, END) + mock_get_ctx.return_value = [_make_fv_context("fv1", ["customer_id"])] + mock_join_keys.return_value = ["customer_id"] + + repo_config = _make_repo_config() + fv = MagicMock() + fv.batch_source = _make_bq_source() + + job = BigQueryOfflineStore.get_historical_features( + config=repo_config, + feature_views=[fv], + feature_refs=["fv1:feature_a"], + entity_df="SELECT customer_id, event_timestamp FROM `project.dataset.entities`", + registry=MagicMock(), + project="feast_test", + ) + + with job._query_generator(): + pass + + mock_upload.assert_called_once() + mock_union_table.assert_not_called()