From 0838f0db367327ac7130181bd4ec50e393808e80 Mon Sep 17 00:00:00 2001 From: Simon Hearne Date: Mon, 28 Sep 2026 13:19:02 +0100 Subject: [PATCH 1/2] fix: Make Milvus placeholder vectors valid on Milvus servers Feature views without a vector field get a placeholder vector because Milvus requires one per collection. The placeholder was 1-dimensional, filled with NaN and left unindexed. Milvus Lite accepts all three, but Milvus servers and Zilliz Cloud reject dim < 2 and non-finite values, and refuse to load a collection with an unindexed vector field, so these feature views could not be created or read. The placeholder is now 2-dimensional, zero-filled and FLAT-indexed. Vector fields without vector_index=True also get a FLAT index so the collection can be loaded. Existing collections keep working because the placeholder is filled to the dimension recorded in the collection. Also fixes the Milvus docs page title and example config. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Simon Hearne --- .secrets.baseline | 4 +- docs/reference/online-stores/milvus.md | 45 +++- .../milvus_online_store/milvus.py | 53 +++-- .../online_store/test_milvus_remote.py | 173 ++++++++++++++ .../online_store/test_milvus_online_store.py | 213 ++++++++++++++++++ 5 files changed, 469 insertions(+), 19 deletions(-) create mode 100644 sdk/python/tests/integration/online_store/test_milvus_remote.py create mode 100644 sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py diff --git a/.secrets.baseline b/.secrets.baseline index 0e781c9ce67..2a358cc8a04 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -185,7 +185,7 @@ "filename": "docs/reference/online-stores/milvus.md", "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", "is_verified": false, - "line_number": 41 + "line_number": 54 } ], "docs/reference/registries/sql.md": [ @@ -1564,5 +1564,5 @@ } ] }, - "generated_at": "2026-09-15T09:12:05Z" + "generated_at": "2026-09-28T14:23:47Z" } diff --git a/docs/reference/online-stores/milvus.md b/docs/reference/online-stores/milvus.md index 58f7dbd167a..dc98511440c 100644 --- a/docs/reference/online-stores/milvus.md +++ b/docs/reference/online-stores/milvus.md @@ -1,4 +1,4 @@ -# Redis online store +# Milvus online store ## Description @@ -19,11 +19,11 @@ Feast supports both milvus-lite 2.x and 3.x. However, if you upgrade from milvus See the [milvus-lite GitHub page](https://github.com/milvus-io/milvus-lite) for more details. {% endhint %} -You can get started by using any of the other templates (e.g. `feast init -t gcp` or `feast init -t snowflake` or `feast init -t aws`), and then swapping in Redis as the online store as seen below in the examples. +You can get started by using any of the other templates (e.g. `feast init -t gcp` or `feast init -t snowflake` or `feast init -t aws`), and then swapping in Milvus as the online store as seen below in the examples. ## Examples -Connecting to a local MilvusDB instance: +Using Milvus Lite, which stores data in a local file: {% code title="feature_store.yaml" %} ```yaml @@ -33,18 +33,55 @@ provider: local online_store: type: milvus path: "data/online_store.db" - connection_string: "localhost:6379" embedding_dim: 128 index_type: "FLAT" metric_type: "COSINE" +``` +{% endcode %} + +Connecting to a self-hosted Milvus server: + +{% code title="feature_store.yaml" %} +```yaml +project: my_feature_repo +registry: data/registry.db +provider: local +online_store: + type: milvus + host: "http://localhost" + port: 19530 username: "username" password: "password" + embedding_dim: 128 + index_type: "IVF_FLAT" + metric_type: "COSINE" ``` {% endcode %} +## Configuration options + +| Option | Default | Description | +|:-------|:--------|:------------| +| `path` | `""` | Path to a Milvus Lite database file. Used when `provider: local` and `path` is set. | +| `host` | `http://localhost` | Milvus server host, including the scheme. | +| `port` | `19530` | Milvus server port. | +| `username` / `password` | `""` | Credentials, sent as the token `username:password`. | +| `embedding_dim` | `128` | Dimension of vector fields. | +| `index_type` | `FLAT` | Index type for vector fields with `vector_index=True`. | +| `metric_type` | `COSINE` | Default metric when a field does not set `vector_search_metric`. | +| `nlist` | `128` | `nlist` index parameter. | +| `vector_enabled` | `true` | Enables vector search. | +| `varchar_max_length` | `65535` | Default `max_length` of VARCHAR fields. Override per field with the `max_length` tag. | +| `enable_openai_compatible_store` | `false` | Store numeric features as native Milvus numeric types. | The full set of configuration options is available in [MilvusOnlineStoreConfig](https://rtd.feast.dev/en/latest/#feast.infra.online_stores.milvus.MilvusOnlineStoreConfig). +## Feature views without vectors + +Milvus requires every collection to have a vector field. For feature views that have no vector +feature, Feast adds a 2-dimensional `_placeholder_vector` field with a FLAT index and fills it with zeros. +It is never returned or searched. + ## 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/milvus_online_store/milvus.py b/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py index 00079938a86..610b3f4412f 100644 --- a/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py +++ b/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py @@ -114,6 +114,13 @@ DataType.BOOL, } +# Milvus requires every collection to have a vector field, so feature views +# without one get a small placeholder vector. Milvus servers reject vectors +# with fewer than 2 dimensions and non-finite values, and a collection can only +# be loaded once every vector field is indexed. +PLACEHOLDER_VECTOR_FIELD = "_placeholder_vector" +PLACEHOLDER_VECTOR_DIM = 2 + def _milvus_escape_string(s: str) -> str: """Escape a string for safe use inside a Milvus single-quoted literal. @@ -348,9 +355,9 @@ def _get_or_create_collection( if not has_vector_field: fields.append( FieldSchema( - name="_placeholder_vector", + name=PLACEHOLDER_VECTOR_FIELD, dtype=DataType.FLOAT_VECTOR, - dim=1, + dim=PLACEHOLDER_VECTOR_DIM, ) ) schema = CollectionSchema( @@ -368,14 +375,12 @@ def _get_or_create_collection( index_params = self.client.prepare_index_params() indices_added = False for vector_field in schema.fields: - if ( - vector_field.dtype - in [ - DataType.FLOAT_VECTOR, - DataType.BINARY_VECTOR, - ] - and vector_field.name in vector_field_dict - ): + if vector_field.dtype not in [ + DataType.FLOAT_VECTOR, + DataType.BINARY_VECTOR, + ]: + continue + if vector_field.name in vector_field_dict: metric = vector_field_dict[ vector_field.name ].vector_search_metric @@ -387,7 +392,20 @@ def _get_or_create_collection( index_name=f"vector_index_{vector_field.name}", params={"nlist": config.online_store.nlist}, ) - indices_added = True + else: + # Vector fields that aren't searched (the placeholder, + # or arrays without vector_index) still need an index, + # otherwise Milvus servers refuse to load the collection. + index_params.add_index( + collection_name=collection_name, + field_name=vector_field.name, + metric_type="L2" + if vector_field.name == PLACEHOLDER_VECTOR_FIELD + else config.online_store.metric_type, + index_type="FLAT", + index_name=f"vector_index_{vector_field.name}", + ) + indices_added = True if indices_added: self.client.create_index( collection_name=collection_name, @@ -423,6 +441,15 @@ def online_write_batch( collection_field_types = { field["name"]: field["type"] for field in collection["fields"] } + # Collections created by older Feast versions may use a 1-dim placeholder. + placeholder_dim = next( + ( + int(field.get("params", {}).get("dim", PLACEHOLDER_VECTOR_DIM)) + for field in collection["fields"] + if field["name"] == PLACEHOLDER_VECTOR_FIELD + ), + PLACEHOLDER_VECTOR_DIM, + ) schema_internal_fields = {"event_ts", "created_ts"} collection_has_native_numerics = any( collection_field_types.get(name) in MILVUS_NATIVE_NUMERIC_TYPES @@ -472,8 +499,8 @@ def online_write_batch( for field in required_fields: if field not in single_entity_record: field_type = collection_field_types.get(field, DataType.VARCHAR) - if field == "_placeholder_vector": - single_entity_record[field] = [float("nan")] + if field == PLACEHOLDER_VECTOR_FIELD: + single_entity_record[field] = [0.0] * placeholder_dim else: single_entity_record[field] = _default_for_milvus_type( field_type diff --git a/sdk/python/tests/integration/online_store/test_milvus_remote.py b/sdk/python/tests/integration/online_store/test_milvus_remote.py new file mode 100644 index 00000000000..47025ea2598 --- /dev/null +++ b/sdk/python/tests/integration/online_store/test_milvus_remote.py @@ -0,0 +1,173 @@ +"""Integration tests for the Milvus online store against a Milvus server or Zilliz Cloud. + +These tests only run when ``ZILLIZ_URI`` and ``ZILLIZ_TOKEN`` are set, e.g.:: + + ZILLIZ_URI=https://.zillizcloud.com ZILLIZ_TOKEN= \ + pytest --integration sdk/python/tests/integration/online_store/test_milvus_remote.py + +They also run against a self-hosted Milvus server, e.g. +``ZILLIZ_URI=http://localhost:19530 ZILLIZ_TOKEN=root:Milvus``. +""" + +import os +import time +import uuid +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any, Callable, Dict, Iterator, List, Optional, TypeVar +from urllib.parse import urlparse + +import pytest + +from feast import Entity, FeatureView +from feast.field import Field +from feast.infra.online_stores.milvus_online_store.milvus import MilvusOnlineStore +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 Float32, Int64, String +from feast.value_type import ValueType + +T = TypeVar("T") + +ZILLIZ_URI = os.environ.get("ZILLIZ_URI") +ZILLIZ_TOKEN = os.environ.get("ZILLIZ_TOKEN") + +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif( + not (ZILLIZ_URI and ZILLIZ_TOKEN), + reason="ZILLIZ_URI and ZILLIZ_TOKEN must be set to run Milvus server tests", + ), +] + + +def _connection_config() -> Dict[str, Any]: + assert ZILLIZ_URI and ZILLIZ_TOKEN + parsed = urlparse(ZILLIZ_URI) + default_port = 443 if parsed.scheme == "https" else 19530 + username, _, password = ZILLIZ_TOKEN.partition(":") + return { + "host": f"{parsed.scheme}://{parsed.hostname}", + "port": parsed.port or default_port, + "username": username, + "password": password, + } + + +def _repo_config(tmp_path: Path, project: str, **online_store: Any) -> RepoConfig: + return RepoConfig( + project=project, + provider="local", + registry=str(tmp_path / "registry.db"), + online_store={ + "type": "milvus", + "embedding_dim": 2, + **_connection_config(), + **online_store, + }, + entity_key_serialization_version=3, + repo_path=tmp_path, + ) + + +@pytest.fixture +def project() -> str: + return f"feast_it_{uuid.uuid4().hex[:8]}" + + +@pytest.fixture +def store() -> Iterator[MilvusOnlineStore]: + store = MilvusOnlineStore() + yield store + if store.client is not None: + for name in list(store._collections): + store.client.drop_collection(name) + + +def _eventually(fn: Callable[[], T], check: Callable[[T], bool]) -> T: + """Retry ``fn`` until ``check`` passes, tolerating Bounded consistency.""" + deadline = time.monotonic() + 15 + while True: + result = fn() + if check(result) or time.monotonic() > deadline: + return result + time.sleep(0.5) + + +def _entity_key(driver_id: int) -> EntityKeyProto: + return EntityKeyProto( + join_keys=["driver_id"], entity_values=[ValueProto(int64_val=driver_id)] + ) + + +def _write_rows( + store: MilvusOnlineStore, + config: RepoConfig, + fv: FeatureView, + rows: Dict[int, Dict[str, ValueProto]], +) -> None: + now = datetime.now(timezone.utc) + store.online_write_batch( + config, + fv, + [(_entity_key(k), dict(v), now, now) for k, v in rows.items()], + progress=None, + ) + + +def _read( + store: MilvusOnlineStore, + config: RepoConfig, + fv: FeatureView, + driver_ids: List[int], + features: List[str], +) -> List[Optional[Dict[str, ValueProto]]]: + results = store.online_read( + config, fv, [_entity_key(d) for d in driver_ids], features + ) + return [values for _, values in results] + + +def _scalar_feature_view() -> FeatureView: + return FeatureView( + name="driver_stats", + entities=[ + Entity( + name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64 + ) + ], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="trips_today", dtype=Float32), + Field(name="city", dtype=String), + ], + ) + + +def test_scalar_feature_view_round_trip( + tmp_path: Path, project: str, store: MilvusOnlineStore +) -> None: + """Feature views without vectors rely on the placeholder vector.""" + config = _repo_config(tmp_path, project) + fv = _scalar_feature_view() + store.update(config, [], [fv], [], [], partial=False) + + _write_rows( + store, + config, + fv, + { + 1: { + "trips_today": ValueProto(float_val=3.0), + "city": ValueProto(string_val="Paris"), + } + }, + ) + rows = _eventually( + lambda: _read(store, config, fv, [1], ["trips_today", "city"]), + lambda rows: rows[0] is not None, + ) + + assert rows[0] is not None and rows[0]["city"].string_val == "Paris" diff --git a/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py b/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py new file mode 100644 index 00000000000..e51aceebb2f --- /dev/null +++ b/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py @@ -0,0 +1,213 @@ +"""Unit tests for the Milvus online store, run against Milvus Lite or a mocked client.""" + +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any, Dict, List, Optional +from unittest.mock import MagicMock, patch + +from pymilvus import DataType, MilvusClient + +from feast import Entity, FeatureView +from feast.field import Field +from feast.infra.online_stores.milvus_online_store.milvus import ( + PLACEHOLDER_VECTOR_DIM, + PLACEHOLDER_VECTOR_FIELD, + MilvusOnlineStore, + MilvusOnlineStoreConfig, +) +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 Float32, Int64, String +from feast.value_type import ValueType + +MILVUS_MODULE = "feast.infra.online_stores.milvus_online_store.milvus" + + +def _lite_config(tmp_path: Path, **online_store: Any) -> RepoConfig: + return RepoConfig( + project="test_milvus", + provider="local", + registry=str(tmp_path / "registry.db"), + online_store={ + "type": "milvus", + "path": str(tmp_path / "online_store.db"), + "embedding_dim": 2, + **online_store, + }, + entity_key_serialization_version=3, + repo_path=tmp_path, + ) + + +def _mock_config(**online_store: Any) -> MagicMock: + config = MagicMock() + config.project = "test_milvus" + config.entity_key_serialization_version = 3 + config.registry.enable_online_feature_view_versioning = False + config.provider = "local" + config.repo_path = None + config.online_store = MilvusOnlineStoreConfig(**online_store) + return config + + +def _mock_client(mock_client_cls: MagicMock, has_collection: bool) -> MagicMock: + mock_client = MagicMock() + mock_client_cls.return_value = mock_client + mock_client.has_collection.return_value = has_collection + mock_client.prepare_index_params.side_effect = MilvusClient.prepare_index_params + return mock_client + + +def _created_indexes(mock_client: MagicMock) -> Dict[str, Dict[str, Any]]: + """Map field name -> index definition for indexes passed to the client.""" + index_params = [] + for call in ( + mock_client.create_collection.call_args, + mock_client.create_index.call_args, + ): + if call is not None and call.kwargs.get("index_params") is not None: + index_params.extend(call.kwargs["index_params"]) + return {index.field_name: index.to_dict() for index in index_params} + + +def _driver_entity() -> Entity: + return Entity(name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64) + + +def _scalar_feature_view(name: str = "driver_stats") -> FeatureView: + return FeatureView( + name=name, + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="trips_today", dtype=Float32), + Field(name="city", dtype=String), + ], + ) + + +def _entity_key(driver_id: int) -> EntityKeyProto: + return EntityKeyProto( + join_keys=["driver_id"], entity_values=[ValueProto(int64_val=driver_id)] + ) + + +def _write_rows( + store: MilvusOnlineStore, + config: RepoConfig, + fv: FeatureView, + rows: Dict[int, Dict[str, ValueProto]], +) -> None: + now = datetime.now(timezone.utc) + store.online_write_batch( + config, + fv, + [(_entity_key(k), dict(v), now, now) for k, v in rows.items()], + progress=None, + ) + + +def _read( + store: MilvusOnlineStore, + config: RepoConfig, + fv: FeatureView, + driver_ids: List[int], + features: List[str], +) -> List[Optional[Dict[str, ValueProto]]]: + results = store.online_read( + config, fv, [_entity_key(d) for d in driver_ids], features + ) + return [values for _, values in results] + + +def test_scalar_feature_view_round_trip_with_placeholder(tmp_path: Path) -> None: + config = _lite_config(tmp_path) + fv = _scalar_feature_view() + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + + _write_rows( + store, + config, + fv, + { + 1: { + "trips_today": ValueProto(float_val=3.0), + "city": ValueProto(string_val="Paris"), + }, + 2: { + "trips_today": ValueProto(float_val=5.0), + "city": ValueProto(string_val="Rome"), + }, + }, + ) + rows = _read(store, config, fv, [1, 2, 3], ["trips_today", "city"]) + + assert rows[0] is not None and rows[0]["city"].string_val == "Paris" + assert rows[1] is not None and rows[1]["trips_today"].float_val == 5.0 + assert rows[2] is None + + collection = store.client.describe_collection("test_milvus_driver_stats") + placeholder = next( + f for f in collection["fields"] if f["name"] == PLACEHOLDER_VECTOR_FIELD + ) + assert placeholder["params"]["dim"] == PLACEHOLDER_VECTOR_DIM + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_placeholder_vector_is_indexed_and_valid(mock_client_cls: MagicMock) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + + store = MilvusOnlineStore() + store._get_or_create_collection(_mock_config(), _scalar_feature_view()) + + schema = mock_client.create_collection.call_args.kwargs["schema"] + placeholder = next(f for f in schema.fields if f.name == PLACEHOLDER_VECTOR_FIELD) + assert placeholder.dtype == DataType.FLOAT_VECTOR + # Milvus servers reject vectors with fewer than two dimensions. + assert placeholder.params["dim"] >= 2 + + assert PLACEHOLDER_VECTOR_FIELD in _created_indexes(mock_client) + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_placeholder_values_are_finite_and_match_collection_dim( + mock_client_cls: MagicMock, +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=True) + # A collection created by an older Feast version, with a 1-dim placeholder. + mock_client.describe_collection.return_value = { + "collection_name": "test_milvus_driver_stats", + "fields": [ + {"name": "driver_id_pk", "type": DataType.VARCHAR, "params": {}}, + {"name": "driver_id", "type": DataType.VARCHAR, "params": {}}, + {"name": "event_ts", "type": DataType.INT64, "params": {}}, + {"name": "created_ts", "type": DataType.INT64, "params": {}}, + {"name": "trips_today", "type": DataType.VARCHAR, "params": {}}, + {"name": "city", "type": DataType.VARCHAR, "params": {}}, + { + "name": PLACEHOLDER_VECTOR_FIELD, + "type": DataType.FLOAT_VECTOR, + "params": {"dim": 1}, + }, + ], + } + + store = MilvusOnlineStore() + config = _mock_config() + _write_rows( + store, + config, + _scalar_feature_view(), + { + 1: { + "trips_today": ValueProto(float_val=1.0), + "city": ValueProto(string_val="Oslo"), + } + }, + ) + + data = mock_client.upsert.call_args.kwargs["data"] + assert data[0][PLACEHOLDER_VECTOR_FIELD] == [0.0] From f75c4445eaa3074df1cede85f1423fe848dff601 Mon Sep 17 00:00:00 2001 From: Simon Hearne Date: Mon, 28 Sep 2026 13:21:13 +0100 Subject: [PATCH 2/2] fix: Load Milvus collections once instead of on every query online_read and retrieve_online_documents_v2 called load_collection on every request, adding a round-trip to each read. The call also hid the fact that newly created collections were never loaded on Milvus servers, because indexes were created after the collection. Collections are now created with their index params, which makes Milvus load them straight away. Existing collections are loaded only if their load state isn't Loaded, and only the first time a store accesses them. The per-query load_collection calls are removed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Simon Hearne --- docs/reference/online-stores/milvus.md | 7 ++ .../milvus_online_store/milvus.py | 36 +++--- .../online_store/test_milvus_remote.py | 108 +++++++++++++++++- .../online_store/test_milvus_online_store.py | 90 +++++++++++++++ 4 files changed, 224 insertions(+), 17 deletions(-) diff --git a/docs/reference/online-stores/milvus.md b/docs/reference/online-stores/milvus.md index dc98511440c..93267d171dd 100644 --- a/docs/reference/online-stores/milvus.md +++ b/docs/reference/online-stores/milvus.md @@ -76,6 +76,13 @@ online_store: The full set of configuration options is available in [MilvusOnlineStoreConfig](https://rtd.feast.dev/en/latest/#feast.infra.online_stores.milvus.MilvusOnlineStoreConfig). +## Collection loading + +Feast creates collections together with their indexes, which makes Milvus load them straight away. +When Feast finds an existing collection it checks its load state and loads it only if needed. +Reads and searches never load collections, so a collection released outside Feast is only reloaded +the next time a Feast process first accesses it. + ## Feature views without vectors Milvus requires every collection to have a vector field. For feature views that have no vector diff --git a/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py b/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py index 610b3f4412f..016f4dc9e59 100644 --- a/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py +++ b/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py @@ -12,6 +12,7 @@ FieldSchema, MilvusClient, ) +from pymilvus.client.types import LoadState from feast import Entity from feast.feature_view import FeatureView @@ -367,13 +368,7 @@ def _get_or_create_collection( collection_name=collection_name ) if not collection_exists: - self.client.create_collection( - collection_name=collection_name, - dimension=config.online_store.embedding_dim, - schema=schema, - ) index_params = self.client.prepare_index_params() - indices_added = False for vector_field in schema.fields: if vector_field.dtype not in [ DataType.FLOAT_VECTOR, @@ -405,19 +400,31 @@ def _get_or_create_collection( index_type="FLAT", index_name=f"vector_index_{vector_field.name}", ) - indices_added = True - if indices_added: - self.client.create_index( - collection_name=collection_name, - index_params=index_params, - ) + # Every collection has at least one vector field, and every + # vector field is indexed, so passing the index params here + # makes Milvus create the indexes and load the collection. + self.client.create_collection( + collection_name=collection_name, + dimension=config.online_store.embedding_dim, + schema=schema, + index_params=index_params, + ) else: - self.client.load_collection(collection_name) + self._ensure_loaded(collection_name) + # Collections are only cached once loaded, so reads and searches + # don't need to load them again. self._collections[collection_name] = self.client.describe_collection( collection_name ) return self._collections[collection_name] + def _ensure_loaded(self, collection_name: str) -> None: + """Load an existing collection unless Milvus already has it loaded.""" + assert self.client is not None, "Milvus client is not initialized" + load_state = self.client.get_load_state(collection_name).get("state") + if load_state != LoadState.Loaded: + self.client.load_collection(collection_name) + def online_write_batch( self, config: RepoConfig, @@ -560,7 +567,6 @@ def online_read( + ", ".join([f"'{e}'" for e in composite_entities]) + "]" ) - self.client.load_collection(collection_name) results = self.client.query( collection_name=collection_name, filter=query_filter_for_entities, @@ -773,8 +779,6 @@ def retrieve_online_documents_v2( ann_search_field = field["name"] break - self.client.load_collection(collection_name) - if filters and filters_contain_numeric_comparison(filters): collection_field_types = { f["name"]: f["type"] for f in collection["fields"] diff --git a/sdk/python/tests/integration/online_store/test_milvus_remote.py b/sdk/python/tests/integration/online_store/test_milvus_remote.py index 47025ea2598..001f35e83ab 100644 --- a/sdk/python/tests/integration/online_store/test_milvus_remote.py +++ b/sdk/python/tests/integration/online_store/test_milvus_remote.py @@ -15,6 +15,7 @@ from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any, Callable, Dict, Iterator, List, Optional, TypeVar +from unittest.mock import patch from urllib.parse import urlparse import pytest @@ -25,7 +26,7 @@ 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 Float32, Int64, String +from feast.types import Array, Float32, Int64, String from feast.value_type import ValueType T = TypeVar("T") @@ -171,3 +172,108 @@ def test_scalar_feature_view_round_trip( ) assert rows[0] is not None and rows[0]["city"].string_val == "Paris" + + +def _vector_feature_view(name: str = "driver_embeddings") -> FeatureView: + return FeatureView( + name=name, + entities=[ + Entity( + name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64 + ) + ], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field( + name="embedding", + dtype=Array(Float32), + vector_index=True, + vector_search_metric="COSINE", + ), + Field(name="city", dtype=String), + ], + ) + + +def _vector_rows() -> Dict[int, Dict[str, ValueProto]]: + def embedding(x: float, y: float) -> ValueProto: + value = ValueProto() + value.float_list_val.val.extend([x, y]) + return value + + return { + 1: {"embedding": embedding(1.0, 0.0), "city": ValueProto(string_val="Paris")}, + 2: {"embedding": embedding(0.0, 1.0), "city": ValueProto(string_val="Rome")}, + } + + +def _search( + store: MilvusOnlineStore, + config: RepoConfig, + fv: FeatureView, + embedding: List[float], + top_k: int = 1, + **kwargs: Any, +) -> List[Dict[str, ValueProto]]: + results = store.retrieve_online_documents_v2( + config, + fv, + ["embedding", "city"], + embedding=embedding, + top_k=top_k, + distance_metric="COSINE", + **kwargs, + ) + return [values for _, _, values in results if values] + + +def test_load_collection_not_called_per_query( + tmp_path: Path, project: str, store: MilvusOnlineStore +) -> None: + config = _repo_config(tmp_path, project) + fv = _vector_feature_view() + store.update(config, [], [fv], [], [], partial=False) + _write_rows(store, config, fv, _vector_rows()) + + assert store.client is not None + with patch.object( + store.client, "load_collection", wraps=store.client.load_collection + ) as load_spy: + hits = _eventually( + lambda: _search(store, config, fv, [1.0, 0.0]), + lambda hits: len(hits) == 1, + ) + for _ in range(3): + _read(store, config, fv, [1, 2], ["city"]) + _search(store, config, fv, [1.0, 0.0]) + + assert hits[0]["city"].string_val == "Paris" + assert load_spy.call_count == 0 + + +def test_released_collection_is_loaded_once( + tmp_path: Path, project: str, store: MilvusOnlineStore +) -> None: + config = _repo_config(tmp_path, project) + fv = _vector_feature_view() + store.update(config, [], [fv], [], [], partial=False) + _write_rows(store, config, fv, _vector_rows()) + assert store.client is not None + collection_name = f"{project}_{fv.name}" + store.client.release_collection(collection_name) + + # A fresh store, e.g. a new feature server process, finds it unloaded. + fresh_store = MilvusOnlineStore() + fresh_store.client = store.client + with patch.object( + store.client, "load_collection", wraps=store.client.load_collection + ) as load_spy: + rows = _eventually( + lambda: _read(fresh_store, config, fv, [1], ["city"]), + lambda rows: rows[0] is not None, + ) + _read(fresh_store, config, fv, [1], ["city"]) + + assert rows[0] is not None and rows[0]["city"].string_val == "Paris" + assert load_spy.call_count == 1 diff --git a/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py b/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py index e51aceebb2f..5da3293d9b5 100644 --- a/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py +++ b/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py @@ -5,7 +5,9 @@ from typing import Any, Dict, List, Optional from unittest.mock import MagicMock, patch +import pytest from pymilvus import DataType, MilvusClient +from pymilvus.client.types import LoadState from feast import Entity, FeatureView from feast.field import Field @@ -211,3 +213,91 @@ def test_placeholder_values_are_finite_and_match_collection_dim( data = mock_client.upsert.call_args.kwargs["data"] assert data[0][PLACEHOLDER_VECTOR_FIELD] == [0.0] + + +def _existing_collection_description() -> Dict[str, Any]: + return { + "collection_name": "test_milvus_driver_stats", + "fields": [ + {"name": "driver_id_pk", "type": DataType.VARCHAR, "params": {}}, + {"name": "driver_id", "type": DataType.VARCHAR, "params": {}}, + {"name": "event_ts", "type": DataType.INT64, "params": {}}, + {"name": "created_ts", "type": DataType.INT64, "params": {}}, + {"name": "trips_today", "type": DataType.VARCHAR, "params": {}}, + {"name": "city", "type": DataType.VARCHAR, "params": {}}, + { + "name": PLACEHOLDER_VECTOR_FIELD, + "type": DataType.FLOAT_VECTOR, + "params": {"dim": PLACEHOLDER_VECTOR_DIM}, + }, + ], + } + + +@pytest.mark.parametrize( + "load_state, expected_loads", + [(LoadState.Loaded, 0), (LoadState.NotLoad, 1)], +) +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_existing_collection_is_loaded_at_most_once( + mock_client_cls: MagicMock, load_state: LoadState, expected_loads: int +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=True) + mock_client.describe_collection.return_value = _existing_collection_description() + mock_client.get_load_state.return_value = {"state": load_state} + mock_client.query.return_value = [] + + store = MilvusOnlineStore() + config = _mock_config() + fv = _scalar_feature_view() + for _ in range(5): + store.online_read(config, fv, [_entity_key(1)], ["city"]) + + assert mock_client.load_collection.call_count == expected_loads + assert mock_client.query.call_count == 5 + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_new_collection_is_created_with_indexes_so_it_loads( + mock_client_cls: MagicMock, +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + + store = MilvusOnlineStore() + store._get_or_create_collection(_mock_config(), _scalar_feature_view()) + + # MilvusClient.create_collection loads the collection when it is given + # index params; creating indexes separately would leave it unloaded. + assert mock_client.create_collection.call_args.kwargs["index_params"] + mock_client.create_index.assert_not_called() + mock_client.load_collection.assert_not_called() + + +def test_load_collection_not_called_per_query(tmp_path: Path) -> None: + config = _lite_config(tmp_path) + fv = _scalar_feature_view() + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + _write_rows( + store, + config, + fv, + { + 1: { + "trips_today": ValueProto(float_val=1.0), + "city": ValueProto(string_val="Oslo"), + } + }, + ) + + assert store.client is not None + with patch.object( + store.client, "load_collection", wraps=store.client.load_collection + ) as load_spy: + for _ in range(3): + _read(store, config, fv, [1], ["city"]) + store.retrieve_online_documents_v2( + config, fv, ["city"], embedding=None, top_k=1, query_string="Oslo" + ) + + assert load_spy.call_count == 0