Skip to content

Commit ee7f255

Browse files
simonhearneclaude
authored andcommitted
feat: Add consistency_level to the Milvus online store config
Adds two optional settings, each Strong, Bounded, Session or Eventually: consistency_level is sent with every read and search, and collection_consistency_level is set when Feast creates a collection. When unset nothing is sent, so Milvus keeps its default (Bounded) exactly as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Simon Hearne <simon.hearne@gmail.com>
1 parent 0056565 commit ee7f255

4 files changed

Lines changed: 177 additions & 1 deletion

File tree

‎docs/reference/online-stores/milvus.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,8 @@ online_store:
9494
| `nlist` | `128` | `nlist` index parameter, used when `index_params` is unset. |
9595
| `index_params` | unset | Index build parameters passed to Milvus, e.g. `{M: 16, efConstruction: 200}` for HNSW. Defaults to `{nlist: <nlist>}`, or no parameters for `AUTOINDEX`. |
9696
| `search_params` | unset | Search parameters passed to Milvus, e.g. `{ef: 64}` for HNSW or `{level: 2}` for `AUTOINDEX`. Defaults to `{nprobe: 10}`, or no parameters for `AUTOINDEX`. |
97+
| `consistency_level` | unset | `Strong`, `Bounded`, `Session` or `Eventually`. Sent with every read and search. When unset, Milvus uses the collection's level. |
98+
| `collection_consistency_level` | unset | `Strong`, `Bounded`, `Session` or `Eventually`. Set when Feast creates a collection. When unset, Milvus uses its default (`Bounded`). |
9799
| `vector_enabled` | `true` | Enables vector search. |
98100
| `varchar_max_length` | `65535` | Default `max_length` of VARCHAR fields. Override per field with the `max_length` tag. |
99101
| `enable_openai_compatible_store` | `false` | Store numeric features as native Milvus numeric types. |
@@ -130,6 +132,18 @@ online_store:
130132
Index parameters only apply when Feast creates a collection. To change them for an existing
131133
collection, run `feast teardown` and `feast apply`, then materialize again.
132134

135+
## Consistency level
136+
137+
By default Milvus uses `Bounded` consistency, so a read issued straight after materialization may
138+
not see the newest writes for a short time. Set `consistency_level: Strong` if reads must always see
139+
the latest writes, at the cost of higher read latency. See the
140+
[Milvus consistency documentation](https://milvus.io/docs/consistency.md).
141+
142+
`consistency_level` applies to Feast's reads and searches and takes effect immediately.
143+
`collection_consistency_level` sets the collection's own default, which Milvus uses for requests
144+
that don't specify a level, such as those from other clients. It only applies when Feast creates a
145+
collection; to change it, run `feast teardown` and `feast apply`, then materialize again.
146+
133147
## Collection loading
134148

135149
Feast creates collections together with their indexes, which makes Milvus load them straight away.

‎sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,16 @@ class MilvusOnlineStoreConfig(FeastConfigBaseModel, VectorStoreConfig):
230230
# Search params, e.g. {"ef": 64}, or {"level": 2} for AUTOINDEX.
231231
# Defaults to {"nprobe": 10}, or {} for AUTOINDEX.
232232
search_params: Optional[Dict[str, Any]] = None
233+
# Sent with every read and search. When unset, Milvus uses the
234+
# collection's level.
235+
consistency_level: Optional[
236+
Literal["Strong", "Bounded", "Session", "Eventually"]
237+
] = None
238+
# Set when Feast creates a collection. When unset, Milvus uses its
239+
# default (Bounded).
240+
collection_consistency_level: Optional[
241+
Literal["Strong", "Bounded", "Session", "Eventually"]
242+
] = None
233243
username: Optional[StrictStr] = ""
234244
password: Optional[StrictStr] = ""
235245
enable_openai_compatible_store: Optional[bool] = False
@@ -421,6 +431,7 @@ def _get_or_create_collection(
421431
dimension=config.online_store.embedding_dim,
422432
schema=schema,
423433
index_params=index_params,
434+
**_collection_consistency_kwargs(config.online_store),
424435
)
425436
else:
426437
self._ensure_loaded(collection_name)
@@ -584,6 +595,7 @@ def online_read(
584595
collection_name=collection_name,
585596
filter=query_filter_for_entities,
586597
output_fields=output_fields,
598+
**_consistency_kwargs(config.online_store),
587599
)
588600
# Group hits by composite key.
589601
grouped_hits: Dict[str, Any] = {}
@@ -863,6 +875,7 @@ def _combine_exprs(*parts: Optional[str]) -> Optional[str]:
863875
limit=top_k,
864876
output_fields=output_fields,
865877
filter=combined_filter,
878+
**_consistency_kwargs(config.online_store),
866879
)
867880

