From 72b4aa2b33009d1be399ed26cfb1fe091758aab1 Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:26:31 +0530 Subject: [PATCH] feat: Batch MongoDB online reads across feature views The generic OnlineStore._read_features_per_fv loop issues one online_read per feature view, so a request spanning N feature views costs N find round trips on the sync path and N concurrent finds on the async path. Redis, PostgreSQL, DynamoDB and Bigtable already override that seam to batch; MongoDB now does too. The MongoDB online store keeps every feature view of an entity in one document (features.. and event_timestamps.), so the per-view reads can be served by a single find. The override resolves every view's entity ids up front, queries the de-duplicated union of those ids with one $in filter, projects the event timestamp and only the requested features of each view, and then hands each view the documents of its own entity ids in order. A view that was never written for an entity, whose document exists because of another view, is still reported as not found. MongoDB rejects a projection that names both a document and one of its fields. A feature view requested under several aliases is therefore projected once, with the union of the aliases' features, or as a whole if one alias reads all of its features. online_read and online_read_async now build their projection through the same _projection helper as the batched path. Following the PostgreSQL, DynamoDB and Bigtable implementations, a single-view request keeps the generic path, and so do requests larger than the new max_batched_result_rows setting (entity rows x feature views, default 2048, 0 disables batching). The batched find holds the features of every view at once, so its peak memory grows with the number of views. Refs #3259 Signed-off-by: NopeCharon <115794254+NopeCharon@users.noreply.github.com> --- .../online-server-performance-tuning.md | 13 +- docs/reference/online-stores/mongodb.md | 13 + .../mongodb_online_store/mongodb.py | 282 ++++++++++++- .../online_store/test_mongodb_batched_read.py | 303 ++++++++++++++ .../online_store/test_mongodb_batched_read.py | 376 ++++++++++++++++++ 5 files changed, 961 insertions(+), 26 deletions(-) create mode 100644 sdk/python/tests/integration/online_store/test_mongodb_batched_read.py create mode 100644 sdk/python/tests/unit/infra/online_store/test_mongodb_batched_read.py diff --git a/docs/how-to-guides/online-server-performance-tuning.md b/docs/how-to-guides/online-server-performance-tuning.md index 33887a76770..1383c08750b 100644 --- a/docs/how-to-guides/online-server-performance-tuning.md +++ b/docs/how-to-guides/online-server-performance-tuning.md @@ -39,6 +39,8 @@ When the server processes a `get_online_features()` call, it groups the requeste **DynamoDB exception:** DynamoDB stores each feature view in its own table and overrides `_read_features_per_fv()` to pack the keys of every feature view into **shared `BatchGetItem` requests**, since one request can read from several tables. A request touching any number of feature views costs as few as **1** request (up to `batch_size` keys per request, sent in parallel) on both the sync and async paths. As with PostgreSQL, requests larger than `max_batched_result_rows` (entity rows × feature views, default 2048) read one view at a time, single-view requests are never batched, and `max_batched_result_rows: 0` turns batching off. **Bigtable exception:** Bigtable keeps every feature view keyed on the same entities in one shared table, with rows keyed `{entity_id}#{feature_view_name}`, and overrides `_read_features_per_fv()` to fetch the rows of all those views with **one `ReadRows` call per table**. A request touching any number of feature views on the same entities costs **1** call; views on different entity sets cost one call per entity set. This applies to the sync path, which is the only read path Bigtable has. As with PostgreSQL and DynamoDB, requests larger than `max_batched_result_rows` (entity rows × feature views, default 2048) read one view at a time, single-view requests are never batched, and `max_batched_result_rows: 0` turns batching off. The call's row filter selects, for the rows of each view, only the features requested from that view. A request whose filter would come close to Bigtable's 20 KB row filter limit also reads one view at a time. + +**MongoDB exception:** MongoDB stores every feature view of an entity in the same document and overrides `_read_features_per_fv()` to read all requested feature views with a **single `find`** over the entity ids of every view, projecting only the features requested from each view. A request touching any number of feature views costs **1** query on both the sync and async paths. As with PostgreSQL, DynamoDB and Bigtable, requests larger than `max_batched_result_rows` (entity rows × feature views, default 2048) read one view at a time, single-view requests are never batched, and `max_batched_result_rows: 0` turns batching off. {% endhint %} ### Feature services are free (and can be faster) @@ -93,7 +95,7 @@ Requesting just `combined_score` triggers reads from **both** `driver_stats_fv` ## Pre-computed feature vectors -When a `get_online_features()` request touches multiple feature views, the server issues a separate store read per feature view. For services spanning 5–15+ feature views, this fan-out dominates latency — even where the store batches its reads (Redis, PostgreSQL, DynamoDB), the protobuf deserialization and response-building overhead grows linearly with the number of views. +When a `get_online_features()` request touches multiple feature views, the server issues a separate store read per feature view. For services spanning 5–15+ feature views, this fan-out dominates latency — even where the store batches its reads (Redis, PostgreSQL, DynamoDB, Bigtable, MongoDB), the protobuf deserialization and response-building overhead grows linearly with the number of views. **Pre-computed feature vectors** solve this by storing all of a feature service's features for each entity as a single serialized blob. At read time, the server fetches one blob per entity instead of N reads per feature view, reducing the operation to O(1). @@ -289,7 +291,7 @@ The online store is the single largest factor in `get_online_features()` latency | **Redis / Dragonfly** | < 1 ms | No (threadpool) | Ultra-low latency, high throughput; all FV reads batched into 1 pipeline | Requires in-memory capacity for your dataset | | **DynamoDB** | 2–5 ms | Yes | Serverless, auto-scaling on AWS; FV reads packed into shared batch requests | Pay-per-request cost; batch API limits (100 items) | | **PostgreSQL** | 3–10 ms | No (threadpool) | Teams with existing Postgres infra; all FV reads batched into 1 query | Connection pooling needed at scale | -| **MongoDB** | 2–5 ms | Yes | Flexible schema, async-native | Requires index tuning for large datasets | +| **MongoDB** | 2–5 ms | Yes | Flexible schema, async-native; all FV reads batched into 1 query | Requires index tuning for large datasets | | **Aerospike** | < 1 ms | No (threadpool) | Ultra-low latency, hybrid memory (RAM + SSD), large datasets | Namespace must be pre-configured on the cluster | | **Bigtable** | 3–8 ms | No (threadpool) | Large-scale GCP workloads; FV reads on the same entities batched into 1 `ReadRows` call | Row-key design affects read performance | | **Cassandra / ScyllaDB** | 2–5 ms | No (threadpool) | Multi-region, write-heavy | Tunable consistency; requires DC-aware routing | @@ -315,7 +317,7 @@ The feature server can read from the online store using either an **async** or * | Store | Async read | Async write | Notes | | ----- | ---------- | ----------- | ----- | | **DynamoDB** | Yes | Yes | Uses `aiobotocore` for non-blocking I/O. `_read_features_per_fv` is overridden to pack all feature view reads into shared `BatchGetItem` requests | -| **MongoDB** | Yes | Yes | Uses `motor` (async MongoDB driver) | +| **MongoDB** | Yes | Yes | Uses PyMongo's native `AsyncMongoClient`. `_read_features_per_fv` is overridden to batch all feature view reads into a single `find` | | **PostgreSQL** | Implemented | No | Has `online_read_async` but does not yet advertise via `async_supported`; uses sync/threadpool path. `_read_features_per_fv` is overridden to batch all feature view reads into a single `UNION ALL` query | | **Redis** | Implemented | **Yes** | `online_read_async` and `online_write_batch_async` both implemented; uses sync/threadpool path for `get_online_features` (`_read_features_per_fv` overridden with batched single pipeline) | | **Aerospike** | Implemented | No | Async methods wrap the blocking C client via `run_in_executor`; does not yet advertise via `async_supported`, so the server still uses the threadpool path | @@ -465,7 +467,7 @@ online_store: ### MongoDB tuning -MongoDB supports async reads natively. Use `client_kwargs` to pass performance options directly to the PyMongo / Motor driver: +MongoDB supports async reads natively. Use `client_kwargs` to pass performance options directly to the PyMongo driver: ```yaml online_store: @@ -482,7 +484,8 @@ online_store: - **`maxPoolSize` / `minPoolSize`**: Controls the driver connection pool. Default `maxPoolSize` is 100 in PyMongo, but explicitly setting it ensures predictability across versions. - **`connectTimeoutMS` / `socketTimeoutMS`**: Tighter timeouts improve p99 by failing fast on slow connections. -- MongoDB is one of the stores with **full async support** (read and write), so it benefits from concurrent feature view reads via `asyncio.gather()`. +- **`max_batched_result_rows`**: Requests spanning several feature views read every view with a single `find`, up to this many entity rows × feature views (default 2048). Set to `0` to read one feature view at a time. +- MongoDB is one of the stores with **full async support** (read and write), so the feature server reads it without a thread pool. ### Aerospike tuning diff --git a/docs/reference/online-stores/mongodb.md b/docs/reference/online-stores/mongodb.md index e5251747e77..803628e23ce 100644 --- a/docs/reference/online-stores/mongodb.md +++ b/docs/reference/online-stores/mongodb.md @@ -149,6 +149,19 @@ Both sync and async methods are fully supported: * `online_read` / `online_read_async` * `online_write_batch` / `online_write_batch_async` +## Batched Multi-Feature-View Reads + +Every feature view of an entity is stored in the same document. When a request spans several feature views, they are all read with a single `find` over the entity ids of every view, which projects only the event timestamp and the features requested from each view. A request for 10 feature views therefore costs **1** query instead of 10, on both the sync and async read paths. Requests larger than `max_batched_result_rows` (entity rows × feature views, default 2048) read one feature view at a time instead, because the single query holds the features of every view at once and its peak memory grows with the number of views. A single-view request is never batched. Set `max_batched_result_rows: 0` to turn batching off. + +{% code title="feature_store.yaml" %} +```yaml +online_store: + type: mongodb + connection_string: "mongodb://localhost:27017" + max_batched_result_rows: 2048 # set to 0 to read one feature view at a time +``` +{% endcode %} + ## Functionality Matrix The set of functionality supported by online stores is described in detail [here](overview.md#functionality). diff --git a/sdk/python/feast/infra/online_stores/mongodb_online_store/mongodb.py b/sdk/python/feast/infra/online_stores/mongodb_online_store/mongodb.py index 16dd572bf5b..2fe87df6db4 100644 --- a/sdk/python/feast/infra/online_stores/mongodb_online_store/mongodb.py +++ b/sdk/python/feast/infra/online_stores/mongodb_online_store/mongodb.py @@ -3,7 +3,20 @@ import time from datetime import datetime from logging import getLogger -from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Union +from typing import ( + Any, + Callable, + Dict, + List, + Literal, + NamedTuple, + Optional, + Sequence, + Tuple, + Union, +) + +from pydantic import NonNegativeInt try: from pymongo import AsyncMongoClient, MongoClient, UpdateOne @@ -17,6 +30,7 @@ raise FeastExtrasDependencyImportError("mongodb", str(e)) import feast.version +from feast import utils from feast.batch_feature_view import BatchFeatureView from feast.entity import Entity from feast.feature_view import FeatureView @@ -43,6 +57,16 @@ DRIVER_METADATA = DriverInfo(name="Feast", version=feast.version.get_version()) +# Default for ``MongoDBOnlineStoreConfig.max_batched_result_rows``: the largest +# request, measured as entity rows x feature views, whose feature views are read with +# a single find. Every feature view of an entity is stored in the same document, so +# one find over the entity ids of all the views can replace one find per view. That +# find holds the features of every view at once, so its peak memory grows with the +# number of views, while the relative saving from fewer round trips shrinks as +# requests grow. Past the limit the generic path is used instead, which reads and +# releases a single view at a time. +MAX_BATCHED_RESULT_ROWS = 2048 + _MONGO_COMPARISON_OPS: Dict[str, str] = { "eq": "$eq", "ne": "$ne", @@ -102,6 +126,16 @@ def translate_compound(self, f: CompoundFilter) -> Dict[str, Any]: return {"$or": clauses} +class _BatchedRead(NamedTuple): + """One feature view's share of a batched online read.""" + + table: FeatureView + requested_features: List[str] + ids: List[bytes] + idxs: Tuple[List[int], ...] + output_len: int + + class MongoDBOnlineStoreConfig(FeastConfigBaseModel, VectorStoreConfig): """MongoDB configuration. @@ -122,6 +156,9 @@ class MongoDBOnlineStoreConfig(FeastConfigBaseModel, VectorStoreConfig): """Seconds to wait for a newly created Atlas Search index to become READY.""" vector_index_wait_poll_interval: float = 1.0 """Seconds between polls when waiting for an Atlas Search index to become READY.""" + max_batched_result_rows: NonNegativeInt = MAX_BATCHED_RESULT_ROWS + """Largest request, as entity rows x feature views, whose feature views are read + with a single find. Set to 0 to always read one feature view at a time.""" class MongoDBOnlineStore(OnlineStore): @@ -271,16 +308,7 @@ def online_read( ] query_filter = {"_id": {"$in": ids}} - projection = { - "_id": 1, - f"event_timestamps.{table.name}": 1, - } - if requested_features: - projection.update( - {f"features.{table.name}.{x}": 1 for x in requested_features} - ) - else: - projection[f"features.{table.name}"] = 1 + projection = self._projection({table.name: requested_features}) cursor = clxn.find(query_filter, projection=projection) docs = {doc["_id"]: doc for doc in cursor} @@ -796,16 +824,7 @@ async def online_read_async( ] query_filter = {"_id": {"$in": ids}} - projection = { - "_id": 1, - f"event_timestamps.{table.name}": 1, - } - if requested_features: - projection.update( - {f"features.{table.name}.{x}": 1 for x in requested_features} - ) - else: - projection[f"features.{table.name}"] = 1 + projection = self._projection({table.name: requested_features}) cursor = clxn.find(query_filter, projection=projection) docs = {doc["_id"]: doc async for doc in cursor} @@ -838,6 +857,227 @@ async def online_write_batch_async( if progress: progress(len(data)) + # -- Batched reads across feature views ----------------------------- + + def _read_features_per_fv( + self, + config: RepoConfig, + grouped_refs: List, + join_key_values: Dict, + entity_name_to_join_key_map: Dict, + online_features_response, + full_feature_names: bool, + include_feature_view_version_metadata: bool, + ) -> None: + """Read every requested feature view with a single find. + + The generic path issues one find per feature view. Every feature view of an + entity is stored in the same document here, so one find over the entity ids + of all the views, projecting the features requested from each, returns what + the per-view finds would. + """ + if not self._should_batch(config, grouped_refs, join_key_values): + return super()._read_features_per_fv( + config, + grouped_refs, + join_key_values, + entity_name_to_join_key_map, + online_features_response, + full_feature_names, + include_feature_view_version_metadata, + ) + + reads = self._prepare_batched_reads( + config, grouped_refs, join_key_values, entity_name_to_join_key_map + ) + query_filter, projection = self._batched_query(reads) + + clxn = self._get_collection(config) + cursor = clxn.find(query_filter, projection=projection) + docs = {doc["_id"]: doc for doc in cursor} + + self._populate_from_docs( + reads, + docs, + online_features_response, + full_feature_names, + include_feature_view_version_metadata, + ) + + async def _read_features_per_fv_async( + self, + config: RepoConfig, + grouped_refs: List, + join_key_values: Dict, + entity_name_to_join_key_map: Dict, + online_features_response, + full_feature_names: bool, + include_feature_view_version_metadata: bool, + ) -> None: + """Async version of :meth:`_read_features_per_fv`. + + The generic async path already sends the per-view finds concurrently. + Batching still replaces those finds with one. + """ + if not self._should_batch(config, grouped_refs, join_key_values): + return await super()._read_features_per_fv_async( + config, + grouped_refs, + join_key_values, + entity_name_to_join_key_map, + online_features_response, + full_feature_names, + include_feature_view_version_metadata, + ) + + reads = self._prepare_batched_reads( + config, grouped_refs, join_key_values, entity_name_to_join_key_map + ) + query_filter, projection = self._batched_query(reads) + + clxn = await self._get_collection_async(config) + cursor = clxn.find(query_filter, projection=projection) + docs = {doc["_id"]: doc async for doc in cursor} + + self._populate_from_docs( + reads, + docs, + online_features_response, + full_feature_names, + include_feature_view_version_metadata, + ) + + @staticmethod + def _should_batch( + config: RepoConfig, grouped_refs: List, join_key_values: Dict + ) -> bool: + """Whether to read this request's feature views with a single find. + + A single view has no finds to combine, so it keeps the generic path. The size + check is estimated from the request shape rather than from the resolved keys, + so that deciding against batching costs nothing. The number of entity rows in + the request is an upper bound on the unique keys any one view will read. See + :data:`MAX_BATCHED_RESULT_ROWS`. + """ + if len(grouped_refs) < 2: + return False + entity_rows = max( + (len(values) for values in join_key_values.values()), default=0 + ) + return ( + entity_rows * len(grouped_refs) + <= config.online_store.max_batched_result_rows + ) + + @staticmethod + def _prepare_batched_reads( + config: RepoConfig, + grouped_refs: List, + join_key_values: Dict, + entity_name_to_join_key_map: Dict, + ) -> List[_BatchedRead]: + """Resolve the entity ids each feature view needs before reading. + + Feature views can be keyed on different entities, so the entity ids are + computed per view rather than shared. + """ + reads = [] + for table, requested_features in grouped_refs: + table_entity_values, idxs, output_len = utils._get_unique_entities( + table, join_key_values, entity_name_to_join_key_map + ) + entity_key_protos = utils._get_entity_key_protos(table_entity_values) + reads.append( + _BatchedRead( + table=table, + requested_features=requested_features, + ids=[ + serialize_entity_key( + entity_key, + entity_key_serialization_version=config.entity_key_serialization_version, + ) + for entity_key in entity_key_protos + ], + idxs=idxs, + output_len=output_len, + ) + ) + return reads + + @classmethod + def _batched_query( + cls, reads: List[_BatchedRead] + ) -> Tuple[Dict[str, Any], Dict[str, int]]: + """Build the filter and projection of the one find that serves every view. + + Views keyed on the same entities share documents, so each entity id is + queried once. A feature view requested under several aliases is projected + once, with the union of the features requested under each alias, or as a + whole if any alias reads all of its features. + """ + ids = list(dict.fromkeys(entity_id for read in reads for entity_id in read.ids)) + features_by_view: Dict[str, Optional[List[str]]] = {} + for read in reads: + view_name = read.table.name + if view_name not in features_by_view: + features_by_view[view_name] = read.requested_features or None + else: + features = features_by_view[view_name] + features_by_view[view_name] = ( + list(dict.fromkeys(features + read.requested_features)) + if features and read.requested_features + else None + ) + return {"_id": {"$in": ids}}, cls._projection(features_by_view) + + @staticmethod + def _projection( + features_by_view: Dict[str, Optional[List[str]]], + ) -> Dict[str, int]: + """Project the event timestamp and requested features of each feature view. + + A view without requested features is projected as a whole. MongoDB rejects a + projection that names both a document and one of its fields, so a view is + never projected both ways. + """ + projection = {"_id": 1} + for view_name, features in features_by_view.items(): + projection[f"event_timestamps.{view_name}"] = 1 + if features: + projection.update( + {f"features.{view_name}.{feature}": 1 for feature in features} + ) + else: + projection[f"features.{view_name}"] = 1 + return projection + + @classmethod + def _populate_from_docs( + cls, + reads: List[_BatchedRead], + docs: Dict[bytes, Any], + online_features_response, + full_feature_names: bool, + include_feature_view_version_metadata: bool, + ) -> None: + """Hand each feature view the documents of its own entity ids, in order. + + A document can also hold features requested from other views, or from other + aliases of the same view. Only the features requested from each view are + added to the response. + """ + for read in reads: + utils._populate_response_from_feature_data( + read.requested_features, + cls._convert_raw_docs_to_proto(read.ids, docs, read.table), + read.idxs, + online_features_response, + full_feature_names, + read.table, + read.output_len, + include_feature_view_version_metadata, + ) + def _python_value_to_proto(value: Any) -> ValueProto: """Best-effort conversion of a single Python value to ValueProto.""" diff --git a/sdk/python/tests/integration/online_store/test_mongodb_batched_read.py b/sdk/python/tests/integration/online_store/test_mongodb_batched_read.py new file mode 100644 index 00000000000..99e09c901b0 --- /dev/null +++ b/sdk/python/tests/integration/online_store/test_mongodb_batched_read.py @@ -0,0 +1,303 @@ +"""Integration tests for batched MongoDB online reads. + +The batched path must return exactly what the generic per-feature-view path +returns. These run against a real server because the combined projection is the +part worth checking, and MongoDB rejects projections that a mock would accept. + +Run with: pytest --integration sdk/python/tests/integration/online_store/test_mongodb_batched_read.py +""" + +import uuid +from datetime import datetime, timedelta, timezone +from typing import Dict, List +from unittest.mock import patch + +import pytest + +from feast import Entity, FeatureView +from feast.field import Field +from feast.infra.online_stores.online_store import OnlineStore +from feast.protos.feast.serving.ServingService_pb2 import ( + FieldStatus, + 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 RepoConfig +from feast.types import Int64 +from feast.value_type import ValueType + +pytestmark = pytest.mark.integration +pytest.importorskip("pymongo") + +from pymongo.asynchronous.collection import AsyncCollection # noqa: E402 +from pymongo.collection import Collection # noqa: E402 + +from feast.infra.online_stores.mongodb_online_store.mongodb import ( # noqa: E402 + MongoDBOnlineStore, + MongoDBOnlineStoreConfig, +) + +docker_available = False +try: + import docker + from testcontainers.mongodb import MongoDbContainer + + try: + client = docker.from_env() + client.ping() + docker_available = True + except Exception: + pass +except ImportError: + pass + +_requires_docker = pytest.mark.skipif( + not docker_available, + reason="Docker is not available or not running. Start Docker daemon to run these tests.", +) + +DRIVER = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) +CUSTOMER = Entity( + name="customer", join_keys=["customer_id"], value_type=ValueType.INT64 +) +JOIN_KEY_MAP = {"driver": "driver_id", "customer": "customer_id"} + + +def _feature_view( + name: str, features: List[str], entity: Entity = DRIVER +) -> FeatureView: + return FeatureView( + name=name, + entities=[entity], + ttl=timedelta(0), + schema=[Field(name=feature, dtype=Int64) for feature in features], + ) + + +@pytest.fixture(scope="module") +def mongodb_container(): + container = MongoDbContainer( + "mongo:latest", + username="test", + password="test", # pragma: allowlist secret + ).with_exposed_ports(27017) + container.start() + yield container + container.stop() + + +@pytest.fixture +def config(mongodb_container) -> RepoConfig: + exposed_port = mongodb_container.get_exposed_port(27017) + return RepoConfig( + # A project per test gives each test its own collection. + project=f"batched_{uuid.uuid4().hex[:8]}", + provider="local", + online_store=MongoDBOnlineStoreConfig( + connection_string=f"mongodb://test:test@localhost:{exposed_port}", # pragma: allowlist secret + ), + registry="memory://", + entity_key_serialization_version=3, + ) + + +@pytest.fixture +async def store(config): + store = MongoDBOnlineStore() + yield store + store.teardown(config, [], []) + await store.close() + + +def _write(store, config, fv: FeatureView, join_key: str, rows: Dict) -> None: + """Write ``{entity value: {feature: value}}`` through the store.""" + now = datetime.now(tz=timezone.utc) + store.online_write_batch( + config, + fv, + [ + ( + EntityKeyProto( + join_keys=[join_key], + entity_values=[ValueProto(int64_val=entity_value)], + ), + {name: ValueProto(int64_val=value) for name, value in values.items()}, + now, + now, + ) + for entity_value, values in rows.items() + ], + None, + ) + + +def _args(config, grouped_refs, join_key_values, response): + return dict( + config=config, + grouped_refs=grouped_refs, + join_key_values=join_key_values, + entity_name_to_join_key_map=JOIN_KEY_MAP, + online_features_response=response, + full_feature_names=True, + include_feature_view_version_metadata=False, + ) + + +def _read(store, config, grouped_refs, join_key_values, generic=False): + response = GetOnlineFeaturesResponse() + read = ( + OnlineStore._read_features_per_fv + if generic + else MongoDBOnlineStore._read_features_per_fv + ) + read(store, **_args(config, grouped_refs, join_key_values, response)) + return response + + +async def _read_async(store, config, grouped_refs, join_key_values, generic=False): + response = GetOnlineFeaturesResponse() + read = ( + OnlineStore._read_features_per_fv_async + if generic + else MongoDBOnlineStore._read_features_per_fv_async + ) + await read(store, **_args(config, grouped_refs, join_key_values, response)) + return response + + +def _counting(find, calls: List): + def counted_find(self, *args, **kwargs): + calls.append(kwargs.get("projection")) + return find(self, *args, **kwargs) + + return counted_find + + +def _values(response: GetOnlineFeaturesResponse) -> dict: + """Map each feature name to its (values, statuses) across entity rows.""" + return { + name: ( + [value.int64_val for value in vector.values], + list(vector.statuses), + ) + for name, vector in zip(response.metadata.feature_names.val, response.results) + } + + +def _setup_three_views(store, config): + """Two driver views sharing a feature name, and a customer view. + + Driver 2 has a document, written by fv_a, but no fv_b features, and customer 8 + has no document at all. + """ + fv_a = _feature_view("fv_a", ["feat", "unrequested"]) + fv_b = _feature_view("fv_b", ["feat"]) + fv_c = _feature_view("fv_c", ["visits"], entity=CUSTOMER) + _write( + store, + config, + fv_a, + "driver_id", + {1: {"feat": 11, "unrequested": 1}, 2: {"feat": 12, "unrequested": 2}}, + ) + _write(store, config, fv_b, "driver_id", {1: {"feat": 21}}) + _write(store, config, fv_c, "customer_id", {7: {"visits": 70}}) + grouped_refs = [(fv_a, ["feat"]), (fv_b, ["feat"]), (fv_c, ["visits"])] + join_key_values = { + "driver_id": [ValueProto(int64_val=i) for i in (1, 2, 1)], + "customer_id": [ValueProto(int64_val=i) for i in (7, 8, 7)], + } + return grouped_refs, join_key_values + + +EXPECTED_THREE_VIEWS = { + "fv_a__feat": ([11, 12, 11], [FieldStatus.PRESENT] * 3), + "fv_b__feat": ( + [21, 0, 21], + [FieldStatus.PRESENT, FieldStatus.NOT_FOUND, FieldStatus.PRESENT], + ), + "fv_c__visits": ( + [70, 0, 70], + [FieldStatus.PRESENT, FieldStatus.NOT_FOUND, FieldStatus.PRESENT], + ), +} + + +@_requires_docker +def test_batched_matches_generic_path_in_one_find(store, config): + grouped_refs, join_key_values = _setup_three_views(store, config) + + batched_finds: List = [] + with patch.object(Collection, "find", _counting(Collection.find, batched_finds)): + batched = _read(store, config, grouped_refs, join_key_values) + + generic_finds: List = [] + with patch.object(Collection, "find", _counting(Collection.find, generic_finds)): + generic = _read(store, config, grouped_refs, join_key_values, generic=True) + + assert batched == generic + assert _values(batched) == EXPECTED_THREE_VIEWS + assert len(batched_finds) == 1 + assert len(generic_finds) == 3 + + +@_requires_docker +async def test_async_batched_matches_generic_path_in_one_find(store, config): + grouped_refs, join_key_values = _setup_three_views(store, config) + + batched_finds: List = [] + with patch.object( + AsyncCollection, "find", _counting(AsyncCollection.find, batched_finds) + ): + batched = await _read_async(store, config, grouped_refs, join_key_values) + + generic_finds: List = [] + with patch.object( + AsyncCollection, "find", _counting(AsyncCollection.find, generic_finds) + ): + generic = await _read_async( + store, config, grouped_refs, join_key_values, generic=True + ) + + assert batched == generic + assert _values(batched) == EXPECTED_THREE_VIEWS + assert len(batched_finds) == 1 + assert len(generic_finds) == 3 + + +@_requires_docker +@pytest.mark.parametrize( + "first_features, second_features, expected", + [ + pytest.param( + ["feat_x"], + ["feat_y"], + {"first__feat_x": 1, "second__feat_y": 2}, + id="different_features", + ), + pytest.param([], ["feat_x"], {"second__feat_x": 1}, id="whole_view"), + ], +) +def test_aliases_of_one_view_match_generic_path( + store, config, first_features, second_features, expected +): + """One view under two aliases is projected once, which MongoDB must accept. + + It rejects a projection that names both a document and one of its fields. + """ + fv = _feature_view("fv", ["feat_x", "feat_y", "feat_z"]) + _write(store, config, fv, "driver_id", {1: {"feat_x": 1, "feat_y": 2, "feat_z": 3}}) + grouped_refs = [ + (fv.with_name("first"), first_features), + (fv.with_name("second"), second_features), + ] + join_key_values = {"driver_id": [ValueProto(int64_val=1)]} + + batched = _read(store, config, grouped_refs, join_key_values) + generic = _read(store, config, grouped_refs, join_key_values, generic=True) + + assert batched == generic + assert _values(batched) == { + name: ([value], [FieldStatus.PRESENT]) for name, value in expected.items() + } diff --git a/sdk/python/tests/unit/infra/online_store/test_mongodb_batched_read.py b/sdk/python/tests/unit/infra/online_store/test_mongodb_batched_read.py new file mode 100644 index 00000000000..88ea369d58c --- /dev/null +++ b/sdk/python/tests/unit/infra/online_store/test_mongodb_batched_read.py @@ -0,0 +1,376 @@ +"""Unit tests for batching MongoDB online reads across feature views.""" + +import copy +from datetime import datetime, timedelta, timezone +from typing import Any, Dict, List, Optional, Tuple +from unittest.mock import patch + +import pytest + +pytest.importorskip("pymongo") + +from pydantic import ValidationError # noqa: E402 + +from feast import Entity, FeatureView # noqa: E402 +from feast.field import Field # noqa: E402 +from feast.infra.key_encoding_utils import serialize_entity_key # noqa: E402 +from feast.infra.online_stores.mongodb_online_store.mongodb import ( # noqa: E402 + MAX_BATCHED_RESULT_ROWS, + MongoDBOnlineStore, + MongoDBOnlineStoreConfig, + _BatchedRead, +) +from feast.infra.online_stores.online_store import OnlineStore # noqa: E402 +from feast.protos.feast.serving.ServingService_pb2 import ( # noqa: E402 + FieldStatus, + GetOnlineFeaturesResponse, +) +from feast.protos.feast.types.EntityKey_pb2 import ( # noqa: E402 + EntityKey as EntityKeyProto, +) +from feast.protos.feast.types.Value_pb2 import Value as ValueProto # noqa: E402 +from feast.repo_config import RepoConfig # noqa: E402 +from feast.types import Int64 # noqa: E402 +from feast.value_type import ValueType # noqa: E402 + +DRIVER = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) +CUSTOMER = Entity( + name="customer", join_keys=["customer_id"], value_type=ValueType.INT64 +) +JOIN_KEY_MAP = {"driver": "driver_id", "customer": "customer_id"} +TS = datetime(2026, 1, 1, tzinfo=timezone.utc) + + +def _feature_view( + name: str, features: List[str], entity: Entity = DRIVER +) -> FeatureView: + return FeatureView( + name=name, + entities=[entity], + ttl=timedelta(0), + schema=[Field(name=feature, dtype=Int64) for feature in features], + ) + + +def _config(**online_store) -> RepoConfig: + return RepoConfig( + project="test_mongodb", + provider="local", + online_store={"type": "mongodb", **online_store}, + registry="memory://", + entity_key_serialization_version=3, + ) + + +def _entity_id(join_key: str, value: int) -> bytes: + return serialize_entity_key( + EntityKeyProto( + join_keys=[join_key], entity_values=[ValueProto(int64_val=value)] + ), + entity_key_serialization_version=3, + ) + + +def _project(doc: Dict[str, Any], projection: Dict[str, int]) -> Dict[str, Any]: + """Apply an inclusion projection the way MongoDB does. + + Embedded documents on a projected path are kept, even when the projected field + is missing from them, and a projection naming both a document and one of its + fields is rejected. + """ + paths = [path for path in projection if path != "_id"] + for path in paths: + for other in paths: + assert not other.startswith(path + "."), f"Path collision at {path}" + projected: Dict[str, Any] = {"_id": doc["_id"]} + for path in paths: + source, target = doc, projected + *parents, leaf = path.split(".") + for part in parents: + if not isinstance(source.get(part), dict): + break + source = source[part] + target = target.setdefault(part, {}) + else: + if leaf in source: + target[leaf] = copy.deepcopy(source[leaf]) + return projected + + +class _AsyncCursor: + def __init__(self, docs: List[Dict[str, Any]]): + self._docs = iter(docs) + + def __aiter__(self): + return self + + async def __anext__(self): + try: + return next(self._docs) + except StopIteration: + raise StopAsyncIteration + + +class _FakeCollection: + """Serves find() from in-memory documents and records every call.""" + + def __init__(self): + self.docs: Dict[bytes, Dict[str, Any]] = {} + self.finds: List[Tuple[Dict[str, Any], Dict[str, int]]] = [] + + def write( + self, fv: FeatureView, join_key: str, rows: Dict[int, Dict[str, int]] + ) -> None: + """Store ``{entity value: {feature: value}}`` in the store's document layout.""" + for entity_value, values in rows.items(): + doc = self.docs.setdefault( + _entity_id(join_key, entity_value), + {"_id": _entity_id(join_key, entity_value)}, + ) + doc.setdefault("features", {}).setdefault(fv.name, {}).update(values) + doc.setdefault("event_timestamps", {})[fv.name] = TS + + def _find(self, query_filter, projection) -> List[Dict[str, Any]]: + self.finds.append((query_filter, projection)) + ids = set(query_filter["_id"]["$in"]) + return [ + _project(doc, projection) + for entity_id, doc in self.docs.items() + if entity_id in ids + ] + + def find(self, query_filter, projection): + return iter(self._find(query_filter, projection)) + + +class _FakeAsyncCollection(_FakeCollection): + def find(self, query_filter, projection): + return _AsyncCursor(self._find(query_filter, projection)) + + +def _args(config, grouped_refs, join_key_values, response): + return dict( + config=config, + grouped_refs=grouped_refs, + join_key_values=join_key_values, + entity_name_to_join_key_map=JOIN_KEY_MAP, + online_features_response=response, + full_feature_names=True, + include_feature_view_version_metadata=False, + ) + + +async def _read_sync(store, config, grouped_refs, join_key_values, generic=False): + """Await-compatible, so that the sync and async overrides share one test body.""" + response = GetOnlineFeaturesResponse() + read = ( + OnlineStore._read_features_per_fv + if generic + else MongoDBOnlineStore._read_features_per_fv + ) + read(store, **_args(config, grouped_refs, join_key_values, response)) + return response + + +async def _read_async(store, config, grouped_refs, join_key_values, generic=False): + response = GetOnlineFeaturesResponse() + read = ( + OnlineStore._read_features_per_fv_async + if generic + else MongoDBOnlineStore._read_features_per_fv_async + ) + await read(store, **_args(config, grouped_refs, join_key_values, response)) + return response + + +READERS = [ + pytest.param((_read_sync, _FakeCollection), id="sync"), + pytest.param((_read_async, _FakeAsyncCollection), id="async"), +] + + +def _store(collection: _FakeCollection) -> MongoDBOnlineStore: + store = MongoDBOnlineStore() + store._collection = collection # type: ignore[assignment] + store._collection_async = collection # type: ignore[assignment] + return store + + +def _drivers(*ids: int) -> Dict[str, List[ValueProto]]: + return {"driver_id": [ValueProto(int64_val=i) for i in ids]} + + +def _values(response: GetOnlineFeaturesResponse) -> dict: + """Map each feature name to its (values, statuses) across entity rows.""" + return { + name: ( + [value.int64_val for value in vector.values], + list(vector.statuses), + ) + for name, vector in zip(response.metadata.feature_names.val, response.results) + } + + +@pytest.mark.parametrize("reader", READERS) +async def test_views_read_in_one_find_match_generic_path(reader): + """Views sharing an entity AND a feature name come back from one find. + + Distinct feature names would hide a view reading another view's features, + since the response is keyed by feature name. + """ + read, collection_type = reader + collection = collection_type() + store = _store(collection) + config = _config() + fv_a = _feature_view("fv_a", ["feat", "unrequested"]) + fv_b = _feature_view("fv_b", ["feat"]) + fv_c = _feature_view("fv_c", ["visits"], entity=CUSTOMER) + collection.write(fv_a, "driver_id", {1: {"feat": 11, "unrequested": 1}}) + collection.write(fv_a, "driver_id", {2: {"feat": 12, "unrequested": 2}}) + # Driver 2 has a document, written by fv_a, but fv_b must report it as not found. + collection.write(fv_b, "driver_id", {1: {"feat": 21}}) + # Customer 8 has no document at all. + collection.write(fv_c, "customer_id", {7: {"visits": 70}}) + + grouped_refs = [(fv_a, ["feat"]), (fv_b, ["feat"]), (fv_c, ["visits"])] + join_key_values = { + **_drivers(1, 2, 1), + "customer_id": [ValueProto(int64_val=i) for i in (7, 8, 7)], + } + + batched = await read(store, config, grouped_refs, join_key_values) + + assert len(collection.finds) == 1 + query_filter, projection = collection.finds[0] + assert sorted(query_filter["_id"]["$in"]) == sorted( + [ + _entity_id("driver_id", 1), + _entity_id("driver_id", 2), + _entity_id("customer_id", 7), + _entity_id("customer_id", 8), + ] + ) + assert projection == { + "_id": 1, + "event_timestamps.fv_a": 1, + "features.fv_a.feat": 1, + "event_timestamps.fv_b": 1, + "features.fv_b.feat": 1, + "event_timestamps.fv_c": 1, + "features.fv_c.visits": 1, + } + + generic = await read(store, config, grouped_refs, join_key_values, generic=True) + assert len(collection.finds) == 4 + assert batched == generic + + found, missing = FieldStatus.PRESENT, FieldStatus.NOT_FOUND + assert _values(batched) == { + "fv_a__feat": ([11, 12, 11], [found, found, found]), + "fv_b__feat": ([21, 0, 21], [found, missing, found]), + "fv_c__visits": ([70, 0, 70], [found, missing, found]), + } + + +@pytest.mark.parametrize("reader", READERS) +async def test_aliases_of_one_view_are_projected_once(reader): + """One view under two aliases reads the union of the aliases' features.""" + read, collection_type = reader + collection = collection_type() + store = _store(collection) + config = _config() + fv = _feature_view("fv", ["feat_x", "feat_y", "feat_z"]) + collection.write(fv, "driver_id", {1: {"feat_x": 1, "feat_y": 2, "feat_z": 3}}) + grouped_refs = [ + (fv.with_name("first"), ["feat_x"]), + (fv.with_name("second"), ["feat_y"]), + ] + + batched = await read(store, config, grouped_refs, _drivers(1)) + + assert len(collection.finds) == 1 + query_filter, projection = collection.finds[0] + assert query_filter == {"_id": {"$in": [_entity_id("driver_id", 1)]}} + assert projection == { + "_id": 1, + "event_timestamps.fv": 1, + "features.fv.feat_x": 1, + "features.fv.feat_y": 1, + } + assert _values(batched) == { + "first__feat_x": ([1], [FieldStatus.PRESENT]), + "second__feat_y": ([2], [FieldStatus.PRESENT]), + } + generic = await read(store, config, grouped_refs, _drivers(1), generic=True) + assert batched == generic + + +@pytest.mark.parametrize("whole_view_first", [True, False]) +def test_view_read_whole_is_not_also_projected_by_feature(whole_view_first): + """MongoDB rejects a projection naming a document and one of its fields.""" + fv = _feature_view("fv", ["feat_x"]) + reads = [ + _BatchedRead(fv, [], [b"1"], ([0],), 1), + _BatchedRead(fv.with_name("alias"), ["feat_x"], [b"1"], ([0],), 1), + ] + if not whole_view_first: + reads.reverse() + + query_filter, projection = MongoDBOnlineStore._batched_query(reads) + + assert query_filter == {"_id": {"$in": [b"1"]}} + assert projection == {"_id": 1, "event_timestamps.fv": 1, "features.fv": 1} + + +@pytest.mark.parametrize( + "online_store, n_views, n_rows", + [ + pytest.param({}, 1, 1, id="single_view"), + pytest.param({"max_batched_result_rows": 0}, 2, 1, id="disabled"), + pytest.param({"max_batched_result_rows": 5}, 2, 3, id="over_limit"), + ], +) +@pytest.mark.parametrize("reader", READERS) +async def test_generic_path_reads_each_view(reader, online_store, n_views, n_rows): + """Outside the gate, every view is read by its own online_read call.""" + read, collection_type = reader + store = _store(collection_type()) + config = _config(**online_store) + grouped_refs = [ + (_feature_view(f"fv_{i}", ["feat"]), ["feat"]) for i in range(n_views) + ] + read_views: List[str] = [] + + def online_read( + self, config, table, entity_keys, requested_features: Optional[List] = None + ): + read_views.append(table.name) + return [(None, None)] * len(entity_keys) + + async def online_read_async(self, *args, **kwargs): + return online_read(self, *args, **kwargs) + + with ( + patch.object(MongoDBOnlineStore, "online_read", online_read), + patch.object(MongoDBOnlineStore, "online_read_async", online_read_async), + patch.object(MongoDBOnlineStore, "_batched_query", side_effect=AssertionError), + ): + await read(store, config, grouped_refs, _drivers(*range(n_rows))) + + assert read_views == [f"fv_{i}" for i in range(n_views)] + + +def test_batching_at_the_limit(): + grouped_refs = [(None, []), (None, [])] + config = _config(max_batched_result_rows=4) + assert MongoDBOnlineStore._should_batch(config, grouped_refs, _drivers(1, 2)) + assert not MongoDBOnlineStore._should_batch(config, grouped_refs, _drivers(1, 2, 3)) + + +def test_max_batched_result_rows_config(): + assert MongoDBOnlineStoreConfig().max_batched_result_rows == MAX_BATCHED_RESULT_ROWS + assert ( + MongoDBOnlineStoreConfig(max_batched_result_rows=0).max_batched_result_rows == 0 + ) + with pytest.raises(ValidationError): + MongoDBOnlineStoreConfig(max_batched_result_rows=-1)