diff --git a/docs/reference/online-stores/redis.md b/docs/reference/online-stores/redis.md index f212f03d943..8b8d438db4a 100644 --- a/docs/reference/online-stores/redis.md +++ b/docs/reference/online-stores/redis.md @@ -112,6 +112,34 @@ Benchmark results against Redis 8.6.2 (localhost, 50 entities, 3 features/FV, 30 The speedup grows with the number of feature views and is most pronounced in production environments with non-trivial network RTT to Redis. +### GLIDE client (`client: glide`) + +By default the Redis online store uses redis-py, which packs every command and parses every reply in Python. Each socket receive releases and reacquires the GIL, so in a process running other Python threads each reacquire waits on the switch interval. With many entities and feature views per read, that cost dominates. + +Setting `client: glide` runs the same `HMGET` commands as one non-atomic [GLIDE](https://github.com/valkey-io/valkey-glide) batch. GLIDE has a Rust core, so the batch crosses the FFI boundary once and the fetch runs with the GIL released. + +```yaml +online_store: + type: redis + connection_string: "localhost:6379" + client: glide +``` + +Install the extra to use it: + +```bash +pip install 'feast[glide]' +``` + +Notes: + +* GLIDE reads the same keys and hash fields Feast already writes, so an existing store needs no migration and no rewrite of data. +* The default stays `client: redis`. Writes and `get_online_features_async` keep using redis-py, so only the synchronous read path changes. +* GLIDE supports `host:port`, `db`, `password`, `username`, `ssl`, `socket_timeout`, and `socket_connect_timeout` from `connection_string`. Other parameters are logged and ignored. +* GLIDE has no Sentinel support, so `client: glide` cannot be combined with `redis_type: redis_sentinel`. Use `client: redis` for Sentinel deployments. + +If `client: glide` is set without the extra installed, Feast raises an import error naming the extra to install. + ### Write path: `skip_dedup` for bulk loads By default, `online_write_batch()` checks existing timestamps before writing (to avoid overwriting newer data with older data). This requires two pipeline round trips per batch: one to read existing timestamps, one to write new values. @@ -144,6 +172,7 @@ The Redis online store implements `online_write_batch_async()` using the async R | `key_ttl_seconds` | `null` | Redis `EXPIRE` TTL in seconds applied to the entity hash key after each write. Expires all feature views for that entity together. | | `full_scan_for_deletion` | `true` | When `true`, deleting or renaming a feature view scans Redis to remove its hash fields. Set `false` to skip deletion scans (faster `feast apply`, but leaves orphaned data). | | `skip_dedup` | `false` | When `true`, skips the existing-timestamp read before each write, halving write round trips. Suitable for initial bulk loads; may cause older values to overwrite newer ones under concurrent writers. | +| `client` | `redis` | Read client: `redis` for redis-py, or `glide` to run the synchronous batched read as one non-atomic GLIDE batch. Requires `pip install 'feast[glide]'`. | The full set of configuration options is available in [RedisOnlineStoreConfig](https://rtd.feast.dev/en/latest/#feast.infra.online_stores.redis.RedisOnlineStoreConfig). @@ -172,5 +201,6 @@ Below is a matrix indicating which functionality is supported by the Redis onlin | collocated by entity key | yes | | async batch writes | yes | | batched multi-feature-view reads (single pipeline) | yes | +| optional GLIDE client for synchronous reads | yes | To compare this set of functionality against other online stores, please see the full [functionality matrix](overview.md#functionality-matrix). diff --git a/pyproject.toml b/pyproject.toml index 8fae42d069c..b2974b55a9c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -80,6 +80,7 @@ gcp = [ "fsspec>=2024.1.0", ] ge = ["great_expectations>=0.15.41,<1"] +glide = ["valkey-glide-sync>=2.5,<3"] go = ["cffi>=1.15.0"] grpcio = [ "grpcio>=1.56.2", @@ -166,7 +167,7 @@ test = [ ] ci = [ - "feast[test, aws, azure, cassandra, clickhouse, couchbase, delta, docling, duckdb, elasticsearch, faiss, gcp, ge, go, grpcio, hazelcast, hbase, ibis, iceberg, image, k8s, mcp, milvus, mlflow, mongodb, mssql, mysql, openlineage, opentelemetry, oracle, scylladb, spark, trino, postgres, pytorch, qdrant, rag, ray, redis, singlestore, snowflake, sqlite_vec]", + "feast[test, aws, azure, cassandra, clickhouse, couchbase, delta, docling, duckdb, elasticsearch, faiss, gcp, ge, glide, go, grpcio, hazelcast, hbase, ibis, iceberg, image, k8s, mcp, milvus, mlflow, mongodb, mssql, mysql, openlineage, opentelemetry, oracle, scylladb, spark, trino, postgres, pytorch, qdrant, rag, ray, redis, singlestore, snowflake, sqlite_vec]", "build", "virtualenv==20.23.0", "dbt-artifacts-parser", diff --git a/sdk/python/feast/infra/online_stores/redis.py b/sdk/python/feast/infra/online_stores/redis.py index b50161bd6de..0a2e5526d44 100644 --- a/sdk/python/feast/infra/online_stores/redis.py +++ b/sdk/python/feast/infra/online_stores/redis.py @@ -32,6 +32,7 @@ from pydantic import StrictStr from feast import Entity, FeatureView, RepoConfig, utils +from feast.errors import FeastExtrasDependencyImportError from feast.infra.key_encoding_utils import serialize_entity_key from feast.infra.online_stores.helpers import ( _mmh3, @@ -51,8 +52,6 @@ from redis.cluster import ClusterNode, RedisCluster from redis.sentinel import Sentinel except ImportError as e: - from feast.errors import FeastExtrasDependencyImportError - raise FeastExtrasDependencyImportError("redis", str(e)) logger = logging.getLogger(__name__) @@ -71,6 +70,11 @@ class RedisType(str, Enum): redis_sentinel = "redis_sentinel" +class RedisClient(str, Enum): + redis = "redis" + glide = "glide" + + class RedisOnlineStoreConfig(FeastConfigBaseModel): """Online store config for Redis store""" @@ -80,6 +84,15 @@ class RedisOnlineStoreConfig(FeastConfigBaseModel): redis_type: RedisType = RedisType.redis """Redis type: redis or redis_cluster""" + client: RedisClient = RedisClient.redis + """Redis client used for online reads: ``redis`` (redis-py, default) or ``glide``. + + With ``glide``, the synchronous read paths (``online_read`` and the batched read + behind ``get_online_features``) issue their HMGET commands as one non-atomic GLIDE + batch, so the fetch runs off the GIL. Requires ``pip install 'feast[glide]'``. + Writes and async reads always use redis-py. GLIDE has no Sentinel support, so + ``client: glide`` cannot be combined with ``redis_type: redis_sentinel``.""" + sentinel_master: StrictStr = "mymaster" """Sentinel's master name""" @@ -99,6 +112,115 @@ class RedisOnlineStoreConfig(FeastConfigBaseModel): This may cause older feature values to overwrite newer ones under concurrent writers.""" +def _seconds_to_millis(value: Any) -> Optional[int]: + """Convert a redis-py timeout in seconds to GLIDE's millisecond unit.""" + if value is None: + return None + return int(float(value) * 1000) + + +def _load_glide_sync(): + """Import ``valkey-glide-sync`` on demand. + + The native extension is only loaded when ``client: glide`` is configured, so the + redis extra keeps working for users who did not opt in. + """ + try: + import glide_sync + except ImportError as e: + raise FeastExtrasDependencyImportError("glide", str(e)) from e + return glide_sync + + +_GLIDE_SUPPORTED_CONNECTION_PARAMS = frozenset( + {"ssl", "db", "password", "username", "socket_timeout", "socket_connect_timeout"} +) + + +def _glide_client_config(glide_sync, online_store_config: RedisOnlineStoreConfig): + """Translate a Feast Redis connection string into a GLIDE client configuration.""" + if online_store_config.redis_type == RedisType.redis_sentinel: + raise ValueError( + "client: glide does not support redis_type: redis_sentinel. " + "Use client: redis for Sentinel deployments." + ) + + startup_nodes, params = RedisOnlineStore._parse_connection_string( + online_store_config.connection_string + ) + ignored = sorted(set(params) - _GLIDE_SUPPORTED_CONNECTION_PARAMS) + if ignored: + logger.warning( + "client: glide ignores these Redis connection_string parameters: %s", + ", ".join(ignored), + ) + + credentials = None + password = params.get("password") + username = params.get("username") + if password is not None or username is not None: + credentials = glide_sync.ServerCredentials( + # _parse_connection_string json-decodes values, so a numeric password can + # arrive as an int while GLIDE expects a str. + password=None if password is None else str(password), + username=None if username is None else str(username), + ) + + connection_timeout = _seconds_to_millis(params.get("socket_connect_timeout")) + kwargs: Dict[str, Any] = { + "addresses": [ + glide_sync.NodeAddress(host=node["host"], port=int(node["port"])) + for node in startup_nodes + ], + "use_tls": bool(params.get("ssl", False)), + "credentials": credentials, + "request_timeout": _seconds_to_millis(params.get("socket_timeout")), + "advanced_config": glide_sync.AdvancedGlideClientConfiguration( + connection_timeout=connection_timeout + ) + if connection_timeout is not None + else None, + } + + if online_store_config.redis_type == RedisType.redis_cluster: + # Cluster nodes do not support SELECT, so `db` is not passed along. + return glide_sync.GlideClusterClientConfiguration(**kwargs) + + if "db" in params: + kwargs["database_id"] = int(params["db"]) + return glide_sync.GlideClientConfiguration(**kwargs) + + +def _create_glide_client(glide_sync, online_store_config: RedisOnlineStoreConfig): + """Connect a GLIDE client built from the Redis online store config.""" + config = _glide_client_config(glide_sync, online_store_config) + if online_store_config.redis_type == RedisType.redis_cluster: + return glide_sync.GlideClusterClient.create(config) + return glide_sync.GlideClient.create(config) + + +def _glide_hmget_batch( + glide_sync, + client, + commands: List[Tuple[bytes, List[Union[str, bytes]]]], +) -> List[List[Optional[bytes]]]: + """Run one HMGET per ``(key, fields)`` pair in a single non-atomic GLIDE batch. + + Replies keep the order of ``commands``, so callers can slice them exactly like a + redis-py pipeline result. + """ + batch = ( + glide_sync.ClusterBatch(is_atomic=False) + if isinstance(client, glide_sync.GlideClusterClient) + else glide_sync.Batch(is_atomic=False) + ) + for key, fields in commands: + batch.hmget(key, fields) + + result = client.exec(batch, raise_on_error=True) + return list(result) if result else [] + + class RedisOnlineStore(OnlineStore): """ Redis implementation of the online store interface. @@ -114,6 +236,10 @@ class RedisOnlineStore(OnlineStore): _client_async: Optional[Union[redis_asyncio.Redis, redis_asyncio.RedisCluster]] = ( None ) + # Only set when `client: glide` is configured, so the native extension stays + # untouched for users who never opt in. + _glide_client: Optional[Any] = None + _glide_sync: Optional[Any] = None @property def async_supported(self) -> SupportedAsyncMethods: @@ -225,6 +351,12 @@ def teardown( for join_keys in join_keys_to_delete: self.delete_entity_values(config, list(join_keys)) + # Release the native GLIDE client, if one was ever opened, so teardown does + # not leave its Rust-side resources and file descriptors behind. + if self._glide_client: + self._glide_client.close() + self._glide_client = None + @staticmethod def _parse_connection_string(connection_string: str): """ @@ -305,6 +437,20 @@ async def _get_client_async(self, online_store_config: RedisOnlineStoreConfig): self._client_async = redis_asyncio.Redis(**kwargs) return self._client_async + def _get_glide_sync(self): + """Returns the cached ``glide_sync`` module, importing it on first use.""" + if self._glide_sync is None: + self._glide_sync = _load_glide_sync() + return self._glide_sync + + def _get_glide_client(self, online_store_config: RedisOnlineStoreConfig): + """Creates and caches a GLIDE client built from the online store config.""" + if not self._glide_client: + self._glide_client = _create_glide_client( + self._get_glide_sync(), online_store_config + ) + return self._glide_client + def online_write_batch( self, config: RepoConfig, @@ -538,12 +684,14 @@ def _generate_hset_keys_for_features( feature_view: FeatureView, requested_features: Optional[List[str]] = None, fv_name_override: Optional[str] = None, - ) -> Tuple[List[str], List[str]]: + ) -> Tuple[List[str], List[Union[str, bytes]]]: if not requested_features: requested_features = [f.name for f in feature_view.features] fv_name = fv_name_override or feature_view.name - hset_keys = [_mmh3(f"{fv_name}:{k}") for k in requested_features] + hset_keys: List[Union[str, bytes]] = [ + _mmh3(f"{fv_name}:{k}") for k in requested_features + ] ts_key = f"_ts:{fv_name}" hset_keys.append(ts_key) @@ -553,7 +701,7 @@ def _generate_hset_keys_for_features( def _convert_redis_values_to_protobuf( self, - redis_values: List[List[ByteString]], + redis_values: Sequence[Sequence[Optional[ByteString]]], feature_view: str, requested_features: List[str], ) -> List[Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]]: @@ -562,6 +710,33 @@ def _convert_redis_values_to_protobuf( for values in redis_values ] + def _read_hash_fields( + self, + config: RepoConfig, + commands: List[Tuple[bytes, List[Union[str, bytes]]]], + ) -> List[List[Optional[ByteString]]]: + """Fetch one HMGET reply per ``(key, fields)`` pair, in the given order. + + Defaults to a single redis-py pipeline. When ``client: glide`` is configured + the same commands run as one non-atomic GLIDE batch, so the fetch runs off the + GIL instead of in Python per command. + """ + online_store_config = config.online_store + assert isinstance(online_store_config, RedisOnlineStoreConfig) + + if online_store_config.client == RedisClient.glide: + return _glide_hmget_batch( + self._get_glide_sync(), + self._get_glide_client(online_store_config), + commands, + ) + + client = self._get_client(online_store_config) + with client.pipeline(transaction=False) as pipe: + for redis_key, fields in commands: + pipe.hmget(redis_key, fields) + return pipe.execute() + def online_read( self, config: RepoConfig, @@ -569,10 +744,6 @@ def online_read( entity_keys: List[EntityKeyProto], requested_features: Optional[List[str]] = None, ) -> List[Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]]: - online_store_config = config.online_store - assert isinstance(online_store_config, RedisOnlineStoreConfig) - - client = self._get_client(online_store_config) feature_view = table fv_name = _versioned_fv_name(table, config) @@ -581,11 +752,9 @@ def online_read( ) keys = self._generate_redis_keys_for_entities(config, entity_keys) - with client.pipeline(transaction=False) as pipe: - for redis_key_bin in keys: - pipe.hmget(redis_key_bin, hset_keys) - - redis_values = pipe.execute() + redis_values = self._read_hash_fields( + config, [(redis_key, hset_keys) for redis_key in keys] + ) return self._convert_redis_values_to_protobuf( redis_values, fv_name, requested_features @@ -648,12 +817,14 @@ def _read_features_per_fv( ) if work_items: - client = self._get_client(config.online_store) - with client.pipeline(transaction=False) as pipe: - for _, _, _, hset_keys, redis_keys, _, _ in work_items: - for redis_key in redis_keys: - pipe.hmget(redis_key, hset_keys) - all_results = pipe.execute() + all_results = self._read_hash_fields( + config, + [ + (redis_key, hset_keys) + for _, _, _, hset_keys, redis_keys, _, _ in work_items + for redis_key in redis_keys + ], + ) offset = 0 for ( @@ -751,7 +922,7 @@ async def _read_features_per_fv_async( def _get_features_for_entity( self, - values: List[ByteString], + values: Sequence[Optional[ByteString]], feature_view: str, requested_features: List[str], ) -> Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]: diff --git a/sdk/python/tests/integration/online_store/test_redis_glide_client.py b/sdk/python/tests/integration/online_store/test_redis_glide_client.py new file mode 100644 index 00000000000..3cca321aa64 --- /dev/null +++ b/sdk/python/tests/integration/online_store/test_redis_glide_client.py @@ -0,0 +1,221 @@ +"""Integration tests comparing the redis-py and GLIDE Redis online read paths. + +Rows are always written through the default redis-py client, then read back with +``client: redis`` and ``client: glide``. If GLIDE built different entity keys or +different hashed feature field names, the GLIDE reads would come back NOT_FOUND +instead of matching. + +Run with: pytest --integration sdk/python/tests/integration/online_store/test_redis_glide_client.py +""" + +import shutil +from datetime import datetime, timezone +from typing import Dict, List, Tuple + +import pytest + +from feast import Entity, FeatureView, Field, RepoConfig +from feast.infra.online_stores.redis import ( + RedisClient, + RedisOnlineStore, + RedisOnlineStoreConfig, +) +from feast.protos.feast.serving.ServingService_pb2 import GetOnlineFeaturesResponse +from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto +from feast.protos.feast.types.Value_pb2 import Value as ValueProto +from feast.repo_config import RegistryConfig +from feast.types import Float32, Int64 +from feast.value_type import ValueType + +pytestmark = pytest.mark.integration + + +@pytest.fixture(scope="module") +def redis_address(): + if not shutil.which("docker"): + pytest.skip("Docker not available") + pytest.importorskip("glide_sync") + + from testcontainers.community.redis import RedisContainer + + container = RedisContainer("redis:7").with_exposed_ports(6379) + container.start() + try: + yield f"{container.get_container_host_ip()}:{container.get_exposed_port(6379)}" + finally: + container.stop() + + +def _feature_views() -> Tuple[FeatureView, FeatureView]: + entity = Entity( + name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64 + ) + driver_stats = FeatureView( + name="driver_stats", + entities=[entity], + schema=[ + Field(name="trips_today", dtype=Int64), + Field(name="avg_rating", dtype=Float32), + ], + ) + driver_metrics = FeatureView( + name="driver_metrics", + entities=[entity], + schema=[Field(name="lifetime_trips", dtype=Int64)], + ) + return driver_stats, driver_metrics + + +def _entity_key(driver_id: int) -> EntityKeyProto: + return EntityKeyProto( + join_keys=["driver_id"], entity_values=[ValueProto(int64_val=driver_id)] + ) + + +def _config(redis_address: str, client: RedisClient) -> RepoConfig: + return RepoConfig( + project="test_redis_glide", + provider="local", + online_store=RedisOnlineStoreConfig( + connection_string=redis_address, client=client + ), + registry=RegistryConfig(path="/tmp/test_redis_glide_registry.pb"), + entity_key_serialization_version=3, + ) + + +def _seed(redis_address: str, driver_ids: List[int]) -> None: + """Write rows with the default redis-py client so both paths read the same data.""" + driver_stats, driver_metrics = _feature_views() + config = _config(redis_address, RedisClient.redis) + store = RedisOnlineStore() + now = datetime.now(tz=timezone.utc) + + store.online_write_batch( + config, + driver_stats, + [ + ( + _entity_key(driver_id), + { + "trips_today": ValueProto(int64_val=driver_id * 10), + "avg_rating": ValueProto(float_val=driver_id / 2), + }, + now, + now, + ) + for driver_id in driver_ids + ], + progress=None, + ) + store.online_write_batch( + config, + driver_metrics, + [ + ( + _entity_key(driver_id), + {"lifetime_trips": ValueProto(int64_val=driver_id * 100)}, + now, + now, + ) + for driver_id in driver_ids + ], + progress=None, + ) + + +def _batched_response( + redis_address: str, + client: RedisClient, + entity_ids: List[int], +) -> GetOnlineFeaturesResponse: + """Drive the batched per-feature-view read that backs get_online_features.""" + driver_stats, driver_metrics = _feature_views() + response = GetOnlineFeaturesResponse() + RedisOnlineStore()._read_features_per_fv( + config=_config(redis_address, client), + grouped_refs=[ + (driver_stats, ["trips_today", "avg_rating"]), + (driver_metrics, ["lifetime_trips"]), + ], + join_key_values={ + "driver_id": [ValueProto(int64_val=driver_id) for driver_id in entity_ids] + }, + entity_name_to_join_key_map={"driver_id": "driver_id"}, + online_features_response=response, + full_feature_names=False, + include_feature_view_version_metadata=False, + ) + return response + + +def _features(row) -> Dict[str, ValueProto]: + """Unwrap an online_read row, asserting the entity was found.""" + features = row[1] + assert features is not None, "expected a value for this entity" + return features + + +def _values_by_feature(response: GetOnlineFeaturesResponse) -> Dict[str, List[float]]: + """Per requested feature name, the value of each output row (0.0 when absent). + + ``response.results`` holds one entry per feature, and each entry's ``values`` + holds one value per output row. + """ + return { + name: [ + value.int64_val or value.float_val + for value in response.results[index].values + ] + for index, name in enumerate(response.metadata.feature_names.val) + } + + +def test_glide_online_read_matches_redis_py(redis_address): + driver_stats, _ = _feature_views() + seeded = [1001, 1002, 1003] + _seed(redis_address, seeded) + + # 9999 was never written, so both paths must agree on the empty row. + entity_keys = [_entity_key(driver_id) for driver_id in seeded + [9999]] + requested = ["trips_today", "avg_rating"] + + redis_rows = RedisOnlineStore().online_read( + _config(redis_address, RedisClient.redis), + driver_stats, + entity_keys, + list(requested), + ) + glide_rows = RedisOnlineStore().online_read( + _config(redis_address, RedisClient.glide), + driver_stats, + entity_keys, + list(requested), + ) + + assert glide_rows == redis_rows + # Guard against both paths agreeing on nothing. + assert _features(glide_rows[0])["trips_today"].int64_val == 10010 + assert _features(glide_rows[2])["trips_today"].int64_val == 10030 + assert _features(glide_rows[3])["trips_today"].WhichOneof("val") is None + + +def test_glide_batched_read_matches_redis_py(redis_address): + seeded = [2001, 2002, 2003] + _seed(redis_address, seeded) + + # 2004 was never written, so both paths must agree on the NOT_FOUND row. + entity_ids = [2001, 2002, 2004, 2003] + + redis_response = _batched_response(redis_address, RedisClient.redis, entity_ids) + glide_response = _batched_response(redis_address, RedisClient.glide, entity_ids) + + assert glide_response == redis_response + assert list(glide_response.metadata.feature_names.val) == list( + redis_response.metadata.feature_names.val + ) + + values = _values_by_feature(glide_response) + assert values["trips_today"] == [20010, 20020, 0, 20030] + assert values["avg_rating"] == [1000.5, 1001.0, 0, 1001.5] + assert values["lifetime_trips"] == [200100, 200200, 0, 200300] diff --git a/sdk/python/tests/unit/infra/online_store/test_redis.py b/sdk/python/tests/unit/infra/online_store/test_redis.py index f76c692de72..96c213542c7 100644 --- a/sdk/python/tests/unit/infra/online_store/test_redis.py +++ b/sdk/python/tests/unit/infra/online_store/test_redis.py @@ -1,13 +1,25 @@ import asyncio +import sys from datetime import datetime, timedelta, timezone +from types import SimpleNamespace +from typing import List, Tuple, Union from unittest.mock import AsyncMock, MagicMock, patch import pytest from google.protobuf.timestamp_pb2 import Timestamp from feast import Entity, FeatureView, Field, FileSource, RepoConfig +from feast.errors import FeastExtrasDependencyImportError from feast.infra.online_stores.helpers import _mmh3 -from feast.infra.online_stores.redis import RedisOnlineStore, RedisOnlineStoreConfig +from feast.infra.online_stores.redis import ( + RedisClient, + RedisOnlineStore, + RedisOnlineStoreConfig, + RedisType, + _glide_client_config, + _glide_hmget_batch, + _load_glide_sync, +) from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto from feast.protos.feast.types.Value_pb2 import Value as ValueProto from feast.types import Int32 @@ -622,3 +634,345 @@ def test_online_write_batch_async_exists_and_is_coroutine(): store = RedisOnlineStore() assert hasattr(store, "online_write_batch_async") assert inspect.iscoroutinefunction(store.online_write_batch_async) + + +# --------------------------------------------------------------------------------- +# GLIDE client (client: glide) +# --------------------------------------------------------------------------------- + +GLIDE_PATH = "feast.infra.online_stores.redis._load_glide_sync" +GLIDE_BATCH_PATH = "feast.infra.online_stores.redis._glide_hmget_batch" + + +def _online_read_config(client: RedisClient = RedisClient.redis) -> RepoConfig: + return RepoConfig( + provider="local", + project="test", + entity_key_serialization_version=3, + registry="dummy_registry.db", + online_store=RedisOnlineStoreConfig(client=client), + ) + + +def _pipeline_mock(results): + pipe = MagicMock() + pipe.__enter__ = MagicMock(return_value=pipe) + pipe.__exit__ = MagicMock(return_value=False) + pipe.execute.return_value = results + return pipe + + +def _two_entity_keys() -> list: + return [ + EntityKeyProto(join_keys=["entity"], entity_values=[ValueProto(int32_val=1)]), + EntityKeyProto(join_keys=["entity"], entity_values=[ValueProto(int32_val=2)]), + ] + + +def test_client_defaults_to_redis_py(): + """Default config must keep using redis-py.""" + assert RedisOnlineStoreConfig().client is RedisClient.redis + + +def test_default_client_reads_through_redis_pipeline( + redis_online_store: RedisOnlineStore, feature_view +): + """Without an opt-in, reads must go through the redis-py pipeline only.""" + pipe = _pipeline_mock([[None] * 4, [None] * 4]) + mock_client = MagicMock() + mock_client.pipeline.return_value = pipe + + def fail_if_glide_is_loaded(): + raise AssertionError("glide_sync must not be loaded for the default client") + + with ( + patch.object(redis_online_store, "_get_client", return_value=mock_client), + patch(GLIDE_PATH, side_effect=fail_if_glide_is_loaded), + ): + redis_online_store.online_read( + _online_read_config(), feature_view, _two_entity_keys(), ["feature_10"] + ) + + assert mock_client.pipeline.call_count == 1 + assert pipe.hmget.call_count == 2 + + +def test_glide_client_is_opt_in_per_config( + redis_online_store: RedisOnlineStore, feature_view +): + """client: glide must select the GLIDE batch and skip the redis-py pipeline.""" + pipe = _pipeline_mock([[None] * 4, [None] * 4]) + mock_client = MagicMock() + mock_client.pipeline.return_value = pipe + fake_glide_batch = MagicMock(return_value=[[None] * 4, [None] * 4]) + + with ( + patch.object(redis_online_store, "_get_client", return_value=mock_client), + patch(GLIDE_PATH, return_value=object()) as load_glide, + patch.object(redis_online_store, "_get_glide_client", return_value=object()), + patch(GLIDE_BATCH_PATH, fake_glide_batch), + ): + rows = redis_online_store.online_read( + _online_read_config(RedisClient.glide), + feature_view, + _two_entity_keys(), + ["feature_10"], + ) + + load_glide.assert_called_once() + glide_commands = fake_glide_batch.call_args.args[2] + assert len(glide_commands) == 2 + assert mock_client.pipeline.call_count == 0 + # Feature values are still converted with the shared redis-py response handling. + assert len(rows) == 2 + + +def test_glide_path_issues_same_commands_as_redis_path( + redis_online_store: RedisOnlineStore, feature_view +): + """Both clients must read the same entity keys with the same hashed fields.""" + entity_keys = _two_entity_keys() + + pipe = _pipeline_mock([[None] * 4, [None] * 4]) + mock_client = MagicMock() + mock_client.pipeline.return_value = pipe + with patch.object(redis_online_store, "_get_client", return_value=mock_client): + redis_online_store.online_read( + _online_read_config(), feature_view, entity_keys, ["feature_10"] + ) + redis_commands = [call.args for call in pipe.hmget.call_args_list] + fake_glide_batch = MagicMock(return_value=[[None] * 4, [None] * 4]) + + with ( + patch(GLIDE_PATH, return_value=object()), + patch.object(redis_online_store, "_get_glide_client", return_value=object()), + patch(GLIDE_BATCH_PATH, fake_glide_batch), + ): + redis_online_store.online_read( + _online_read_config(RedisClient.glide), + feature_view, + entity_keys, + ["feature_10"], + ) + + glide_commands = fake_glide_batch.call_args.args[2] + assert glide_commands == redis_commands + # The hashed field names and the _ts field come from the existing helpers. + key, fields = glide_commands[0] + assert fields[0] == _mmh3(f"{feature_view.name}:feature_10") + assert fields[-1] == f"_ts:{feature_view.name}" + + +def test_glide_hmget_batch_is_one_non_atomic_batch(): + """The GLIDE read must be a single non-atomic batch of HMGET commands.""" + + class FakeBatch: + def __init__(self, is_atomic): + self.is_atomic = is_atomic + self.commands = [] + + def hmget(self, key, fields): + self.commands.append((key, list(fields))) + return self + + class FakeGlideClient: + def __init__(self): + self.exec_calls = [] + + def exec(self, batch, raise_on_error): + self.exec_calls.append((batch, raise_on_error)) + return [[b"value", None], [None, None]] + + fake_glide_sync = SimpleNamespace( + Batch=FakeBatch, + ClusterBatch=FakeBatch, + GlideClusterClient=type("FakeGlideClusterClient", (), {}), + ) + glide_client = FakeGlideClient() + commands: List[Tuple[bytes, List[Union[str, bytes]]]] = [ + (b"key1", ["f1", "_ts:fv"]), + (b"key2", ["f1", "_ts:fv"]), + ] + + result = _glide_hmget_batch(fake_glide_sync, glide_client, commands) + + assert len(glide_client.exec_calls) == 1 + batch, raise_on_error = glide_client.exec_calls[0] + assert batch.is_atomic is False + assert raise_on_error is True + assert batch.commands == commands + assert result == [[b"value", None], [None, None]] + + +def test_glide_hmget_batch_uses_cluster_batch_for_cluster_clients(): + """Redis Cluster reads must use ClusterBatch, not the standalone Batch.""" + + class FakeBatch: + def __init__(self, is_atomic): + self.is_atomic = is_atomic + + def hmget(self, key, fields): + return self + + class FakeClusterBatch(FakeBatch): + pass + + class FakeGlideClusterClient: + def __init__(self): + self.batch_types = [] + + def exec(self, batch, raise_on_error): + self.batch_types.append(type(batch)) + return [[None]] + + fake_glide_sync = SimpleNamespace( + Batch=FakeBatch, + ClusterBatch=FakeClusterBatch, + GlideClusterClient=FakeGlideClusterClient, + ) + glide_client = FakeGlideClusterClient() + + _glide_hmget_batch(fake_glide_sync, glide_client, [(b"key1", ["f1"])]) + + assert glide_client.batch_types == [FakeClusterBatch] + + +def test_missing_glide_dependency_raises_clear_error(monkeypatch): + """Opting in without the extra installed must fail with an actionable error.""" + monkeypatch.setitem(sys.modules, "glide_sync", None) + + with pytest.raises(FeastExtrasDependencyImportError) as exc_info: + _load_glide_sync() + + assert "glide_sync" in str(exc_info.value) + assert "pip install 'feast[glide]'" in str(exc_info.value) + + +def test_glide_client_config_parses_connection_string(): + glide_sync = pytest.importorskip("glide_sync") + + config = _glide_client_config( + glide_sync, + RedisOnlineStoreConfig( + connection_string=( + "redis.example.com:6380,db=2,password=hunter2,username=feast," + "ssl=true,socket_timeout=1.5,socket_connect_timeout=2" + ) + ), + ) + + assert [(address.host, address.port) for address in config.addresses] == [ + ("redis.example.com", 6380) + ] + assert config.database_id == 2 + assert config.use_tls is True + assert config.credentials.password == "hunter2" # pragma: allowlist secret + assert config.credentials.username == "feast" + # redis-py takes timeouts in seconds, GLIDE in milliseconds. + assert config.request_timeout == 1500 + assert config.advanced_config.connection_timeout == 2000 + + +def test_glide_client_config_defaults_tls_and_timeouts_off(): + glide_sync = pytest.importorskip("glide_sync") + + config = _glide_client_config( + glide_sync, RedisOnlineStoreConfig(connection_string="localhost:6379") + ) + + assert config.use_tls is False + assert config.credentials is None + assert config.database_id is None + assert config.request_timeout is None + assert config.advanced_config is None + + +def test_glide_client_config_parses_cluster_connection_string(): + glide_sync = pytest.importorskip("glide_sync") + + config = _glide_client_config( + glide_sync, + RedisOnlineStoreConfig( + redis_type=RedisType.redis_cluster, + connection_string="redis1:6379,redis2:6379,ssl=true,password=hunter2", + ), + ) + + assert [(address.host, address.port) for address in config.addresses] == [ + ("redis1", 6379), + ("redis2", 6379), + ] + assert config.use_tls is True + assert config.credentials.password == "hunter2" # pragma: allowlist secret + # Cluster nodes do not support SELECT, so db is not forwarded. + assert config.database_id is None + + +def test_glide_client_config_rejects_sentinel(): + """GLIDE has no Sentinel support, so the combination must fail loudly.""" + glide_sync = pytest.importorskip("glide_sync") + + with pytest.raises(ValueError, match="redis_sentinel"): + _glide_client_config( + glide_sync, + RedisOnlineStoreConfig( + redis_type=RedisType.redis_sentinel, + connection_string="sentinel1:26379", + ), + ) + + +def test_glide_client_config_warns_about_ignored_params(caplog): + glide_sync = pytest.importorskip("glide_sync") + + with caplog.at_level("WARNING"): + _glide_client_config( + glide_sync, + RedisOnlineStoreConfig( + connection_string="localhost:6379,skip_full_coverage_check=true" + ), + ) + + assert "skip_full_coverage_check" in caplog.text + + +def test_glide_module_is_imported_once_per_store( + redis_online_store: RedisOnlineStore, feature_view +): + """The glide_sync module is cached on the store, not re-imported per read.""" + with ( + patch(GLIDE_PATH, return_value=object()) as load_glide, + patch.object(redis_online_store, "_get_glide_client", return_value=object()), + patch(GLIDE_BATCH_PATH, MagicMock(return_value=[[None] * 4])), + ): + for _ in range(2): + redis_online_store.online_read( + _online_read_config(RedisClient.glide), + feature_view, + _two_entity_keys()[:1], + ["feature_10"], + ) + + load_glide.assert_called_once() + + +def test_teardown_closes_the_glide_client( + redis_online_store: RedisOnlineStore, repo_config: RepoConfig +): + """teardown must release the native GLIDE client and clear the cache.""" + glide_client = MagicMock() + redis_online_store._glide_client = glide_client + + redis_online_store.teardown(repo_config, [], []) + + glide_client.close.assert_called_once() + assert redis_online_store._glide_client is None + + +def test_teardown_without_a_glide_client_does_not_raise( + redis_online_store: RedisOnlineStore, repo_config: RepoConfig +): + """A store that never opted into GLIDE must tear down cleanly.""" + redis_online_store.teardown(repo_config, [], []) + + assert redis_online_store._glide_client is None