diff --git a/sdk/python/feast/infra/compute_engines/snowflake/snowflake_engine.py b/sdk/python/feast/infra/compute_engines/snowflake/snowflake_engine.py index 3cc9262f489..2af1b488808 100644 --- a/sdk/python/feast/infra/compute_engines/snowflake/snowflake_engine.py +++ b/sdk/python/feast/infra/compute_engines/snowflake/snowflake_engine.py @@ -1,8 +1,10 @@ +import functools import os import re -import shutil +import warnings from datetime import timezone -from typing import Literal, Optional, Sequence, Union +from tempfile import TemporaryDirectory +from typing import Literal, Optional, Sequence, Set, Tuple, Union import click import pandas as pd @@ -34,6 +36,7 @@ execute_snowflake_statement, get_snowflake_online_store_path, package_snowpark_zip, + snowpark_udf_fingerprint, ) from feast.on_demand_feature_view import OnDemandFeatureView from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto @@ -124,6 +127,19 @@ def validate_python_udf_runtime_version(cls, v: str) -> str: return v +_SNOWPARK_DIR = f"{os.path.dirname(feast.__file__)}/infra/utils/snowflake/snowpark" +_UDF_CREATION_SQL = f"{_SNOWPARK_DIR}/snowflake_python_udfs_creation.sql" +_UDF_DELETION_SQL = f"{_SNOWPARK_DIR}/snowflake_python_udfs_deletion.sql" + + +def _udf_data(python_udf_runtime_version: str) -> Tuple[str, Set[str]]: + with open(_UDF_CREATION_SQL, "r") as file: + sql = file.read() + fingerprint = snowpark_udf_fingerprint(sql, python_udf_runtime_version) + templates = set(re.findall(r"[\w$]*PROJECT_NAME[\w$]*", sql)) + return fingerprint, templates + + class SnowflakeComputeEngine(ComputeEngine): def get_historical_features( self, registry: BaseRegistry, task: HistoricalRetrievalTask @@ -145,17 +161,18 @@ def update( entities_to_keep: Sequence[Entity], ): stage_path = f'"{self.repo_config.batch_engine.database}"."{self.repo_config.batch_engine.schema_}"."feast_{project}"' + udf_namespace = self._udf_namespace(project) + udf_path = f"{stage_path}/{udf_namespace}" with GetSnowflakeConnection(self.repo_config.batch_engine) as conn: - # Always (re)deploy the materialization functions, using - # `CREATE OR REPLACE FUNCTION` below, instead of skipping deployment - # when functions already exist. Previously, an early return here - # (triggered by a `SHOW USER FUNCTIONS` check) combined with - # `CREATE FUNCTION IF NOT EXISTS` in the SQL template meant that - # once UDFs were deployed for a project, they were never - # redeployed -- so a config change to `python_udf_runtime_version` - # (e.g. after Snowflake decommissions a runtime) would silently - # keep using the stale, already-deployed runtime version. See - # https://github.com/feast-dev/feast/pull/6608#discussion_r3602461959. + if self._udf_names(udf_namespace) <= self._query_udf_names( + conn, udf_namespace + ): + click.echo( + f"Materialization functions for {Style.BRIGHT + Fore.GREEN}{project}{Style.RESET_ALL} already exist." + ) + click.echo() + return None + click.echo( f"Deploying materialization functions for {Style.BRIGHT + Fore.GREEN}{project}{Style.RESET_ALL}" ) @@ -164,21 +181,19 @@ def update( query = f"CREATE STAGE IF NOT EXISTS {stage_path}" execute_snowflake_statement(conn, query) - copy_path, zip_path = package_snowpark_zip(project) - query = f"PUT file://{zip_path} @{stage_path}" - execute_snowflake_statement(conn, query) - - shutil.rmtree(copy_path) + with TemporaryDirectory() as copy_path: + zip_path = package_snowpark_zip(copy_path) + query = f"PUT file://{zip_path} @{udf_path}" + execute_snowflake_statement(conn, query) # Execute snowflake python udf creation functions - sql_function_file = f"{os.path.dirname(feast.__file__)}/infra/utils/snowflake/snowpark/snowflake_python_udfs_creation.sql" - with open(sql_function_file, "r") as file: + with open(_UDF_CREATION_SQL, "r") as file: sqlFile = file.read() sqlCommands = sqlFile.split(";") for command in sqlCommands: - command = command.replace("STAGE_HOLDER", f"{stage_path}") - command = command.replace("PROJECT_NAME", f"{project}") + command = command.replace("STAGE_HOLDER", f"{udf_path}") + command = command.replace("PROJECT_NAME", f"{udf_namespace}") query = command.replace( "RUNTIME_VERSION_HOLDER", self.repo_config.batch_engine.python_udf_runtime_version, @@ -192,24 +207,59 @@ def teardown_infra( project: str, fvs: Sequence[Union[BatchFeatureView, StreamFeatureView, FeatureView]], entities: Sequence[Entity], + ): + try: + self._teardown_udfs(project, fvs, entities) + except Exception as e: + warnings.warn( + f"Could not drop the Snowflake materialization UDFs for {project}, " + f"continuing the teardown: {e}", + RuntimeWarning, + ) + + def _teardown_udfs( + self, + project: str, + fvs: Sequence[Union[BatchFeatureView, StreamFeatureView, FeatureView]], + entities: Sequence[Entity], ): stage_path = f'"{self.repo_config.batch_engine.database}"."{self.repo_config.batch_engine.schema_}"."feast_{project}"' + udf_namespace = self._udf_namespace(project) with GetSnowflakeConnection(self.repo_config.batch_engine) as conn: query = f"DROP STAGE IF EXISTS {stage_path}" execute_snowflake_statement(conn, query) # Execute snowflake python udf deletion functions - sql_function_file = f"{os.path.dirname(feast.__file__)}/infra/utils/snowflake/snowpark/snowflake_python_udfs_deletion.sql" - with open(sql_function_file, "r") as file: + with open(_UDF_DELETION_SQL, "r") as file: sqlFile = file.read() sqlCommands = sqlFile.split(";") for command in sqlCommands: - query = command.replace("PROJECT_NAME", f"{project}") + query = command.replace("PROJECT_NAME", f"{udf_namespace}") execute_snowflake_statement(conn, query) return None + def _udf_namespace(self, project: str) -> str: + return f"{project}_{self._udf_fingerprint}" + + def _udf_names(self, udf_namespace: str) -> Set[str]: + return { + name.replace("PROJECT_NAME", udf_namespace).upper() + for name in self._udf_templates + } + + def _query_udf_names(self, conn, udf_namespace: str) -> Set[str]: + schema = f'"{self.repo_config.batch_engine.database}"."{self.repo_config.batch_engine.schema_}"' + query = f"SHOW USER FUNCTIONS LIKE 'FEAST_{udf_namespace.upper()}_%' IN SCHEMA {schema}" + cursor = execute_snowflake_statement(conn, query) + name_index = [column.name for column in cursor.description].index("name") + return {row[name_index].upper() for row in cursor.fetchall()} + + @functools.lru_cache(maxsize=None) + def _ensure_udfs(self, project: str) -> None: + self.update(project, [], [], [], []) + def __init__( self, *, @@ -228,6 +278,9 @@ def __init__( online_store=online_store, **kwargs, ) + self._udf_fingerprint, self._udf_templates = _udf_data( + repo_config.batch_engine.python_udf_runtime_version + ) def _materialize_one( self, @@ -262,6 +315,7 @@ def _materialize_one( job_id = f"{feature_view.name}-{start_date}-{end_date}" try: + self._ensure_udfs(project) offline_job = self.offline_store.pull_latest_from_table_or_query( config=self.repo_config, data_source=feature_view.batch_source, # type: ignore[arg-type] @@ -374,6 +428,7 @@ def generate_snowflake_materialization_query( project: str, ) -> str: assert feature_view.batch_source is not None + udf_namespace = self._udf_namespace(project) if feature_view.batch_source.created_timestamp_column: fv_created_str = f',"{feature_view.batch_source.created_timestamp_column}"' else: @@ -397,7 +452,7 @@ def generate_snowflake_materialization_query( feature_value_type_name = feature.dtype.to_value_type().name feature_sql = _convert_value_name_to_snowflake_udf( - feature_value_type_name, project + feature_value_type_name, udf_namespace ) if feature_value_type_name == "UNIX_TIMESTAMP": @@ -414,9 +469,9 @@ def generate_snowflake_materialization_query( features_str = ",\n".join(feature_sql_list) if repo_config.online_store.type == "snowflake.online": - serial_func = f"feast_{project}_serialize_entity_keys" + serial_func = f"feast_{udf_namespace}_serialize_entity_keys" else: - serial_func = f"feast_{project}_entity_key_proto_to_string" + serial_func = f"feast_{udf_namespace}_entity_key_proto_to_string" fv_to_proto_sql = f""" SELECT diff --git a/sdk/python/feast/infra/utils/snowflake/snowflake_utils.py b/sdk/python/feast/infra/utils/snowflake/snowflake_utils.py index e22d4857a19..2fa299428c8 100644 --- a/sdk/python/feast/infra/utils/snowflake/snowflake_utils.py +++ b/sdk/python/feast/infra/utils/snowflake/snowflake_utils.py @@ -1,4 +1,5 @@ import configparser +import hashlib import os import random import shutil @@ -140,24 +141,42 @@ def get_snowflake_online_store_path( return online_path -def package_snowpark_zip(project_name) -> Tuple[str, str]: - path = os.path.dirname(feast.__file__) - copy_path = path + f"/snowflake_feast_{project_name}" +# Feast source files packaged into the Snowpark UDF zip (paths relative to the +# `feast` package). The UDFs import their serialization code from this zip. +SNOWPARK_ZIP_FILES = ( + "/infra/utils/snowflake/snowpark/snowflake_udfs.py", + "/infra/key_encoding_utils.py", + "/type_map.py", + "/value_type.py", + "/protos/feast/types/Value_pb2.py", + "/protos/feast/types/EntityKey_pb2.py", +) + - if os.path.exists(copy_path): - shutil.rmtree(copy_path) +def snowpark_udf_fingerprint(*extra: str) -> str: + """Content hash of the Snowpark UDF payload, plus any `extra` inputs. - copy_files = [ - "/infra/utils/snowflake/snowpark/snowflake_udfs.py", - "/infra/key_encoding_utils.py", - "/type_map.py", - "/value_type.py", - "/protos/feast/types/Value_pb2.py", - "/protos/feast/types/EntityKey_pb2.py", - ] + Hashes the source files in `SNOWPARK_ZIP_FILES` rather than the zip itself: + `shutil.make_archive` embeds file modification times, so identical code + zips to different bytes on every install. + """ + path = os.path.dirname(feast.__file__) + digest = hashlib.sha256() + for feast_file in SNOWPARK_ZIP_FILES: + digest.update(feast_file.encode("utf8") + b"\0") + with open(path + feast_file, "rb") as file: + digest.update(file.read()) + digest.update(b"\0") + for value in extra: + digest.update(value.encode("utf8") + b"\0") + return digest.hexdigest()[:8] + + +def package_snowpark_zip(copy_path: str) -> str: + path = os.path.dirname(feast.__file__) package_path = copy_path + "/feast" - for feast_file in copy_files: + for feast_file in SNOWPARK_ZIP_FILES: idx = feast_file.rfind("/") if idx > -1: Path(package_path + feast_file[:idx]).mkdir(parents=True, exist_ok=True) @@ -167,7 +186,7 @@ def package_snowpark_zip(project_name) -> Tuple[str, str]: zip_path = shutil.make_archive(package_path, "zip", copy_path) - return copy_path, zip_path + return zip_path def _run_snowflake_field_mapping(snowflake_job_sql: str, field_mapping: dict) -> str: diff --git a/sdk/python/feast/infra/utils/snowflake/snowpark/snowflake_python_udfs_creation.sql b/sdk/python/feast/infra/utils/snowflake/snowpark/snowflake_python_udfs_creation.sql index b1a0d85f526..a9f6610acdd 100644 --- a/sdk/python/feast/infra/utils/snowflake/snowpark/snowflake_python_udfs_creation.sql +++ b/sdk/python/feast/infra/utils/snowflake/snowpark/snowflake_python_udfs_creation.sql @@ -1,4 +1,4 @@ -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_binary_to_bytes_proto(df BINARY) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_binary_to_bytes_proto(df BINARY) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -6,7 +6,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_binary_to_bytes_proto(df HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_binary_to_bytes_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_varchar_to_string_proto(df VARCHAR) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_varchar_to_string_proto(df VARCHAR) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -14,7 +14,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_varchar_to_string_proto( HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_varchar_to_string_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_bytes_to_list_bytes_proto(df ARRAY) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_array_bytes_to_list_bytes_proto(df ARRAY) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -22,7 +22,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_bytes_to_list_byte HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_array_bytes_to_list_bytes_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_varchar_to_list_string_proto(df ARRAY) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_array_varchar_to_list_string_proto(df ARRAY) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -30,7 +30,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_varchar_to_list_st HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_array_varchar_to_list_string_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_number_to_list_int32_proto(df ARRAY) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_array_number_to_list_int32_proto(df ARRAY) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -38,7 +38,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_number_to_list_int HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_array_number_to_list_int32_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_number_to_list_int64_proto(df ARRAY) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_array_number_to_list_int64_proto(df ARRAY) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -46,7 +46,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_number_to_list_int HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_array_number_to_list_int64_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_float_to_list_double_proto(df ARRAY) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_array_float_to_list_double_proto(df ARRAY) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -54,7 +54,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_float_to_list_doub HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_array_float_to_list_double_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_boolean_to_list_bool_proto(df ARRAY) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_array_boolean_to_list_bool_proto(df ARRAY) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -62,7 +62,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_boolean_to_list_bo HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_array_boolean_to_list_bool_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_timestamp_to_list_unix_timestamp_proto(df ARRAY) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_array_timestamp_to_list_unix_timestamp_proto(df ARRAY) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -70,7 +70,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_array_timestamp_to_list_ HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_array_timestamp_to_list_unix_timestamp_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_number_to_int32_proto(df NUMBER) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_number_to_int32_proto(df NUMBER) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -78,7 +78,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_number_to_int32_proto(df HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_number_to_int32_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_number_to_int64_proto(df NUMBER) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_number_to_int64_proto(df NUMBER) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -86,7 +86,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_number_to_int64_proto(df HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_number_to_int64_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_float_to_double_proto(df DOUBLE) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_float_to_double_proto(df DOUBLE) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -94,7 +94,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_float_to_double_proto(df HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_float_to_double_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_boolean_to_bool_proto(df BOOLEAN) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_boolean_to_bool_proto(df BOOLEAN) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -102,7 +102,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_boolean_to_bool_proto(df HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_boolean_to_bool_boolean_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_timestamp_to_unix_timestamp_proto(df NUMBER) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_snowflake_timestamp_to_unix_timestamp_proto(df NUMBER) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -110,7 +110,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_snowflake_timestamp_to_unix_timest HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_snowflake_timestamp_to_unix_timestamp_proto' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_serialize_entity_keys(names ARRAY, data ARRAY, types ARRAY) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_serialize_entity_keys(names ARRAY, data ARRAY, types ARRAY) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' @@ -118,7 +118,7 @@ CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_serialize_entity_keys(names ARRAY, HANDLER = 'feast.infra.utils.snowflake.snowpark.snowflake_udfs.feast_serialize_entity_keys' IMPORTS = ('@STAGE_HOLDER/feast.zip'); -CREATE OR REPLACE FUNCTION feast_PROJECT_NAME_entity_key_proto_to_string(names ARRAY, data ARRAY, types ARRAY) +CREATE FUNCTION IF NOT EXISTS feast_PROJECT_NAME_entity_key_proto_to_string(names ARRAY, data ARRAY, types ARRAY) RETURNS BINARY LANGUAGE PYTHON RUNTIME_VERSION = 'RUNTIME_VERSION_HOLDER' diff --git a/sdk/python/feast/infra/utils/snowflake/snowpark/snowflake_python_udfs_deletion.sql b/sdk/python/feast/infra/utils/snowflake/snowpark/snowflake_python_udfs_deletion.sql index ff96bdd8f20..687d708c412 100644 --- a/sdk/python/feast/infra/utils/snowflake/snowpark/snowflake_python_udfs_deletion.sql +++ b/sdk/python/feast/infra/utils/snowflake/snowpark/snowflake_python_udfs_deletion.sql @@ -2,6 +2,20 @@ DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_binary_to_bytes_proto(BINAR DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_varchar_to_string_proto(VARCHAR); +DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_array_bytes_to_list_bytes_proto(ARRAY); + +DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_array_varchar_to_list_string_proto(ARRAY); + +DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_array_number_to_list_int32_proto(ARRAY); + +DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_array_number_to_list_int64_proto(ARRAY); + +DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_array_float_to_list_double_proto(ARRAY); + +DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_array_boolean_to_list_bool_proto(ARRAY); + +DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_array_timestamp_to_list_unix_timestamp_proto(ARRAY); + DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_number_to_int32_proto(NUMBER); DROP FUNCTION IF EXISTS feast_PROJECT_NAME_snowflake_number_to_int64_proto(NUMBER); diff --git a/sdk/python/tests/unit/infra/compute_engines/snowflake/test_snowflake_compute_engine.py b/sdk/python/tests/unit/infra/compute_engines/snowflake/test_snowflake_compute_engine.py index f450c124bed..049b8a25b02 100644 --- a/sdk/python/tests/unit/infra/compute_engines/snowflake/test_snowflake_compute_engine.py +++ b/sdk/python/tests/unit/infra/compute_engines/snowflake/test_snowflake_compute_engine.py @@ -7,20 +7,20 @@ Together, this meant a user changing `python_udf_runtime_version` (e.g. after Snowflake decommissions a runtime) would never actually get the new runtime version deployed -- the stale, already-deployed UDFs were left untouched. - -The fix removes the early return and switches the SQL template to -`CREATE OR REPLACE FUNCTION`, so `update()` always (re)deploys the UDFs using -the currently configured runtime version. """ -import shutil -import tempfile +import re +from typing import Tuple from unittest.mock import MagicMock, patch +import pytest + +from feast.field import Field from feast.infra.compute_engines.snowflake.snowflake_engine import ( SnowflakeComputeEngine, SnowflakeComputeEngineConfig, ) +from feast.types import Float64, Int64, String MODULE = "feast.infra.compute_engines.snowflake.snowflake_engine" @@ -41,20 +41,36 @@ def _make_engine(python_udf_runtime_version: str = "3.10") -> SnowflakeComputeEn ) -def _run_update(engine: SnowflakeComputeEngine, mock_execute: MagicMock) -> None: +def _show_functions_cursor(names: Tuple[str, ...]) -> MagicMock: + cursor = MagicMock() + name_column = MagicMock() + name_column.name = "name" + cursor.description = [name_column] + cursor.fetchall.return_value = [(name,) for name in names] + return cursor + + +def _run_update( + engine: SnowflakeComputeEngine, + mock_execute: MagicMock, + deployed: Tuple[str, ...] = (), +) -> None: + mock_execute.side_effect = lambda conn, query: ( + _show_functions_cursor(deployed) + if query.startswith("SHOW USER FUNCTIONS") + else MagicMock() + ) mock_conn_cm = MagicMock() mock_conn_cm.__enter__ = MagicMock(return_value=MagicMock()) mock_conn_cm.__exit__ = MagicMock(return_value=False) - def _fake_package_snowpark_zip(project_name): - copy_path = tempfile.mkdtemp() - return copy_path, f"{copy_path}/feast.zip" + def _fake_package_snowpark_zip(copy_path): + return f"{copy_path}/feast.zip" with ( patch(f"{MODULE}.GetSnowflakeConnection", return_value=mock_conn_cm), patch(f"{MODULE}.execute_snowflake_statement", mock_execute), patch(f"{MODULE}.package_snowpark_zip", side_effect=_fake_package_snowpark_zip), - patch(f"{MODULE}.shutil.rmtree", side_effect=shutil.rmtree), ): engine.update( project="myproject", @@ -65,53 +81,210 @@ def _fake_package_snowpark_zip(project_name): ) -def test_update_never_short_circuits_on_existing_functions(): - """update() must not query `SHOW USER FUNCTIONS` and skip deployment -- - that early-return path is what caused stale runtime versions to stick - around after a config change. - """ +def _executed(mock_execute: MagicMock) -> list: + return [call.args[1] for call in mock_execute.call_args_list] + + +def _create_function_queries(mock_execute: MagicMock) -> list: + return [q for q in _executed(mock_execute) if "CREATE FUNCTION" in q] + + +def test_update_creates_versioned_udfs_without_replacing(): engine = _make_engine() + udf_namespace = engine._udf_namespace("myproject") mock_execute = MagicMock() _run_update(engine, mock_execute) - executed_queries = [call.args[1] for call in mock_execute.call_args_list] - assert not any("SHOW USER FUNCTIONS" in q for q in executed_queries), ( - "update() should no longer perform a SHOW USER FUNCTIONS check that " - "causes it to skip (re)deploying the UDFs" + queries = _executed(mock_execute) + creates = _create_function_queries(mock_execute) + assert creates + assert not any("OR REPLACE" in q for q in queries) + assert all( + f"CREATE FUNCTION IF NOT EXISTS feast_{udf_namespace}_" in q for q in creates ) - assert any("CREATE OR REPLACE FUNCTION" in q for q in executed_queries), ( - "update() should deploy UDFs using CREATE OR REPLACE FUNCTION so " - "redeploys pick up a changed python_udf_runtime_version" + stage = '"FEAST"."PUBLIC"."feast_myproject"' + assert all( + f"IMPORTS = ('@{stage}/{udf_namespace}/feast.zip')" in q for q in creates + ) + assert any( + q.endswith(f"@{stage}/{udf_namespace}") for q in queries if q.startswith("PUT") ) -def test_update_redeploys_with_current_runtime_version_on_every_call(): - """Calling update() twice (simulating two `feast apply` runs, e.g. before - and after a user bumps `python_udf_runtime_version`) must deploy the UDFs - both times, each time using whatever runtime version is currently - configured. - """ - engine = _make_engine(python_udf_runtime_version="3.11") +def _deployed_names(engine: SnowflakeComputeEngine) -> Tuple[str, ...]: mock_execute = MagicMock() - _run_update(engine, mock_execute) - first_call_count = mock_execute.call_count - assert first_call_count > 0 + return tuple( + name.upper() + for q in _create_function_queries(mock_execute) + for name in re.findall(r"IF NOT EXISTS (\w+)\(", q) + ) + + +def test_udf_names_match_the_deployed_udfs(): + engine = _make_engine() + names = engine._udf_names(engine._udf_namespace("myproject")) + assert names + assert names == set(_deployed_names(engine)) + + +def test_update_skips_when_the_current_set_is_deployed(): + """CREATE ... IF NOT EXISTS and PUT need CREATE/WRITE privileges even when + nothing is created, so a deployed set must not be touched at all.""" + engine = _make_engine() + mock_execute = MagicMock() + + _run_update(engine, mock_execute, deployed=_deployed_names(engine)) + + queries = _executed(mock_execute) + assert len(queries) == 1 + assert queries[0].startswith("SHOW USER FUNCTIONS LIKE 'FEAST_MYPROJECT_") + + +def test_update_skips_when_other_names_also_match(): + engine = _make_engine() + names = _deployed_names(engine) + mock_execute = MagicMock() + + _run_update(engine, mock_execute, deployed=(*names, "FEAST_MYPROJECT1X")) + + assert len(_executed(mock_execute)) == 1 + + +def test_update_redeploys_a_partial_set(): + engine = _make_engine() + mock_execute = MagicMock() + + _run_update(engine, mock_execute, deployed=_deployed_names(engine)[:-1]) + + assert _create_function_queries(mock_execute) + + +def test_update_ignores_another_versions_set(): + old, new = _make_engine("3.10"), _make_engine("3.11") + mock_execute = MagicMock() + + _run_update(new, mock_execute, deployed=_deployed_names(old)) + + assert _create_function_queries(mock_execute) + + +def test_runtime_version_change_deploys_a_new_set(): + """Changing `python_udf_runtime_version` must deploy UDFs with the new + runtime under new names, rather than reusing the stale ones.""" + old, new = _make_engine("3.10"), _make_engine("3.11") + assert old._udf_namespace("p") != new._udf_namespace("p") + assert old._udf_namespace("p") == _make_engine("3.10")._udf_namespace("p") + assert re.fullmatch(r"p_[0-9a-f]{8}", old._udf_namespace("p")) + + mock_execute = MagicMock() + _run_update(new, mock_execute) + + creates = _create_function_queries(mock_execute) + assert all("RUNTIME_VERSION = '3.11'" in q for q in creates) + assert all(f"feast_{new._udf_namespace('myproject')}_" in q for q in creates) + +def test_materialization_query_calls_the_deployed_udfs(): + engine = _make_engine() + mock_execute = MagicMock() _run_update(engine, mock_execute) - second_call_count = mock_execute.call_count - assert second_call_count == 2 * first_call_count, ( - "the second update() call should re-run the full deployment (no " - "early return), just like the first" - ) + deployed = { + name.upper() + for q in _create_function_queries(mock_execute) + for name in re.findall(r"IF NOT EXISTS (\w+)\(", q) + } - executed_queries = [call.args[1] for call in mock_execute.call_args_list] - create_function_queries = [ - q for q in executed_queries if "CREATE OR REPLACE FUNCTION" in q - ] - assert create_function_queries, "expected CREATE OR REPLACE FUNCTION queries" - assert all("RUNTIME_VERSION = '3.11'" in q for q in create_function_queries), ( - "every deployed UDF should use the currently configured " - "python_udf_runtime_version ('3.11'), including on redeploy" + feature_view = MagicMock() + feature_view.batch_source.created_timestamp_column = None + feature_view.batch_source.timestamp_field = "ts" + feature_view.entity_columns = [Field(name="userid", dtype=Int64)] + engine.repo_config.online_store.type = "redis" + query = engine.generate_snowflake_materialization_query( + engine.repo_config, + "SELECT 1", + feature_view, + [Field(name="score", dtype=Float64), Field(name="label", dtype=String)], + "myproject", ) + + called = {name.upper() for name in re.findall(r"(feast_\w+?)\(", query, re.I)} + assert called and called <= deployed + + +def test_materialization_deploys_udfs_once_per_engine(): + engine = _make_engine() + with patch.object(engine, "update") as mock_update: + engine._ensure_udfs("myproject") + engine._ensure_udfs("myproject") + mock_update.assert_called_once_with("myproject", [], [], [], []) + + +def test_teardown_drops_the_current_set(): + engine = _make_engine() + mock_execute = MagicMock() + mock_conn_cm = MagicMock() + mock_conn_cm.__enter__ = MagicMock(return_value=MagicMock()) + mock_conn_cm.__exit__ = MagicMock(return_value=False) + with ( + patch(f"{MODULE}.GetSnowflakeConnection", return_value=mock_conn_cm), + patch(f"{MODULE}.execute_snowflake_statement", mock_execute), + ): + engine.teardown_infra(project="myproject", fvs=[], entities=[]) + + drops = [q for q in _executed(mock_execute) if "DROP FUNCTION" in q] + assert drops + assert all(f"feast_{engine._udf_namespace('myproject')}_" in q for q in drops) + + +def _signature(name: str, args: str) -> Tuple[str, Tuple[str, ...]]: + # Creates declare "df ARRAY", drops just "ARRAY"; keep only the types. + return name.upper(), tuple(a.split()[-1].upper() for a in args.split(",")) + + +def test_teardown_drops_every_deployed_udf(): + """The deletion SQL is maintained separately from the creation SQL; a UDF + missing from it is silently left behind by `feast teardown`.""" + engine = _make_engine() + create_execute = MagicMock() + _run_update(engine, create_execute) + created = { + _signature(name, args) + for q in _create_function_queries(create_execute) + for name, args in re.findall(r"IF NOT EXISTS (\w+)\(([^)]*)\)", q) + } + + drop_execute = MagicMock() + mock_conn_cm = MagicMock() + mock_conn_cm.__enter__ = MagicMock(return_value=MagicMock()) + mock_conn_cm.__exit__ = MagicMock(return_value=False) + with ( + patch(f"{MODULE}.GetSnowflakeConnection", return_value=mock_conn_cm), + patch(f"{MODULE}.execute_snowflake_statement", drop_execute), + ): + engine.teardown_infra(project="myproject", fvs=[], entities=[]) + dropped = { + _signature(name, args) + for q in _executed(drop_execute) + for name, args in re.findall(r"DROP FUNCTION IF EXISTS (\w+)\(([^)]*)\)", q) + } + + assert created + assert created == dropped + + +def test_teardown_warns_and_continues_when_drop_fails(): + """Dropping needs ownership; without it, teardown must warn instead of + raising so the rest of `feast teardown` (e.g. the registry) still runs.""" + engine = _make_engine() + mock_conn_cm = MagicMock() + mock_conn_cm.__enter__ = MagicMock(return_value=MagicMock()) + mock_conn_cm.__exit__ = MagicMock(return_value=False) + denied = MagicMock(side_effect=RuntimeError("Insufficient privileges")) + with ( + patch(f"{MODULE}.GetSnowflakeConnection", return_value=mock_conn_cm), + patch(f"{MODULE}.execute_snowflake_statement", denied), + pytest.warns(RuntimeWarning, match="Insufficient privileges"), + ): + engine.teardown_infra(project="myproject", fvs=[], entities=[]) diff --git a/sdk/python/tests/unit/infra/utils/snowflake/test_snowflake_utils.py b/sdk/python/tests/unit/infra/utils/snowflake/test_snowflake_utils.py index 4bb02076354..73a061dd6dc 100644 --- a/sdk/python/tests/unit/infra/utils/snowflake/test_snowflake_utils.py +++ b/sdk/python/tests/unit/infra/utils/snowflake/test_snowflake_utils.py @@ -1,3 +1,4 @@ +import os import tempfile from typing import Optional from unittest.mock import MagicMock, patch @@ -9,6 +10,7 @@ from feast.infra.utils.snowflake.snowflake_utils import ( GetSnowflakeConnection, execute_snowflake_statement, + package_snowpark_zip, parse_private_key_path, ) @@ -167,3 +169,10 @@ def test_valid_query_raises_on_none_cursor(self): with pytest.raises(Exception, match="Snowflake query failed"): execute_snowflake_statement(mock_conn, "SELECT 1") + + +def test_package_snowpark_zip_builds_in_the_given_directory(): + with tempfile.TemporaryDirectory() as copy_path: + zip_path = package_snowpark_zip(copy_path) + assert zip_path == f"{copy_path}/feast.zip" + assert os.path.exists(zip_path)