Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 76 additions & 13 deletions sdk/python/feast/infra/offline_stores/snowflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 }}'
Comment thread
daniel-kristjansson marked this conversation as resolved.
Resolved
{% if featureview.ttl %}
AND "{{ featureview.timestamp_field }}" >= TIMESTAMP '{{ featureview.min_event_timestamp }}'
Comment thread
daniel-kristjansson marked this conversation as resolved.
Resolved
Comment thread
daniel-kristjansson marked this conversation as resolved.
Resolved
{% endif %}
),

/*
Expand Down
248 changes: 248 additions & 0 deletions sdk/python/tests/integration/offline_store/test_snowflake_pruning.py
Original file line number Diff line number Diff line change
@@ -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()
Loading