868881
elif embedding is not None and config.online_store.vector_enabled:
@@ -880,6 +893,7 @@ def _combine_exprs(*parts: Optional[str]) -> Optional[str]:
880893
limit=top_k,
881894
output_fields=output_fields,
882895
filter=metadata_filter_expr,
896+
**_consistency_kwargs(config.online_store),
883897
)
884898

885899
elif query_string is not None:
@@ -915,6 +929,7 @@ def _combine_exprs(*parts: Optional[str]) -> Optional[str]:
915929
filter=combined_filter or text_filter,
916930
output_fields=output_fields,
917931
limit=top_k,
932+
**_consistency_kwargs(config.online_store),
918933
)
919934

920935
results = [
@@ -1053,6 +1068,22 @@ def _search_params(online_config: MilvusOnlineStoreConfig) -> Dict[str, Any]:
10531068
return {"nprobe": 10}
10541069

10551070

1071+
def _consistency_kwargs(online_config: MilvusOnlineStoreConfig) -> Dict[str, Any]:
1072+
"""Read and search kwargs; only pass a level when configured."""
1073+
if online_config.consistency_level:
1074+
return {"consistency_level": online_config.consistency_level}
1075+
return {}
1076+
1077+
1078+
def _collection_consistency_kwargs(
1079+
online_config: MilvusOnlineStoreConfig,
1080+
) -> Dict[str, Any]:
1081+
"""create_collection kwargs; only pass a level when configured."""
1082+
if online_config.collection_consistency_level:
1083+
return {"consistency_level": online_config.collection_consistency_level}
1084+
return {}
1085+
1086+
10561087
def _milvus_token(online_config: MilvusOnlineStoreConfig) -> str:
10571088
"""Return the token to authenticate with: ``token``, else ``username:password``."""
10581089
if online_config.token:

‎sdk/python/tests/integration/online_store/test_milvus_remote.py‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,3 +312,51 @@ def test_autoindex_with_search_level(
312312
lambda hits: len(hits) == 1,
313313
)
314314
assert hits[0]["city"].string_val == "Paris"
315+
316+
317+
@pytest.mark.parametrize(
318+
"collection_consistency_level, consistency_level",
319+
[(None, None), ("Strong", None), (None, "Strong")],
320+
)
321+
def test_consistency_level(
322+
tmp_path: Path,
323+
project: str,
324+
store: MilvusOnlineStore,
325+
collection_consistency_level: Optional[str],
326+
consistency_level: Optional[str],
327+
) -> None:
328+
online_store = {
329+
key: value
330+
for key, value in {
331+
"collection_consistency_level": collection_consistency_level,
332+
"consistency_level": consistency_level,
333+
}.items()
334+
if value
335+
}
336+
config = _repo_config(tmp_path, project, **online_store)
337+
fv = _scalar_feature_view()
338+
store.update(config, [], [fv], [], [], partial=False)
339+
340+
assert store.client is not None
341+
description = store.client.describe_collection(f"{project}_{fv.name}")
342+
# Only collection_consistency_level sets the collection's level; Milvus
343+
# defaults to Bounded.
344+
assert description["consistency_level_name"] == (
345+
collection_consistency_level or "Bounded"
346+
)
347+
348+
if consistency_level == "Strong":
349+
# A Strong read sees the previous write, even on a Bounded collection.
350+
_write_rows(
351+
store,
352+
config,
353+
fv,
354+
{
355+
1: {
356+
"trips_today": ValueProto(float_val=1.0),
357+
"city": ValueProto(string_val="Oslo"),
358+
}
359+
},
360+
)
361+
rows = _read(store, config, fv, [1], ["city"])
362+
assert rows[0] is not None and rows[0]["city"].string_val == "Oslo"

‎sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py‎

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22

33
from datetime import datetime, timedelta, timezone
44
from pathlib import Path
5-
from typing import Any, Dict, List, Optional
5+
from typing import Any, Dict, List, Optional, Tuple
66
from unittest.mock import MagicMock, patch
77

88
import pytest
9+
from pydantic import ValidationError
910
from pymilvus import DataType, MilvusClient
1011
from pymilvus.client.types import LoadState
1112

@@ -496,3 +497,85 @@ def test_autoindex_search_with_level(tmp_path: Path) -> None:
496497

497498
assert len(results) == 1
498499
assert results[0][2] is not None and results[0][2]["city"].string_val == "Paris"
500+
501+
502+
def _consistency_calls(
503+
**online_store: Any,
504+
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
505+
"""Return the kwargs of create_collection calls and of query/search calls."""
506+
with patch(f"{MILVUS_MODULE}.MilvusClient") as mock_client_cls:
507+
mock_client = _mock_client(mock_client_cls, has_collection=False)
508+
mock_client.describe_collection.return_value = {
509+
"collection_name": "test_milvus_driver_embeddings",
510+
"fields": [
511+
{"name": "driver_id_pk", "type": DataType.VARCHAR, "params": {}},
512+
{"name": "event_ts", "type": DataType.INT64, "params": {}},
513+
{"name": "created_ts", "type": DataType.INT64, "params": {}},
514+
{
515+
"name": "embedding",
516+
"type": DataType.FLOAT_VECTOR,
517+
"params": {"dim": 2},
518+
},
519+
{"name": "city", "type": DataType.VARCHAR, "params": {}},
520+
],
521+
}
522+
mock_client.search.return_value = [[]]
523+
mock_client.query.return_value = []
524+
525+
store = MilvusOnlineStore()
526+
config = _mock_config(embedding_dim=2, **online_store)
527+
fv = _vector_feature_view()
528+
store.online_read(config, fv, [_entity_key(1)], ["city"])
529+
store.retrieve_online_documents_v2(
530+
config, fv, ["embedding", "city"], embedding=[1.0, 0.0], top_k=1
531+
)
532+
store.retrieve_online_documents_v2(
533+
config, fv, ["city"], embedding=None, top_k=1, query_string="Paris"
534+
)
535+
create_calls = [
536+
call.kwargs for call in mock_client.create_collection.call_args_list
537+
]
538+
read_calls = [
539+
call.kwargs
540+
for call in mock_client.query.call_args_list
541+
+ mock_client.search.call_args_list
542+
]
543+
return create_calls, read_calls
544+
545+
546+
def test_consistency_levels_not_sent_when_unset() -> None:
547+
create_calls, read_calls = _consistency_calls()
548+
549+
assert len(create_calls) == 1 and len(read_calls) == 3
550+
assert all("consistency_level" not in kwargs for kwargs in create_calls)
551+
assert all("consistency_level" not in kwargs for kwargs in read_calls)
552+
553+
554+
def test_consistency_level_applied_to_reads_and_searches_only() -> None:
555+
create_calls, read_calls = _consistency_calls(consistency_level="Strong")
556+
557+
assert "consistency_level" not in create_calls[0]
558+
assert len(read_calls) == 3
559+
assert all(kwargs["consistency_level"] == "Strong" for kwargs in read_calls)
560+
561+
562+
def test_collection_consistency_level_applied_on_create_only() -> None:
563+
create_calls, read_calls = _consistency_calls(collection_consistency_level="Strong")
564+
565+
assert create_calls[0]["consistency_level"] == "Strong"
566+
assert all("consistency_level" not in kwargs for kwargs in read_calls)
567+
568+
569+
def test_collection_and_read_consistency_levels_independent() -> None:
570+
create_calls, read_calls = _consistency_calls(
571+
collection_consistency_level="Session", consistency_level="Strong"
572+
)
573+
574+
assert create_calls[0]["consistency_level"] == "Session"
575+
assert all(kwargs["consistency_level"] == "Strong" for kwargs in read_calls)
576+
577+
578+
@pytest.mark.parametrize("field", ["consistency_level", "collection_consistency_level"])
579+
def test_invalid_consistency_level_rejected(field: str) -> None:
580+
with pytest.raises(ValidationError):
581+
MilvusOnlineStoreConfig(**{field: "Immediate"})

0 commit comments

Comments
 (0)