From f9be11eda7afb3dd7efe4028bd2eeec8fdbdd940 Mon Sep 17 00:00:00 2001 From: jiwidi Date: Mon, 9 Nov 2026 11:50:52 +0100 Subject: [PATCH 1/2] fix: Round-trip every Feast type and null in the Milvus online store With the default configuration the Milvus online store could not return most non-numeric Feast types as written. A Bool failed to read, a UnixTimestamp got no column so every write of it failed, an Array(String) failed to read, a numeric array without vector_index was declared as a vector of embedding_dim and could not be written, Bytes came back as base64 text and Json as the base64 of its protobuf. A missing value was stored as the column's default, which failed to read for a numeric text column and came back as 0 or false for a native one. Search hits decoded only primitive types, and entity columns were written as the text of their Python value. The write path now stores every scalar natively or as text, bytes as base64 and every other value as the base64 of its ValueProto, for features and entity columns alike, and one helper rebuilds the ValueProto for reads and searches from every declared field type. UnixTimestamp gets a column, only a field with vector_index=True becomes a vector, with the dimension from Field.vector_length before embedding_dim, and an empty text in a numeric or timestamp column reads as null. Array(Bool) with vector_index is rejected, because Milvus binary vectors were written unpacked and indexed with a float metric and could not work. The new milvus.nullable field tag makes a column nullable, so a missing value is stored and read as null. Signed-off-by: jiwidi --- docs/reference/online-stores/milvus.md | 31 ++ .../milvus_online_store/milvus.py | 388 ++++++++---------- .../online_store/test_milvus_remote.py | 59 ++- .../online_store/test_milvus_online_store.py | 291 ++++++++++++- 4 files changed, 552 insertions(+), 217 deletions(-) diff --git a/docs/reference/online-stores/milvus.md b/docs/reference/online-stores/milvus.md index aa7f19a8e34..72fd434390b 100644 --- a/docs/reference/online-stores/milvus.md +++ b/docs/reference/online-stores/milvus.md @@ -225,6 +225,37 @@ 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. +## Field types + +Each feature is a column of the collection. A value comes back as it was written, whatever its +type. + +| Feast type | Default | With `enable_openai_compatible_store: true` | +|:-----------|:--------|:--------------------------------------------| +| `String` | `VARCHAR` | `VARCHAR` | +| `Bool`, `Int32`, `Int64`, `Float32`, `Float64` | `VARCHAR` holding the value as text | `BOOL`, `INT32`, `INT64`, `FLOAT`, `DOUBLE` | +| `UnixTimestamp` | `VARCHAR` holding the seconds as text | `INT64` | +| `Bytes` | `VARCHAR` holding base64 | `VARCHAR` holding base64 | +| `Array` with `vector_index=True` | `FLOAT_VECTOR` with the field's `vector_length`, or `embedding_dim` when it is unset | the same | +| Every other type, such as an array without `vector_index`, `Json`, `Map` or `Struct` | `VARCHAR` holding the serialized value | the same | + +Filters apply to `VARCHAR` and native columns. A column that holds a serialized value can be read +but not filtered on. + +`Array(Bool)` cannot be a vector field: Milvus binary vectors are not supported. + +A missing or null value is written as the column's default: an empty string, `0` or `false`. Feast +reads an empty string in a numeric or timestamp text column as null, but a missing `String` or +`Bytes` value comes back empty and a `0` in a native numeric column comes back as `0`. Tag a field +with `milvus.nullable: "true"` to store null as `NULL` instead: + +```python +Field(name="rating", dtype=Float32, tags={"milvus.nullable": "true"}) +``` + +The tag applies when Feast creates the collection, and it needs Milvus 2.5 or later. Entity, +partition key and vector fields cannot be nullable. + ## 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 a740f06156e..5d63f9029ed 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 @@ -16,6 +16,7 @@ from feast import Entity from feast.feature_view import FeatureView +from feast.field import Field from feast.filter_models import ( ComparisonFilter, CompoundFilter, @@ -38,7 +39,6 @@ from feast.type_map import ( PROTO_VALUE_TO_VALUE_TYPE_MAP, VALUE_TYPE_TO_PROTO_VALUE_MAP, - feast_value_type_to_python_type, ) from feast.types import ( VALUE_TYPES_TO_FEAST_TYPES, @@ -64,6 +64,7 @@ PROTO_VALUE_TO_VALUE_TYPE_MAP["double_val"]: DataType.DOUBLE, PROTO_VALUE_TO_VALUE_TYPE_MAP["int32_val"]: DataType.INT32, PROTO_VALUE_TO_VALUE_TYPE_MAP["int64_val"]: DataType.INT64, + PROTO_VALUE_TO_VALUE_TYPE_MAP["unix_timestamp_val"]: DataType.INT64, PROTO_VALUE_TO_VALUE_TYPE_MAP["float_list_val"]: DataType.FLOAT_VECTOR, PROTO_VALUE_TO_VALUE_TYPE_MAP["int32_list_val"]: DataType.FLOAT_VECTOR, PROTO_VALUE_TO_VALUE_TYPE_MAP["int64_list_val"]: DataType.FLOAT_VECTOR, @@ -114,6 +115,7 @@ DataType.DOUBLE, DataType.BOOL, } +MILVUS_VECTOR_TYPES = {DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR} # Milvus requires every collection to have a vector field, so feature views # without one get a small placeholder vector. Milvus servers reject vectors @@ -354,49 +356,61 @@ def _get_or_create_collection( ] fields_to_add = [f for f in table.schema if f.name not in fields_to_exclude] use_typed = config.online_store.enable_openai_compatible_store + partition_key = _partition_key_name(config.online_store, table) + entity_columns = {column.name for column in table.entity_columns} for field in fields_to_add: - dtype = FEAST_PRIMITIVE_TO_MILVUS_TYPE_MAPPING.get(field.dtype) - if dtype is None and isinstance(field.dtype, ComplexFeastType): - dtype = DataType.VARCHAR - if dtype: - if dtype == DataType.FLOAT_VECTOR: - fields.append( - FieldSchema( - name=field.name, - dtype=dtype, - dim=config.online_store.embedding_dim, - ) + dtype = _milvus_field_type(field) + if dtype == DataType.BINARY_VECTOR: + raise ValueError( + f"Field '{field.name}': Array(Bool) cannot be a vector field," + " Milvus binary vectors are not supported." + ) + nullable = _nullable_tag(field) + if nullable and ( + field.name in entity_columns + or field.name == partition_key + or dtype in MILVUS_VECTOR_TYPES + ): + raise ValueError( + f"Field '{field.name}' cannot be nullable: entity, partition" + " key and vector fields must always have a value." + ) + options: Dict[str, Any] = {"nullable": True} if nullable else {} + if dtype in MILVUS_VECTOR_TYPES: + fields.append( + FieldSchema( + name=field.name, + dtype=dtype, + dim=field.vector_length + or config.online_store.embedding_dim, ) - elif use_typed and dtype in MILVUS_NATIVE_NUMERIC_TYPES: - fields.append( - FieldSchema( - name=field.name, - dtype=dtype, + ) + elif use_typed and dtype in MILVUS_NATIVE_NUMERIC_TYPES: + fields.append(FieldSchema(name=field.name, dtype=dtype, **options)) + else: + if "max_length" in field.tags: + try: + field_max_length = int(field.tags["max_length"]) + except (ValueError, TypeError): + raise ValueError( + f"Field '{field.name}' has invalid max_length tag" + f" '{field.tags['max_length']}': must be an integer." ) - ) - else: - if "max_length" in field.tags: - try: - field_max_length = int(field.tags["max_length"]) - except (ValueError, TypeError): - raise ValueError( - f"Field '{field.name}' has invalid max_length tag" - f" '{field.tags['max_length']}': must be an integer." - ) - if not (1 <= field_max_length <= 65535): - raise ValueError( - f"Field '{field.name}' max_length tag must be" - f" between 1 and 65535, got {field_max_length}" - ) - else: - field_max_length = varchar_max_length - fields.append( - FieldSchema( - name=field.name, - dtype=DataType.VARCHAR, - max_length=field_max_length, + if not (1 <= field_max_length <= 65535): + raise ValueError( + f"Field '{field.name}' max_length tag must be" + f" between 1 and 65535, got {field_max_length}" ) + else: + field_max_length = varchar_max_length + fields.append( + FieldSchema( + name=field.name, + dtype=DataType.VARCHAR, + max_length=field_max_length, + **options, ) + ) has_vector_field = any( f.dtype in (DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR) for f in fields @@ -409,7 +423,6 @@ def _get_or_create_collection( dim=PLACEHOLDER_VECTOR_DIM, ) ) - partition_key = _partition_key_name(config.online_store, table) if partition_key: _mark_partition_key(fields, partition_key, table.name) schema = CollectionSchema( @@ -512,6 +525,9 @@ def online_write_batch( ), PLACEHOLDER_VECTOR_DIM, ) + nullable_fields = { + field["name"] for field in collection["fields"] if field.get("nullable") + } schema_internal_fields = {"event_ts", "created_ts"} collection_has_native_numerics = any( collection_field_types.get(name) in MILVUS_NATIVE_NUMERIC_TYPES @@ -528,17 +544,10 @@ def online_write_batch( created_ts_int = ( int(to_naive_utc(created_ts).timestamp() * 1e6) if created_ts else 0 ) - entity_dict = { - join_key: feast_value_type_to_python_type(value) - for join_key, value in zip( - entity_key.join_keys, entity_key.entity_values - ) - } - values_dict.update(entity_dict) + values_dict.update(zip(entity_key.join_keys, entity_key.entity_values)) values_dict = _extract_proto_values_to_dict( values_dict, vector_cols=vector_cols, - serialize_to_string=True, use_native_numeric_types=collection_has_native_numerics, ) @@ -563,6 +572,8 @@ def online_write_batch( field_type = collection_field_types.get(field, DataType.VARCHAR) if field == PLACEHOLDER_VECTOR_FIELD: single_entity_record[field] = [0.0] * placeholder_dim + elif field in nullable_fields: + single_entity_record[field] = None else: single_entity_record[field] = _default_for_milvus_type( field_type @@ -638,12 +649,8 @@ def online_read( # Map the features to their Feast types. feature_name_feast_primitive_type_map = { - f.name: f.dtype for f in table.features + f.name: f.dtype for f in list(table.schema) + list(table.features) } - if getattr(table, "write_to_online_store", False): - feature_name_feast_primitive_type_map.update( - {f.name: f.dtype for f in table.schema} - ) # Build a dictionary mapping composite key -> (res_ts, res) results_dict: Dict[ str, Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]] @@ -657,7 +664,6 @@ def online_read( res = {} res_ts = None for field in output_fields: - val = ValueProto() field_value = hit.get(field, None) if field_value is None and ":" in field: _, field_short = field.split(":", 1) @@ -669,57 +675,13 @@ def online_read( # We do not return the composite key value pass else: - feature_feast_primitive_type = ( + key_to_use = field.split(":", 1)[-1] if ":" in field else field + res[key_to_use] = _stored_value_to_proto( + field_value, feature_name_feast_primitive_type_map.get( field, PrimitiveFeastType.INVALID - ) + ), ) - feature_fv_dtype = from_feast_type(feature_feast_primitive_type) - proto_attr = VALUE_TYPE_TO_PROTO_VALUE_MAP.get(feature_fv_dtype) - if proto_attr: - if proto_attr == "bytes_val": - setattr(val, proto_attr, field_value.encode()) - elif proto_attr in [ - "int32_val", - "int64_val", - "float_val", - "double_val", - "string_val", - ]: - setattr( - val, - proto_attr, - type(getattr(val, proto_attr))(field_value), - ) - elif proto_attr in [ - "int32_list_val", - "int64_list_val", - "float_list_val", - "double_list_val", - ]: - getattr(val, proto_attr).val.extend(field_value) - elif proto_attr in [ - "map_val", - "map_list_val", - "struct_val", - "struct_list_val", - "json_list_val", - ]: - if isinstance(field_value, str) and field_value: - try: - proto_bytes = base64.b64decode(field_value) - val.ParseFromString(proto_bytes) - except Exception: - setattr(val, "string_val", field_value) - else: - setattr(val, proto_attr, field_value) - else: - raise ValueError( - f"Unsupported ValueType: {feature_feast_primitive_type} with feature view value {field_value} for feature {field} with value type {proto_attr}" - ) - # res[field] = val - key_to_use = field.split(":", 1)[-1] if ":" in field else field - res[key_to_use] = val results_dict[key] = (res_ts, res if res else None) # Map the results back into a list matching the original order of composite_keys. @@ -843,9 +805,7 @@ def retrieve_online_documents_v2( List of tuples containing the event timestamp, entity key, and feature values """ entity_name_feast_primitive_type_map = { - k.name: k.dtype - for k in list(table.entity_columns) + list(table.features) - if isinstance(k.dtype, PrimitiveFeastType) + k.name: k.dtype for k in list(table.schema) + list(table.features) } self.client = self._connect(config) collection_name = _table_id( @@ -1032,7 +992,6 @@ def _combine_exprs(*parts: Optional[str]) -> Optional[str]: else None ) for field in output_fields: - val = ValueProto() field_value = hit.get("entity", {}).get(field, None) # entity_key_proto = None if field in ["created_ts", "event_ts"]: @@ -1042,57 +1001,15 @@ def _combine_exprs(*parts: Optional[str]) -> Optional[str]: embedding ) res[ann_search_field] = serialized_embedding - elif ( - entity_name_feast_primitive_type_map.get( - field, PrimitiveFeastType.INVALID - ) - == PrimitiveFeastType.STRING - ): - res[field] = ValueProto(string_val=str(field_value)) - elif ( - entity_name_feast_primitive_type_map.get( - field, PrimitiveFeastType.INVALID - ) - == PrimitiveFeastType.BYTES - ): - try: - decoded_bytes = base64.b64decode(field_value) - res[field] = ValueProto(bytes_val=decoded_bytes) - except Exception: - res[field] = ValueProto(string_val=str(field_value)) - elif entity_name_feast_primitive_type_map.get( - field, PrimitiveFeastType.INVALID - ) in [ - PrimitiveFeastType.INT64, - PrimitiveFeastType.INT32, - ]: - res[field] = ValueProto(int64_val=int(field_value)) - elif entity_name_feast_primitive_type_map.get( - field, PrimitiveFeastType.INVALID - ) in [ - PrimitiveFeastType.FLOAT64, - PrimitiveFeastType.FLOAT32, - ]: - res[field] = ValueProto(double_val=float(field_value)) - elif ( - entity_name_feast_primitive_type_map.get( - field, PrimitiveFeastType.INVALID - ) - == PrimitiveFeastType.BOOL - ): - res[field] = ValueProto(bool_val=bool(field_value)) elif field == composite_key_name: pass - elif isinstance(field_value, bytes): - val.ParseFromString(field_value) - res[field] = val - elif isinstance(field_value, int): - res[field] = ValueProto(int64_val=field_value) - elif isinstance(field_value, float): - res[field] = ValueProto(double_val=field_value) else: - val.string_val = str(field_value) - res[field] = val + res[field] = _stored_value_to_proto( + field_value, + entity_name_feast_primitive_type_map.get( + field, PrimitiveFeastType.INVALID + ), + ) raw_distance = hit.get("distance", None) res["distance"] = ( ValueProto(float_val=raw_distance) @@ -1263,70 +1180,111 @@ def _default_for_milvus_type(dtype: DataType) -> Any: return _MILVUS_TYPE_DEFAULTS.get(dtype, "") +_NUMERIC_SCALAR_PROTO_TYPES = ( + "double_val", + "float_val", + "int32_val", + "int64_val", + "bool_val", + "unix_timestamp_val", +) + + def _extract_proto_values_to_dict( - input_dict: Dict[str, Any], + input_dict: Dict[str, ValueProto], vector_cols: List[str], - serialize_to_string: bool = False, use_native_numeric_types: bool = False, ) -> Dict[str, Any]: - numeric_vector_list_types = [ - k - for k in PROTO_VALUE_TO_VALUE_TYPE_MAP.keys() - if k is not None and ("list" in k or "set" in k) and "string" not in k - ] - numeric_types = [ - "double_val", - "float_val", - "int32_val", - "int64_val", - "bool_val", - ] - output_dict = {} - for feature_name, feature_values in input_dict.items(): - for proto_val_type in PROTO_VALUE_TO_VALUE_TYPE_MAP: - if not isinstance(feature_values, (int, float, str)): - if feature_values.HasField(proto_val_type): - if proto_val_type in numeric_vector_list_types: - if serialize_to_string and feature_name not in vector_cols: - vector_values = getattr( - feature_values, proto_val_type - ).SerializeToString() - else: - vector_values = getattr(feature_values, proto_val_type).val - else: - if ( - serialize_to_string - and proto_val_type - not in ["string_val", "bytes_val", "unix_timestamp_val"] - + numeric_types - ): - vector_values = base64.b64encode( - feature_values.SerializeToString() - ).decode("utf-8") - elif proto_val_type == "bytes_val": - byte_data = getattr(feature_values, proto_val_type) - vector_values = base64.b64encode(byte_data).decode("utf-8") - elif ( - use_native_numeric_types and proto_val_type in numeric_types - ): - vector_values = getattr(feature_values, proto_val_type) - else: - if not isinstance(feature_values, str): - vector_values = str( - getattr(feature_values, proto_val_type) - ) - else: - vector_values = getattr(feature_values, proto_val_type) - output_dict[feature_name] = vector_values - else: - if serialize_to_string: - if use_native_numeric_types and isinstance( - feature_values, (int, float) - ): - output_dict[feature_name] = feature_values - else: - if not isinstance(feature_values, str): - feature_values = str(feature_values) - output_dict[feature_name] = feature_values + """Convert the values of one row to what the collection stores. + A vector column gets its list of numbers. A numeric is stored natively or as + text, a string as is, bytes as base64 text. Every other value, such as a + list, a map or JSON, is stored as the base64 of its serialized ValueProto so + it comes back as written. A null value is left out: the caller writes None + or the column's default for it. + """ + output_dict: Dict[str, Any] = {} + for feature_name, value in input_dict.items(): + proto_val_type = value.WhichOneof("val") + if proto_val_type is None: + continue + stored = getattr(value, proto_val_type) + if feature_name in vector_cols: + output_dict[feature_name] = list(stored.val) + elif proto_val_type == "string_val": + output_dict[feature_name] = stored + elif proto_val_type == "bytes_val": + output_dict[feature_name] = base64.b64encode(stored).decode("utf-8") + elif proto_val_type in _NUMERIC_SCALAR_PROTO_TYPES: + output_dict[feature_name] = ( + stored if use_native_numeric_types else str(stored) + ) + else: + output_dict[feature_name] = base64.b64encode( + value.SerializeToString() + ).decode("utf-8") return output_dict + + +def _stored_value_to_proto(stored: Any, feast_type: Any) -> ValueProto: + """Rebuild the ValueProto of a feature from what the collection stores. + + The inverse of ``_extract_proto_values_to_dict``. None, and the empty text + that a collection without nullable columns stores for a missing value, are + null. + """ + val = ValueProto() + if stored is None: + return val + proto_attr = VALUE_TYPE_TO_PROTO_VALUE_MAP.get(from_feast_type(feast_type)) + if proto_attr is None: + # A column the feature view does not declare, for example an entity key. + if isinstance(stored, bool): + val.bool_val = stored + elif isinstance(stored, int): + val.int64_val = stored + elif isinstance(stored, float): + val.double_val = stored + else: + val.string_val = str(stored) + return val + if isinstance(stored, list): + getattr(val, proto_attr).val.extend(stored) + return val + if proto_attr == "string_val": + val.string_val = str(stored) + return val + if proto_attr == "bytes_val": + val.bytes_val = base64.b64decode(stored) + return val + if stored == "": + return val + if proto_attr == "bool_val": + val.bool_val = ( + stored if isinstance(stored, bool) else str(stored).lower() == "true" + ) + elif proto_attr in ("int32_val", "int64_val", "unix_timestamp_val"): + setattr(val, proto_attr, int(stored)) + elif proto_attr in ("float_val", "double_val"): + setattr(val, proto_attr, float(stored)) + else: + val.ParseFromString(base64.b64decode(stored)) + return val + + +def _milvus_field_type(field: Field) -> DataType: + """The Milvus type of a feature: a vector only for ``vector_index`` fields, + a native scalar where the collection stores them, VARCHAR for the rest.""" + if isinstance(field.dtype, Array) and not field.vector_index: + return DataType.VARCHAR + return FEAST_PRIMITIVE_TO_MILVUS_TYPE_MAPPING.get(field.dtype, DataType.VARCHAR) + + +def _nullable_tag(field: Field) -> bool: + value = field.tags.get("milvus.nullable", "false").lower() + if value not in ("true", "false"): + raise ValueError( + f"Field '{field.name}' has invalid milvus.nullable tag" + f" '{field.tags['milvus.nullable']}': must be 'true' or 'false'." + ) + return value == "true" 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 aceb5873e85..7831fc24bfb 100644 --- a/sdk/python/tests/integration/online_store/test_milvus_remote.py +++ b/sdk/python/tests/integration/online_store/test_milvus_remote.py @@ -25,9 +25,20 @@ from feast.filter_models import ComparisonFilter 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 StringList from feast.protos.feast.types.Value_pb2 import Value as ValueProto from feast.repo_config import RepoConfig -from feast.types import Array, Float32, Int64, String +from feast.types import ( + Array, + Bool, + Bytes, + Float32, + Float64, + Int64, + Json, + String, + UnixTimestamp, +) from feast.value_type import ValueType T = TypeVar("T") @@ -520,3 +531,49 @@ def test_online_delete(tmp_path: Path, project: str, store: MilvusOnlineStore) - _write_rows(store, config, fv, {1: _vector_rows()[1]}) rows = _read(store, config, fv, [1], ["city"]) assert rows[0] is not None and rows[0]["city"].string_val == "Paris" + + +@pytest.mark.parametrize("native", [False, True], ids=["varchar", "native_numerics"]) +def test_every_type_round_trips_and_nullable_columns_store_null( + tmp_path: Path, project: str, store: MilvusOnlineStore, native: bool +) -> None: + config = _repo_config( + tmp_path, + project, + enable_openai_compatible_store=native, + consistency_level="Strong", + ) + fv = FeatureView( + name="typed", + 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="flag", dtype=Bool), + Field(name="blob", dtype=Bytes), + Field(name="seen_at", dtype=UnixTimestamp), + Field(name="doc", dtype=Json), + Field(name="tags", dtype=Array(String)), + Field(name="score", dtype=Float64, tags={"milvus.nullable": "true"}), + ], + ) + values = { + "flag": ValueProto(bool_val=False), + "blob": ValueProto(bytes_val=b"\x00\xff"), + "seen_at": ValueProto(unix_timestamp_val=1_700_000_000), + "doc": ValueProto(json_val='{"a": [1, 2]}'), + "tags": ValueProto(string_list_val=StringList(val=["a", "b"])), + "score": ValueProto(double_val=2.5), + } + store.update(config, [], [fv], [], [], partial=False) + + _write_rows(store, config, fv, {1: values, 2: {**values, "score": ValueProto()}}) + rows = _read(store, config, fv, [1, 2], list(values)) + + assert rows[0] == values + assert rows[1] is not None and rows[1]["score"].WhichOneof("val") is None + assert rows[1]["tags"] == values["tags"] 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 0b04d823dce..f43776b1db2 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 @@ -20,9 +20,27 @@ MilvusOnlineStoreConfig, ) from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto +from feast.protos.feast.types.Value_pb2 import ( + FloatList, + Int64List, + StringList, +) from feast.protos.feast.types.Value_pb2 import Value as ValueProto from feast.repo_config import RepoConfig -from feast.types import Array, Float32, Int64, String +from feast.type_map import python_values_to_proto_values +from feast.types import ( + Array, + Bool, + Bytes, + Float32, + Float64, + Int32, + Int64, + Json, + Map, + String, + UnixTimestamp, +) from feast.value_type import ValueType MILVUS_MODULE = "feast.infra.online_stores.milvus_online_store.milvus" @@ -946,3 +964,274 @@ def test_online_delete_with_no_entity_keys_sends_nothing( ) mock_client_cls.assert_not_called() + + +def _typed_feature_view(name: str, dtype: Any, **field_kwargs: Any) -> FeatureView: + return FeatureView( + name=name, + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="value", dtype=dtype, **field_kwargs), + ], + ) + + +_TYPED_VALUES: List[Tuple[Any, ValueProto]] = [ + (Bool, ValueProto(bool_val=False)), + (Int32, ValueProto(int32_val=-7)), + (Int64, ValueProto(int64_val=1 << 40)), + (Float32, ValueProto(float_val=0.1)), + (Float64, ValueProto(double_val=2.5)), + (String, ValueProto(string_val="True")), + (Bytes, ValueProto(bytes_val=b"\x00\xff")), + (Bytes, ValueProto(bytes_val=b"")), + (UnixTimestamp, ValueProto(unix_timestamp_val=1_700_000_000)), + (Json, ValueProto(json_val='{"a": [1, 2]}')), + (Array(String), ValueProto(string_list_val=StringList(val=["a", "b"]))), + (Array(Int64), ValueProto(int64_list_val=Int64List(val=[1, 2, 3]))), + (Map, python_values_to_proto_values([{"a": "x", "n": 1}], ValueType.MAP)[0]), +] + + +@pytest.mark.parametrize( + "online_store", + [{}, {"enable_openai_compatible_store": True}], + ids=["varchar", "native_numerics"], +) +def test_every_feast_type_round_trips( + tmp_path: Path, online_store: Dict[str, Any] +) -> None: + config = _lite_config(tmp_path, **online_store) + store = MilvusOnlineStore() + + for index, (dtype, value) in enumerate(_TYPED_VALUES): + fv = _typed_feature_view(f"typed_{index}", dtype) + store.update(config, [], [fv], [], [], partial=False) + _write_rows(store, config, fv, {1: {"value": value}}) + rows = _read(store, config, fv, [1], ["value"]) + assert rows[0] is not None and rows[0]["value"] == value, dtype + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_column_types_follow_vector_index_and_vector_length( + mock_client_cls: MagicMock, +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + fv = FeatureView( + name="catalog", + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field( + name="embedding", + dtype=Array(Float32), + vector_index=True, + vector_length=3, + ), + Field(name="history", dtype=Array(Float32)), + Field(name="seen_at", dtype=UnixTimestamp), + ], + ) + + for native, seen_at_type in [(False, DataType.VARCHAR), (True, DataType.INT64)]: + MilvusOnlineStore()._get_or_create_collection( + _mock_config(embedding_dim=2, enable_openai_compatible_store=native), fv + ) + schema = mock_client.create_collection.call_args.kwargs["schema"] + fields = {field.name: field for field in schema.fields} + assert fields["embedding"].dtype == DataType.FLOAT_VECTOR + assert fields["embedding"].params["dim"] == 3 + assert fields["history"].dtype == DataType.VARCHAR + assert fields["seen_at"].dtype == seen_at_type + assert PLACEHOLDER_VECTOR_FIELD not in fields + + +def test_missing_value_in_a_text_column_reads_as_null(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(), "city": ValueProto(string_val="Paris")}}, + ) + rows = _read(store, config, fv, [1], ["trips_today", "city"]) + + assert rows[0] is not None + assert rows[0]["trips_today"].WhichOneof("val") is None + assert rows[0]["city"].string_val == "Paris" + + +def test_nullable_tag_stores_null_instead_of_the_column_default( + tmp_path: Path, +) -> None: + config = _lite_config(tmp_path, enable_openai_compatible_store=True) + fv = FeatureView( + name="driver_stats", + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="trips_today", dtype=Float32, tags={"milvus.nullable": "true"}), + Field(name="rating", dtype=Float32), + ], + ) + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + assert store.client is not None + description = store.client.describe_collection("test_milvus_driver_stats") + nullable = {f["name"]: f.get("nullable", False) for f in description["fields"]} + assert nullable["trips_today"] and not nullable["rating"] + + _write_rows( + store, config, fv, {1: {"trips_today": ValueProto(), "rating": ValueProto()}} + ) + rows = _read(store, config, fv, [1], ["trips_today", "rating"]) + + assert rows[0] is not None + assert rows[0]["trips_today"].WhichOneof("val") is None + # A column that is not nullable keeps the type's default. + assert rows[0]["rating"].float_val == 0.0 + + +@pytest.mark.parametrize( + "field, match", + [ + ( + Field(name="driver_id", dtype=Int64, tags={"milvus.nullable": "true"}), + "cannot be nullable", + ), + ( + Field( + name="embedding", + dtype=Array(Float32), + vector_index=True, + tags={"milvus.nullable": "true"}, + ), + "cannot be nullable", + ), + ( + Field(name="city", dtype=String, tags={"milvus.nullable": "maybe"}), + "invalid milvus.nullable tag", + ), + ], + ids=["entity", "vector", "invalid"], +) +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_nullable_tag_is_rejected_where_a_value_is_required( + mock_client_cls: MagicMock, field: Field, match: str +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + schema = [Field(name="driver_id", dtype=Int64)] if field.name != "driver_id" else [] + fv = FeatureView( + name="driver_stats", + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=schema + [field], + ) + + with pytest.raises(ValueError, match=match): + MilvusOnlineStore()._get_or_create_collection(_mock_config(), fv) + + mock_client.create_collection.assert_not_called() + + +def test_search_hits_decode_values_like_reads(tmp_path: Path) -> None: + config = _lite_config(tmp_path) + fv = FeatureView( + name="documents", + entities=[_driver_entity()], + 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="flag", dtype=Bool), + Field(name="blob", dtype=Bytes), + Field(name="doc", dtype=Json), + Field(name="tags", dtype=Array(String)), + Field(name="labels", dtype=Map), + ], + ) + values = { + "embedding": ValueProto(float_list_val=FloatList(val=[1.0, 0.0])), + "flag": ValueProto(bool_val=False), + "blob": ValueProto(bytes_val=b"\x00\xff"), + "doc": ValueProto(json_val='{"a": 1}'), + "tags": ValueProto(string_list_val=StringList(val=["a", "b"])), + "labels": python_values_to_proto_values([{"a": "x"}], ValueType.MAP)[0], + } + features = ["flag", "blob", "doc", "tags", "labels"] + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + _write_rows(store, config, fv, {1: values}) + + hits = store.retrieve_online_documents_v2(config, fv, features, [1.0, 0.0], top_k=1) + + assert len(hits) == 1 + _, _, hit = hits[0] + assert hit is not None + expected = {name: values[name] for name in features} + assert {name: hit[name] for name in features} == expected + assert _read(store, config, fv, [1], features) == [expected] + + +def test_entity_columns_use_the_same_encoding_as_features(tmp_path: Path) -> None: + config = _lite_config(tmp_path) + fv = FeatureView( + name="devices", + entities=[ + Entity(name="device", join_keys=["device"], value_type=ValueType.BYTES), + Entity( + name="seen", join_keys=["seen"], value_type=ValueType.UNIX_TIMESTAMP + ), + ], + ttl=timedelta(days=1), + schema=[ + Field(name="device", dtype=Bytes), + Field(name="seen", dtype=UnixTimestamp), + Field(name="city", dtype=String), + ], + ) + key = EntityKeyProto( + join_keys=["device", "seen"], + entity_values=[ + ValueProto(bytes_val=b"\x00\xff"), + ValueProto(unix_timestamp_val=1_700_000_000), + ], + ) + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + now = datetime.now(timezone.utc) + store.online_write_batch( + config, fv, [(key, {"city": ValueProto(string_val="Oslo")}, now, now)], None + ) + + _, values = store.online_read(config, fv, [key], ["device", "seen", "city"])[0] + + assert values == { + "device": ValueProto(bytes_val=b"\x00\xff"), + "seen": ValueProto(unix_timestamp_val=1_700_000_000), + "city": ValueProto(string_val="Oslo"), + } + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_bool_array_cannot_be_a_vector_field(mock_client_cls: MagicMock) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + fv = _typed_feature_view("flags", Array(Bool), vector_index=True) + + with pytest.raises(ValueError, match="binary vectors are not supported"): + MilvusOnlineStore()._get_or_create_collection(_mock_config(), fv) + + mock_client.create_collection.assert_not_called() From d825b1f146d3000affe8339ca54888c24d209363 Mon Sep 17 00:00:00 2001 From: jiwidi Date: Mon, 9 Nov 2026 12:03:37 +0100 Subject: [PATCH 2/2] feat: Add native complex types and scalar index tags to the Milvus online store With enable_openai_compatible_store the Milvus online store stored numeric features as native columns, but arrays and Json values were still base64 text, so a filter could not reach them and Milvus could not validate them. With the flag, an array of scalars without vector_index is now an ARRAY column of the element type, with milvus.max_capacity elements at most, and a Json value, or an array of them, is a JSON column. Both columns are nullable unless the field says otherwise, so a missing value stays null. A Json value must be an object or an array, because PyMilvus cannot store a top-level string, number or bool in a JSON column, and JSON null is stored as a null column value. Map and Struct values stay serialized, because JSON cannot hold their nested bytes, timestamps or empty typed lists. The column types of an existing collection decide how a row is written and read, so collections created before this change keep working. Filter keys can address a JSON path or an array element, for example attributes["price"] or tags[0]. Field tags declare scalar indexes, which Feast creates with the collection: milvus.index names the index type of a scalar column, milvus.index_params passes its parameters and milvus.json_indexes lists JSON path indexes of a JSON column. For an existing collection without them Feast logs a warning, as it does for a missing partition key. Signed-off-by: jiwidi --- docs/reference/online-stores/milvus.md | 56 ++- .../milvus_online_store/milvus.py | 331 +++++++++++++---- .../online_store/test_milvus_remote.py | 98 ++++- .../online_store/test_milvus_online_store.py | 337 +++++++++++++++++- 4 files changed, 744 insertions(+), 78 deletions(-) diff --git a/docs/reference/online-stores/milvus.md b/docs/reference/online-stores/milvus.md index 72fd434390b..c893f700c44 100644 --- a/docs/reference/online-stores/milvus.md +++ b/docs/reference/online-stores/milvus.md @@ -101,7 +101,7 @@ online_store: | `partition_key_isolation` | unset | Enables partition key isolation on a new collection that has a partition key. When unset, Milvus uses its default. | | `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. | +| `enable_openai_compatible_store` | `false` | Store numeric, array, `Json`, `Map` and `Struct` features as native Milvus types. See [Field types](#field-types). | The full set of configuration options is available in [MilvusOnlineStoreConfig](https://rtd.feast.dev/en/latest/#feast.infra.online_stores.milvus.MilvusOnlineStoreConfig). @@ -237,10 +237,32 @@ type. | `UnixTimestamp` | `VARCHAR` holding the seconds as text | `INT64` | | `Bytes` | `VARCHAR` holding base64 | `VARCHAR` holding base64 | | `Array` with `vector_index=True` | `FLOAT_VECTOR` with the field's `vector_length`, or `embedding_dim` when it is unset | the same | -| Every other type, such as an array without `vector_index`, `Json`, `Map` or `Struct` | `VARCHAR` holding the serialized value | the same | +| `Array` of `String`, `Bool`, `Int32`, `Int64`, `Float32`, `Float64` or `UnixTimestamp` without `vector_index` | `VARCHAR` holding the serialized value | `ARRAY` of the element type, with at most `milvus.max_capacity` elements. The default and the maximum are 4096 | +| `Json` and `Array(Json)` | `VARCHAR` holding the serialized value | `JSON` | +| Every other type, including `Map` and `Struct` | `VARCHAR` holding the serialized value | the same | Filters apply to `VARCHAR` and native columns. A column that holds a serialized value can be read -but not filtered on. +but not filtered on. A filter key can address a JSON path or an array element with Milvus syntax: + +```python +ComparisonFilter(type="gt", key='attributes["price"]', value=100) +ComparisonFilter(type="eq", key="tags[0]", value="sale") +``` + +A `Json` value in a `JSON` column must be an object or an array: a top-level string, number or +boolean is rejected, and `null` is stored as a null column value and reads as a missing value. The +value comes back as the JSON text of the stored document, so its formatting is normalized. `Map` and +`Struct` values stay serialized, because JSON cannot hold their nested bytes, timestamps or empty +typed lists. `JSON` and `ARRAY` columns are nullable unless the field has `milvus.nullable: "false"`. + +{% hint style="warning" %} +`enable_openai_compatible_store` only applies when Feast creates a collection. Feast detects the +column types of an existing collection, so reads and writes keep working whichever way it was +created. `feast teardown` drops the collections of every feature view in the project, online reads +fail until materialization finishes, and rows that exist only in the online store are lost. To +migrate without a teardown, add a copy of the feature view under a new name, materialize it, move +readers to it, then remove the old view. +{% endhint %} `Array(Bool)` cannot be a vector field: Milvus binary vectors are not supported. @@ -256,6 +278,34 @@ Field(name="rating", dtype=Float32, tags={"milvus.nullable": "true"}) The tag applies when Feast creates the collection, and it needs Milvus 2.5 or later. Entity, partition key and vector fields cannot be nullable. +## Scalar indexes + +A filter on a scalar column scans the collection unless the column has an index. Declare indexes +with field tags, and Feast creates them with the collection: + +```python +Field(name="brand_id", dtype=String, tags={"milvus.index": "INVERTED"}), +Field(name="price", dtype=Float64, tags={"milvus.index": "STL_SORT"}), +Field( + name="attributes", + dtype=Json, + tags={ + "milvus.json_indexes": '[{"json_path": "attributes[\\"price\\"]", "json_cast_type": "double"}]' + }, +), +``` + +`milvus.index` names a scalar index type the server supports, such as `INVERTED`, `BITMAP`, +`STL_SORT`, `Trie` or `AUTOINDEX`, and `milvus.index_params` passes a JSON object of parameters. +`milvus.json_indexes` is a JSON list of index definitions for paths of a `JSON` column, each with a +`json_path`, a `json_cast_type` and an optional `index_type` that defaults to `INVERTED`. It needs +native types and a Milvus server with JSON path indexes. Vector indexes come from `index_type` and +`index_params` in the store config. + +Indexes only apply when Feast creates a collection. For an existing collection without them, Feast +logs a warning. To add them, run `feast teardown` and `feast apply`, then materialize again, or use +the staged cutover described under [Field types](#field-types). + ## 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 5d63f9029ed..2235feeed08 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,4 +1,5 @@ import base64 +import json import logging import re from datetime import datetime @@ -116,6 +117,22 @@ DataType.BOOL, } MILVUS_VECTOR_TYPES = {DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR} +# Feast types stored as a JSON column when native types are enabled. Map and +# Struct stay serialized: JSON cannot hold their nested bytes, timestamps or +# empty typed lists. +_JSON_VALUE_TYPES = {ValueType.JSON, ValueType.JSON_LIST} +# Element types of an ARRAY column when native types are enabled. +_ARRAY_ELEMENT_TYPES: Dict[Any, DataType] = { + PrimitiveFeastType.STRING: DataType.VARCHAR, + PrimitiveFeastType.BOOL: DataType.BOOL, + PrimitiveFeastType.INT32: DataType.INT32, + PrimitiveFeastType.INT64: DataType.INT64, + PrimitiveFeastType.FLOAT32: DataType.FLOAT, + PrimitiveFeastType.FLOAT64: DataType.DOUBLE, + PrimitiveFeastType.UNIX_TIMESTAMP: DataType.INT64, +} +MAX_ARRAY_CAPACITY = 4096 +_FILTER_KEY = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*(\[("[^"\\]*"|\d+)\])*$') # Milvus requires every collection to have a vector field, so feature views # without one get a small placeholder vector. Milvus servers reject vectors @@ -167,9 +184,10 @@ def translate(self, filters: FilterType) -> Optional[str]: def translate_comparison(self, f: ComparisonFilter) -> str: key, value, op_type = f.key, f.value, f.type - if not re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", key): + if not _FILTER_KEY.match(key): raise ValueError( - f"Invalid filter key: {key!r}. Keys must be valid field identifiers." + f"Invalid filter key: {key!r}. Keys must be field identifiers, with" + ' optional JSON or array subscripts such as doc["a"] or tags[0].' ) milvus_ops = {"gt": ">", "gte": ">=", "lt": "<", "lte": "<="} @@ -358,59 +376,36 @@ def _get_or_create_collection( use_typed = config.online_store.enable_openai_compatible_store partition_key = _partition_key_name(config.online_store, table) entity_columns = {column.name for column in table.entity_columns} + scalar_indexes: List[Dict[str, Any]] = [] for field in fields_to_add: - dtype = _milvus_field_type(field) - if dtype == DataType.BINARY_VECTOR: + spec = _column_spec( + field, + use_typed, + varchar_max_length, + config.online_store.embedding_dim, + ) + if spec["dtype"] == DataType.BINARY_VECTOR: raise ValueError( f"Field '{field.name}': Array(Bool) cannot be a vector field," " Milvus binary vectors are not supported." ) nullable = _nullable_tag(field) + if nullable is None: + nullable = spec.get("nullable", False) if nullable and ( field.name in entity_columns or field.name == partition_key - or dtype in MILVUS_VECTOR_TYPES + or spec["dtype"] in MILVUS_VECTOR_TYPES ): raise ValueError( f"Field '{field.name}' cannot be nullable: entity, partition" " key and vector fields must always have a value." ) - options: Dict[str, Any] = {"nullable": True} if nullable else {} - if dtype in MILVUS_VECTOR_TYPES: - fields.append( - FieldSchema( - name=field.name, - dtype=dtype, - dim=field.vector_length - or config.online_store.embedding_dim, - ) - ) - elif use_typed and dtype in MILVUS_NATIVE_NUMERIC_TYPES: - fields.append(FieldSchema(name=field.name, dtype=dtype, **options)) - else: - if "max_length" in field.tags: - try: - field_max_length = int(field.tags["max_length"]) - except (ValueError, TypeError): - raise ValueError( - f"Field '{field.name}' has invalid max_length tag" - f" '{field.tags['max_length']}': must be an integer." - ) - if not (1 <= field_max_length <= 65535): - raise ValueError( - f"Field '{field.name}' max_length tag must be" - f" between 1 and 65535, got {field_max_length}" - ) - else: - field_max_length = varchar_max_length - fields.append( - FieldSchema( - name=field.name, - dtype=DataType.VARCHAR, - max_length=field_max_length, - **options, - ) - ) + spec.pop("nullable", None) + if nullable: + spec["nullable"] = True + scalar_indexes.extend(_scalar_index_specs(field, spec["dtype"])) + fields.append(FieldSchema(name=field.name, **spec)) has_vector_field = any( f.dtype in (DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR) for f in fields @@ -462,6 +457,8 @@ def _get_or_create_collection( index_type="FLAT", index_name=f"vector_index_{vector_field.name}", ) + for scalar_index in scalar_indexes: + index_params.add_index(**scalar_index) # 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. @@ -475,6 +472,11 @@ def _get_or_create_collection( ) else: self._ensure_loaded(collection_name) + _warn_if_scalar_indexes_missing( + self.client, + 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( @@ -509,7 +511,6 @@ def online_write_batch( ) -> None: self.client = self._connect(config) collection = self._get_or_create_collection(config, table) - vector_cols = [f.name for f in table.features if f.vector_index] entity_batch_to_insert = [] unique_entities: dict[str, dict[str, Any]] = {} required_fields = {field["name"] for field in collection["fields"]} @@ -528,11 +529,6 @@ def online_write_batch( nullable_fields = { field["name"] for field in collection["fields"] if field.get("nullable") } - schema_internal_fields = {"event_ts", "created_ts"} - collection_has_native_numerics = any( - collection_field_types.get(name) in MILVUS_NATIVE_NUMERIC_TYPES - for name in required_fields - schema_internal_fields - ) for entity_key, values_dict, timestamp, created_ts in data: entity_key_str = serialize_entity_key( entity_key, @@ -546,9 +542,7 @@ def online_write_batch( ) values_dict.update(zip(entity_key.join_keys, entity_key.entity_values)) values_dict = _extract_proto_values_to_dict( - values_dict, - vector_cols=vector_cols, - use_native_numeric_types=collection_has_native_numerics, + values_dict, collection_field_types ) # Remove timestamp fields that are handled separately to avoid conflicts @@ -576,7 +570,7 @@ def online_write_batch( single_entity_record[field] = None else: single_entity_record[field] = _default_for_milvus_type( - field_type + field, field_type ) # Keep one row per entity: the latest event timestamp wins, then the # latest created timestamp, then the last row of the batch. @@ -608,6 +602,7 @@ def online_read( config.project, table, config.registry.enable_online_feature_view_versioning ) collection = self._get_or_create_collection(config, table) + column_types = {field["name"]: field["type"] for field in collection["fields"]} composite_key_name = _get_composite_key_name(table) @@ -681,6 +676,7 @@ def online_read( feature_name_feast_primitive_type_map.get( field, PrimitiveFeastType.INVALID ), + column_types.get(key_to_use), ) results_dict[key] = (res_ts, res if res else None) @@ -979,6 +975,7 @@ def _combine_exprs(*parts: Optional[str]) -> Optional[str]: "Either vector_enabled must be True for embedding search or query_string must be provided for keyword search" ) + column_types = {field["name"]: field["type"] for field in collection["fields"]} result_list = [] for hits in results: for hit in hits: @@ -1009,6 +1006,7 @@ def _combine_exprs(*parts: Optional[str]) -> Optional[str]: entity_name_feast_primitive_type_map.get( field, PrimitiveFeastType.INVALID ), + column_types.get(field), ) raw_distance = hit.get("distance", None) res["distance"] = ( @@ -1176,7 +1174,12 @@ def _get_composite_key_name(table: FeatureView) -> str: } -def _default_for_milvus_type(dtype: DataType) -> Any: +def _default_for_milvus_type(field_name: str, dtype: DataType) -> Any: + if dtype in (DataType.JSON, DataType.ARRAY): + raise ValueError( + f"Feature '{field_name}' has no value and its column cannot be null:" + " give it a value or remove the milvus.nullable tag" + ) return _MILVUS_TYPE_DEFAULTS.get(dtype, "") @@ -1191,34 +1194,35 @@ def _default_for_milvus_type(dtype: DataType) -> Any: def _extract_proto_values_to_dict( - input_dict: Dict[str, ValueProto], - vector_cols: List[str], - use_native_numeric_types: bool = False, + input_dict: Dict[str, ValueProto], column_types: Dict[str, DataType] ) -> Dict[str, Any]: - """Convert the values of one row to what the collection stores. + """Convert the values of one row to what each column stores. - A vector column gets its list of numbers. A numeric is stored natively or as - text, a string as is, bytes as base64 text. Every other value, such as a - list, a map or JSON, is stored as the base64 of its serialized ValueProto so - it comes back as written. A null value is left out: the caller writes None - or the column's default for it. + A vector or ARRAY column gets a list, a JSON column the Python value and a + native scalar column the number or bool. A VARCHAR column gets text: the + string, a number as text, bytes as base64, and every other value as the + base64 of its serialized ValueProto, so it comes back as written. A null + value is left out: the caller writes None or the column's default for it. """ output_dict: Dict[str, Any] = {} for feature_name, value in input_dict.items(): + column_type = column_types.get(feature_name) proto_val_type = value.WhichOneof("val") if proto_val_type is None: continue stored = getattr(value, proto_val_type) - if feature_name in vector_cols: + if column_type in MILVUS_VECTOR_TYPES or column_type == DataType.ARRAY: output_dict[feature_name] = list(stored.val) + elif column_type == DataType.JSON: + output_dict[feature_name] = _json_column_value(feature_name, value) + elif column_type in MILVUS_NATIVE_NUMERIC_TYPES: + output_dict[feature_name] = stored elif proto_val_type == "string_val": output_dict[feature_name] = stored elif proto_val_type == "bytes_val": output_dict[feature_name] = base64.b64encode(stored).decode("utf-8") elif proto_val_type in _NUMERIC_SCALAR_PROTO_TYPES: - output_dict[feature_name] = ( - stored if use_native_numeric_types else str(stored) - ) + output_dict[feature_name] = str(stored) else: output_dict[feature_name] = base64.b64encode( value.SerializeToString() @@ -1226,8 +1230,10 @@ def _extract_proto_values_to_dict( return output_dict -def _stored_value_to_proto(stored: Any, feast_type: Any) -> ValueProto: - """Rebuild the ValueProto of a feature from what the collection stores. +def _stored_value_to_proto( + stored: Any, feast_type: Any, column_type: Optional[DataType] = None +) -> ValueProto: + """Rebuild the ValueProto of a feature from what its column stores. The inverse of ``_extract_proto_values_to_dict``. None, and the empty text that a collection without nullable columns stores for a missing value, are @@ -1236,7 +1242,8 @@ def _stored_value_to_proto(stored: Any, feast_type: Any) -> ValueProto: val = ValueProto() if stored is None: return val - proto_attr = VALUE_TYPE_TO_PROTO_VALUE_MAP.get(from_feast_type(feast_type)) + value_type = from_feast_type(feast_type) + proto_attr = VALUE_TYPE_TO_PROTO_VALUE_MAP.get(value_type) if proto_attr is None: # A column the feature view does not declare, for example an entity key. if isinstance(stored, bool): @@ -1248,7 +1255,14 @@ def _stored_value_to_proto(stored: Any, feast_type: Any) -> ValueProto: else: val.string_val = str(stored) return val + if column_type == DataType.JSON: + if value_type == ValueType.JSON_LIST: + val.json_list_val.val.extend(json.dumps(item) for item in stored) + else: + val.json_val = json.dumps(stored) + return val if isinstance(stored, list): + getattr(val, proto_attr).SetInParent() getattr(val, proto_attr).val.extend(stored) return val if proto_attr == "string_val": @@ -1272,16 +1286,189 @@ def _stored_value_to_proto(stored: Any, feast_type: Any) -> ValueProto: return val +def _json_column_value(feature_name: str, value: ValueProto) -> Any: + """The Python value that PyMilvus stores in a JSON column. + + PyMilvus 3.0 stores dicts and lists as they are, turns a top-level JSON + string into text that Milvus cannot read back and rejects a top-level + number or bool, so only objects and arrays are accepted. JSON null is + stored as a NULL column value. + """ + if value.WhichOneof("val") == "json_list_val": + return [json.loads(item) for item in value.json_list_val.val] + try: + document = json.loads(value.json_val) + except ValueError as error: + raise ValueError(f"Feature '{feature_name}' is not valid JSON: {error}") + if document is None or isinstance(document, (dict, list)): + return document + raise ValueError( + f"Feature '{feature_name}': a Milvus JSON column holds an object or an" + f" array, not a top-level {type(document).__name__}" + ) + + def _milvus_field_type(field: Field) -> DataType: - """The Milvus type of a feature: a vector only for ``vector_index`` fields, - a native scalar where the collection stores them, VARCHAR for the rest.""" + """The Milvus type of a feature without native types: a vector only for + ``vector_index`` fields, a numeric type where the store keeps them native, + VARCHAR for the rest.""" if isinstance(field.dtype, Array) and not field.vector_index: return DataType.VARCHAR return FEAST_PRIMITIVE_TO_MILVUS_TYPE_MAPPING.get(field.dtype, DataType.VARCHAR) -def _nullable_tag(field: Field) -> bool: - value = field.tags.get("milvus.nullable", "false").lower() +def _column_spec( + field: Field, native: bool, varchar_max_length: int, embedding_dim: Optional[int] +) -> Dict[str, Any]: + """The FieldSchema arguments of a feature's column. + + A ``vector_index`` field is a vector. With native types, scalars get their + own type, arrays of scalars become ARRAY and Json, Map and Struct values + become JSON. Everything else is VARCHAR: text, base64 bytes or a + serialized value. + """ + dtype = _milvus_field_type(field) + if dtype in MILVUS_VECTOR_TYPES: + return {"dtype": dtype, "dim": field.vector_length or embedding_dim} + max_length = _max_length_tag(field, varchar_max_length) + if native: + if from_feast_type(field.dtype) in _JSON_VALUE_TYPES: + return {"dtype": DataType.JSON, "nullable": True} + if isinstance(field.dtype, Array): + element = _ARRAY_ELEMENT_TYPES.get(field.dtype.base_type) + if element is not None: + spec: Dict[str, Any] = { + "dtype": DataType.ARRAY, + "element_type": element, + "max_capacity": _max_capacity_tag(field), + "nullable": True, + } + if element == DataType.VARCHAR: + spec["max_length"] = max_length + return spec + elif dtype in MILVUS_NATIVE_NUMERIC_TYPES: + return {"dtype": dtype} + return {"dtype": DataType.VARCHAR, "max_length": max_length} + + +def _max_length_tag(field: Field, default: int) -> int: + if "max_length" not in field.tags: + return default + try: + max_length = int(field.tags["max_length"]) + except (ValueError, TypeError): + raise ValueError( + f"Field '{field.name}' has invalid max_length tag" + f" '{field.tags['max_length']}': must be an integer." + ) + if not (1 <= max_length <= 65535): + raise ValueError( + f"Field '{field.name}' max_length tag must be" + f" between 1 and 65535, got {max_length}" + ) + return max_length + + +def _max_capacity_tag(field: Field) -> int: + value = field.tags.get("milvus.max_capacity", str(MAX_ARRAY_CAPACITY)) + try: + capacity = int(value) + except (ValueError, TypeError): + raise ValueError( + f"Field '{field.name}' has invalid milvus.max_capacity tag" + f" '{value}': must be an integer." + ) + if not (1 <= capacity <= MAX_ARRAY_CAPACITY): + raise ValueError( + f"Field '{field.name}' milvus.max_capacity tag must be" + f" between 1 and {MAX_ARRAY_CAPACITY}, got {capacity}" + ) + return capacity + + +def _json_tag(field: Field, tag: str, expected: type) -> Any: + if tag not in field.tags: + return None + try: + value = json.loads(field.tags[tag]) + except ValueError: + value = None + if not isinstance(value, expected): + raise ValueError( + f"Field '{field.name}' tag {tag} must be a JSON {expected.__name__}," + f" got {field.tags[tag]!r}" + ) + return value + + +def _scalar_index_specs(field: Field, dtype: DataType) -> List[Dict[str, Any]]: + """The indexes that the ``milvus.index`` and ``milvus.json_indexes`` tags declare.""" + specs: List[Dict[str, Any]] = [] + index_type = field.tags.get("milvus.index") + params = _json_tag(field, "milvus.index_params", dict) + if params is not None and index_type is None: + raise ValueError( + f"Field '{field.name}' has a milvus.index_params tag without milvus.index" + ) + if index_type is not None: + if dtype in MILVUS_VECTOR_TYPES: + raise ValueError( + f"Field '{field.name}' is a vector: set its index with index_type" + " and index_params in the online store config, not with a tag" + ) + specs.append( + { + "field_name": field.name, + "index_type": index_type, + "index_name": f"scalar_index_{field.name}", + "params": params or {}, + } + ) + json_indexes = _json_tag(field, "milvus.json_indexes", list) + if json_indexes: + if dtype != DataType.JSON: + raise ValueError( + f"Field '{field.name}' has a milvus.json_indexes tag but is not" + " stored as JSON" + ) + for position, json_index in enumerate(json_indexes): + if not isinstance(json_index, dict) or "json_path" not in json_index: + raise ValueError( + f"Field '{field.name}' milvus.json_indexes entries must be" + " objects with a json_path" + ) + json_params = dict(json_index) + specs.append( + { + "field_name": field.name, + "index_type": json_params.pop("index_type", "INVERTED"), + "index_name": f"json_index_{field.name}_{position}", + "params": json_params, + } + ) + return specs + + +def _warn_if_scalar_indexes_missing( + client: MilvusClient, collection_name: str, index_names: List[str] +) -> None: + if not index_names: + return + missing = sorted(set(index_names) - set(client.list_indexes(collection_name))) + if missing: + logger.warning( + "Collection '%s' does not have the indexes %s that field tags declare. " + "Indexes only apply when a collection is created: run `feast teardown` " + "and `feast apply`, then materialize again to use them.", + collection_name, + missing, + ) + + +def _nullable_tag(field: Field) -> Optional[bool]: + if "milvus.nullable" not in field.tags: + return None + value = field.tags["milvus.nullable"].lower() if value not in ("true", "false"): raise ValueError( f"Field '{field.name}' has invalid milvus.nullable tag" 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 7831fc24bfb..82cbbc30eb8 100644 --- a/sdk/python/tests/integration/online_store/test_milvus_remote.py +++ b/sdk/python/tests/integration/online_store/test_milvus_remote.py @@ -25,9 +25,10 @@ from feast.filter_models import ComparisonFilter 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 StringList +from feast.protos.feast.types.Value_pb2 import FloatList, Int64List, StringList from feast.protos.feast.types.Value_pb2 import Value as ValueProto from feast.repo_config import RepoConfig +from feast.type_map import python_values_to_proto_values from feast.types import ( Array, Bool, @@ -36,6 +37,7 @@ Float64, Int64, Json, + Map, String, UnixTimestamp, ) @@ -577,3 +579,97 @@ def test_every_type_round_trips_and_nullable_columns_store_null( assert rows[0] == values assert rows[1] is not None and rows[1]["score"].WhichOneof("val") is None assert rows[1]["tags"] == values["tags"] + + +def test_native_complex_types_filters_and_tag_indexes( + tmp_path: Path, project: str, store: MilvusOnlineStore +) -> None: + config = _repo_config( + tmp_path, + project, + enable_openai_compatible_store=True, + consistency_level="Strong", + ) + fv = FeatureView( + name="products", + 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="brand", dtype=String, tags={"milvus.index": "INVERTED"}), + Field( + name="attributes", + dtype=Json, + tags={ + "milvus.json_indexes": ( + '[{"json_path": "attributes[\\"price\\"]",' + ' "json_cast_type": "double"}]' + ) + }, + ), + Field(name="labels", dtype=Map), + Field(name="tags", dtype=Array(String), tags={"milvus.max_capacity": "8"}), + Field(name="counts", dtype=Array(Int64), tags={"milvus.nullable": "true"}), + ], + ) + rows = { + 1: { + "embedding": ValueProto(float_list_val=FloatList(val=[1.0, 0.0])), + "brand": ValueProto(string_val="acme"), + "attributes": ValueProto(json_val='{"price": 10, "color": "red"}'), + "labels": python_values_to_proto_values( + [{"a": "x", "n": 1}], ValueType.MAP + )[0], + "tags": ValueProto(string_list_val=StringList(val=["red", "sale"])), + "counts": ValueProto(int64_list_val=Int64List(val=[1, 2, 3])), + }, + 2: { + "embedding": ValueProto(float_list_val=FloatList(val=[0.0, 1.0])), + "brand": ValueProto(string_val="globex"), + "attributes": ValueProto(json_val='{"price": 50}'), + "labels": python_values_to_proto_values([{"a": "y"}], ValueType.MAP)[0], + "tags": ValueProto(string_list_val=StringList(val=[])), + "counts": ValueProto(), + }, + } + store.update(config, [], [fv], [], [], partial=False) + assert store.client is not None + indexes = set(store.client.list_indexes(f"{project}_{fv.name}")) + assert {"scalar_index_brand", "json_index_attributes_0"} <= indexes + + _write_rows(store, config, fv, rows) + read = _read( + store, config, fv, [1, 2], ["brand", "attributes", "labels", "tags", "counts"] + ) + assert read[0] == {k: v for k, v in rows[1].items() if k != "embedding"} + assert read[1] is not None and read[1]["counts"].WhichOneof("val") is None + + hits = store.retrieve_online_documents_v2( + config, + fv, + ["brand", "attributes"], + embedding=[1.0, 0.0], + top_k=5, + distance_metric="COSINE", + filters=ComparisonFilter(type="gt", key='attributes["price"]', value=20), + ) + assert [hit["brand"].string_val for _, _, hit in hits if hit] == ["globex"] + + assert read[1]["tags"] == rows[2]["tags"] + store.online_delete( + config, fv, filters=ComparisonFilter(type="eq", key="tags[0]", value="red") + ) + assert [row is None for row in _read(store, config, fv, [1, 2], ["brand"])] == [ + True, + 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 f43776b1db2..5e06c530da0 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 @@ -16,11 +16,13 @@ from feast.infra.online_stores.milvus_online_store.milvus import ( PLACEHOLDER_VECTOR_DIM, PLACEHOLDER_VECTOR_FIELD, + MilvusFilterTranslator, MilvusOnlineStore, MilvusOnlineStoreConfig, ) from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto from feast.protos.feast.types.Value_pb2 import ( + BoolList, FloatList, Int64List, StringList, @@ -39,6 +41,7 @@ Json, Map, String, + Struct, UnixTimestamp, ) from feast.value_type import ValueType @@ -1036,7 +1039,10 @@ def test_column_types_follow_vector_index_and_vector_length( ], ) - for native, seen_at_type in [(False, DataType.VARCHAR), (True, DataType.INT64)]: + for native, seen_at_type, history_type in [ + (False, DataType.VARCHAR, DataType.VARCHAR), + (True, DataType.INT64, DataType.ARRAY), + ]: MilvusOnlineStore()._get_or_create_collection( _mock_config(embedding_dim=2, enable_openai_compatible_store=native), fv ) @@ -1044,7 +1050,7 @@ def test_column_types_follow_vector_index_and_vector_length( fields = {field.name: field for field in schema.fields} assert fields["embedding"].dtype == DataType.FLOAT_VECTOR assert fields["embedding"].params["dim"] == 3 - assert fields["history"].dtype == DataType.VARCHAR + assert fields["history"].dtype == history_type assert fields["seen_at"].dtype == seen_at_type assert PLACEHOLDER_VECTOR_FIELD not in fields @@ -1235,3 +1241,330 @@ def test_bool_array_cannot_be_a_vector_field(mock_client_cls: MagicMock) -> None MilvusOnlineStore()._get_or_create_collection(_mock_config(), fv) mock_client.create_collection.assert_not_called() + + +def _native_config(tmp_path: Path, **online_store: Any) -> RepoConfig: + return _lite_config(tmp_path, enable_openai_compatible_store=True, **online_store) + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_native_types_get_json_and_array_columns(mock_client_cls: MagicMock) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + fv = FeatureView( + name="catalog", + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="attributes", dtype=Json), + Field(name="labels", dtype=Map), + Field(name="tags", dtype=Array(String), tags={"milvus.max_capacity": "16"}), + Field(name="counts", dtype=Array(Int64)), + Field(name="blobs", dtype=Array(Bytes)), + ], + ) + + MilvusOnlineStore()._get_or_create_collection( + _mock_config(enable_openai_compatible_store=True), fv + ) + + fields = { + field.name: field.to_dict() + for field in mock_client.create_collection.call_args.kwargs["schema"].fields + } + assert fields["attributes"]["type"] == DataType.JSON + assert fields["attributes"]["nullable"] is True + assert fields["labels"]["type"] == DataType.VARCHAR + assert fields["tags"]["type"] == DataType.ARRAY + assert fields["tags"]["nullable"] is True + assert fields["tags"]["element_type"] == DataType.VARCHAR + assert fields["tags"]["params"] == {"max_capacity": 16, "max_length": 65535} + assert fields["counts"]["element_type"] == DataType.INT64 + assert fields["counts"]["params"] == {"max_capacity": 4096} + assert fields["blobs"]["type"] == DataType.VARCHAR + + +_NATIVE_COMPLEX_VALUES: List[Tuple[Any, ValueProto]] = [ + (Json, ValueProto(json_val='{"a": [1, 2], "b": "x"}')), + (Map, python_values_to_proto_values([{"a": "x", "n": 1}], ValueType.MAP)[0]), + ( + Struct({"a": Int64}), + python_values_to_proto_values([{"a": 1}], ValueType.STRUCT)[0], + ), + (Json, ValueProto(json_val="[]")), + (Array(String), ValueProto(string_list_val=StringList(val=["a", "b"]))), + (Array(String), ValueProto(string_list_val=StringList(val=[]))), + (Array(Int64), ValueProto(int64_list_val=Int64List(val=[1, 2, 3]))), + (Array(Bool), ValueProto(bool_list_val=BoolList(val=[True, False]))), + (Array(Float32), ValueProto(float_list_val=FloatList(val=[0.5, 1.5]))), + (Array(Json), ValueProto(json_list_val=StringList(val=[]))), + ( + Array(Json), + python_values_to_proto_values([['{"a": 1}', '{"b": 2}']], ValueType.JSON_LIST)[ + 0 + ], + ), + ( + Array(Map), + python_values_to_proto_values([[{"a": 1}, {"a": 2}]], ValueType.MAP_LIST)[0], + ), +] + + +def test_native_complex_values_round_trip(tmp_path: Path) -> None: + config = _native_config(tmp_path) + store = MilvusOnlineStore() + + for index, (dtype, value) in enumerate(_NATIVE_COMPLEX_VALUES): + fv = _typed_feature_view(f"native_{index}", dtype) + store.update(config, [], [fv], [], [], partial=False) + _write_rows( + store, config, fv, {1: {"value": value}, 2: {"value": ValueProto()}} + ) + rows = _read(store, config, fv, [1, 2], ["value"]) + assert rows[0] is not None and rows[0]["value"] == value, dtype + assert rows[1] is not None and rows[1]["value"].WhichOneof("val") is None + + +def _attributes_feature_view(tags: Optional[Dict[str, str]] = None) -> FeatureView: + return FeatureView( + name="products", + entities=[_driver_entity()], + 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="brand", dtype=String, tags={"milvus.index": "INVERTED"}), + Field(name="attributes", dtype=Json, tags=tags), + Field(name="tags", dtype=Array(String)), + ], + ) + + +def _product_rows() -> Dict[int, Dict[str, ValueProto]]: + return { + 1: { + "embedding": ValueProto(float_list_val=FloatList(val=[1.0, 0.0])), + "brand": ValueProto(string_val="acme"), + "attributes": ValueProto(json_val='{"price": 10}'), + "tags": ValueProto(string_list_val=StringList(val=["red", "sale"])), + }, + 2: { + "embedding": ValueProto(float_list_val=FloatList(val=[0.0, 1.0])), + "brand": ValueProto(string_val="globex"), + "attributes": ValueProto(json_val='{"price": 50}'), + "tags": ValueProto(string_list_val=StringList(val=["blue"])), + }, + } + + +def test_filters_address_json_paths_and_array_elements(tmp_path: Path) -> None: + config = _native_config(tmp_path) + fv = _attributes_feature_view() + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + _write_rows(store, config, fv, _product_rows()) + + hits = store.retrieve_online_documents_v2( + config, + fv, + ["brand", "attributes"], + [1.0, 0.0], + top_k=5, + filters=ComparisonFilter(type="gt", key='attributes["price"]', value=20), + ) + assert [hit["brand"].string_val for _, _, hit in hits if hit] == ["globex"] + + store.online_delete( + config, fv, filters=ComparisonFilter(type="eq", key="tags[0]", value="blue") + ) + assert [row is None for row in _read(store, config, fv, [1, 2], ["brand"])] == [ + False, + True, + ] + + +@pytest.mark.parametrize( + "key, valid", + [ + ("brand", True), + ('attributes["price"]', True), + ('attributes["a"]["b"]', True), + ("tags[0]", True), + ("brand-id", False), + ('attributes["price', False), + ("brand; drop", False), + ], +) +def test_filter_keys_allow_json_paths_and_array_elements(key: str, valid: bool) -> None: + translator = MilvusFilterTranslator() + comparison = ComparisonFilter(type="eq", key=key, value=1) + + if valid: + assert translator.translate(comparison) == f"{key} == 1" + else: + with pytest.raises(ValueError, match="Invalid filter key"): + translator.translate(comparison) + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_index_tags_create_scalar_and_json_path_indexes( + mock_client_cls: MagicMock, +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + fv = _attributes_feature_view( + tags={ + "milvus.json_indexes": ( + '[{"json_path": "attributes[\\"price\\"]", "json_cast_type": "double"}]' + ) + } + ) + + MilvusOnlineStore()._get_or_create_collection( + _mock_config(enable_openai_compatible_store=True), fv + ) + + created = _created_indexes(mock_client) + assert created["brand"]["index_type"] == "INVERTED" + assert created["brand"]["index_name"] == "scalar_index_brand" + assert created["attributes"]["index_name"] == "json_index_attributes_0" + assert created["attributes"]["index_type"] == "INVERTED" + assert created["attributes"]["json_path"] == 'attributes["price"]' + assert created["attributes"]["json_cast_type"] == "double" + assert created["embedding"]["index_type"] == "FLAT" + + +@pytest.mark.parametrize( + "field, online_store, match", + [ + ( + Field(name="brand", dtype=String, tags={"milvus.index_params": "{}"}), + {}, + "without milvus.index", + ), + ( + Field( + name="brand", + dtype=String, + tags={"milvus.index": "INVERTED", "milvus.index_params": "nope"}, + ), + {}, + "must be a JSON dict", + ), + ( + Field( + name="brand", + dtype=String, + tags={"milvus.json_indexes": '[{"json_path": "brand"}]'}, + ), + {"enable_openai_compatible_store": True}, + "not stored as JSON", + ), + ( + Field( + name="embedding", + dtype=Array(Float32), + vector_index=True, + tags={"milvus.index": "INVERTED"}, + ), + {}, + "is a vector", + ), + ( + Field(name="tags", dtype=Array(String), tags={"milvus.max_capacity": "0"}), + {"enable_openai_compatible_store": True}, + "milvus.max_capacity tag must be", + ), + ], + ids=[ + "params_without_index", + "bad_json", + "json_index_on_text", + "vector", + "capacity", + ], +) +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_index_and_capacity_tags_are_validated( + mock_client_cls: MagicMock, field: Field, online_store: Dict[str, Any], match: str +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + fv = FeatureView( + name="products", + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=[Field(name="driver_id", dtype=Int64), field], + ) + + with pytest.raises(ValueError, match=match): + MilvusOnlineStore()._get_or_create_collection(_mock_config(**online_store), fv) + + mock_client.create_collection.assert_not_called() + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_missing_tag_indexes_on_an_existing_collection_are_logged( + 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 = _existing_collection_description() + mock_client.list_indexes.return_value = ["vector_index__placeholder_vector"] + fv = 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, tags={"milvus.index": "INVERTED"}), + ], + ) + + MilvusOnlineStore()._get_or_create_collection(_mock_config(), fv) + + assert "scalar_index_city" in caplog.text + mock_client.create_index.assert_not_called() + + +def test_json_null_reads_as_missing_and_json_scalars_are_rejected( + tmp_path: Path, +) -> None: + config = _native_config(tmp_path) + fv = _typed_feature_view("documents", Json) + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + + _write_rows(store, config, fv, {1: {"value": ValueProto(json_val="null")}}) + rows = _read(store, config, fv, [1], ["value"]) + assert rows[0] is not None and rows[0]["value"].WhichOneof("val") is None + + for text, match in [ + ('"text"', "not a top-level str"), + ("12", "not a top-level int"), + ("not json", "not valid JSON"), + ]: + with pytest.raises(ValueError, match=match): + _write_rows(store, config, fv, {2: {"value": ValueProto(json_val=text)}}) + + +def test_a_json_column_that_cannot_be_null_rejects_a_missing_value( + tmp_path: Path, +) -> None: + config = _native_config(tmp_path) + fv = _typed_feature_view("documents", Json, tags={"milvus.nullable": "false"}) + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + assert store.client is not None + description = store.client.describe_collection("test_milvus_documents") + assert not next(f for f in description["fields"] if f["name"] == "value").get( + "nullable", False + ) + + with pytest.raises(ValueError, match="cannot be null"): + _write_rows(store, config, fv, {1: {"value": ValueProto()}})