diff --git a/sdk/python/feast/infra/offline_stores/snowflake.py b/sdk/python/feast/infra/offline_stores/snowflake.py index 316ce2658e9..4ae05e32fc4 100644 --- a/sdk/python/feast/infra/offline_stores/snowflake.py +++ b/sdk/python/feast/infra/offline_stores/snowflake.py @@ -3,7 +3,7 @@ import os import uuid import warnings -from datetime import date, datetime, timezone +from datetime import date, datetime, timedelta, timezone from decimal import Decimal from functools import reduce from pathlib import Path @@ -366,13 +366,21 @@ def query_generator() -> Iterator[str]: entity_schema, expected_join_keys, entity_df_event_timestamp_col ) + uploaded_range = _get_uploaded_entity_df_event_timestamp_range( + entity_df, + table_name, + entity_df_event_timestamp_col, + snowflake_conn, + entity_df_event_timestamp_range, + ) + # Build a query context containing all information required to template the Snowflake SQL query query_context = offline_utils.get_feature_view_query_context( feature_refs, feature_views, registry, project, - entity_df_event_timestamp_range, + _pruning_timestamp_range(uploaded_range), ) query_context = _fix_entity_selections_identifiers(query_context) @@ -1340,23 +1348,73 @@ def _get_entity_df_event_timestamp_range( entity_df_event_timestamp.max().to_pydatetime(), ) elif isinstance(entity_df, str): - # If the entity_df is a string (SQL query), determine range - # from table - query = f'SELECT MIN("{entity_df_event_timestamp_col}") AS "min_value", MAX("{entity_df_event_timestamp_col}") AS "max_value" FROM ({entity_df})' - results = execute_snowflake_statement(snowflake_conn, query).fetchall() - - entity_df_event_timestamp_range = cast(Tuple[datetime, datetime], results[0]) - if ( - entity_df_event_timestamp_range[0] is None - or entity_df_event_timestamp_range[1] is None - ): - raise EntitySQLEmptyResults(entity_df) + entity_df_event_timestamp_range = _query_event_timestamp_range( + f"({entity_df})", entity_df_event_timestamp_col, snowflake_conn, entity_df + ) else: raise InvalidEntityType(type(entity_df)) return entity_df_event_timestamp_range +def _query_event_timestamp_range( + from_expression: str, + entity_df_event_timestamp_col: str, + snowflake_conn: SnowflakeConnection, + entity_df: str, +) -> Tuple[datetime, datetime]: + query = f'SELECT MIN("{entity_df_event_timestamp_col}") AS "min_value", MAX("{entity_df_event_timestamp_col}") AS "max_value" FROM {from_expression}' + results = execute_snowflake_statement(snowflake_conn, query).fetchall() + + timestamp_range = cast(Tuple[datetime, datetime], results[0]) + if timestamp_range[0] is None or timestamp_range[1] is None: + raise EntitySQLEmptyResults(entity_df) + return timestamp_range + + +def _get_uploaded_entity_df_event_timestamp_range( + entity_df: Union[pd.DataFrame, str], + table_name: str, + entity_df_event_timestamp_col: str, + snowflake_conn: SnowflakeConnection, + entity_df_event_timestamp_range: Tuple[datetime, datetime], +) -> Tuple[datetime, datetime]: + """Return the entity timestamp range of the uploaded entity table. + + A SQL entity_df is re-executed by _upload_entity_df, so it may return rows + that were not there when entity_df_event_timestamp_range was measured. + Measure the uploaded table instead. A DataFrame is uploaded as is, so its + range is still accurate. + """ + if isinstance(entity_df, str): + return _query_event_timestamp_range( + f'"{table_name}"', + entity_df_event_timestamp_col, + snowflake_conn, + entity_df, + ) + return entity_df_event_timestamp_range + + +def _pruning_timestamp_range( + entity_df_event_timestamp_range: Tuple[datetime, datetime], +) -> Tuple[datetime, datetime]: + """Adjust the entity timestamp range for feature-table pruning. + + The minimum is converted to UTC so that get_feature_view_query_context + subtracts the TTL as elapsed time, matching the per-row TTL in SQL. Wall-clock + subtraction on a ZoneInfo datetime is off by an hour across DST transitions. + + The maximum is padded by a millisecond because Python datetimes hold + microseconds while the uploaded entity rows and feature table can hold + nanoseconds. + """ + min_ts, max_ts = entity_df_event_timestamp_range + if min_ts.tzinfo is not None: + min_ts = min_ts.astimezone(timezone.utc) + return min_ts, max_ts + timedelta(milliseconds=1) + + MULTIPLE_FEATURE_VIEW_POINT_IN_TIME_JOIN = """ /* 0. Compute a deterministic hash for the `left_table_query_string` that will be used throughout @@ -1411,6 +1469,11 @@ def _get_entity_df_event_timestamp_range( "{{ feature }}" as {% if full_feature_names %}"{{ featureview.name }}__{{featureview.field_mapping.get(feature, feature)}}"{% else %}"{{ featureview.field_mapping.get(feature, feature) }}"{% endif %}{% if loop.last %}{% else %}, {% endif %} {% endfor %} FROM {{ featureview.table_subquery }} + WHERE + "{{ featureview.timestamp_field }}" <= TIMESTAMP '{{ featureview.max_event_timestamp }}' + {% if featureview.ttl %} + AND "{{ featureview.timestamp_field }}" >= TIMESTAMP '{{ featureview.min_event_timestamp }}' + {% endif %} ), /* diff --git a/sdk/python/tests/integration/offline_store/test_snowflake_pruning.py b/sdk/python/tests/integration/offline_store/test_snowflake_pruning.py new file mode 100644 index 00000000000..54509e41659 --- /dev/null +++ b/sdk/python/tests/integration/offline_store/test_snowflake_pruning.py @@ -0,0 +1,248 @@ +"""Regression tests for feature-table pruning in the Snowflake point-in-time join. + +These exercise the ``__subquery`` timestamp bounds added in +https://github.com/feast-dev/feast/pull/7230. The pruning predicates are only +allowed to remove rows that the ASOF join and TTL filter would discard anyway, +so every test asserts that a row which is eligible for the point-in-time join is +still returned. +""" + +import os +from datetime import timedelta +from zoneinfo import ZoneInfo + +import pandas as pd +import pytest + +from feast.entity import Entity +from feast.feature_view import FeatureView +from feast.infra.offline_stores.snowflake_source import SnowflakeSource +from feast.infra.utils.snowflake.snowflake_utils import ( + GetSnowflakeConnection, + execute_snowflake_statement, +) +from tests.universal.feature_repos.integration_test_repo_config import ( + IntegrationTestRepoConfig, +) +from tests.universal.feature_repos.repo_configuration import ( + construct_test_environment, +) +from tests.universal.feature_repos.universal.data_sources.snowflake import ( + SnowflakeDataSourceCreator, +) + +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif( + not os.getenv("SNOWFLAKE_CI_DEPLOYMENT"), + reason="Snowflake account not configured in CI (SNOWFLAKE_CI_DEPLOYMENT not set)", + ), +] + + +def _make_environment(): + return construct_test_environment( + IntegrationTestRepoConfig( + online_store="sqlite", + offline_store_creator=SnowflakeDataSourceCreator, + ), + None, + ) + + +def _execute(environment, sql: str) -> None: + with GetSnowflakeConnection( + environment.data_source_creator.offline_store_config + ) as conn: + execute_snowflake_statement(conn, sql) + + +def _create_table(environment, suffix: str, columns: str) -> str: + table = environment.data_source_creator.get_prefixed_table_name(suffix) + _execute(environment, f'CREATE OR REPLACE TABLE "{table}" ({columns})') + environment.data_source_creator.tables.append(table) + return table + + +def _feature_source(table: str) -> SnowflakeSource: + return SnowflakeSource(table=table, timestamp_field="event_timestamp") + + +def _driver_view( + name: str, source: SnowflakeSource, ttl: timedelta = timedelta(0) +) -> FeatureView: + return FeatureView( + name=name, + entities=[Entity(name="driver", join_keys=["driver_id"])], + ttl=ttl, + source=source, + ) + + +def test_pruning_upper_bound_uses_uploaded_entity_snapshot(): + """A SQL entity_df re-runs when the job materializes. + + The range is measured at get_historical_features() time but the entity SQL is + re-executed by _upload_entity_df() when to_sql()/to_df() runs. If the query + returns a newer row the second time, the upper pruning bound must come from + that uploaded snapshot, not from the first execution. + """ + environment = _make_environment() + environment.setup() + store = environment.feature_store + try: + feature_table = _create_table( + environment, + "stale_bounds_features", + '"driver_id" INT, "event_timestamp" TIMESTAMP_NTZ(9), "value" FLOAT', + ) + entity_table = _create_table( + environment, + "stale_bounds_entities", + '"driver_id" INT, "event_timestamp" TIMESTAMP_NTZ(9)', + ) + _execute( + environment, + f'INSERT INTO "{feature_table}" VALUES ' + "(1, TIMESTAMP '2024-01-01 00:00:00.000000000', 1.0)", + ) + _execute( + environment, + f'INSERT INTO "{entity_table}" VALUES ' + "(1, TIMESTAMP '2024-01-01 00:00:00.000000000')", + ) + + driver = Entity(name="driver", join_keys=["driver_id"]) + feature_view = _driver_view("stale_bounds_fv", _feature_source(feature_table)) + store.apply([driver, feature_view]) + + job = store.get_historical_features( + entity_df=f'SELECT "driver_id", "event_timestamp" FROM "{entity_table}"', + features=["stale_bounds_fv:value"], + ) + + _execute( + environment, + f'INSERT INTO "{feature_table}" VALUES ' + "(2, TIMESTAMP '2024-01-01 01:00:00.000000000', 2.0)", + ) + _execute( + environment, + f'INSERT INTO "{entity_table}" VALUES ' + "(2, TIMESTAMP '2024-01-01 01:00:00.000000000')", + ) + + df = job.to_df() + + row = df.loc[df["driver_id"] == 2] + assert len(row) == 1 + assert row["value"].iloc[0] == 2.0 + finally: + environment.teardown() + + +def test_pruning_upper_bound_keeps_sub_microsecond_matches(): + """The upper bound must not truncate sub-microsecond entity timestamps. + + pandas loses nanosecond digits when the entity timestamp is converted with + to_pydatetime(), while the uploaded entity row and the feature table keep + them. A feature in the same microsecond as the latest entity timestamp is + still eligible for the ASOF join and must survive pruning. + """ + environment = _make_environment() + environment.setup() + store = environment.feature_store + try: + feature_table = _create_table( + environment, + "sub_microsecond_features", + '"driver_id" INT, "event_timestamp" TIMESTAMP_NTZ(9), "value" FLOAT', + ) + _execute( + environment, + f'INSERT INTO "{feature_table}" VALUES ' + "(1, TIMESTAMP '2024-06-01 00:00:00.123456700', 42.0)", + ) + + driver = Entity(name="driver", join_keys=["driver_id"]) + feature_view = _driver_view( + "sub_microsecond_fv", _feature_source(feature_table) + ) + store.apply([driver, feature_view]) + + entity_df = pd.DataFrame( + { + "driver_id": [1], + "event_timestamp": pd.to_datetime(["2024-06-01 00:00:00.123456789"]), + } + ) + assert entity_df["event_timestamp"].iloc[0].nanosecond == 789 + + df = store.get_historical_features( + entity_df=entity_df, + features=["sub_microsecond_fv:value"], + ).to_df() + + assert df["value"].iloc[0] == 42.0 + finally: + environment.teardown() + + +def test_pruning_lower_bound_uses_utc_elapsed_time_across_dst(): + """The TTL lower bound is elapsed time, not wall-clock time. + + With coerce_tz_aware disabled, the minimum entity timestamp keeps its + ZoneInfo. Subtracting the TTL from that datetime does wall-clock arithmetic, + so across a spring-forward transition the Python cutoff lands one hour later + in UTC than the per-row TTL. A feature inside the TTL must not be pruned. + + The timezone must be a ZoneInfo, not a tz string: pandas 2.x resolves strings + to pytz, whose localized datetimes carry a fixed offset and so already + subtract elapsed time, hiding the bug. + + Entity at noon America/New_York on 2025-03-09 is 16:00 UTC. A 24h TTL keeps + 16:30 UTC on 2025-03-08, but wall-clock subtraction produces 17:00 UTC. + """ + environment = _make_environment() + environment.setup() + store = environment.feature_store + try: + feature_table = _create_table( + environment, + "dst_features", + '"driver_id" INT, "event_timestamp" TIMESTAMP_NTZ(9), "value" FLOAT', + ) + _execute( + environment, + f'INSERT INTO "{feature_table}" VALUES ' + "(1, TIMESTAMP '2025-03-08 16:30:00.000000000', 7.0)", + ) + + driver = Entity(name="driver", join_keys=["driver_id"]) + feature_view = _driver_view( + "dst_fv", _feature_source(feature_table), ttl=timedelta(days=1) + ) + store.apply([driver, feature_view]) + + store.config.coerce_tz_aware = False + entity_df = pd.DataFrame( + { + "driver_id": [1], + "event_timestamp": pd.Series( + [ + pd.Timestamp( + "2025-03-09 12:00:00", tz=ZoneInfo("America/New_York") + ) + ] + ), + } + ) + + df = store.get_historical_features( + entity_df=entity_df, + features=["dst_fv:value"], + ).to_df() + + assert df["value"].iloc[0] == 7.0 + finally: + environment.teardown() diff --git a/sdk/python/tests/unit/infra/offline_stores/test_snowflake.py b/sdk/python/tests/unit/infra/offline_stores/test_snowflake.py index 6e7f9bcf5d4..fb7e0d28001 100644 --- a/sdk/python/tests/unit/infra/offline_stores/test_snowflake.py +++ b/sdk/python/tests/unit/infra/offline_stores/test_snowflake.py @@ -1,20 +1,23 @@ import re +from datetime import datetime, timedelta from types import SimpleNamespace from unittest.mock import ANY, MagicMock, patch +from zoneinfo import ZoneInfo import pandas as pd import pytest from pytest_mock import MockFixture -from feast import FeatureView, Field, FileSource +from feast import Entity, FeatureView, Field, FileSource from feast.infra.offline_stores.snowflake import ( + SnowflakeOfflineStore, SnowflakeOfflineStoreConfig, SnowflakeRetrievalJob, ) from feast.infra.offline_stores.snowflake_source import SnowflakeSource from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig from feast.repo_config import RepoConfig -from feast.types import Array, String +from feast.types import Array, Float32, Int64, String @pytest.fixture(params=["s3", "s3gov"]) @@ -137,3 +140,167 @@ def test_snowflake_source_integer_column_types( ) assert list(source.get_table_column_names_and_types(config)) == [("ID", expected)] + + +# Feature-table pruning bounds in the point-in-time join. +# +# The "__subquery" CTE filters the feature table by +# timestamp_field <= max_event_timestamp +# timestamp_field >= min_event_timestamp (only when the view has a TTL) +# These predicates may only drop rows that the ASOF join and per-row TTL filter +# would discard anyway. The integration tests in +# tests/integration/offline_store/test_snowflake_pruning.py check the end-to-end +# result; these check the rendered bounds without a Snowflake account. + +_PRUNING_UPPER_BOUND = re.compile(r"\"event_timestamp\" <= TIMESTAMP '([^']+)'") +_PRUNING_LOWER_BOUND = re.compile(r"\"event_timestamp\" >= TIMESTAMP '([^']+)'") + + +def _pruning_bounds(entity_df: pd.DataFrame | str, ttl: timedelta): + """Render the point-in-time SQL and return its (lower, upper) pruning bounds.""" + driver = Entity(name="driver", join_keys=["driver_id"]) + feature_view = FeatureView( + name="driver_fv", + entities=[driver], + ttl=ttl, + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="value", dtype=Float32), + ], + source=SnowflakeSource( + database="FEAST", + schema="PUBLIC", + table="DRIVER_FEATURES", + timestamp_field="event_timestamp", + ), + ) + config = RepoConfig( + registry="s3://ml-test/repo/registry.db", + project="test", + provider="local", + online_store=SqliteOnlineStoreConfig(type="sqlite"), + offline_store=SnowflakeOfflineStoreConfig( + type="snowflake.offline", + account="snow", + user="snow", + password="snow", + role="snow", + warehouse="snow", + database="FEAST", + schema="OFFLINE", + ), + entity_key_serialization_version=3, + ) + registry = MagicMock() + registry.list_on_demand_feature_views.return_value = [] + + with ( + patch("feast.infra.offline_stores.snowflake.GetSnowflakeConnection"), + patch("feast.infra.offline_stores.snowflake._upload_entity_df"), + ): + job = SnowflakeOfflineStore.get_historical_features( + config=config, + feature_views=[feature_view], + feature_refs=["driver_fv:value"], + entity_df=entity_df, + registry=registry, + project="test", + ) + with job._query_generator() as query: + sql = query + + lower = _PRUNING_LOWER_BOUND.search(sql) + upper = _PRUNING_UPPER_BOUND.search(sql) + assert upper is not None, sql + return ( + pd.Timestamp(lower.group(1)) if lower else None, + pd.Timestamp(upper.group(1)), + ) + + +def test_pruning_upper_bound_keeps_sub_microsecond_entity_timestamps(): + """to_pydatetime() drops nanoseconds from the entity maximum. + + The uploaded entity row keeps them, so a feature in the same microsecond is + still eligible for the ASOF join. The upper bound must not fall below the + full-precision entity timestamp. + """ + entity_ts = pd.Timestamp("2024-06-01 00:00:00.123456789") + entity_df = pd.DataFrame({"driver_id": [1], "event_timestamp": [entity_ts]}) + + _, upper = _pruning_bounds(entity_df, ttl=timedelta(0)) + + assert upper >= entity_ts + + +def test_pruning_lower_bound_uses_utc_elapsed_time_across_dst(): + """With coerce_tz_aware disabled the TTL must be elapsed time, not wall-clock. + + Noon America/New_York on 2025-03-09 is 16:00 UTC, the day of the + spring-forward transition. The per-row TTL in SQL subtracts 86400 seconds, + so 16:00 UTC on 2025-03-08 is eligible. Subtracting timedelta(days=1) from a + ZoneInfo datetime is wall-clock arithmetic and yields 17:00 UTC, pruning + eligible features between 16:00 and 17:00 UTC. + + The timezone must be a ZoneInfo: pandas 2.x resolves tz strings to pytz, + whose localized datetimes carry a fixed offset and hide the bug. + """ + entity_df = pd.DataFrame( + { + "driver_id": [1], + "event_timestamp": pd.Series( + [pd.Timestamp("2025-03-09 12:00:00", tz=ZoneInfo("America/New_York"))] + ), + } + ) + assert isinstance( + entity_df["event_timestamp"].min().to_pydatetime().tzinfo, ZoneInfo + ) + + lower, _ = _pruning_bounds(entity_df, ttl=timedelta(days=1)) + + assert lower is not None + assert lower <= pd.Timestamp("2025-03-08 16:00:00") + + +def test_pruning_bounds_use_uploaded_entity_snapshot_for_sql_entity_df(): + """A SQL entity_df is executed again when the entity table is uploaded. + + get_historical_features() measures MIN/MAX over the entity SQL up front, but + the join uses the temp table that _upload_entity_df() creates later. If the + SQL returns newer rows by then, bounds from the first execution would prune + their features. The bounds must come from the uploaded table. + """ + entity_sql = 'SELECT "driver_id", "event_timestamp" FROM "ENTITIES"' + first_range = (datetime(2024, 1, 1, 0, 0), datetime(2024, 1, 1, 0, 0)) + uploaded_range = (datetime(2023, 12, 31, 0, 0), datetime(2024, 1, 1, 1, 0)) + range_queries = [] + + def fake_execute(conn, query): + cursor = MagicMock() + if query.endswith("LIMIT 1"): + cursor.fetch_pandas_all.return_value = pd.DataFrame( + { + "driver_id": pd.Series([1], dtype="int64"), + "event_timestamp": pd.to_datetime(["2024-01-01"]), + } + ) + elif query.startswith("SELECT MIN("): + range_queries.append(query) + is_entity_sql = query.endswith(f"FROM ({entity_sql})") + cursor.fetchall.return_value = [ + first_range if is_entity_sql else uploaded_range + ] + return cursor + + with patch( + "feast.infra.offline_stores.snowflake.execute_snowflake_statement", + side_effect=fake_execute, + ): + lower, upper = _pruning_bounds(entity_sql, ttl=timedelta(hours=1)) + + assert len(range_queries) == 2 + assert range_queries[0].endswith(f"FROM ({entity_sql})") + assert re.search(r'FROM "feast_entity_df_[0-9a-f]+"$', range_queries[1]) + assert upper >= pd.Timestamp(uploaded_range[1]) + assert lower <= pd.Timestamp(uploaded_range[0]) - pd.Timedelta(hours=1)