From 6d2feef4ee43e60d1f3ff090fbc1f3317ffad45d Mon Sep 17 00:00:00 2001 From: Chaitany Patel Date: Tue, 22 Sep 2026 17:40:20 +0530 Subject: [PATCH 1/4] added online append Signed-off-by: Chaitany Patel --- .../feast/infra/online_stores/online_store.py | 52 ++++++++ sdk/python/feast/infra/online_stores/redis.py | 119 ++++++++++++++++++ .../feast/infra/passthrough_provider.py | 54 +++++++- .../online_store/test_online_store_base.py | 17 +++ .../unit/infra/online_store/test_redis.py | 117 ++++++++++++++++- .../tests/unit/test_online_config_apply.py | 66 +++++++++- skills/feast-architecture/SKILL.md | 1 + 7 files changed, 417 insertions(+), 9 deletions(-) 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..00ccfc44ee0 100644 --- a/sdk/python/feast/infra/online_stores/redis.py +++ b/sdk/python/feast/infra/online_stores/redis.py @@ -43,6 +43,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 +65,16 @@ def _versioned_fv_name(table: FeatureView, config: RepoConfig) -> str: ) +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" @@ -739,6 +750,114 @@ 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 don't delete these keys yet. + - Member: the row's feature values as a serialized ``feast.types.Map``. + Repeating the same values moves that member to the new row's time. + - 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 = f"seq:{_versioned_fv_name(table, config)}:".encode("utf8") + # 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, + ) + member = MapProto(val=values).SerializeToString(deterministic=True) + events_by_key.setdefault(redis_key_bin, {})[member] = _epoch_micros( + timestamp + ) + 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/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..b2067a88d8a 100644 --- a/sdk/python/tests/unit/infra/online_store/test_redis.py +++ b/sdk/python/tests/unit/infra/online_store/test_redis.py @@ -8,7 +8,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 +22,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 +1091,117 @@ 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_value_for_an_entity( + redis_online_store: RedisOnlineStore, feature_view +): + """Each different value is kept. A repeated value moves to its newer time.""" + 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), + ] + ) + 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:feature_view_1:") + start_micros = int(start.timestamp()) * 1_000_000 + values_by_offset = { + score - start_micros: MapProto.FromString(member).val["feature_10"].int32_val + for member, score in events.items() + } + assert values_by_offset == {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_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: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` From a3cdeacebf091bd507c410f2fdcbaa49caf5107c Mon Sep 17 00:00:00 2001 From: Chaitany Patel Date: Mon, 23 Nov 2026 14:58:56 +0530 Subject: [PATCH 2/4] fix: Keep each sequence event when a late event repeats its values The sorted set member was only the serialized feature values, so two events with the same values shared one member. A late, older event then moved that member back to its own time, and the max_age trim could drop it, losing the newer event. This happened within one batch (last row wins) and across writes (ZADD replaces the score). Prefix the member with the event time as an 8-byte big-endian integer of microseconds. Each event is now its own member, and writing the same event time and values again still adds nothing. Signed-off-by: Chaitany Patel --- sdk/python/feast/infra/online_stores/redis.py | 16 +++--- .../unit/infra/online_store/test_redis.py | 53 ++++++++++++++++--- 2 files changed, 56 insertions(+), 13 deletions(-) diff --git a/sdk/python/feast/infra/online_stores/redis.py b/sdk/python/feast/infra/online_stores/redis.py index 00ccfc44ee0..038d12372f8 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 ( @@ -765,8 +766,10 @@ def online_append( - Key: ``seq::`` + the entity's hash key. delete_table and teardown don't delete these keys yet. - - Member: the row's feature values as a serialized ``feast.types.Map``. - Repeating the same values moves that member to the new row's time. + - 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. @@ -844,10 +847,11 @@ def _group_append_events( entity_key, entity_key_serialization_version=config.entity_key_serialization_version, ) - member = MapProto(val=values).SerializeToString(deterministic=True) - events_by_key.setdefault(redis_key_bin, {})[member] = _epoch_micros( - timestamp - ) + 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]]: 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 b2067a88d8a..ba6ec049197 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 @@ -1103,10 +1104,13 @@ def _append_client_and_pipe(): return client, pipe -def test_online_append_keeps_each_value_for_an_entity( +def test_online_append_keeps_each_event_for_an_entity( redis_online_store: RedisOnlineStore, feature_view ): - """Each different value is kept. A repeated value moves to its newer time.""" + """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" ) @@ -1117,6 +1121,7 @@ def test_online_append_keeps_each_value_for_an_entity( (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() @@ -1129,11 +1134,13 @@ def test_online_append_keeps_each_value_for_an_entity( key, events = pipe.zadd.call_args.args assert key.startswith(b"seq:feature_view_1:") start_micros = int(start.timestamp()) * 1_000_000 - values_by_offset = { - score - start_micros: MapProto.FromString(member).val["feature_10"].int32_val - for member, score in events.items() - } - assert values_by_offset == {1_000_000: 2, 2_000_000: 3, 3_000_000: 1} + 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() @@ -1173,6 +1180,38 @@ def test_online_append_applies_max_length_and_max_age( 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 ): From 60b29ea29708b220d5ee153506d3a141415a2bf1 Mon Sep 17 00:00:00 2001 From: Chaitany Patel Date: Mon, 23 Nov 2026 18:04:00 +0530 Subject: [PATCH 3/4] fix: Delete sequence keys in Redis delete_table and teardown online_append writes each entity's events to a "seq::" key, but delete_table and teardown only scanned for keys that start with the entity key, so they never found these. Removing a feature view or tearing down the store left the events in Redis, and with the default key_ttl_seconds=None they never expired. delete_table and teardown now also scan "seq::" followed by the entity key prefix and the project, and delete the matches, so other feature views and projects keep their keys. Adds an integration test against a real Redis that writes events, deletes a view, tears down another, and checks which keys are left. Signed-off-by: Chaitany Patel --- sdk/python/feast/infra/online_stores/redis.py | 47 +++++++- .../test_redis_sequence_cleanup.py | 105 ++++++++++++++++++ 2 files changed, 147 insertions(+), 5 deletions(-) create mode 100644 sdk/python/tests/integration/online_store/test_redis_sequence_cleanup.py diff --git a/sdk/python/feast/infra/online_stores/redis.py b/sdk/python/feast/infra/online_stores/redis.py index 038d12372f8..28c99a75365 100644 --- a/sdk/python/feast/infra/online_stores/redis.py +++ b/sdk/python/feast/infra/online_stores/redis.py @@ -346,16 +346,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) @@ -393,6 +401,30 @@ 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 = b"".join( + [ + f"seq:{_versioned_fv_name(table, config)}:".encode("utf8"), + _redis_key_prefix(table.join_keys), + b"*", + config.project.encode("utf8"), + ] + ) + 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, @@ -435,6 +467,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: @@ -765,7 +802,7 @@ def online_append( overwriting the entity's hash. - Key: ``seq::`` + the entity's hash key. delete_table and - teardown don't delete these keys yet. + 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 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..2c6092f634a --- /dev/null +++ b/sdk/python/tests/integration/online_store/test_redis_sequence_cleanup.py @@ -0,0 +1,105 @@ +"""Integration test: delete_table and teardown remove the sequence keys that +online_append writes to Redis. + +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() + project_a, project_b = ( + _config("project_a", redis_port), + _config("project_b", redis_port), + ) + clicks, views = _sequence_view("clicks"), _sequence_view("views") + _append_events(store, project_a, clicks) + _append_events(store, project_a, views) + _append_events(store, project_b, clicks) + + client = redis.Redis(port=redis_port) + + def sequence_keys(): + return sorted( + key.split(b":")[1].decode() + "@" + key[-9:].decode() + for key in client.scan_iter(b"seq:*") + ) + + assert sequence_keys() == [ + "clicks@project_a", + "clicks@project_b", + "views@project_a", + ] + + # Deleting a view removes only its keys in its project. + store.delete_table(project_a, clicks) + assert sequence_keys() == ["clicks@project_b", "views@project_a"] + + # Teardown removes the keys of the views it is given, in its project. + store.teardown(project_a, [views], []) + assert sequence_keys() == ["clicks@project_b"] From ab432367f96003595de4582a2cd710e71e9c9c26 Mon Sep 17 00:00:00 2001 From: Chaitany Patel Date: Tue, 24 Nov 2026 18:14:00 +0530 Subject: [PATCH 4/4] fix: Scope Redis sequence keys to their project Sequence keys were seq:: + entity key + project, and cleanup scanned seq::*. The * also matched another project whose name ends with this one's, so deleting view clicks in project demo also deleted its keys in project other_demo. Keys are now seq::: + entity key. Project names can't contain ':', so the scan seq:::* matches one project only. The integration test now uses projects demo and other_demo. Signed-off-by: Chaitany Patel --- sdk/python/feast/infra/online_stores/redis.py | 24 ++++++------ .../test_redis_sequence_cleanup.py | 39 ++++++++++--------- .../unit/infra/online_store/test_redis.py | 4 +- 3 files changed, 36 insertions(+), 31 deletions(-) diff --git a/sdk/python/feast/infra/online_stores/redis.py b/sdk/python/feast/infra/online_stores/redis.py index 28c99a75365..708a080c958 100644 --- a/sdk/python/feast/infra/online_stores/redis.py +++ b/sdk/python/feast/infra/online_stores/redis.py @@ -66,6 +66,15 @@ 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. @@ -406,14 +415,7 @@ def _delete_sequence_keys( ) -> None: """Delete the feature view's sequence keys written by online_append, in this project only.""" - scan_pattern = b"".join( - [ - f"seq:{_versioned_fv_name(table, config)}:".encode("utf8"), - _redis_key_prefix(table.join_keys), - b"*", - config.project.encode("utf8"), - ] - ) + scan_pattern = _sequence_key_prefix(table, config) + b"*" keys = list(client.scan_iter(scan_pattern)) if not keys: return @@ -801,8 +803,8 @@ def online_append( 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. + - 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 @@ -875,7 +877,7 @@ def _group_append_events( ], ) -> Dict[bytes, Dict[Union[str, bytes], int]]: """Group rows by key, so each key gets one ZADD and one trim per batch.""" - key_prefix = f"seq:{_versioned_fv_name(table, config)}:".encode("utf8") + 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: 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 index 2c6092f634a..d35246174f1 100644 --- a/sdk/python/tests/integration/online_store/test_redis_sequence_cleanup.py +++ b/sdk/python/tests/integration/online_store/test_redis_sequence_cleanup.py @@ -1,5 +1,5 @@ """Integration test: delete_table and teardown remove the sequence keys that -online_append writes to Redis. +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 """ @@ -73,33 +73,36 @@ def test_delete_table_and_teardown_remove_sequence_keys(redis_port): import redis store = RedisOnlineStore() - project_a, project_b = ( - _config("project_a", redis_port), - _config("project_b", redis_port), + # 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, project_a, clicks) - _append_events(store, project_a, views) - _append_events(store, project_b, clicks) + _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(): - return sorted( - key.split(b":")[1].decode() + "@" + key[-9:].decode() - for key in client.scan_iter(b"seq:*") - ) + # 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@project_a", - "clicks@project_b", - "views@project_a", + "clicks@demo", + "clicks@other_demo", + "views@demo", ] # Deleting a view removes only its keys in its project. - store.delete_table(project_a, clicks) - assert sequence_keys() == ["clicks@project_b", "views@project_a"] + 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(project_a, [views], []) - assert sequence_keys() == ["clicks@project_b"] + store.teardown(demo, [views], []) + assert sequence_keys() == ["clicks@other_demo"] 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 ba6ec049197..f1347510bda 100644 --- a/sdk/python/tests/unit/infra/online_store/test_redis.py +++ b/sdk/python/tests/unit/infra/online_store/test_redis.py @@ -1132,7 +1132,7 @@ def test_online_append_keeps_each_event_for_an_entity( pipe.hset.assert_not_called() pipe.zadd.assert_called_once() key, events = pipe.zadd.call_args.args - assert key.startswith(b"seq:feature_view_1:") + 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(): @@ -1240,7 +1240,7 @@ def test_online_append_async_uses_async_client( ) key, events = async_pipe.zadd.call_args.args - assert key.startswith(b"seq:feature_view_1:") + 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()