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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions sdk/python/feast/infra/online_stores/online_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
170 changes: 166 additions & 4 deletions sdk/python/feast/infra/online_stores/redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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

Expand All @@ -64,6 +66,25 @@ def _versioned_fv_name(table: FeatureView, config: RepoConfig) -> str:
)


def _sequence_key_prefix(table: FeatureView, config: RepoConfig) -> bytes:
"""Return ``seq:<project>:<feature view>:``, 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"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:<project>:<feature view>:`` + 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))
Comment on lines +825 to +829

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Late duplicates erase newer sequence events

When identical feature values for an entity arrive newest first, online_append replaces the newer timestamp with the older one. Age or length trimming can then delete the entry even though the newer event qualified for retention.

Learn more

write_to_online_store routes append-mode DataFrames through ingest_df without sorting the rows. Redis stores one timestamp per sorted-set member, and _group_append_events uses only the feature values as the member. Within one batch, the last row with matching values wins; across batches, ZADD unconditionally replaces the existing score. The newer timestamp is lost in both cases, and the retention commands can then remove the remaining entry. online_append_async has the same behavior.

Example: At noon, write a value of 7 for entity 42 with an 11:55 event time and a one-hour age limit. Then append a delayed 10:00 event with the same value. Redis moves the entry to 10:00 and trims it, leaving no record of the 11:55 event. Submitting the two rows in that order in one batch has the same result.

Recommended fix: Include the event timestamp in the member identity so the older event can be trimmed independently. If retaining the payload-only format for now, keep the maximum timestamp in each batch and prevent Redis score updates from decreasing an existing score, using ZADD GT where supported. Cover newest-first inputs both within one batch and across writes.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

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]]
Comment thread
franciscojavierarceo marked this conversation as resolved.
Resolved
],
) -> 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]:
Expand Down
54 changes: 48 additions & 6 deletions sdk/python/feast/infra/passthrough_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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 (
Expand Down
Loading
Loading