diff --git a/docs/reference/online-stores/milvus.md b/docs/reference/online-stores/milvus.md index 723194c4420..bc1561a3e3f 100644 --- a/docs/reference/online-stores/milvus.md +++ b/docs/reference/online-stores/milvus.md @@ -102,6 +102,8 @@ online_store: | `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. | +| `mutation_timeout` | unset | Timeout in seconds that PyMilvus applies to each upsert and delete attempt, and after which it stops retrying. When unset, PyMilvus applies its default retry policy. See [Mutation timeout](#mutation-timeout). | +| `fail_on_schema_mismatch` | `false` | Raise an error, instead of logging a warning, when an existing collection does not have the fields the feature view declares. See [Schema mismatch](#schema-mismatch). | The full set of configuration options is available in [MilvusOnlineStoreConfig](https://rtd.feast.dev/en/latest/#feast.infra.online_stores.milvus.MilvusOnlineStoreConfig). @@ -225,6 +227,32 @@ with an empty group is rejected, so a mistake cannot delete more rows than it na leaves no tombstone: a later write creates it again, and Feast does not order a delete against writes from other processes. Deletion works on every collection that Feast created. +## Mutation timeout + +PyMilvus retries a failed upsert or delete, and a call without a timeout can wait for a long time, +for example while a cluster refuses writes because it is at its memory quota. `mutation_timeout` is +passed to PyMilvus as the timeout of each attempt, and PyMilvus stops retrying once the elapsed time +exceeds it, so a call ends within the timeout plus one attempt: + +```yaml +online_store: + type: milvus + mutation_timeout: 60 +``` + +After a timeout, the result on the server is unknown: the batch may have been applied in part or in +full. Upserts and deletes of the same rows are idempotent, so the caller can repeat the call. + +## Schema mismatch + +A collection's schema only applies when Feast creates it. When Feast finds an existing collection +whose fields differ from the feature view, because a field was added or removed or a vector +dimension changed, it logs a warning that names each difference and keeps using the collection. +Set `fail_on_schema_mismatch: true` to raise an error instead, so that a changed feature view is +caught at `feast apply` before any data is written. To apply the new schema, run `feast teardown` +and `feast apply`, then materialize again. Field types are not compared: Feast reads and writes a +collection with the types it has. + ## Field types Each feature is a column of the collection. A value comes back as it was written, whatever its 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 e2fcd5cabf3..5e8dfa069d0 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 @@ -1,6 +1,7 @@ import base64 import json import logging +import math import re from datetime import datetime from pathlib import Path @@ -280,6 +281,24 @@ class MilvusOnlineStoreConfig(FeastConfigBaseModel, VectorStoreConfig): password: Optional[StrictStr] = "" enable_openai_compatible_store: Optional[bool] = False varchar_max_length: Optional[int] = 65535 + # Timeout in seconds that PyMilvus applies to each upsert and delete attempt. + # PyMilvus stops retrying once the elapsed time exceeds it, so a call can + # overrun by up to one attempt. When unset, PyMilvus applies its default + # retry policy. + mutation_timeout: Optional[float] = None + + @field_validator("mutation_timeout") + @classmethod + def validate_mutation_timeout(cls, v): + if v is not None and not (math.isfinite(v) and v > 0): + raise ValueError( + f"mutation_timeout must be a positive number of seconds, got {v}" + ) + return v + + # Raise an error, instead of logging a warning, when an existing collection + # does not have the fields the feature view declares. + fail_on_schema_mismatch: Optional[bool] = False @field_validator("num_partitions") @classmethod @@ -477,15 +496,14 @@ def _get_or_create_collection( collection_name, [index["index_name"] for index in scalar_indexes], ) - # 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 - ) - if collection_exists and partition_key: - _warn_if_partition_key_missing( - self._collections[collection_name], partition_key - ) + description = self.client.describe_collection(collection_name) + if collection_exists: + _check_schema(config.online_store, schema, description) + if partition_key: + _warn_if_partition_key_missing(description, partition_key) + # Collections are only cached once loaded and checked, so reads and + # searches don't need to load or check them again. + self._collections[collection_name] = description return self._collections[collection_name] def _ensure_loaded(self, collection_name: str) -> None: @@ -588,6 +606,7 @@ def online_write_batch( self.client.upsert( collection_name=collection["collection_name"], data=entity_batch_to_insert, + **_mutation_kwargs(config.online_store), ) def online_read( @@ -731,7 +750,11 @@ def online_delete( if not self.client.has_collection(collection_name): return self._ensure_loaded(collection_name) - self.client.delete(collection_name=collection_name, **selector) + self.client.delete( + collection_name=collection_name, + **selector, + **_mutation_kwargs(config.online_store), + ) def update( self, @@ -744,6 +767,16 @@ def update( ): self.client = self._connect(config) for table in tables_to_keep: + # Check the schema again: the feature view may have changed since this + # process cached the collection. + self._collections.pop( + _table_id( + config.project, + table, + config.registry.enable_online_feature_view_versioning, + ), + None, + ) self._get_or_create_collection(config, table) # Always drop the base collection plus any "_v{N}" siblings, regardless of @@ -1041,6 +1074,13 @@ def _table_id(project: str, table: FeatureView, enable_versioning: bool = False) return compute_table_id(project, table, enable_versioning) +def _mutation_kwargs(online_config: MilvusOnlineStoreConfig) -> Dict[str, Any]: + """PyMilvus applies ``timeout`` to each attempt and stops retrying after it.""" + if online_config.mutation_timeout is None: + return {} + return {"timeout": online_config.mutation_timeout} + + def _is_autoindex(online_config: MilvusOnlineStoreConfig) -> bool: return (online_config.index_type or "").upper() == "AUTOINDEX" @@ -1102,6 +1142,61 @@ def _mark_partition_key( field.is_partition_key = True +def _schema_mismatches( + schema: CollectionSchema, collection: Dict[str, Any] +) -> List[str]: + """Fields that differ between a feature view's schema and an existing collection. + + Field types are not compared: reads and writes adapt to the types a collection + has, for example numeric fields stored as VARCHAR. + """ + declared = {field.name: field for field in schema.fields} + existing = {field["name"]: field for field in collection["fields"]} + mismatches = [ + f"field '{name}' is not in the collection" + for name in declared + if name not in existing + ] + [ + f"field '{name}' is not in the feature view" + for name in existing + if name not in declared + ] + for name in declared: + # Older Feast versions created a 1-dim placeholder; writes adapt to it. + if name not in existing or name == PLACEHOLDER_VECTOR_FIELD: + continue + declared_dim = declared[name].params.get("dim") + existing_dim = existing[name].get("params", {}).get("dim") + if declared_dim is None or existing_dim is None: + continue + if int(declared_dim) != int(existing_dim): + mismatches.append( + f"field '{name}' has dim {existing_dim}, " + f"the feature view declares dim {declared_dim}" + ) + return mismatches + + +def _check_schema( + online_config: MilvusOnlineStoreConfig, + schema: CollectionSchema, + collection: Dict[str, Any], +) -> None: + """Log, or raise with ``fail_on_schema_mismatch``, the schema differences.""" + mismatches = _schema_mismatches(schema, collection) + if not mismatches: + return + message = ( + f"Collection '{collection['collection_name']}' does not match the feature " + f"view schema: {'; '.join(mismatches)}. A collection's schema only applies " + "when it is created: run `feast teardown` and `feast apply`, then " + "materialize again to use the new schema." + ) + if online_config.fail_on_schema_mismatch: + raise ValueError(message) + logger.warning(message) + + def _warn_if_partition_key_missing( collection: Dict[str, Any], partition_key: str ) -> None: 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 6274e1e674c..db277db102f 100644 --- a/sdk/python/tests/integration/online_store/test_milvus_remote.py +++ b/sdk/python/tests/integration/online_store/test_milvus_remote.py @@ -672,3 +672,46 @@ def test_native_complex_types_filters_and_tag_indexes( True, False, ] + + +def test_mutation_timeout( + tmp_path: Path, project: str, store: MilvusOnlineStore +) -> None: + config = _repo_config( + tmp_path, project, mutation_timeout=5, consistency_level="Strong" + ) + fv = _vector_feature_view() + store.update(config, [], [fv], [], [], partial=False) + + _write_rows(store, config, fv, _vector_rows()) + rows = _read(store, config, fv, [1, 2], ["city"]) + assert [row["city"].string_val for row in rows if row] == ["Paris", "Rome"] + + store.online_delete(config, fv, [_entity_key(1), _entity_key(2)]) + assert _read(store, config, fv, [1, 2], ["city"]) == [None, None] + + +def test_schema_mismatch( + tmp_path: Path, project: str, store: MilvusOnlineStore +) -> None: + config = _repo_config(tmp_path, project) + store.update(config, [], [_scalar_feature_view()], [], [], partial=False) + changed = 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), + Field(name="country", dtype=String), + ], + ) + + strict = _repo_config(tmp_path, project, fail_on_schema_mismatch=True) + with pytest.raises(ValueError, match="field 'country' is not in the collection"): + MilvusOnlineStore().update(strict, [], [changed], [], [], partial=False) 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 4375f985497..6e32c3bc6de 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 @@ -1560,3 +1560,136 @@ def test_a_json_column_that_cannot_be_null_rejects_a_missing_value( with pytest.raises(ValueError, match="cannot be null"): _write_rows(store, config, fv, {1: {"value": ValueProto()}}) + + +@pytest.mark.parametrize("timeout", [0, -1, float("nan"), float("inf")]) +def test_invalid_mutation_timeout_rejected(timeout: float) -> None: + with pytest.raises(ValidationError, match="mutation_timeout"): + MilvusOnlineStoreConfig(mutation_timeout=timeout) + + +@pytest.mark.parametrize( + "online_store, expected", + [({}, {}), ({"mutation_timeout": 5}, {"timeout": 5})], +) +def test_mutation_timeout_sent_to_upserts_and_deletes( + tmp_path: Path, online_store: Dict[str, Any], expected: Dict[str, Any] +) -> None: + config = _lite_config(tmp_path, **online_store) + fv = _scalar_feature_view() + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + assert store.client is not None + + with ( + patch.object(store.client, "upsert", wraps=store.client.upsert) as upsert, + patch.object(store.client, "delete", wraps=store.client.delete) as delete, + ): + _write_rows(store, config, fv, {1: {"city": ValueProto(string_val="Paris")}}) + store.online_delete(config, fv, [_entity_key(1)]) + + for call in (upsert.call_args, delete.call_args): + sent = {key: call.kwargs[key] for key in expected} + assert sent == expected and ("timeout" in call.kwargs) == bool(expected) + assert _read(store, config, fv, [1], ["city"]) == [None] + + +def _mismatched_collection_description() -> Dict[str, Any]: + """The scalar collection without ``city``, with ``country`` and a 1-dim placeholder.""" + description = _existing_collection_description() + description["fields"] = [ + field for field in description["fields"] if field["name"] != "city" + ] + [{"name": "country", "type": DataType.VARCHAR, "params": {}}] + for field in description["fields"]: + if field["name"] == PLACEHOLDER_VECTOR_FIELD: + field["params"] = {"dim": 1} + return description + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_schema_mismatch_is_logged_by_default( + mock_client_cls: MagicMock, caplog: pytest.LogCaptureFixture +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=True) + mock_client.get_load_state.return_value = {"state": LoadState.Loaded} + mock_client.describe_collection.return_value = _mismatched_collection_description() + + MilvusOnlineStore()._get_or_create_collection( + _mock_config(), _scalar_feature_view() + ) + + assert "field 'city' is not in the collection" in caplog.text + assert "field 'country' is not in the feature view" in caplog.text + assert PLACEHOLDER_VECTOR_FIELD not in caplog.text + mock_client.create_collection.assert_not_called() + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_schema_mismatch_raises_when_configured(mock_client_cls: MagicMock) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=True) + mock_client.get_load_state.return_value = {"state": LoadState.Loaded} + mock_client.describe_collection.return_value = _mismatched_collection_description() + store = MilvusOnlineStore() + + with pytest.raises(ValueError, match="field 'city' is not in the collection"): + store._get_or_create_collection( + _mock_config(fail_on_schema_mismatch=True), _scalar_feature_view() + ) + + assert store._collections == {} + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_vector_dimension_mismatch_is_reported(mock_client_cls: MagicMock) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=True) + mock_client.get_load_state.return_value = {"state": LoadState.Loaded} + mock_client.describe_collection.return_value = { + "collection_name": "test_milvus_driver_embeddings", + "fields": [ + {"name": "driver_id_pk", "type": DataType.VARCHAR, "params": {}}, + {"name": "event_ts", "type": DataType.INT64, "params": {}}, + {"name": "created_ts", "type": DataType.INT64, "params": {}}, + {"name": "driver_id", "type": DataType.VARCHAR, "params": {}}, + {"name": "embedding", "type": DataType.FLOAT_VECTOR, "params": {"dim": 3}}, + {"name": "city", "type": DataType.VARCHAR, "params": {}}, + ], + } + + with pytest.raises(ValueError, match="dim 3, the feature view declares dim 2"): + MilvusOnlineStore()._get_or_create_collection( + _mock_config(embedding_dim=2, fail_on_schema_mismatch=True), + _vector_feature_view(), + ) + + +def test_schema_mismatch_on_an_existing_collection( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + config = _lite_config(tmp_path) + store = MilvusOnlineStore() + store.update(config, [], [_scalar_feature_view()], [], [], partial=False) + changed = FeatureView( + name="driver_stats", + 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), + Field(name="country", dtype=String), + ], + ) + + # The same process applies the changed view: the cached collection is checked again. + store.update(config, [], [changed], [], [], partial=False) + assert "field 'country' is not in the collection" in caplog.text + + with pytest.raises(ValueError, match="field 'country' is not in the collection"): + store.update( + _lite_config(tmp_path, fail_on_schema_mismatch=True), + [], + [changed], + [], + [], + partial=False, + )