diff --git a/sdk/python/feast/infra/online_stores/online_store.py b/sdk/python/feast/infra/online_stores/online_store.py index 8527bf94c87..71e8a0b8710 100644 --- a/sdk/python/feast/infra/online_stores/online_store.py +++ b/sdk/python/feast/infra/online_stores/online_store.py @@ -103,6 +103,58 @@ async def online_write_batch_async( f"Online store {self.__class__.__name__} does not support online write batch async" ) + def online_append( + self, + config: RepoConfig, + table: FeatureView, + data: List[ + Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]] + ], + progress: Optional[Callable[[int], Any]] = None, + ) -> None: + """ + Appends rows without overwriting earlier values for the same entity key. + + Called instead of online_write_batch when the feature view's online_config + sets write_mode="append". Tz-naive timestamps are treated as UTC. + + Args: + config: The config for the current feature store. + table: The feature view the rows belong to. + data: Rows as (entity key, feature values, event timestamp, + created timestamp or None). + progress: Called with the number of rows written, to show progress. + """ + raise NotImplementedError( + f"Online store {self.__class__.__name__} does not support online append" + ) + + async def online_append_async( + self, + config: RepoConfig, + table: FeatureView, + data: List[ + Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]] + ], + progress: Optional[Callable[[int], Any]] = None, + ) -> None: + """ + Appends rows without overwriting earlier values for the same entity key Asynchronously. + + Called instead of online_write_batch when the feature view's online_config + sets write_mode="append". Tz-naive timestamps are treated as UTC. + + Args: + config: The config for the current feature store. + table: The feature view the rows belong to. + data: Rows as (entity key, feature values, event timestamp, + created timestamp or None). + progress: Called with the number of rows written, to show progress. + """ + raise NotImplementedError( + f"Online store {self.__class__.__name__} does not support online append async" + ) + @abstractmethod def online_read( self, diff --git a/sdk/python/feast/infra/online_stores/redis.py b/sdk/python/feast/infra/online_stores/redis.py index fef5fa12e7d..708a080c958 100644 --- a/sdk/python/feast/infra/online_stores/redis.py +++ b/sdk/python/feast/infra/online_stores/redis.py @@ -13,6 +13,7 @@ # limitations under the License. import json import logging +import struct from datetime import datetime, timezone from enum import Enum from typing import ( @@ -43,6 +44,7 @@ from feast.infra.online_stores.online_store import OnlineStore from feast.infra.supported_async_methods import SupportedAsyncMethods from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto +from feast.protos.feast.types.Value_pb2 import Map as MapProto from feast.protos.feast.types.Value_pb2 import Value as ValueProto from feast.repo_config import FeastConfigBaseModel @@ -64,6 +66,25 @@ def _versioned_fv_name(table: FeatureView, config: RepoConfig) -> str: ) +def _sequence_key_prefix(table: FeatureView, config: RepoConfig) -> bytes: + """Return ``seq:::``, the start of every sequence key. + + Project names can't contain ``:``, so a scan for this prefix matches one + project only, even when another project's name ends with this one's. + """ + return f"seq:{config.project}:{_versioned_fv_name(table, config)}:".encode("utf8") + + +def _epoch_micros(dt: datetime) -> int: + """Return microseconds since 1970-01-01 UTC. Naive datetimes are treated as UTC. + + Used as the Redis score: microseconds stay exact there; nanoseconds get rounded. + """ + ts = Timestamp() + ts.FromDatetime(utils.make_tzaware(dt)) + return ts.ToMicroseconds() + + class RedisType(str, Enum): redis = "redis" redis_cluster = "redis_cluster" @@ -334,16 +355,24 @@ def delete_entity_values(self, config: RepoConfig, join_keys: List[str]): def delete_table(self, config: RepoConfig, table: FeatureView): """ - Delete all rows in Redis for a specific feature view. - - Uses a two-phase pipelined approach to avoid an O(K) synchronous hkeys - call inside the scan loop (N+1 pattern). + Delete all rows in Redis for a specific feature view: its fields in the + entity hashes, and the sequence keys online_append wrote for it. Args: config: Feast config table: Feature view to delete """ client = self._get_client(config.online_store) + self._delete_hash_fields(client, config, table) + self._delete_sequence_keys(client, config, table) + + def _delete_hash_fields(self, client: Any, config: RepoConfig, table: FeatureView): + """ + Delete the feature view's fields from the entity hashes. + + Uses a two-phase pipelined approach to avoid an O(K) synchronous hkeys + call inside the scan loop (N+1 pattern). + """ prefix = _redis_key_prefix(table.join_keys) fv_name = _versioned_fv_name(table, config) @@ -381,6 +410,23 @@ def delete_table(self, config: RepoConfig, table: FeatureView): logger.debug(f"Deleted {deleted_count} rows for feature view {fv_name}") + def _delete_sequence_keys( + self, client: Any, config: RepoConfig, table: FeatureView + ) -> None: + """Delete the feature view's sequence keys written by online_append, + in this project only.""" + scan_pattern = _sequence_key_prefix(table, config) + b"*" + keys = list(client.scan_iter(scan_pattern)) + if not keys: + return + + with client.pipeline(transaction=False) as pipe: + for key in keys: + pipe.delete(key) + pipe.execute() + + logger.debug(f"Deleted {len(keys)} sequence keys for feature view {table.name}") + def update( self, config: RepoConfig, @@ -423,6 +469,11 @@ def teardown( for join_keys in join_keys_to_delete: self.delete_entity_values(config, list(join_keys)) + if tables: + client = self._get_client(config.online_store) + for table in tables: + self._delete_sequence_keys(client, config, table) + # 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: @@ -739,6 +790,117 @@ async def online_write_batch_async( if progress: progress(len(results)) + def online_append( + self, + config: RepoConfig, + table: FeatureView, + data: List[ + Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]] + ], + progress: Optional[Callable[[int], Any]] = None, + ) -> None: + """ + Appends rows to a sorted set per entity and feature view, instead of + overwriting the entity's hash. + + - Key: ``seq:::`` + the entity's hash key. + delete_table and teardown delete these keys too. + - Member: the event time as an 8-byte big-endian signed integer of + microseconds, followed by the row's feature values as a serialized + ``feast.types.Map``. Writing the same event time and values again + adds nothing, so re-materializing a time range doesn't add duplicates. + - Score: the event time from _epoch_micros. + - Limits: after each ZADD, drop events older than max_age, then keep the + newest max_length. Not atomic: readers should read at most max_length. + - TTL: only key_ttl_seconds, the same as the hash keys. + """ + online_store_config = config.online_store + assert isinstance(online_store_config, RedisOnlineStoreConfig) + + client = self._get_client(online_store_config) + events_by_key = self._group_append_events(config, table, data) + max_length, cutoff = self._append_limits(table) + with client.pipeline(transaction=False) as pipe: + for redis_key_bin, events in events_by_key.items(): + pipe.zadd(redis_key_bin, events) + if cutoff is not None: + pipe.zremrangebyscore(redis_key_bin, "-inf", f"({cutoff}") + if max_length: + pipe.zremrangebyrank(redis_key_bin, 0, -(max_length + 1)) + if online_store_config.key_ttl_seconds: + pipe.expire( + name=redis_key_bin, time=online_store_config.key_ttl_seconds + ) + pipe.execute() + + if progress: + progress(len(data)) + + async def online_append_async( + self, + config: RepoConfig, + table: FeatureView, + data: List[ + Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]] + ], + progress: Optional[Callable[[int], Any]] = None, + ) -> None: + """Async version of online_append using the async Redis client.""" + online_store_config = config.online_store + assert isinstance(online_store_config, RedisOnlineStoreConfig) + + client = await self._get_client_async(online_store_config) + events_by_key = self._group_append_events(config, table, data) + max_length, cutoff = self._append_limits(table) + async with client.pipeline(transaction=False) as pipe: + for redis_key_bin, events in events_by_key.items(): + pipe.zadd(redis_key_bin, events) + if cutoff is not None: + pipe.zremrangebyscore(redis_key_bin, "-inf", f"({cutoff}") + if max_length: + pipe.zremrangebyrank(redis_key_bin, 0, -(max_length + 1)) + if online_store_config.key_ttl_seconds: + pipe.expire( + name=redis_key_bin, time=online_store_config.key_ttl_seconds + ) + await pipe.execute() + + if progress: + progress(len(data)) + + def _group_append_events( + self, + config: RepoConfig, + table: FeatureView, + data: List[ + Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]] + ], + ) -> Dict[bytes, Dict[Union[str, bytes], int]]: + """Group rows by key, so each key gets one ZADD and one trim per batch.""" + key_prefix = _sequence_key_prefix(table, config) + # str | bytes keys match zadd's mapping type in the redis stubs. + events_by_key: Dict[bytes, Dict[Union[str, bytes], int]] = {} + for entity_key, values, timestamp, _ in data: + redis_key_bin = key_prefix + _redis_key( + config.project, + entity_key, + entity_key_serialization_version=config.entity_key_serialization_version, + ) + event_micros = _epoch_micros(timestamp) + member = struct.pack(">q", event_micros) + MapProto( + val=values + ).SerializeToString(deterministic=True) + events_by_key.setdefault(redis_key_bin, {})[member] = event_micros + return events_by_key + + def _append_limits(self, table: FeatureView) -> Tuple[Optional[int], Optional[int]]: + """Return max_length and the max_age cutoff in microseconds.""" + online_config = table.online_config + max_length = online_config.max_length if online_config else None + max_age = online_config.max_age if online_config else None + cutoff = _epoch_micros(utils._utc_now() - max_age) if max_age else None + return max_length, cutoff + def _generate_redis_keys_for_entities( self, config: RepoConfig, entity_keys: List[EntityKeyProto] ) -> List[bytes]: diff --git a/sdk/python/feast/infra/passthrough_provider.py b/sdk/python/feast/infra/passthrough_provider.py index 6b51d8c9fc1..08470c9285e 100644 --- a/sdk/python/feast/infra/passthrough_provider.py +++ b/sdk/python/feast/infra/passthrough_provider.py @@ -56,6 +56,14 @@ DEFAULT_BATCH_SIZE = 10_000 +def _uses_append_write_mode(feature_view: BaseFeatureView) -> bool: + return ( + isinstance(feature_view, FeatureView) + and feature_view.online_config is not None + and feature_view.online_config.write_mode == "append" + ) + + class PassthroughProvider(Provider): """ The passthrough provider delegates all operations to the underlying online and offline stores. @@ -211,6 +219,30 @@ async def online_write_batch_async( config, table, data, progress ) + def online_append( + self, + config: RepoConfig, + table: Union[FeatureView, BaseFeatureView, OnDemandFeatureView], + data: List[ + Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]] + ], + progress: Optional[Callable[[int], Any]], + ) -> None: + if self.online_store: + self.online_store.online_append(config, table, data, progress) + + async def online_append_async( + self, + config: RepoConfig, + table: Union[FeatureView, BaseFeatureView, OnDemandFeatureView], + data: List[ + Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]] + ], + progress: Optional[Callable[[int], Any]], + ) -> None: + if self.online_store: + await self.online_store.online_append_async(config, table, data, progress) + def offline_write_batch( self, config: RepoConfig, @@ -402,9 +434,14 @@ def ingest_df( df=df, field_mapping=field_mapping, ) - self.online_write_batch( - self.repo_config, feature_view, rows_to_write, progress=None - ) + if _uses_append_write_mode(feature_view): + self.online_append( + self.repo_config, feature_view, rows_to_write, progress=None + ) + else: + self.online_write_batch( + self.repo_config, feature_view, rows_to_write, progress=None + ) async def ingest_df_async( self, @@ -417,9 +454,14 @@ async def ingest_df_async( df=df, field_mapping=field_mapping, ) - await self.online_write_batch_async( - self.repo_config, feature_view, rows_to_write, progress=None - ) + if _uses_append_write_mode(feature_view): + await self.online_append_async( + self.repo_config, feature_view, rows_to_write, progress=None + ) + else: + await self.online_write_batch_async( + self.repo_config, feature_view, rows_to_write, progress=None + ) def ingest_df_to_offline_store(self, feature_view: FeatureView, table: pa.Table): if ( diff --git a/sdk/python/tests/integration/online_store/test_redis_sequence_cleanup.py b/sdk/python/tests/integration/online_store/test_redis_sequence_cleanup.py new file mode 100644 index 00000000000..d35246174f1 --- /dev/null +++ b/sdk/python/tests/integration/online_store/test_redis_sequence_cleanup.py @@ -0,0 +1,108 @@ +"""Integration test: delete_table and teardown remove the sequence keys that +online_append writes to Redis, and only in their own project. + +Run with: pytest --integration sdk/python/tests/integration/online_store/test_redis_sequence_cleanup.py +""" + +import shutil +from datetime import datetime, timezone + +import pytest + +from feast import Entity, FeatureView, Field, FileSource, OnlineConfig +from feast.infra.online_stores.redis import RedisOnlineStore, RedisOnlineStoreConfig +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 RepoConfig +from feast.types import Int64 +from feast.value_type import ValueType + + +@pytest.fixture +def redis_port(): + try: + from testcontainers.redis import RedisContainer + except ImportError: + pytest.skip("testcontainers[redis] not installed") + + container = RedisContainer("redis:7").with_exposed_ports(6379) + container.start() + yield int(container.get_exposed_port(6379)) + container.stop() + + +def _config(project: str, port: int) -> RepoConfig: + return RepoConfig( + project=project, + provider="local", + online_store=RedisOnlineStoreConfig(connection_string=f"localhost:{port}"), + registry="unused_registry.db", + entity_key_serialization_version=3, + ) + + +def _sequence_view(name: str) -> FeatureView: + driver = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) + return FeatureView( + name=name, + entities=[driver], + schema=[Field(name="driver_id", dtype=Int64), Field(name="trips", dtype=Int64)], + source=FileSource(path="unused.parquet", timestamp_field="event_timestamp"), + online_config=OnlineConfig(mode="sequence", write_mode="append"), + ) + + +def _append_events(store, config, view) -> None: + entity_key = EntityKeyProto( + join_keys=["driver_id"], entity_values=[ValueProto(int64_val=1001)] + ) + now = datetime.now(tz=timezone.utc) + store.online_append( + config, + view, + [ + (entity_key, {"trips": ValueProto(int64_val=trips)}, now, None) + for trips in (1, 2) + ], + ) + + +@pytest.mark.integration +@pytest.mark.skipif(not shutil.which("docker"), reason="Docker not available") +def test_delete_table_and_teardown_remove_sequence_keys(redis_port): + import redis + + store = RedisOnlineStore() + # other_demo ends with demo, so a scan for demo's keys must not match it. + demo, other_demo = ( + _config("demo", redis_port), + _config("other_demo", redis_port), + ) + clicks, views = _sequence_view("clicks"), _sequence_view("views") + _append_events(store, demo, clicks) + _append_events(store, demo, views) + _append_events(store, other_demo, clicks) + + client = redis.Redis(port=redis_port) + + def sequence_keys(): + # Key: seq::: + labels = [] + for key in client.scan_iter(b"seq:*"): + _, project, view, _ = key.split(b":", 3) + labels.append(f"{view.decode()}@{project.decode()}") + return sorted(labels) + + assert sequence_keys() == [ + "clicks@demo", + "clicks@other_demo", + "views@demo", + ] + + # Deleting a view removes only its keys in its project. + store.delete_table(demo, clicks) + assert sequence_keys() == ["clicks@other_demo", "views@demo"] + + # Teardown removes the keys of the views it is given, in its project. + store.teardown(demo, [views], []) + assert sequence_keys() == ["clicks@other_demo"] diff --git a/sdk/python/tests/unit/infra/online_store/test_online_store_base.py b/sdk/python/tests/unit/infra/online_store/test_online_store_base.py index 11195521deb..f4998f76d03 100644 --- a/sdk/python/tests/unit/infra/online_store/test_online_store_base.py +++ b/sdk/python/tests/unit/infra/online_store/test_online_store_base.py @@ -1,3 +1,4 @@ +import asyncio from unittest.mock import MagicMock import pytest @@ -53,3 +54,19 @@ def test_online_read_returns_list(self): def test_cannot_instantiate_abstract(self): with pytest.raises(TypeError): OnlineStore() + + def test_online_append_not_implemented_by_default(self): + store = ConcreteOnlineStore() + with pytest.raises(NotImplementedError, match="does not support online append"): + store.online_append(config=MagicMock(), table=MagicMock(), data=[]) + + def test_online_append_async_not_implemented_by_default(self): + store = ConcreteOnlineStore() + with pytest.raises( + NotImplementedError, match="does not support online append async" + ): + asyncio.run( + store.online_append_async( + config=MagicMock(), table=MagicMock(), data=[] + ) + ) 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 744a7f3ac64..f1347510bda 100644 --- a/sdk/python/tests/unit/infra/online_store/test_redis.py +++ b/sdk/python/tests/unit/infra/online_store/test_redis.py @@ -1,4 +1,5 @@ import asyncio +import struct import sys from datetime import datetime, timedelta, timezone from types import SimpleNamespace @@ -8,7 +9,7 @@ import pytest from google.protobuf.timestamp_pb2 import Timestamp -from feast import Entity, FeatureView, Field, FileSource, RepoConfig +from feast import Entity, FeatureView, Field, FileSource, OnlineConfig, RepoConfig from feast.errors import FeastExtrasDependencyImportError from feast.infra.online_stores.helpers import _mmh3 from feast.infra.online_stores.redis import ( @@ -22,6 +23,7 @@ _load_glide_sync, ) from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto +from feast.protos.feast.types.Value_pb2 import Map as MapProto from feast.protos.feast.types.Value_pb2 import Value as ValueProto from feast.types import Int32 @@ -1090,3 +1092,155 @@ def test_teardown_without_a_glide_client_does_not_raise( redis_online_store.teardown(repo_config, [], []) assert redis_online_store._glide_client is None + + +def _append_client_and_pipe(): + """Return a mock Redis client and the pipeline it hands out.""" + pipe = MagicMock() + pipe.__enter__ = MagicMock(return_value=pipe) + pipe.__exit__ = MagicMock(return_value=False) + client = MagicMock() + client.pipeline.return_value = pipe + return client, pipe + + +def test_online_append_keeps_each_event_for_an_entity( + redis_online_store: RedisOnlineStore, feature_view +): + """Each event is kept, even when its values repeat an earlier event. + + An event with the same time and values as another is stored once. + """ + feature_view.online_config = OnlineConfig( + mode="sequence", max_length=10, write_mode="append" + ) + start = datetime(2026, 1, 1, tzinfo=timezone.utc) + data = _single_entity_batch( + [ + (start, 1), + (start + timedelta(seconds=1), 2), + (start + timedelta(seconds=2), 3), + (start + timedelta(seconds=3), 1), + (start + timedelta(seconds=3), 1), + ] + ) + client, pipe = _append_client_and_pipe() + + with patch.object(redis_online_store, "_get_client", return_value=client): + redis_online_store.online_append(_dedup_config(), feature_view, data) + + pipe.hset.assert_not_called() + pipe.zadd.assert_called_once() + key, events = pipe.zadd.call_args.args + assert key.startswith(b"seq:test:feature_view_1:") + start_micros = int(start.timestamp()) * 1_000_000 + values_by_offset = {} + for member, score in events.items(): + (member_micros,) = struct.unpack(">q", member[:8]) + assert member_micros == score + values = MapProto.FromString(member[8:]) + values_by_offset[score - start_micros] = values.val["feature_10"].int32_val + assert values_by_offset == {0: 1, 1_000_000: 2, 2_000_000: 3, 3_000_000: 1} + pipe.zremrangebyrank.assert_called_once_with(key, 0, -11) + pipe.zremrangebyscore.assert_not_called() + pipe.expire.assert_not_called() + + +@pytest.mark.parametrize("key_ttl_seconds", [None, 60]) +def test_online_append_applies_max_length_and_max_age( + redis_online_store: RedisOnlineStore, feature_view, key_ttl_seconds +): + """Trims by max_age and max_length. Only key_ttl_seconds sets a key TTL.""" + feature_view.online_config = OnlineConfig( + mode="sequence", max_length=2, max_age=timedelta(days=1), write_mode="append" + ) + config = RepoConfig( + provider="local", + project="test", + entity_key_serialization_version=3, + registry="dummy_registry.db", + online_store=RedisOnlineStoreConfig(key_ttl_seconds=key_ttl_seconds), + ) + now = datetime(2026, 1, 2, tzinfo=timezone.utc) + client, pipe = _append_client_and_pipe() + + with patch.object(redis_online_store, "_get_client", return_value=client): + with patch("feast.utils._utc_now", return_value=now): + redis_online_store.online_append( + config, feature_view, _single_entity_batch([(now, 1)]) + ) + + key = pipe.zadd.call_args.args[0] + cutoff_micros = int((now - timedelta(days=1)).timestamp()) * 1_000_000 + pipe.zremrangebyscore.assert_called_once_with(key, "-inf", f"({cutoff_micros}") + pipe.zremrangebyrank.assert_called_once_with(key, 0, -3) + if key_ttl_seconds: + pipe.expire.assert_called_once_with(name=key, time=key_ttl_seconds) + else: + pipe.expire.assert_not_called() + + +def test_online_append_keeps_a_newer_event_when_a_late_event_repeats_its_values( + redis_online_store: RedisOnlineStore, feature_view +): + """A late, older event with the same values doesn't move the newer event's + time, so the max_age trim can't drop it. Same batch or a later write.""" + feature_view.online_config = OnlineConfig( + mode="sequence", max_age=timedelta(hours=1), write_mode="append" + ) + now = datetime(2026, 1, 1, 12, tzinfo=timezone.utc) + newer = now - timedelta(minutes=5) + older = now - timedelta(hours=2) + cutoff_micros = int((now - timedelta(hours=1)).timestamp()) * 1_000_000 + + def scores_left_after(writes): + """Replay the ZADDs and the max_age trim the way Redis applies them.""" + client, pipe = _append_client_and_pipe() + with patch.object(redis_online_store, "_get_client", return_value=client): + with patch("feast.utils._utc_now", return_value=now): + for batch in writes: + redis_online_store.online_append( + _dedup_config(), feature_view, _single_entity_batch(batch) + ) + members: dict = {} + for call in pipe.zadd.call_args_list: + members.update(call.args[1]) + return sorted(s for s in members.values() if s >= cutoff_micros) + + newer_micros = int(newer.timestamp()) * 1_000_000 + assert scores_left_after([[(newer, 7), (older, 7)]]) == [newer_micros] + assert scores_left_after([[(newer, 7)], [(older, 7)]]) == [newer_micros] + + +def test_online_append_async_uses_async_client( + redis_online_store: RedisOnlineStore, feature_view +): + """Queues the same commands on the async client's pipeline.""" + feature_view.online_config = OnlineConfig( + mode="sequence", max_length=10, write_mode="append" + ) + start = datetime(2026, 1, 1, tzinfo=timezone.utc) + data = _single_entity_batch([(start, 1), (start + timedelta(seconds=1), 2)]) + + async_pipe = AsyncMock() + async_pipe.__aenter__ = AsyncMock(return_value=async_pipe) + async_pipe.__aexit__ = AsyncMock(return_value=False) + async_pipe.zadd = MagicMock() + async_pipe.zremrangebyrank = MagicMock() + mock_async_client = AsyncMock() + mock_async_client.pipeline = MagicMock(return_value=async_pipe) + + with patch.object( + redis_online_store, + "_get_client_async", + AsyncMock(return_value=mock_async_client), + ): + asyncio.run( + redis_online_store.online_append_async(_dedup_config(), feature_view, data) + ) + + key, events = async_pipe.zadd.call_args.args + assert key.startswith(b"seq:test:feature_view_1:") + assert len(events) == 2 + async_pipe.zremrangebyrank.assert_called_once_with(key, 0, -11) + async_pipe.execute.assert_awaited_once() diff --git a/sdk/python/tests/unit/test_online_config_apply.py b/sdk/python/tests/unit/test_online_config_apply.py index f28d2cb679c..9bb1965773d 100644 --- a/sdk/python/tests/unit/test_online_config_apply.py +++ b/sdk/python/tests/unit/test_online_config_apply.py @@ -1,10 +1,14 @@ -from datetime import timedelta +import asyncio +from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Optional +from unittest.mock import AsyncMock, patch + +import pandas as pd from feast import Entity, FeatureStore, FeatureView, Field, OnlineConfig, ValueType from feast.infra.offline_stores.file_source import FileSource -from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig +from feast.infra.online_stores.sqlite import SqliteOnlineStore, SqliteOnlineStoreConfig from feast.repo_config import RepoConfig from feast.types import Float32, Int64 @@ -72,3 +76,61 @@ def feature_view(online_config: Optional[OnlineConfig]) -> FeatureView: ) finally: store.teardown() + + +def test_write_to_online_store_routes_by_write_mode(tmp_path: Path) -> None: + store = _feature_store(tmp_path) + source = FileSource( + path="events.parquet", + timestamp_field="event_timestamp", + created_timestamp_column="created_timestamp", + ) + entity = Entity(name="event", join_keys=["event_id"], value_type=ValueType.INT64) + schema = [ + Field(name="event_id", dtype=Int64), + Field(name="event_value", dtype=Float32), + ] + append_view = FeatureView( + name="event_sequence", + entities=[entity], + schema=schema, + source=source, + online_config=OnlineConfig(mode="sequence", max_length=10, write_mode="append"), + ) + overwrite_view = FeatureView( + name="event_latest", entities=[entity], schema=schema, source=source + ) + now = datetime.now(tz=timezone.utc) + df = pd.DataFrame( + { + "event_id": [1], + "event_value": [1.0], + "event_timestamp": [now], + "created_timestamp": [now], + } + ) + + try: + store.apply([entity, append_view, overwrite_view]) + with ( + patch.object(SqliteOnlineStore, "online_append") as online_append, + patch.object( + SqliteOnlineStore, "online_append_async", new_callable=AsyncMock + ) as online_append_async, + patch.object(SqliteOnlineStore, "online_write_batch") as online_write_batch, + ): + store.write_to_online_store("event_sequence", df) + asyncio.run(store.write_to_online_store_async("event_sequence", df)) + store.write_to_online_store("event_latest", df) + + assert [call.args[1].name for call in online_append.call_args_list] == [ + "event_sequence" + ] + assert [call.args[1].name for call in online_append_async.await_args_list] == [ + "event_sequence" + ] + assert [call.args[1].name for call in online_write_batch.call_args_list] == [ + "event_latest" + ] + finally: + store.teardown() diff --git a/skills/feast-architecture/SKILL.md b/skills/feast-architecture/SKILL.md index 5a6049d237b..cd587d7c115 100644 --- a/skills/feast-architecture/SKILL.md +++ b/skills/feast-architecture/SKILL.md @@ -124,6 +124,7 @@ Custom providers extend `Provider` and override `update_infra` / `teardown_infra Key methods: - `online_write_batch` — write entity→feature values +- `online_append` / `online_append_async` — append events without overwriting, for feature views whose `online_config` sets `write_mode="append"`; the defaults raise `NotImplementedError` (Redis implements both with a sorted set per entity key) - `online_read` — read by entity keys - `update` — provision/deprovision tables on `feast apply` - `teardown` — clean up on `feast teardown`