From b2bc2a356f7056b8e0e23b4213e2d172a6806e23 Mon Sep 17 00:00:00 2001 From: N-E-W-T-O-N Date: Sun, 15 Nov 2026 22:44:28 +0530 Subject: [PATCH 1/4] Milvus: move the provider to Milvus.Client.V2 Port the Microsoft.Extensions.VectorData Milvus provider from the legacy Milvus.Client to Milvus.Client.V2 3.0.0 (MilvusClientV2 and its request/response API). - Collections take a MilvusClientV2; the host-based registrations build a ConnectConfig from the host, port, database and API key or username/password. - Collection creation sends the schema, the vector and BM25 indexes in one CreateCollection call, then loads the collection and waits for it with LoadTimeout. - Each index is named after its field: Milvus.Client.V2 3.0.0 gives every unnamed index the same default name, and Milvus rejects the second one. - Upserts send rows (UpsertReq.RowsData); queries and searches read the returned columns back into rows. - Hybrid search uses AnnSearchReq with text input for BM25, ranked with RrfReranker(60). - gRPC failures now reach the error handler as MilvusException, with the gRPC status kept. Milvus.Client.V2 cannot take a caller-owned GrpcChannel: a client always owns its channel, and tests route calls through ConnectConfig.ChannelOptions instead. --- Directory.Packages.props | 2 +- MEVD/src/Milvus/ClientWrapper.cs | 12 +- MEVD/src/Milvus/Milvus.csproj | 2 +- MEVD/src/Milvus/MilvusCollection.cs | 174 +++++++++--------- .../Milvus/MilvusCollectionCreateMapping.cs | 59 ++++-- MEVD/src/Milvus/MilvusDynamicCollection.cs | 4 +- MEVD/src/Milvus/MilvusErrorHandler.cs | 4 +- MEVD/src/Milvus/MilvusFieldMapping.cs | 91 +++++---- .../MilvusServiceCollectionExtensions.cs | 56 +++--- MEVD/src/Milvus/MilvusVectorStore.cs | 16 +- MEVD/src/Milvus/README.md | 21 ++- .../MilvusDatabaseTests.cs | 8 +- .../MilvusDependencyInjectionTests.cs | 16 +- .../MilvusEmbeddingGenerationTests.cs | 3 +- .../MilvusEnsureCollectionTests.cs | 21 ++- .../MilvusRoundTripTests.cs | 5 +- .../Support/MilvusTestStore.cs | 12 +- .../test/Milvus.UnitTests/MilvusArrayTests.cs | 5 +- .../MilvusClientLifetimeTests.cs | 42 ++--- .../Milvus.UnitTests/MilvusCollectionTests.cs | 19 +- .../Milvus.UnitTests/MilvusDatabaseTests.cs | 5 +- .../MilvusEnsureCollectionTests.cs | 23 ++- .../Milvus.UnitTests/MilvusFullTextTests.cs | 15 +- .../MilvusHybridSearchTests.cs | 15 +- .../Milvus.UnitTests/MilvusMappingTests.cs | 21 ++- MEVD/test/Milvus.UnitTests/TestClients.cs | 27 +++ 26 files changed, 394 insertions(+), 284 deletions(-) create mode 100644 MEVD/test/Milvus.UnitTests/TestClients.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index ede0ef8..bf00e5d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ - + diff --git a/MEVD/src/Milvus/ClientWrapper.cs b/MEVD/src/Milvus/ClientWrapper.cs index 59370d8..f690c50 100644 --- a/MEVD/src/Milvus/ClientWrapper.cs +++ b/MEVD/src/Milvus/ClientWrapper.cs @@ -1,25 +1,25 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Milvus.Client; +using Milvus.Client.V2; using Microsoft.Shared.Diagnostics; namespace CommunityToolkit.VectorData.Milvus; /// -/// The of a vector store or of a collection. A vector store shares it with the collections it returns, -/// and the it owns is disposed when the last of them is disposed. +/// The of a vector store or of a collection. A vector store shares it with the collections it returns, +/// and the it owns is disposed when the last of them is disposed. /// internal sealed class ClientWrapper : IDisposable { - private readonly MilvusClient? _ownedClient; + private readonly MilvusClientV2? _ownedClient; private int _referenceCount = 1; /// /// Gets the client. /// - public MilvusClient Client { get; } + public MilvusClientV2 Client { get; } /// /// Gets the database name for telemetry, or for a client created by the caller: the SDK does not @@ -35,7 +35,7 @@ internal sealed class ClientWrapper : IDisposable /// /// The database the SDK client connects to, for telemetry: known to the host-based registrations, which create the client. /// - public ClientWrapper(MilvusClient milvusClient, bool ownsClient, string? databaseName = null) + public ClientWrapper(MilvusClientV2 milvusClient, bool ownsClient, string? databaseName = null) { Throw.IfNull(milvusClient); diff --git a/MEVD/src/Milvus/Milvus.csproj b/MEVD/src/Milvus/Milvus.csproj index c786b80..0082115 100644 --- a/MEVD/src/Milvus/Milvus.csproj +++ b/MEVD/src/Milvus/Milvus.csproj @@ -16,7 +16,7 @@ - + diff --git a/MEVD/src/Milvus/MilvusCollection.cs b/MEVD/src/Milvus/MilvusCollection.cs index 1fa882c..e3ca4e7 100644 --- a/MEVD/src/Milvus/MilvusCollection.cs +++ b/MEVD/src/Milvus/MilvusCollection.cs @@ -5,7 +5,12 @@ using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Runtime.CompilerServices; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Requests.Collection; +using Milvus.Client.V2.Requests.Dml; +using Milvus.Client.V2.Requests.Dql; +using Milvus.Client.V2.Responses.Dql; +using Milvus.Client.V2.Types; using Microsoft.Extensions.AI; using Microsoft.Extensions.VectorData; using Microsoft.Extensions.VectorData.ProviderServices; @@ -18,11 +23,9 @@ namespace CommunityToolkit.VectorData.Milvus; /// /// The data type of the record key. Can be , or . /// The data model to use for adding, updating and retrieving data from storage. -#pragma warning disable CA1711 // Identifiers should not have incorrect suffix public class MilvusCollection : VectorStoreCollection, IKeywordHybridSearchable where TKey : notnull where TRecord : class -#pragma warning restore CA1711 // Identifiers should not have incorrect suffix { /// The default options for vector search. private static readonly VectorSearchOptions s_defaultVectorSearchOptions = new(); @@ -35,9 +38,6 @@ public class MilvusCollection : VectorStoreCollectionMilvus client that can be used to manage the collections and records in a Milvus store. private readonly ClientWrapper _clientWrapper; - /// Milvus client of the records of the collection. - private readonly global::Milvus.Client.MilvusCollection _records; - /// The model for this collection. private readonly CollectionModel _model; @@ -67,7 +67,7 @@ public class MilvusCollection : VectorStoreCollectionThrown for any misconfigured options. [RequiresDynamicCode("This constructor is incompatible with NativeAOT. For dynamic mapping via Dictionary, instantiate MilvusDynamicCollection instead.")] [RequiresUnreferencedCode("This constructor is incompatible with trimming. For dynamic mapping via Dictionary, instantiate MilvusDynamicCollection instead")] - public MilvusCollection(MilvusClient milvusClient, string name, bool ownsClient, MilvusCollectionOptions? options = null) + public MilvusCollection(MilvusClientV2 milvusClient, string name, bool ownsClient, MilvusCollectionOptions? options = null) : this(() => new ClientWrapper(milvusClient, ownsClient), name, options) { } @@ -139,8 +139,6 @@ internal MilvusCollection(Func clientFactory, string name, Func public override Task CollectionExistsAsync(CancellationToken cancellationToken = default) - => RunOperationAsync("CollectionExists", () => _clientWrapper.Client.HasCollectionAsync(Name, cancellationToken: cancellationToken)); + => RunOperationAsync("CollectionExists", () => HasCollectionAsync(cancellationToken)); + + private async Task HasCollectionAsync(CancellationToken cancellationToken) + => (await _clientWrapper.Client.HasCollectionAsync(new HasCollectionReq { CollectionName = Name }, cancellationToken).ConfigureAwait(false)).Has; /// public override Task EnsureCollectionExistsAsync(CancellationToken cancellationToken = default) @@ -170,40 +171,26 @@ public override Task EnsureCollectionExistsAsync(CancellationToken cancellationT { // The indexes are created with the collection. Those of an existing collection stay as they are: Milvus rejects // an index with other settings on an indexed field, or on a field the collection does not have. - if (!await _clientWrapper.Client.HasCollectionAsync(Name, cancellationToken: cancellationToken).ConfigureAwait(false)) + if (!await HasCollectionAsync(cancellationToken).ConfigureAwait(false)) { - await _clientWrapper.Client.CreateCollectionAsync(Name, MilvusCollectionCreateMapping.MapCollectionSchema(_model), - cancellationToken: cancellationToken).ConfigureAwait(false); - foreach (var vector in _model.VectorProperties) + await _clientWrapper.Client.CreateCollectionAsync(new CreateCollectionReq { - var indexType = MilvusCollectionCreateMapping.GetIndexType(vector); - var parameters = indexType == IndexType.Hnsw - ? new Dictionary - { - ["M"] = _hnswM.ToString(System.Globalization.CultureInfo.InvariantCulture), - ["efConstruction"] = _hnswEfConstruction.ToString(System.Globalization.CultureInfo.InvariantCulture) - } : null; - await _records.CreateIndexAsync(vector.StorageName, indexType, - MilvusCollectionCreateMapping.GetMetric(vector), extraParams: parameters, - cancellationToken: cancellationToken).ConfigureAwait(false); - } - foreach (var property in MilvusCollectionCreateMapping.GetFullTextProperties(_model)) - { - await _records.CreateIndexAsync(MilvusCollectionCreateMapping.GetBm25FieldName(property), IndexType.SparseInvertedIndex, - SimilarityMetricType.Bm25, cancellationToken: cancellationToken).ConfigureAwait(false); - } + CollectionName = Name, + Schema = MilvusCollectionCreateMapping.MapCollectionSchema(_model), + Indexes = MilvusCollectionCreateMapping.MapIndexes(_model, _hnswM, _hnswEfConstruction), + ConsistencyLevel = ConsistencyLevel.Strong, + }, cancellationToken).ConfigureAwait(false); } - await _records.LoadAsync(cancellationToken: cancellationToken).ConfigureAwait(false); - await _records.WaitForCollectionLoadAsync(timeout: _loadTimeout, cancellationToken: cancellationToken).ConfigureAwait(false); + await LoadAsync(cancellationToken).ConfigureAwait(false); }); /// public override Task EnsureCollectionDeletedAsync(CancellationToken cancellationToken = default) => RunOperationAsync("DeleteCollection", async () => { - if (await _clientWrapper.Client.HasCollectionAsync(Name, cancellationToken: cancellationToken).ConfigureAwait(false)) + if (await HasCollectionAsync(cancellationToken).ConfigureAwait(false)) { - await _records.DropAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + await _clientWrapper.Client.DropCollectionAsync(new DropCollectionReq { CollectionName = Name }, cancellationToken).ConfigureAwait(false); } }); @@ -238,7 +225,7 @@ public override async IAsyncEnumerable GetAsync( } var parameters = CreateQueryParameters(includeVectors); var entries = await RunOperationAsync(OperationName, - () => _records.QueryRowsAsync(KeyFilter(keyList), parameters, cancellationToken)).ConfigureAwait(false); + () => QueryRowsAsync(KeyFilter(keyList), parameters, cancellationToken)).ConfigureAwait(false); foreach (var entry in entries) { yield return _mapper.MapFromStorageToDataModel(entry, includeVectors); @@ -260,7 +247,8 @@ public override Task DeleteAsync(IEnumerable keys, CancellationToken cance var keyList = keys.ToList(); return keyList.Count == 0 ? Task.CompletedTask - : RunOperationAsync(MilvusConstants.DeleteName, () => _records.DeleteAsync(KeyFilter(keyList), cancellationToken: cancellationToken)); + : RunOperationAsync(MilvusConstants.DeleteName, () => _clientWrapper.Client.DeleteAsync( + new DeleteReq { CollectionName = Name, Expression = KeyFilter(keyList), ConsistencyLevel = ConsistencyLevel.Strong }, cancellationToken)); } /// @@ -322,7 +310,7 @@ public override async Task UpsertAsync(IEnumerable records, Cancellatio } if (rows.Count > 0) { - await RunOperationAsync(MilvusConstants.UpsertName, () => _records.UpsertAsync(MilvusFieldMapping.CreateColumns(_model, rows), cancellationToken: cancellationToken)).ConfigureAwait(false); + await RunOperationAsync(MilvusConstants.UpsertName, () => _clientWrapper.Client.UpsertAsync(new UpsertReq { CollectionName = Name, RowsData = rows }, cancellationToken)).ConfigureAwait(false); } } @@ -363,22 +351,28 @@ public override async IAsyncEnumerable> SearchAsync< } if (MilvusCollectionCreateMapping.GetIndexType(vectorProperty) == IndexType.Hnsw) { - parameters.ExtraParameters["ef"] = Math.Max(MilvusConstants.DefaultHnswSearchEf, top + options.Skip).ToString(System.Globalization.CultureInfo.InvariantCulture); + parameters.Ef = Math.Max(MilvusConstants.DefaultHnswSearchEf, top + options.Skip); } - var results = await RunOperationAsync("Search", () => SearchAllowingEmptyResultsAsync( - () => _records.SearchAsync(vectorProperty.StorageName, [vector], - MilvusCollectionCreateMapping.GetMetric(vectorProperty), top, parameters, cancellationToken), - parameters.OutputFields)).ConfigureAwait(false); + var request = new SearchReq + { + CollectionName = Name, + VectorFieldName = vectorProperty.StorageName, + Vectors = [vector], + MetricType = MilvusCollectionCreateMapping.GetMetric(vectorProperty), + Limit = top, + Parameters = parameters, + }; + var results = await RunOperationAsync("Search", () => _clientWrapper.Client.SearchAsync(request, cancellationToken)).ConfigureAwait(false); if (IsEmpty(results)) { yield break; } - foreach (var hit in results.GetHits()) + foreach (var (row, rawScore) in GetHits(results)) { - var score = MilvusCollectionSearchMapping.MapScore(hit.Score, vectorProperty.DistanceFunction); + var score = MilvusCollectionSearchMapping.MapScore(rawScore, vectorProperty.DistanceFunction); if (MilvusCollectionSearchMapping.PassesThreshold(score, options.ScoreThreshold, vectorProperty.DistanceFunction)) { - yield return new VectorSearchResult(MapHit(hit, options.IncludeVectors), score); + yield return new VectorSearchResult(_mapper.MapFromStorageToDataModel(row, options.IncludeVectors), score); } } } @@ -420,74 +414,69 @@ public async IAsyncEnumerable> HybridSearchAsync(vectorProperty.StorageName, [vector], - MilvusCollectionCreateMapping.GetMetric(vectorProperty), candidates) + var vectorSearch = new AnnSearchReq { + VectorFieldName = vectorProperty.StorageName, + Vectors = [vector], + MetricType = MilvusCollectionCreateMapping.GetMetric(vectorProperty), + Limit = candidates, Expression = filter, }; if (MilvusCollectionCreateMapping.GetIndexType(vectorProperty) == IndexType.Hnsw) { vectorSearch.ExtraParameters["ef"] = Math.Max(MilvusConstants.DefaultHnswSearchEf, candidates).ToString(System.Globalization.CultureInfo.InvariantCulture); } - var keywordSearch = new TextAnnSearchRequest(MilvusCollectionCreateMapping.GetBm25FieldName(textProperty), - [string.Join(" ", keywords)], candidates) + var keywordSearch = new AnnSearchReq { + VectorFieldName = MilvusCollectionCreateMapping.GetBm25FieldName(textProperty), + Texts = [string.Join(" ", keywords)], + MetricType = MetricType.Bm25, + Limit = candidates, Expression = filter, }; - var parameters = new HybridSearchParameters { ConsistencyLevel = ConsistencyLevel.Strong }; + var parameters = new SearchParameters { ConsistencyLevel = ConsistencyLevel.Strong }; foreach (var field in GetOutputFields(options.IncludeVectors)) { parameters.OutputFields.Add(field); } - var results = await RunOperationAsync("HybridSearch", () => SearchAllowingEmptyResultsAsync( - () => _records.HybridSearchAsync([vectorSearch, keywordSearch], new RrfReranker(60), limit, parameters, cancellationToken), - parameters.OutputFields)).ConfigureAwait(false); + var request = new HybridSearchReq + { + CollectionName = Name, + SearchRequests = [vectorSearch, keywordSearch], + Reranker = new RrfReranker(60), + Limit = limit, + Parameters = parameters, + }; + var results = await RunOperationAsync("HybridSearch", () => _clientWrapper.Client.HybridSearchAsync(request, cancellationToken)).ConfigureAwait(false); if (IsEmpty(results)) { yield break; } - foreach (var hit in results.GetHits().Skip(options.Skip)) + foreach (var (row, score) in GetHits(results).Skip(options.Skip)) { // A higher RRF score ranks higher: the threshold is a lower bound. - if (options.ScoreThreshold is not { } threshold || hit.Score >= threshold) + if (options.ScoreThreshold is not { } threshold || score >= threshold) { - yield return new VectorSearchResult(MapHit(hit, options.IncludeVectors), hit.Score); + yield return new VectorSearchResult(_mapper.MapFromStorageToDataModel(row, options.IncludeVectors), score); } } } - // TODO: Remove this workaround once the SDK fix is available and adopted: - // https://github.com/milvus-io/milvus-sdk-csharp/issues/191 - // Milvus.Client 2.6.0 cannot decode untyped output fields in an empty response. - // Retry without output fields to verify that this really is an empty search; - // do not hide the SDK error if the retry finds any records. - private static async Task SearchAllowingEmptyResultsAsync(Func> search, IList outputFields) + private static bool IsEmpty(SearchResp results) => (results.Ids.LongIds?.Count ?? results.Ids.StringIds?.Count ?? 0) == 0; + + /// Gets the rows of the hits of a single-vector search, each with its key from the IDs, and their scores. + private IEnumerable<(Dictionary Row, float Score)> GetHits(SearchResp results) { - try - { - return await search().ConfigureAwait(false); - } - catch (NotSupportedException exception) when (exception.Message == "Cannot convert None FieldData to Field") + var rows = MilvusFieldMapping.ReadRows(results.FieldsData); + var keyName = _model.KeyProperty.StorageName; + for (var i = 0; i < results.Scores.Count; i++) { - outputFields.Clear(); - var retry = await search().ConfigureAwait(false); - if (!IsEmpty(retry)) - { - throw; - } - return retry; + var row = i < rows.Count ? rows[i] : new Dictionary(StringComparer.Ordinal); + row[keyName] = results.Ids.LongIds is { } longIds ? longIds[i] : results.Ids.StringIds![i]; + yield return (row, results.Scores[i]); } } - private static bool IsEmpty(SearchResults results) => (results.Ids.LongIds?.Count ?? results.Ids.StringIds?.Count ?? 0) == 0; - - private TRecord MapHit(SearchHit hit, bool includeVectors) - { - var row = hit.Fields.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal); - row[_model.KeyProperty.StorageName] = hit.Id; - return _mapper.MapFromStorageToDataModel(row, includeVectors); - } - private static async ValueTask> GetSearchVectorAsync(TInput searchValue, VectorPropertyModel vectorProperty, CancellationToken cancellationToken) where TInput : notnull => searchValue switch @@ -529,7 +518,7 @@ public override async IAsyncEnumerable GetAsync(Expression _records.QueryRowsAsync(milvusFilter, parameters, cancellationToken)).ConfigureAwait(false); + () => QueryRowsAsync(milvusFilter, parameters, cancellationToken)).ConfigureAwait(false); foreach (var entry in entries) { yield return _mapper.MapFromStorageToDataModel(entry, options.IncludeVectors); @@ -544,7 +533,7 @@ public override async IAsyncEnumerable GetAsync(Expression) ? (MilvusCollectionCreateMapping.GetFullTextProperties(_model).Any() ? this : null) : serviceType.IsInstanceOfType(this) ? this : null; @@ -578,6 +567,21 @@ private QueryParameters CreateQueryParameters(bool includeVectors) return parameters; } + private async Task>> QueryRowsAsync(string filter, QueryParameters parameters, CancellationToken cancellationToken) + { + var response = await _clientWrapper.Client.QueryAsync( + new QueryReq { CollectionName = Name, Expression = filter, Parameters = parameters }, cancellationToken).ConfigureAwait(false); + return MilvusFieldMapping.ReadRows(response.FieldsData); + } + + private Task LoadAsync(CancellationToken cancellationToken) + => _clientWrapper.Client.LoadCollectionAsync(new LoadCollectionReq + { + CollectionName = Name, + Sync = true, + TimeoutMs = (long)_loadTimeout.TotalMilliseconds, + }, cancellationToken); + /// /// Run the given operation and wrap any with . /// diff --git a/MEVD/src/Milvus/MilvusCollectionCreateMapping.cs b/MEVD/src/Milvus/MilvusCollectionCreateMapping.cs index 25a93d1..ef6d64a 100644 --- a/MEVD/src/Milvus/MilvusCollectionCreateMapping.cs +++ b/MEVD/src/Milvus/MilvusCollectionCreateMapping.cs @@ -1,9 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Milvus.Client; +using System.Globalization; using Microsoft.Extensions.VectorData; using Microsoft.Extensions.VectorData.ProviderServices; +using Milvus.Client.V2.Types; namespace CommunityToolkit.VectorData.Milvus; @@ -13,7 +14,7 @@ public static IReadOnlyList MapCollectionDefinition(CollectionModel { var key = model.KeyProperty; List fields = [key.Type == typeof(long) - ? FieldSchema.Create(key.StorageName, isPrimaryKey: true) + ? new FieldSchema(key.StorageName, DataType.Int64, isPrimaryKey: true) : FieldSchema.CreateVarchar(key.StorageName, MilvusConstants.MaxVarCharLength, isPrimaryKey: true)]; foreach (var property in model.DataProperties) { @@ -21,20 +22,22 @@ public static IReadOnlyList MapCollectionDefinition(CollectionModel var nullable = !property.Type.IsValueType || Nullable.GetUnderlyingType(property.Type) is not null; if (MilvusFieldMapping.GetElementType(type) is { } element) { - var name = property.StorageName; - var field = element == typeof(string) ? FieldSchema.CreateVarcharArray(name, MilvusConstants.DefaultArrayCapacity, MilvusConstants.MaxVarCharLength, nullable: true) - : element == typeof(bool) ? FieldSchema.CreateArray(name, MilvusConstants.DefaultArrayCapacity, nullable: true) - : element == typeof(int) ? FieldSchema.CreateArray(name, MilvusConstants.DefaultArrayCapacity, nullable: true) - : element == typeof(long) ? FieldSchema.CreateArray(name, MilvusConstants.DefaultArrayCapacity, nullable: true) - : element == typeof(float) ? FieldSchema.CreateArray(name, MilvusConstants.DefaultArrayCapacity, nullable: true) - : element == typeof(double) ? FieldSchema.CreateArray(name, MilvusConstants.DefaultArrayCapacity, nullable: true) - : throw new NotSupportedException($"Unsupported Milvus array element type '{element}'."); + var field = new FieldSchema(property.StorageName, DataType.Array) + { + ElementDataType = MilvusFieldMapping.GetDataType(element), + MaxCapacity = MilvusConstants.DefaultArrayCapacity, + Nullable = true, + }; + if (element == typeof(string)) + { + field.MaxLength = MilvusConstants.MaxVarCharLength; + } fields.Add(field); continue; } fields.Add(type == typeof(string) ? FieldSchema.CreateVarchar(property.StorageName, MilvusConstants.MaxVarCharLength, nullable: true, enableAnalyzer: property.IsFullTextIndexed) - : FieldSchema.Create(property.StorageName, MilvusFieldMapping.GetDataType(type), nullable: nullable)); + : new FieldSchema(property.StorageName, MilvusFieldMapping.GetDataType(type)) { Nullable = nullable }); } foreach (var vector in model.VectorProperties) { @@ -66,6 +69,32 @@ public static CollectionSchema MapCollectionSchema(CollectionModel model) return schema; } + /// + /// Maps the model to the indexes of the collection: one per vector property, and a sparse inverted index on the + /// hidden BM25 field of each full-text indexed property. Each index is named after its field: Milvus.Client.V2 3.0.0 + /// gives every unnamed index the same default name, and Milvus rejects a second index with that name. + /// + public static IReadOnlyList MapIndexes(CollectionModel model, int hnswM, int hnswEfConstruction) + { + List indexes = []; + foreach (var vector in model.VectorProperties) + { + var indexType = GetIndexType(vector); + var index = new IndexParam(vector.StorageName, indexName: vector.StorageName, indexType: indexType, metricType: GetMetric(vector)); + if (indexType == IndexType.Hnsw) + { + index.ExtraParams["M"] = hnswM.ToString(CultureInfo.InvariantCulture); + index.ExtraParams["efConstruction"] = hnswEfConstruction.ToString(CultureInfo.InvariantCulture); + } + indexes.Add(index); + } + foreach (var property in GetFullTextProperties(model)) + { + indexes.Add(new IndexParam(GetBm25FieldName(property), indexName: GetBm25FieldName(property), indexType: IndexType.SparseInvertedIndex, metricType: MetricType.Bm25)); + } + return indexes; + } + public static IEnumerable GetFullTextProperties(CollectionModel model) => model.DataProperties.Where(p => p.IsFullTextIndexed); @@ -75,11 +104,11 @@ public static IEnumerable GetFullTextProperties(CollectionMod /// public static string GetBm25FieldName(DataPropertyModel property) => property.StorageName + "_bm25"; - public static SimilarityMetricType GetMetric(VectorPropertyModel property) => property.DistanceFunction switch + public static MetricType GetMetric(VectorPropertyModel property) => property.DistanceFunction switch { - null or DistanceFunction.CosineSimilarity => SimilarityMetricType.Cosine, - DistanceFunction.DotProductSimilarity => SimilarityMetricType.Ip, - DistanceFunction.EuclideanSquaredDistance or DistanceFunction.EuclideanDistance => SimilarityMetricType.L2, + null or DistanceFunction.CosineSimilarity => MetricType.Cosine, + DistanceFunction.DotProductSimilarity => MetricType.Ip, + DistanceFunction.EuclideanSquaredDistance or DistanceFunction.EuclideanDistance => MetricType.L2, _ => throw new NotSupportedException($"Milvus does not support distance function '{property.DistanceFunction}'."), }; diff --git a/MEVD/src/Milvus/MilvusDynamicCollection.cs b/MEVD/src/Milvus/MilvusDynamicCollection.cs index f58adc8..35b4a28 100644 --- a/MEVD/src/Milvus/MilvusDynamicCollection.cs +++ b/MEVD/src/Milvus/MilvusDynamicCollection.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Milvus.Client; +using Milvus.Client.V2; namespace CommunityToolkit.VectorData.Milvus; @@ -19,7 +19,7 @@ public sealed class MilvusDynamicCollection : MilvusCollectionThe name of the collection. /// A value indicating whether is disposed when the collection is disposed. /// Optional configuration options for this class. - public MilvusDynamicCollection(MilvusClient milvusClient, string name, bool ownsClient, MilvusCollectionOptions options) + public MilvusDynamicCollection(MilvusClientV2 milvusClient, string name, bool ownsClient, MilvusCollectionOptions options) : this(() => new ClientWrapper(milvusClient, ownsClient), name, options) { } diff --git a/MEVD/src/Milvus/MilvusErrorHandler.cs b/MEVD/src/Milvus/MilvusErrorHandler.cs index 970e933..1c9dc46 100644 --- a/MEVD/src/Milvus/MilvusErrorHandler.cs +++ b/MEVD/src/Milvus/MilvusErrorHandler.cs @@ -3,11 +3,11 @@ using Grpc.Core; using Microsoft.Extensions.VectorData; -using Milvus.Client; +using Milvus.Client.V2; namespace CommunityToolkit.VectorData.Milvus; -// Milvus.Client reports server errors as MilvusException, gRPC errors as RpcException, and a wait that runs out of time, +// Milvus.Client.V2 reports server and gRPC errors as MilvusException (keeping the gRPC status), and a wait that runs out of time, // such as the wait for a collection to load, as TimeoutException. internal static class MilvusErrorHandler { diff --git a/MEVD/src/Milvus/MilvusFieldMapping.cs b/MEVD/src/Milvus/MilvusFieldMapping.cs index 257ca83..18a6ebf 100644 --- a/MEVD/src/Milvus/MilvusFieldMapping.cs +++ b/MEVD/src/Milvus/MilvusFieldMapping.cs @@ -3,20 +3,20 @@ using System.Globalization; using System.Text; -using Milvus.Client; +using Milvus.Client.V2.Types; using Microsoft.Extensions.VectorData.ProviderServices; namespace CommunityToolkit.VectorData.Milvus; internal static class MilvusFieldMapping { - public static MilvusDataType GetDataType(Type type) - => type == typeof(string) ? MilvusDataType.VarChar - : type == typeof(bool) ? MilvusDataType.Bool - : type == typeof(int) ? MilvusDataType.Int32 - : type == typeof(long) ? MilvusDataType.Int64 - : type == typeof(float) ? MilvusDataType.Float - : type == typeof(double) ? MilvusDataType.Double + public static DataType GetDataType(Type type) + => type == typeof(string) ? DataType.VarChar + : type == typeof(bool) ? DataType.Bool + : type == typeof(int) ? DataType.Int32 + : type == typeof(long) ? DataType.Int64 + : type == typeof(float) ? DataType.Float + : type == typeof(double) ? DataType.Double : throw new NotSupportedException($"Unsupported Milvus field type '{type}'."); internal static Type? GetElementType(Type type) @@ -41,45 +41,56 @@ static object ReadArray(object value, bool array) => array ? ((IEnumerable)value).ToArray() : ((IEnumerable)value).ToList(); } - internal static IReadOnlyList CreateColumns(CollectionModel model, IReadOnlyList> rows) + /// + /// Turns the columns of a query or search response into rows keyed by field name. + /// + internal static List> ReadRows(IReadOnlyList columns) { - List fields = []; - var key = model.KeyProperty; - fields.Add(key.Type == typeof(long) ? Scalar(key.StorageName) : Scalar(key.StorageName)); - foreach (var property in model.DataProperties) + var count = columns.Count == 0 ? 0 : columns.Max(c => c.RowCount); + var rows = new List>(count); + for (var i = 0; i < count; i++) { - var name = property.StorageName; - if (GetElementType(property.Type) is { } element) + var row = new Dictionary(StringComparer.Ordinal); + foreach (var column in columns) { - fields.Add(element == typeof(string) ? ArrayColumn(name) - : element == typeof(bool) ? ArrayColumn(name) - : element == typeof(int) ? ArrayColumn(name) - : element == typeof(long) ? ArrayColumn(name) - : element == typeof(float) ? ArrayColumn(name) - : element == typeof(double) ? ArrayColumn(name) - : throw new NotSupportedException($"Unsupported array element type '{element}'.")); - } - else - { - var type = property.Type; - fields.Add(type == typeof(string) ? Scalar(name) - : type == typeof(bool) ? Scalar(name) : type == typeof(bool?) ? Scalar(name) - : type == typeof(int) ? Scalar(name) : type == typeof(int?) ? Scalar(name) - : type == typeof(long) ? Scalar(name) : type == typeof(long?) ? Scalar(name) - : type == typeof(float) ? Scalar(name) : type == typeof(float?) ? Scalar(name) - : type == typeof(double) ? Scalar(name) : type == typeof(double?) ? Scalar(name) - : throw new NotSupportedException($"Unsupported Milvus data type '{type}'.")); + if (column.FieldName.Length > 0 && i < column.RowCount) + { + row[column.FieldName] = ReadCell(column, i); + } } + rows.Add(row); } - foreach (var property in model.VectorProperties) + return rows; + } + + private static object? ReadCell(FieldData column, int index) + { + if (column.ValidData is { } valid && !valid[index]) { - fields.Add(FieldData.CreateFloatVector(property.StorageName, rows.Select(r => (ReadOnlyMemory)r[property.StorageName]!).ToArray())); + return null; } - return fields; - - FieldData Scalar(string name) => FieldData.Create(name, rows.Select(r => (T)r[name]!).ToArray()); - FieldData ArrayColumn(string name) => FieldData.CreateArray(name, - rows.Select(r => r[name] is { } value ? (IReadOnlyList)((IEnumerable)value).ToArray() : null).ToArray()); + return column switch + { + FieldData f => f.Data[index], + FieldData f => f.Data[index], + FieldData f => f.Data[index], + FieldData f => f.Data[index], + FieldData f => f.Data[index], + FieldData f => f.Data[index], + FieldData f => f.Data[index], + FieldData f => f.Data[index], + FieldData f => f.Data[index], + FieldData f => f.Data[index], + FieldData f => f.Data[index], + FieldData> f => f.Data[index], + FieldData?> f => f.Data[index], + FieldData?> f => f.Data[index], + FieldData?> f => f.Data[index], + FieldData?> f => f.Data[index], + FieldData?> f => f.Data[index], + FieldData?> f => f.Data[index], + _ => throw new NotSupportedException($"Unsupported Milvus field data '{column.GetType()}' for field '{column.FieldName}'."), + }; } public static object ToKey(object key) => key is Guid guid ? guid.ToString("D") : key; diff --git a/MEVD/src/Milvus/MilvusServiceCollectionExtensions.cs b/MEVD/src/Milvus/MilvusServiceCollectionExtensions.cs index ec672a3..c7e6af3 100644 --- a/MEVD/src/Milvus/MilvusServiceCollectionExtensions.cs +++ b/MEVD/src/Milvus/MilvusServiceCollectionExtensions.cs @@ -5,7 +5,8 @@ using Microsoft.Extensions.AI; using Microsoft.Extensions.VectorData; using CommunityToolkit.VectorData.Milvus; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using Microsoft.Shared.Diagnostics; namespace Microsoft.Extensions.DependencyInjection; @@ -21,26 +22,26 @@ public static class MilvusServiceCollectionExtensions /// /// Registers a as - /// with returned by + /// with returned by /// or retrieved from the dependency injection container if was not provided. /// - /// + /// [RequiresUnreferencedCode(UnreferencedCodeMessage)] [RequiresDynamicCode(DynamicCodeMessage)] public static IServiceCollection AddMilvusVectorStore( this IServiceCollection services, - Func? clientProvider = default, + Func? clientProvider = default, Func? optionsProvider = default, ServiceLifetime lifetime = ServiceLifetime.Singleton) => AddKeyedMilvusVectorStore(services, serviceKey: null, clientProvider, optionsProvider, lifetime); /// /// Registers a keyed as - /// with returned by or retrieved from the dependency injection container if was not provided. + /// with returned by or retrieved from the dependency injection container if was not provided. /// /// The to register the on. /// The key with which to associate the vector store. - /// The provider. + /// The provider. /// Options provider to further configure the . /// The service lifetime for the store. Defaults to . /// Service collection. @@ -49,7 +50,7 @@ public static IServiceCollection AddMilvusVectorStore( public static IServiceCollection AddKeyedMilvusVectorStore( this IServiceCollection services, object? serviceKey, - Func? clientProvider = default, + Func? clientProvider = default, Func? optionsProvider = default, ServiceLifetime lifetime = ServiceLifetime.Singleton) => AddKeyedMilvusVectorStoreCore(services, serviceKey, clientProvider, optionsProvider, lifetime, ownsClient: false); @@ -57,7 +58,7 @@ public static IServiceCollection AddKeyedMilvusVectorStore( private static IServiceCollection AddKeyedMilvusVectorStoreCore( this IServiceCollection services, object? serviceKey, - Func? clientProvider, + Func? clientProvider, Func? optionsProvider, ServiceLifetime lifetime, bool ownsClient, string? databaseName = null) { @@ -65,7 +66,7 @@ private static IServiceCollection AddKeyedMilvusVectorStoreCore( services.Add(new ServiceDescriptor(typeof(MilvusVectorStore), serviceKey, (sp, _) => { - var client = clientProvider is null ? sp.GetRequiredService() : clientProvider(sp); + var client = clientProvider is null ? sp.GetRequiredService() : clientProvider(sp); var options = GetStoreOptions(sp, optionsProvider); // Clients created by host overloads are owned, and their database is known; supplied clients remain caller-owned. @@ -127,7 +128,7 @@ public static IServiceCollection AddKeyedMilvusVectorStore( { Throw.IfNullOrWhitespace(host); - return AddKeyedMilvusVectorStoreCore(services, serviceKey, _ => new MilvusClient(host, port, https, database), _ => options, + return AddKeyedMilvusVectorStoreCore(services, serviceKey, _ => CreateClient(host, port, https, database), _ => options, lifetime, ownsClient: true, databaseName: database ?? "default"); } @@ -185,7 +186,7 @@ public static IServiceCollection AddKeyedMilvusVectorStore( Throw.IfNullOrWhitespace(host); Throw.IfNullOrWhitespace(apiKey); - return AddKeyedMilvusVectorStoreCore(services, serviceKey, _ => new MilvusClient(host, apiKey, port, https, database), _ => options, + return AddKeyedMilvusVectorStoreCore(services, serviceKey, _ => CreateClient(host, port, https, database, apiKey: apiKey), _ => options, lifetime, ownsClient: true, databaseName: database ?? "default"); } @@ -248,20 +249,20 @@ public static IServiceCollection AddKeyedMilvusVectorStore( Throw.IfNullOrWhitespace(username); Throw.IfNullOrWhitespace(password); - return AddKeyedMilvusVectorStoreCore(services, serviceKey, _ => new MilvusClient(host, username, password, port, https, database), _ => options, + return AddKeyedMilvusVectorStoreCore(services, serviceKey, _ => CreateClient(host, port, https, database, username: username, password: password), _ => options, lifetime, ownsClient: true, databaseName: database ?? "default"); } /// /// Registers a as - /// with returned by or retrieved from the dependency injection container if was not provided. + /// with returned by or retrieved from the dependency injection container if was not provided. /// [RequiresUnreferencedCode(UnreferencedCodeMessage)] [RequiresDynamicCode(DynamicCodeMessage)] public static IServiceCollection AddMilvusCollection( this IServiceCollection services, string name, - Func? clientProvider = default, + Func? clientProvider = default, Func? optionsProvider = default, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TKey : notnull @@ -270,12 +271,12 @@ public static IServiceCollection AddMilvusCollection( /// /// Registers a keyed as - /// with returned by or retrieved from the dependency injection container if was not provided. + /// with returned by or retrieved from the dependency injection container if was not provided. /// /// The to register the on. /// The key with which to associate the collection. /// The name of the collection. - /// The provider. + /// The provider. /// Options provider to further configure the . /// The service lifetime for the store. Defaults to . /// Service collection. @@ -285,7 +286,7 @@ public static IServiceCollection AddKeyedMilvusCollection( this IServiceCollection services, object? serviceKey, string name, - Func? clientProvider = default, + Func? clientProvider = default, Func? optionsProvider = default, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TKey : notnull @@ -298,7 +299,7 @@ private static IServiceCollection AddKeyedMilvusCollectionCore( this IServiceCollection services, object? serviceKey, string name, - Func? clientProvider, + Func? clientProvider, Func? optionsProvider, ServiceLifetime lifetime, bool ownsClient, string? databaseName = null) where TKey : notnull @@ -309,7 +310,7 @@ private static IServiceCollection AddKeyedMilvusCollectionCore( services.Add(new ServiceDescriptor(typeof(MilvusCollection), serviceKey, (sp, _) => { - var client = clientProvider is null ? sp.GetRequiredService() : clientProvider(sp); + var client = clientProvider is null ? sp.GetRequiredService() : clientProvider(sp); var options = GetCollectionOptions(sp, optionsProvider); // Clients created by host overloads are owned, and their database is known; supplied clients remain caller-owned. @@ -385,7 +386,7 @@ public static IServiceCollection AddKeyedMilvusCollection( { Throw.IfNullOrWhitespace(host); - return AddKeyedMilvusCollectionCore(services, serviceKey, name, _ => new MilvusClient(host, port, https, database), _ => options, + return AddKeyedMilvusCollectionCore(services, serviceKey, name, _ => CreateClient(host, port, https, database), _ => options, lifetime, ownsClient: true, databaseName: database ?? "default"); } @@ -451,7 +452,7 @@ public static IServiceCollection AddKeyedMilvusCollection( Throw.IfNullOrWhitespace(host); Throw.IfNullOrWhitespace(apiKey); - return AddKeyedMilvusCollectionCore(services, serviceKey, name, _ => new MilvusClient(host, apiKey, port, https, database), _ => options, + return AddKeyedMilvusCollectionCore(services, serviceKey, name, _ => CreateClient(host, port, https, database, apiKey: apiKey), _ => options, lifetime, ownsClient: true, databaseName: database ?? "default"); } @@ -522,7 +523,7 @@ public static IServiceCollection AddKeyedMilvusCollection( Throw.IfNullOrWhitespace(username); Throw.IfNullOrWhitespace(password); - return AddKeyedMilvusCollectionCore(services, serviceKey, name, _ => new MilvusClient(host, username, password, port, https, database), _ => options, + return AddKeyedMilvusCollectionCore(services, serviceKey, name, _ => CreateClient(host, port, https, database, username: username, password: password), _ => options, lifetime, ownsClient: true, databaseName: database ?? "default"); } @@ -553,4 +554,15 @@ public static IServiceCollection AddKeyedMilvusCollection( ? options // There is nothing to change. : new(options) { EmbeddingGenerator = embeddingGenerator }; // Create a brand new copy in order to avoid modifying the original options. } + + private static MilvusClientV2 CreateClient(string host, int port, bool https, string? database, + string? apiKey = null, string? username = null, string? password = null) + => new(new ConnectConfig + { + Uri = new UriBuilder(https ? "https" : "http", host, port).Uri.ToString(), + Database = database, + ApiKey = apiKey, + Username = username, + Password = password, + }); } diff --git a/MEVD/src/Milvus/MilvusVectorStore.cs b/MEVD/src/Milvus/MilvusVectorStore.cs index 7631bc5..f215d48 100644 --- a/MEVD/src/Milvus/MilvusVectorStore.cs +++ b/MEVD/src/Milvus/MilvusVectorStore.cs @@ -3,7 +3,9 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Requests.Collection; +using Milvus.Client.V2.Responses.Collection; using Microsoft.Extensions.AI; using Microsoft.Extensions.VectorData; using Microsoft.Extensions.VectorData.ProviderServices; @@ -46,7 +48,7 @@ public sealed class MilvusVectorStore : VectorStore /// Milvus client that can be used to manage the collections and records in a Milvus store. /// A value indicating whether is disposed after the vector store and the collections it returns are all disposed. /// Optional configuration options for this class. - public MilvusVectorStore(MilvusClient milvusClient, bool ownsClient, MilvusVectorStoreOptions? options = default) + public MilvusVectorStore(MilvusClientV2 milvusClient, bool ownsClient, MilvusVectorStoreOptions? options = default) : this(new ClientWrapper(milvusClient, ownsClient), options) { } @@ -118,14 +120,14 @@ public override async IAsyncEnumerable ListCollectionNamesAsync([Enumera { const string OperationName = "ListCollectionNames"; - var collections = await MilvusErrorHandler.RunAsync>( + var collections = await MilvusErrorHandler.RunAsync( new VectorStoreCollectionMetadata { VectorStoreSystemName = MilvusConstants.VectorStoreSystemName, VectorStoreName = _clientWrapper.DatabaseName }, OperationName, - () => _clientWrapper.Client.ListCollectionsAsync(cancellationToken: cancellationToken)).ConfigureAwait(false); + () => _clientWrapper.Client.ListCollectionsAsync(new ListCollectionsReq(), cancellationToken)).ConfigureAwait(false); - foreach (var collection in collections) + foreach (var collection in collections.CollectionNames) { - yield return collection.Name; + yield return collection; } } @@ -151,7 +153,7 @@ public override async Task EnsureCollectionDeletedAsync(string name, Cancellatio return serviceKey is not null ? null : serviceType == typeof(VectorStoreMetadata) ? _metadata : - serviceType == typeof(MilvusClient) ? _clientWrapper.Client : + serviceType == typeof(MilvusClientV2) ? _clientWrapper.Client : serviceType.IsInstanceOfType(this) ? this : null; } diff --git a/MEVD/src/Milvus/README.md b/MEVD/src/Milvus/README.md index 34490c1..a89ff61 100644 --- a/MEVD/src/Milvus/README.md +++ b/MEVD/src/Milvus/README.md @@ -4,7 +4,7 @@ Milvus provider for [Microsoft.Extensions.VectorData](https://learn.microsoft.co [Milvus](https://milvus.io/) is an open-source vector database for AI applications. -The provider is built on [Milvus.Client](https://www.nuget.org/packages/Milvus.Client), the Milvus C# SDK. +The provider is built on [Milvus.Client.V2](https://www.nuget.org/packages/Milvus.Client.V2) (`MilvusClientV2`), the second-generation Milvus C# SDK. Requires Milvus 2.6 or later. @@ -40,13 +40,13 @@ For more information, see the [Microsoft.Extensions.VectorData documentation](ht - `IsIndexed` does not create scalar indexes; Milvus can filter scalar fields without them. Supported vector indexes are automatic (default), Flat, and HNSW. - Field storage names must use ASCII letters, digits and underscores, starting with a letter or underscore. Reserved Milvus keywords are rejected during model construction. Varchar fields allow up to 65535 bytes. Schema changes on an existing collection require explicit management through the SDK. - Collection names must use ASCII letters, digits and underscores, start with a letter or underscore, and have at most 255 characters: Milvus rejects other names, such as `chathistory-local`. -- For NativeAOT, use dynamic dictionary collections with explicit definitions: the typed collection APIs use reflection. Publishing with trimming or NativeAOT shows the warnings `IL2104` and `IL3053` of the dependency `Milvus.Client`. -- On .NET Framework, `Milvus.Client` calls Milvus over WinHTTP (`WinHttpHandler`, which `Grpc.Net.Client` brings in). This needs: - - A TLS endpoint: `https: true` (the default) on the host-based registrations, or `ssl: true` on `MilvusClient`. A plaintext endpoint fails with `Response protocol downgraded to HTTP/1.1`. - - A server certificate that Windows trusts. To validate it another way, create the `MilvusClient` on a `GrpcChannel` with a `WinHttpHandler` and pass that client to the provider. +- For NativeAOT, use dynamic dictionary collections with explicit definitions: the typed collection APIs use reflection. Publishing with trimming or NativeAOT shows the warnings `IL2104` and `IL3053` of the dependency `Milvus.Client.V2`. +- On .NET Framework, `Milvus.Client.V2` calls Milvus over WinHTTP (`WinHttpHandler`, which `Grpc.Net.Client` brings in). This needs: + - A TLS endpoint: `https: true` (the default) on the host-based registrations, or an `https://` URI in the `ConnectConfig` of a `MilvusClientV2`. A plaintext endpoint fails with `Response protocol downgraded to HTTP/1.1`. + - A server certificate that Windows trusts. To validate it another way, set `ConnectConfig.ChannelOptions` to `GrpcChannelOptions` with a `WinHttpHandler` and pass that client to the provider. - Windows 11 or later. Windows Server 2019 and 2022 support gRPC over WinHTTP only partially. See [Microsoft's gRPC requirements for .NET Framework](https://learn.microsoft.com/aspnet/core/grpc/netstandard#net-framework). - Verified on Windows 11 with .NET Framework 4.7.2 against Milvus 2.6.25 over TLS. + Verified on Windows 11 with .NET Framework 4.7.2 against Milvus 2.6.25 over TLS with the V1 `Milvus.Client`; not yet re-verified with `Milvus.Client.V2`. Host-based registrations accept `database`, `username`/`password`, or `apiKey`. The two authentication modes are mutually exclusive. Keyed variants are also available: @@ -55,11 +55,14 @@ builder.Services.AddMilvusVectorStore("milvus.example.com", https: true, database: "catalog", username: "some", password: password); ``` -Host-based registrations report the selected database as `VectorStoreName` in the metadata of the store and of its collections, or `default` when none is selected. An existing `MilvusClient` does not expose the database it uses, so with a supplied client `VectorStoreName` is null. Host-based registrations own their SDK client; supplied clients remain caller-owned: +Host-based registrations report the selected database as `VectorStoreName` in the metadata of the store and of its collections, or `default` when none is selected. An existing `MilvusClientV2` does not expose the database it uses, so with a supplied client `VectorStoreName` is null. Host-based registrations own their SDK client; supplied clients remain caller-owned: ```csharp -var client = new MilvusClient("milvus.example.com", port: 19530, ssl: true, - database: "catalog"); +var client = new MilvusClientV2(new ConnectConfig +{ + Uri = "https://milvus.example.com:19530", + Database = "catalog", +}); builder.Services.AddMilvusVectorStore(_ => client); ``` diff --git a/MEVD/test/Milvus.ConformanceTests/MilvusDatabaseTests.cs b/MEVD/test/Milvus.ConformanceTests/MilvusDatabaseTests.cs index 8a9caa2..670bf13 100644 --- a/MEVD/test/Milvus.ConformanceTests/MilvusDatabaseTests.cs +++ b/MEVD/test/Milvus.ConformanceTests/MilvusDatabaseTests.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using CommunityToolkit.VectorData.Milvus; +using Milvus.Client.V2.Requests.Collection; +using Milvus.Client.V2.Requests.Database; using Milvus.ConformanceTests.Support; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.VectorData; @@ -18,7 +20,7 @@ public async Task HostRegistrationUsesSelectedDatabase(bool apiKey) var server = MilvusTestStore.Instance; var database = "ct_db_" + Guid.NewGuid().ToString("N"); var name = "records_" + Guid.NewGuid().ToString("N"); - await server.Client.CreateDatabaseAsync(database); + await server.Client.CreateDatabaseAsync(new CreateDatabaseReq { DatabaseName = database }); try { var services = new ServiceCollection(); @@ -37,7 +39,7 @@ public async Task HostRegistrationUsesSelectedDatabase(bool apiKey) { await collection.EnsureCollectionExistsAsync(); Assert.True(await collection.CollectionExistsAsync()); - Assert.False(await server.Client.HasCollectionAsync(name)); + Assert.False((await server.Client.HasCollectionAsync(new HasCollectionReq { CollectionName = name })).Has); Assert.Equal(database, Assert.IsType(store.GetService(typeof(VectorStoreMetadata))).VectorStoreName); Assert.Equal(database, Assert.IsType(collection.GetService(typeof(VectorStoreCollectionMetadata))).VectorStoreName); } @@ -48,7 +50,7 @@ public async Task HostRegistrationUsesSelectedDatabase(bool apiKey) } finally { - await server.Client.DropDatabaseAsync(database); + await server.Client.DropDatabaseAsync(new DropDatabaseReq { DatabaseName = database }); } } } diff --git a/MEVD/test/Milvus.ConformanceTests/MilvusDependencyInjectionTests.cs b/MEVD/test/Milvus.ConformanceTests/MilvusDependencyInjectionTests.cs index c354d87..b7b7d9e 100644 --- a/MEVD/test/Milvus.ConformanceTests/MilvusDependencyInjectionTests.cs +++ b/MEVD/test/Milvus.ConformanceTests/MilvusDependencyInjectionTests.cs @@ -4,7 +4,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using CommunityToolkit.VectorData.Milvus; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.ConformanceTests.Support; +using Milvus.Client.V2.Types; using VectorData.ConformanceTests; using Xunit; @@ -42,10 +44,10 @@ private static string ApiKeyProvider(IServiceProvider sp, object? serviceKey = n { yield return (services, serviceKey, name, lifetime) => serviceKey is null ? services - .AddSingleton(sp => new MilvusClient(Host, ApiKey, Port)) + .AddSingleton(sp => MilvusTestStore.CreateClient(Host, Port, ApiKey)) .AddMilvusCollection(name, lifetime: lifetime) : services - .AddSingleton(sp => new MilvusClient(Host, ApiKey, Port)) + .AddSingleton(sp => MilvusTestStore.CreateClient(Host, Port, ApiKey)) .AddKeyedMilvusCollection(serviceKey, name, lifetime: lifetime); yield return (services, serviceKey, name, lifetime) => serviceKey is null @@ -56,9 +58,9 @@ private static string ApiKeyProvider(IServiceProvider sp, object? serviceKey = n yield return (services, serviceKey, name, lifetime) => serviceKey is null ? services.AddMilvusCollection( - name, sp => new MilvusClient(HostProvider(sp), ApiKeyProvider(sp), PortProvider(sp)), lifetime: lifetime) + name, sp => MilvusTestStore.CreateClient(HostProvider(sp), PortProvider(sp), ApiKeyProvider(sp)), lifetime: lifetime) : services.AddKeyedMilvusCollection( - serviceKey, name, sp => new MilvusClient(HostProvider(sp, serviceKey), ApiKeyProvider(sp, serviceKey), PortProvider(sp, serviceKey)), lifetime: lifetime); + serviceKey, name, sp => MilvusTestStore.CreateClient(HostProvider(sp, serviceKey), PortProvider(sp, serviceKey), ApiKeyProvider(sp, serviceKey)), lifetime: lifetime); } } @@ -74,10 +76,10 @@ private static string ApiKeyProvider(IServiceProvider sp, object? serviceKey = n yield return (services, serviceKey, lifetime) => serviceKey is null ? services - .AddSingleton(sp => new MilvusClient(Host, ApiKey, Port)) + .AddSingleton(sp => MilvusTestStore.CreateClient(Host, Port, ApiKey)) .AddMilvusVectorStore(lifetime: lifetime) : services - .AddSingleton(sp => new MilvusClient(Host, ApiKey, Port)) + .AddSingleton(sp => MilvusTestStore.CreateClient(Host, Port, ApiKey)) .AddKeyedMilvusVectorStore(serviceKey, lifetime: lifetime); } } diff --git a/MEVD/test/Milvus.ConformanceTests/MilvusEmbeddingGenerationTests.cs b/MEVD/test/Milvus.ConformanceTests/MilvusEmbeddingGenerationTests.cs index 73472e3..51ea786 100644 --- a/MEVD/test/Milvus.ConformanceTests/MilvusEmbeddingGenerationTests.cs +++ b/MEVD/test/Milvus.ConformanceTests/MilvusEmbeddingGenerationTests.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using Milvus.ConformanceTests.Support; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using CommunityToolkit.VectorData.Milvus; using Microsoft.Extensions.AI; using Microsoft.Extensions.DependencyInjection; diff --git a/MEVD/test/Milvus.ConformanceTests/MilvusEnsureCollectionTests.cs b/MEVD/test/Milvus.ConformanceTests/MilvusEnsureCollectionTests.cs index a0a4193..37f3d4f 100644 --- a/MEVD/test/Milvus.ConformanceTests/MilvusEnsureCollectionTests.cs +++ b/MEVD/test/Milvus.ConformanceTests/MilvusEnsureCollectionTests.cs @@ -3,7 +3,10 @@ using CommunityToolkit.VectorData.Milvus; using Microsoft.Extensions.VectorData; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; +using Milvus.Client.V2.Requests.Collection; +using Milvus.Client.V2.Requests.Index; using Milvus.ConformanceTests.Support; using Xunit; @@ -17,11 +20,15 @@ public async Task EnsureCollectionExistsKeepsTheIndexOfAnExistingCollection() // The collection exists with an HNSW index, where the model asks for a Flat one: as another tool could create it. var client = MilvusTestStore.Instance.Client; var name = "ct_existing_index_" + Guid.NewGuid().ToString("N"); - await client.CreateCollectionAsync(name, - [FieldSchema.CreateVarchar("Id", 65535, isPrimaryKey: true), FieldSchema.CreateVarchar("Text", 65535, nullable: true), FieldSchema.CreateFloatVector("Vector", 3)]); - var records = client.GetCollection(name); - await records.CreateIndexAsync("Vector", IndexType.Hnsw, SimilarityMetricType.Cosine, - extraParams: new Dictionary { ["M"] = "8", ["efConstruction"] = "64" }); + var schema = new CollectionSchema(); + schema.Fields.Add(FieldSchema.CreateVarchar("Id", 65535, isPrimaryKey: true)); + schema.Fields.Add(FieldSchema.CreateVarchar("Text", 65535, nullable: true)); + schema.Fields.Add(FieldSchema.CreateFloatVector("Vector", 3)); + await client.CreateCollectionAsync(new CreateCollectionReq { CollectionName = name, Schema = schema }); + var index = new IndexParam("Vector", indexType: IndexType.Hnsw, metricType: MetricType.Cosine); + index.ExtraParams["M"] = "8"; + index.ExtraParams["efConstruction"] = "64"; + await client.CreateIndexAsync(new CreateIndexReq { CollectionName = name, Indexes = [index] }); using var collection = new MilvusCollection(client, name, ownsClient: false); try { @@ -29,7 +36,7 @@ await records.CreateIndexAsync("Vector", IndexType.Hnsw, SimilarityMetricType.Co await collection.UpsertAsync(new Record { Id = "a", Text = "apples", Vector = new float[] { 1, 0, 0 } }); Assert.Equal("a", Assert.Single(await collection.SearchAsync(new float[] { 1, 0, 0 }, 1).ToListAsync()).Record.Id); - Assert.Contains(Assert.Single(await records.DescribeIndexAsync("Vector")).Params, p => p.Value == "HNSW"); + Assert.Equal(IndexType.Hnsw, Assert.Single((await client.DescribeIndexAsync(new DescribeIndexReq { CollectionName = name, FieldName = "Vector" })).Indexes).IndexType); } finally { diff --git a/MEVD/test/Milvus.ConformanceTests/MilvusRoundTripTests.cs b/MEVD/test/Milvus.ConformanceTests/MilvusRoundTripTests.cs index 7cd34ef..bab74ab 100644 --- a/MEVD/test/Milvus.ConformanceTests/MilvusRoundTripTests.cs +++ b/MEVD/test/Milvus.ConformanceTests/MilvusRoundTripTests.cs @@ -3,7 +3,8 @@ using CommunityToolkit.VectorData.Milvus; using Microsoft.Extensions.VectorData; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using Xunit; using Milvus.ConformanceTests.Support; @@ -11,7 +12,7 @@ namespace Milvus.ConformanceTests; public sealed class MilvusRoundTripTests : IClassFixture { - private readonly MilvusClient _client; + private readonly MilvusClientV2 _client; public MilvusRoundTripTests(MilvusFixture fixture) => _client = ((MilvusTestStore)fixture.TestStore).Client; diff --git a/MEVD/test/Milvus.ConformanceTests/Support/MilvusTestStore.cs b/MEVD/test/Milvus.ConformanceTests/Support/MilvusTestStore.cs index 52c8dde..ef10fb8 100644 --- a/MEVD/test/Milvus.ConformanceTests/Support/MilvusTestStore.cs +++ b/MEVD/test/Milvus.ConformanceTests/Support/MilvusTestStore.cs @@ -3,7 +3,8 @@ using CommunityToolkit.VectorData.Milvus; using Microsoft.Extensions.VectorData; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using Testcontainers.Milvus; using VectorData.ConformanceTests.Support; @@ -23,9 +24,9 @@ internal sealed class MilvusTestStore : TestStore public int Port { get; private set; } - private MilvusClient? _client; + private MilvusClientV2? _client; - public MilvusClient Client => _client ?? throw new InvalidOperationException("Not initialized"); + public MilvusClientV2 Client => _client ?? throw new InvalidOperationException("Not initialized"); public MilvusVectorStore GetVectorStore(MilvusVectorStoreOptions options) => new(Client, ownsClient: false, options); @@ -33,6 +34,9 @@ private MilvusTestStore() { } + public static MilvusClientV2 CreateClient(string host, int port, string? apiKey = null) + => new(new ConnectConfig { Uri = $"http://{host}:{port}", ApiKey = apiKey }); + protected override async Task StartAsync() { if (_container is not null) @@ -43,7 +47,7 @@ protected override async Task StartAsync() var port = int.Parse(Environment.GetEnvironmentVariable("MILVUS_PORT") ?? "19530", System.Globalization.CultureInfo.InvariantCulture); Host = host; Port = _container?.GetMappedPublicPort(19530) ?? port; - _client = new MilvusClient(Host, Port); + _client = CreateClient(Host, Port); DefaultVectorStore = new MilvusVectorStore(_client, ownsClient: false); } diff --git a/MEVD/test/Milvus.UnitTests/MilvusArrayTests.cs b/MEVD/test/Milvus.UnitTests/MilvusArrayTests.cs index 28bb1f9..7ee430f 100644 --- a/MEVD/test/Milvus.UnitTests/MilvusArrayTests.cs +++ b/MEVD/test/Milvus.UnitTests/MilvusArrayTests.cs @@ -4,7 +4,8 @@ using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.VectorData; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using Xunit; namespace CommunityToolkit.VectorData.Milvus.UnitTests; @@ -25,7 +26,7 @@ public void SchemaSupportsNativeArrayElements(Type element) new VectorStoreVectorProperty("Vector", typeof(float[]), 3)] }; var model = new MilvusModelBuilder().BuildDynamic(definition, null); var field = Assert.Single(MilvusCollectionCreateMapping.MapCollectionDefinition(model), f => f.Name == "Values"); - Assert.Equal(MilvusDataType.Array, field.DataType); + Assert.Equal(DataType.Array, field.DataType); Assert.Equal(MilvusFieldMapping.GetDataType(element), field.ElementDataType); Assert.True(field.Nullable); Assert.Equal(4096, field.MaxCapacity); diff --git a/MEVD/test/Milvus.UnitTests/MilvusClientLifetimeTests.cs b/MEVD/test/Milvus.UnitTests/MilvusClientLifetimeTests.cs index c30ed44..f6b4709 100644 --- a/MEVD/test/Milvus.UnitTests/MilvusClientLifetimeTests.cs +++ b/MEVD/test/Milvus.UnitTests/MilvusClientLifetimeTests.cs @@ -10,7 +10,8 @@ using Grpc.Core; using Grpc.Net.Client; using Microsoft.Extensions.VectorData; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Requests.Collection; using Xunit; namespace CommunityToolkit.VectorData.Milvus.UnitTests; @@ -18,11 +19,12 @@ namespace CommunityToolkit.VectorData.Milvus.UnitTests; public sealed class MilvusClientLifetimeTests { [Fact] - public async Task CollectionsPreserveCallerOwnedGrpcChannel() + public async Task OwnedClientIsDisposedWithTheLastCollection() { + // Milvus.Client.V2 has no constructor taking a caller-owned GrpcChannel: the client owns its channel, so + // disposing the owned client disposes the handler too. using var handler = new MilvusHandler(); - using var channel = GrpcChannel.ForAddress("http://localhost", new() { HttpHandler = handler, DisposeHttpClient = true }); - using var client = new MilvusClient(channel); + using var client = TestClients.FromHandler(handler); var store = new MilvusVectorStore(client, ownsClient: true); using var collection = store.GetCollection("records"); store.Dispose(); @@ -30,8 +32,6 @@ public async Task CollectionsPreserveCallerOwnedGrpcChannel() Assert.True(await collection.CollectionExistsAsync()); Assert.False(handler.Disposed); collection.Dispose(); - Assert.False(handler.Disposed); - channel.Dispose(); Assert.True(handler.Disposed); } @@ -39,13 +39,12 @@ public async Task CollectionsPreserveCallerOwnedGrpcChannel() public async Task BorrowedClientSurvivesDisposalOfStoreAndCollection() { using var handler = new MilvusHandler(); - using var channel = GrpcChannel.ForAddress("http://localhost", new() { HttpHandler = handler, DisposeHttpClient = true }); - using var client = new MilvusClient(channel); + using var client = TestClients.FromHandler(handler); using var store = new MilvusVectorStore(client, ownsClient: false); using var collection = store.GetCollection("records"); collection.Dispose(); store.Dispose(); - Assert.True(await client.HasCollectionAsync("records")); + Assert.True((await client.HasCollectionAsync(new HasCollectionReq { CollectionName = "records" })).Has); Assert.False(handler.Disposed); } @@ -54,7 +53,7 @@ public async Task BorrowedClientSurvivesDisposalOfStoreAndCollection() [InlineData(true)] public async Task DisposingCollectionRepeatedlyDoesNotReleaseSiblingShare(bool concurrently) { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var store = new MilvusVectorStore(client, ownsClient: true); using var first = store.GetCollection("first"); using var second = store.GetCollection("second"); @@ -78,7 +77,7 @@ public async Task DisposingCollectionRepeatedlyDoesNotReleaseSiblingShare(bool c [Fact] public async Task DisposingStoreRepeatedlyDoesNotReleaseCollectionShares() { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var store = new MilvusVectorStore(client, ownsClient: true); using var first = store.GetCollection("first"); using var second = store.GetCollection("second"); @@ -96,11 +95,12 @@ public async Task DisposingStoreRepeatedlyDoesNotReleaseCollectionShares() public async Task WrapsGrpcFailuresWithCollectionMetadata() { using var handler = new MilvusHandler { GrpcStatus = "14" }; - using var channel = GrpcChannel.ForAddress("http://localhost", new() { HttpHandler = handler, DisposeHttpClient = true }); - using var client = new MilvusClient(channel); + using var client = TestClients.FromHandler(handler); using var collection = new MilvusCollection(client, "records", ownsClient: false); var exception = await Assert.ThrowsAsync(() => collection.CollectionExistsAsync()); - Assert.IsType(exception.InnerException); + // Milvus.Client.V2 wraps gRPC failures in MilvusException, keeping the gRPC status. + var inner = Assert.IsType(exception.InnerException); + Assert.Equal(StatusCode.Unavailable, inner.GrpcStatusCode); Assert.Equal("milvus", exception.VectorStoreSystemName); Assert.Equal("records", exception.CollectionName); Assert.Equal("CollectionExists", exception.OperationName); @@ -119,9 +119,9 @@ public async Task WrapsMilvusFailuresWithOperationMetadata() [Fact] public async Task OwnedClientIsDisposedWhenTheCollectionCannotBeCreated() { - var unsupportedKey = new MilvusClient("localhost", port: 1); - var invalidModel = new MilvusClient("localhost", port: 1); - var noDefinition = new MilvusClient("localhost", port: 1); + var unsupportedKey = TestClients.Create(port: 1); + var invalidModel = TestClients.Create(port: 1); + var noDefinition = TestClients.Create(port: 1); Assert.Throws(() => new MilvusCollection(unsupportedKey, "records", ownsClient: true)); Assert.Throws(() => new MilvusCollection(invalidModel, "records", ownsClient: true)); @@ -135,7 +135,7 @@ public async Task OwnedClientIsDisposedWhenTheCollectionCannotBeCreated() [Fact] public async Task BorrowedClientSurvivesACollectionThatCannotBeCreated() { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); Assert.Throws(() => new MilvusCollection(client, "records", ownsClient: false)); @@ -145,7 +145,7 @@ public async Task BorrowedClientSurvivesACollectionThatCannotBeCreated() [Fact] public async Task StoreKeepsItsClientWhenOneOfItsCollectionsCannotBeCreated() { - var client = new MilvusClient("localhost", port: 1); + var client = TestClients.Create(port: 1); var store = new MilvusVectorStore(client, ownsClient: true); Assert.Throws(() => store.GetCollection("records")); @@ -157,11 +157,11 @@ public async Task StoreKeepsItsClientWhenOneOfItsCollectionsCannotBeCreated() // Calls the client with a canceled token: a disposed client throws ObjectDisposedException, another the cancellation, // without contacting a server. - private static async Task CallAsync(MilvusClient client) + private static async Task CallAsync(MilvusClientV2 client) { using var canceled = new CancellationTokenSource(); canceled.Cancel(); - return await Record.ExceptionAsync(() => client.HasCollectionAsync("records", cancellationToken: canceled.Token)); + return await Record.ExceptionAsync(() => client.HasCollectionAsync(new HasCollectionReq { CollectionName = "records" }, canceled.Token)); } public sealed class InvalidRecord diff --git a/MEVD/test/Milvus.UnitTests/MilvusCollectionTests.cs b/MEVD/test/Milvus.UnitTests/MilvusCollectionTests.cs index 8dd311d..135d6b4 100644 --- a/MEVD/test/Milvus.UnitTests/MilvusCollectionTests.cs +++ b/MEVD/test/Milvus.UnitTests/MilvusCollectionTests.cs @@ -7,7 +7,8 @@ using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.VectorData; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using Xunit; namespace CommunityToolkit.VectorData.Milvus.UnitTests; @@ -17,7 +18,7 @@ public sealed class MilvusCollectionTests [Fact] public async Task EmptyBatchesDoNotContactServer() { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var collection = new MilvusCollection(client, "records", ownsClient: false); await collection.UpsertAsync(Array.Empty()); await collection.DeleteAsync(Array.Empty()); @@ -27,20 +28,20 @@ public async Task EmptyBatchesDoNotContactServer() [Fact] public void StoreExposesUnderlyingClientAndMetadata() { - using var client = new MilvusClient("localhost"); + using var client = TestClients.Create(); using var store = new MilvusVectorStore(client, ownsClient: false); - Assert.Same(client, store.GetService(typeof(MilvusClient))); + Assert.Same(client, store.GetService(typeof(MilvusClientV2))); Assert.Equal("milvus", Assert.IsType(store.GetService(typeof(VectorStoreMetadata))).VectorStoreSystemName); - Assert.Null(store.GetService(typeof(MilvusClient), "key")); + Assert.Null(store.GetService(typeof(MilvusClientV2), "key")); using var collection = store.GetCollection("records"); - Assert.Same(client, collection.GetService(typeof(MilvusClient))); + Assert.Same(client, collection.GetService(typeof(MilvusClientV2))); Assert.Null(collection.GetService(typeof(IKeywordHybridSearchable))); } [Fact] public void DependencyInjectionResolvesKeyedAndUnkeyedCollections() { - using var client = new MilvusClient("localhost"); + using var client = TestClients.Create(); var services = new ServiceCollection().AddSingleton(client) .AddMilvusVectorStore() .AddKeyedMilvusVectorStore("store") @@ -56,7 +57,7 @@ public void DependencyInjectionResolvesKeyedAndUnkeyedCollections() [Fact] public async Task RejectsInvalidSearchBeforeContactingServer() { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var collection = new MilvusCollection(client, "records", ownsClient: false); await Assert.ThrowsAsync(async () => await collection.SearchAsync(new float[] { 1, 2, 3 }, 0).ToListAsync()); await Assert.ThrowsAsync(async () => await collection.SearchAsync(new float[] { 1 }, 1).ToListAsync()); @@ -65,7 +66,7 @@ public async Task RejectsInvalidSearchBeforeContactingServer() [Fact] public void DynamicCollectionRequiresDefinition() { - using var client = new MilvusClient("localhost"); + using var client = TestClients.Create(); Assert.Throws(() => new MilvusDynamicCollection(client, "records", ownsClient: false, new())); Assert.Throws(() => new MilvusCollection>(client, "records", ownsClient: false)); } diff --git a/MEVD/test/Milvus.UnitTests/MilvusDatabaseTests.cs b/MEVD/test/Milvus.UnitTests/MilvusDatabaseTests.cs index 13e4235..0b8b200 100644 --- a/MEVD/test/Milvus.UnitTests/MilvusDatabaseTests.cs +++ b/MEVD/test/Milvus.UnitTests/MilvusDatabaseTests.cs @@ -4,7 +4,8 @@ using CommunityToolkit.VectorData.UnitTests; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.VectorData; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using Xunit; namespace CommunityToolkit.VectorData.Milvus.UnitTests; @@ -23,7 +24,7 @@ public void OptionsHaveNoDatabase() public void SuppliedClientLeavesTheDatabaseOutOfTheMetadata() { // Milvus.Client does not expose the database it is configured with. - using var client = new MilvusClient("localhost", database: "catalog"); + using var client = TestClients.Create(database: "catalog"); using var store = new MilvusVectorStore(client, ownsClient: false); Assert.Null(Assert.IsType(store.GetService(typeof(VectorStoreMetadata))).VectorStoreName); using var typed = store.GetCollection("records"); diff --git a/MEVD/test/Milvus.UnitTests/MilvusEnsureCollectionTests.cs b/MEVD/test/Milvus.UnitTests/MilvusEnsureCollectionTests.cs index 6aec39b..f7ab0fd 100644 --- a/MEVD/test/Milvus.UnitTests/MilvusEnsureCollectionTests.cs +++ b/MEVD/test/Milvus.UnitTests/MilvusEnsureCollectionTests.cs @@ -11,7 +11,8 @@ using System.Threading.Tasks; using Grpc.Net.Client; using Microsoft.Extensions.VectorData; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using Xunit; namespace CommunityToolkit.VectorData.Milvus.UnitTests; @@ -22,8 +23,7 @@ public sealed class MilvusEnsureCollectionTests public async Task CreatesTheIndexesWithTheCollection() { using var handler = new RecordingHandler { CollectionExists = false }; - using var channel = GrpcChannel.ForAddress("http://localhost", new() { HttpHandler = handler, DisposeHttpClient = true }); - using var client = new MilvusClient(channel); + using var client = TestClients.FromHandler(handler); using var collection = new MilvusCollection(client, "records", ownsClient: false); await collection.EnsureCollectionExistsAsync(); @@ -38,8 +38,7 @@ public async Task CreatesTheIndexesWithTheCollection() public async Task LeavesTheIndexesOfAnExistingCollectionAsTheyAre() { using var handler = new RecordingHandler { CollectionExists = true }; - using var channel = GrpcChannel.ForAddress("http://localhost", new() { HttpHandler = handler, DisposeHttpClient = true }); - using var client = new MilvusClient(channel); + using var client = TestClients.FromHandler(handler); using var collection = new MilvusCollection(client, "records", ownsClient: false); await collection.EnsureCollectionExistsAsync(); @@ -54,8 +53,7 @@ public async Task ReportsALoadThatDoesNotEndAsAVectorStoreException() { // The server reports the load at 1% at each poll. using var handler = new RecordingHandler { CollectionExists = true, LoadingProgress = 1 }; - using var channel = GrpcChannel.ForAddress("http://localhost", new() { HttpHandler = handler, DisposeHttpClient = true }); - using var client = new MilvusClient(channel); + using var client = TestClients.FromHandler(handler); using var collection = new MilvusCollection(client, "records", ownsClient: false, options: new() { LoadTimeout = TimeSpan.FromMilliseconds(100) }); @@ -87,7 +85,7 @@ public void CopiesLoadTimeout() [InlineData(-1)] public void RejectsNonPositiveLoadTimeout(int seconds) { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); var options = new MilvusCollectionOptions { LoadTimeout = TimeSpan.FromSeconds(seconds) }; Assert.Throws(() => @@ -113,7 +111,7 @@ public void DefaultsAndCopiesHnswSettings() [InlineData(16, -1)] public void RejectsNonPositiveHnswSettings(int m, int efConstruction) { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); var options = new MilvusCollectionOptions { HnswM = m, HnswEfConstruction = efConstruction }; Assert.Throws(() => @@ -124,8 +122,7 @@ public void RejectsNonPositiveHnswSettings(int m, int efConstruction) public async Task SendsConfiguredHnswSettingsWhenCreatingIndex() { using var handler = new RecordingHandler(); - using var channel = GrpcChannel.ForAddress("http://localhost", new() { HttpHandler = handler, DisposeHttpClient = true }); - using var client = new MilvusClient(channel); + using var client = TestClients.FromHandler(handler); using var collection = new MilvusCollection(client, "records", ownsClient: false, options: new() { HnswM = 32, HnswEfConstruction = 300 }); @@ -147,7 +144,7 @@ public sealed class HnswRecord public ReadOnlyMemory Vector { get; set; } } - // Answers each gRPC call of Milvus.Client with an empty status, and records the methods called. + // Answers each gRPC call of Milvus.Client.V2 with an empty status, and records the methods called. internal sealed class RecordingHandler : HttpMessageHandler { private readonly List _methods = []; @@ -189,6 +186,8 @@ protected override async Task SendAsync(HttpRequestMessage { "HasCollection" => CollectionExists ? 1 : 0, "GetLoadingProgress" => LoadingProgress, + // Milvus.Client.V2 polls the load state: 3 is Loaded, 2 is Loading. + "GetLoadState" => LoadingProgress == 100 ? 3 : 2, _ => 1, }; var response = new HttpResponseMessage(HttpStatusCode.OK) diff --git a/MEVD/test/Milvus.UnitTests/MilvusFullTextTests.cs b/MEVD/test/Milvus.UnitTests/MilvusFullTextTests.cs index bfdab94..a423214 100644 --- a/MEVD/test/Milvus.UnitTests/MilvusFullTextTests.cs +++ b/MEVD/test/Milvus.UnitTests/MilvusFullTextTests.cs @@ -7,7 +7,8 @@ using CommunityToolkit.VectorData.UnitTests; using Microsoft.Extensions.VectorData; using Microsoft.Extensions.VectorData.ProviderServices; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using Xunit; namespace CommunityToolkit.VectorData.Milvus.UnitTests; @@ -28,11 +29,11 @@ public void FullTextPropertyGetsAnAnalyzerAHiddenSparseFieldAndABm25Function() new VectorStoreDataProperty("Title", typeof(string)))); var text = Assert.Single(schema.Fields, f => f.Name == "body"); - Assert.Equal(MilvusDataType.VarChar, text.DataType); + Assert.Equal(DataType.VarChar, text.DataType); Assert.True(text.EnableAnalyzer); Assert.True(text.Nullable); Assert.False(Assert.Single(schema.Fields, f => f.Name == "Title").EnableAnalyzer); - Assert.Equal(MilvusDataType.SparseFloatVector, Assert.Single(schema.Fields, f => f.Name == "body_bm25").DataType); + Assert.Equal(DataType.SparseFloatVector, Assert.Single(schema.Fields, f => f.Name == "body_bm25").DataType); var function = Assert.Single(schema.Functions); Assert.Equal(FunctionType.Bm25, function.Type); Assert.Equal("body_bm25", function.Name); @@ -47,7 +48,7 @@ public void EachFullTextPropertyGetsItsOwnBm25Field() new VectorStoreDataProperty("Text1", typeof(string)) { IsFullTextIndexed = true }, new VectorStoreDataProperty("Text2", typeof(string)) { IsFullTextIndexed = true })); - Assert.Equal(["Text1_bm25", "Text2_bm25"], schema.Fields.Where(f => f.DataType == MilvusDataType.SparseFloatVector).Select(f => f.Name)); + Assert.Equal(["Text1_bm25", "Text2_bm25"], schema.Fields.Where(f => f.DataType == DataType.SparseFloatVector).Select(f => f.Name)); Assert.Equal(["Text1", "Text2"], schema.Functions.SelectMany(f => f.InputFieldNames)); } @@ -56,7 +57,7 @@ public void ModelWithoutFullTextHasNoBm25FieldOrFunction() { var schema = MilvusCollectionCreateMapping.MapCollectionSchema(Build(new VectorStoreDataProperty("Text", typeof(string)) { IsIndexed = true })); - Assert.DoesNotContain(schema.Fields, f => f.DataType == MilvusDataType.SparseFloatVector || f.EnableAnalyzer); + Assert.DoesNotContain(schema.Fields, f => f.DataType == DataType.SparseFloatVector || f.EnableAnalyzer); Assert.Empty(schema.Functions); } @@ -136,7 +137,7 @@ public void SupportsTheDefinitionOfTheChatHistoryMemoryProviderOfAgentFramework( new VectorStoreVectorProperty("ContentEmbedding", typeof(string), 3), ], }; - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var store = new MilvusVectorStore(client, ownsClient: false, new() { EmbeddingGenerator = new FakeEmbeddingGenerator() }); using var collection = store.GetDynamicCollection("chat_history", definition); @@ -150,7 +151,7 @@ public void SupportsTheDefinitionOfTheChatHistoryMemoryProviderOfAgentFramework( public void SupportsTheDefinitionOfTheTextSearchStoreOfSemanticKernel() { // TextSearchStore of Microsoft.SemanticKernel.Core 1.80.1 creates a typed collection with this definition. - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var store = new MilvusVectorStore(client, ownsClient: false, new() { EmbeddingGenerator = new FakeEmbeddingGenerator() }); using var collection = store.GetCollection("docs", TextSearchStoreDocument.Definition(3)); diff --git a/MEVD/test/Milvus.UnitTests/MilvusHybridSearchTests.cs b/MEVD/test/Milvus.UnitTests/MilvusHybridSearchTests.cs index 94bf9d0..99f4ec1 100644 --- a/MEVD/test/Milvus.UnitTests/MilvusHybridSearchTests.cs +++ b/MEVD/test/Milvus.UnitTests/MilvusHybridSearchTests.cs @@ -8,7 +8,8 @@ using CommunityToolkit.VectorData.UnitTests; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.VectorData; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using Xunit; namespace CommunityToolkit.VectorData.Milvus.UnitTests; @@ -28,7 +29,7 @@ public sealed class MilvusHybridSearchTests [Fact] public void GetServiceReturnsTheCollectionWhenAPropertyIsFullTextIndexed() { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var typed = new MilvusCollection(client, "typed", ownsClient: false); using var dynamic = new MilvusDynamicCollection(client, "dynamic", ownsClient: false, new() { Definition = s_definition, EmbeddingGenerator = new FakeEmbeddingGenerator() }); using var withoutText = new MilvusCollection(client, "without_text", ownsClient: false); @@ -42,7 +43,7 @@ public void GetServiceReturnsTheCollectionWhenAPropertyIsFullTextIndexed() [Fact] public void DependencyInjectionResolvesHybridSearch() { - using var client = new MilvusClient("localhost"); + using var client = TestClients.Create(); using var provider = new ServiceCollection().AddSingleton(client) .AddMilvusCollection("records") .AddKeyedMilvusCollection("key", "other_records") @@ -55,7 +56,7 @@ public void DependencyInjectionResolvesHybridSearch() [Fact] public async Task RejectsInvalidHybridSearchesBeforeContactingTheServer() { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var collection = new MilvusCollection(client, "records", ownsClient: false); await Assert.ThrowsAsync(async () => await collection.HybridSearchAsync(new float[] { 1, 2, 3 }, ["apples"], 0).ToListAsync()); @@ -71,7 +72,7 @@ await Assert.ThrowsAsync(async () => await collection [InlineData(int.MaxValue, 1)] public async Task RejectsTopAndSkipBeyondTheMilvusLimitBeforeContactingTheServer(int top, int skip) { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var collection = new MilvusCollection(client, "records", ownsClient: false); var exception = await Assert.ThrowsAsync(async () => await collection.HybridSearchAsync(new float[] { 1, 2, 3 }, ["apples"], top, @@ -83,7 +84,7 @@ public async Task RejectsTopAndSkipBeyondTheMilvusLimitBeforeContactingTheServer [Fact] public async Task RejectsIncludeVectorsWithEmbeddingGeneration() { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var collection = new MilvusDynamicCollection(client, "records", ownsClient: false, new() { Definition = s_definition, EmbeddingGenerator = new FakeEmbeddingGenerator() }); await Assert.ThrowsAsync(async () => await collection.HybridSearchAsync("apples", ["apples"], 1, new() { IncludeVectors = true }).ToListAsync()); @@ -92,7 +93,7 @@ public async Task RejectsIncludeVectorsWithEmbeddingGeneration() [Fact] public async Task RejectsHybridSearchWithoutAFullTextProperty() { - using var client = new MilvusClient("localhost", port: 1); + using var client = TestClients.Create(port: 1); using var collection = new MilvusCollection(client, "records", ownsClient: false); await Assert.ThrowsAsync(async () => await collection.HybridSearchAsync(new float[] { 1, 2, 3 }, ["apples"], 1).ToListAsync()); diff --git a/MEVD/test/Milvus.UnitTests/MilvusMappingTests.cs b/MEVD/test/Milvus.UnitTests/MilvusMappingTests.cs index e902025..972766f 100644 --- a/MEVD/test/Milvus.UnitTests/MilvusMappingTests.cs +++ b/MEVD/test/Milvus.UnitTests/MilvusMappingTests.cs @@ -7,7 +7,8 @@ using Microsoft.Extensions.AI; using Microsoft.Extensions.VectorData; using Microsoft.Extensions.VectorData.ProviderServices; -using Milvus.Client; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; using Xunit; namespace CommunityToolkit.VectorData.Milvus.UnitTests; @@ -22,12 +23,12 @@ public void SchemaUsesNativeFieldsAndStorageNames() var fields = MilvusCollectionCreateMapping.MapCollectionDefinition(Model()); var key = Assert.Single(fields, f => f.IsPrimaryKey); Assert.Equal("record_id", key.Name); - Assert.Equal(MilvusDataType.VarChar, key.DataType); + Assert.Equal(DataType.VarChar, key.DataType); Assert.False(key.AutoId); Assert.True(Assert.Single(fields, f => f.Name == "label").Nullable); var count = Assert.Single(fields, f => f.Name == "Count"); Assert.True(count.Nullable); - Assert.Equal(MilvusDataType.Int32, count.DataType); + Assert.Equal(DataType.Int32, count.DataType); Assert.Equal(3, Assert.Single(fields, f => f.Name == "Vector").Dimension); } @@ -38,7 +39,7 @@ public void LongKeyUsesInt64() { Properties = [new VectorStoreKeyProperty("Id", typeof(long)), new VectorStoreVectorProperty("Vector", typeof(float[]), 3)], }, null); - Assert.Equal(MilvusDataType.Int64, MilvusCollectionCreateMapping.MapCollectionDefinition(model)[0].DataType); + Assert.Equal(DataType.Int64, MilvusCollectionCreateMapping.MapCollectionDefinition(model)[0].DataType); } [Fact] @@ -75,12 +76,12 @@ public void MapperRejectsWrongDimensions() } [Theory] - [InlineData(null, SimilarityMetricType.Cosine)] - [InlineData(DistanceFunction.CosineSimilarity, SimilarityMetricType.Cosine)] - [InlineData(DistanceFunction.DotProductSimilarity, SimilarityMetricType.Ip)] - [InlineData(DistanceFunction.EuclideanSquaredDistance, SimilarityMetricType.L2)] - [InlineData(DistanceFunction.EuclideanDistance, SimilarityMetricType.L2)] - public void MapsSupportedDistances(string? distance, SimilarityMetricType expected) + [InlineData(null, MetricType.Cosine)] + [InlineData(DistanceFunction.CosineSimilarity, MetricType.Cosine)] + [InlineData(DistanceFunction.DotProductSimilarity, MetricType.Ip)] + [InlineData(DistanceFunction.EuclideanSquaredDistance, MetricType.L2)] + [InlineData(DistanceFunction.EuclideanDistance, MetricType.L2)] + public void MapsSupportedDistances(string? distance, MetricType expected) => Assert.Equal(expected, MilvusCollectionCreateMapping.GetMetric(new VectorPropertyModel("Vector", typeof(float[])) { Dimensions = 3, DistanceFunction = distance })); [Theory] diff --git a/MEVD/test/Milvus.UnitTests/TestClients.cs b/MEVD/test/Milvus.UnitTests/TestClients.cs new file mode 100644 index 0000000..f81e694 --- /dev/null +++ b/MEVD/test/Milvus.UnitTests/TestClients.cs @@ -0,0 +1,27 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Net.Http; +using Milvus.Client.V2; +using Milvus.Client.V2.Types; + +namespace CommunityToolkit.VectorData.Milvus.UnitTests; + +/// Creates instances for tests that do not reach a real server. +internal static class TestClients +{ + public static MilvusClientV2 Create(int port = 19530, string? database = null) + => new(new ConnectConfig { Uri = $"http://localhost:{port}", Database = database }); + + /// + /// Creates a client whose gRPC calls go to . Milvus.Client.V2 cannot take a caller-owned + /// channel, so the channel, and with it the handler, is owned and disposed by the client. + /// + public static MilvusClientV2 FromHandler(HttpMessageHandler handler, string? database = null) + => new(new ConnectConfig + { + Uri = "http://localhost:19530", + Database = database, + ChannelOptions = new() { HttpHandler = handler, DisposeHttpClient = true }, + }); +} From 279b6aa916c5668d8d10e54187d982e26981609f Mon Sep 17 00:00:00 2001 From: N-E-W-T-O-N Date: Thu, 19 Nov 2026 01:17:10 +0530 Subject: [PATCH 2/4] Milvus: address review feedback - Use Milvus.Client.V2 3.0.1, which fixes searches with no results (milvus-io/milvus-sdk-csharp#198) and search in trimmed and NativeAOT apps (milvus-io/milvus-sdk-csharp#204). - Throw when Milvus returns fewer rows than search hits, instead of returning records with only their key, with tests. - README: drop the IL2104/IL3053 note, which 3.0.1 no longer produces, and record the .NET Framework check with Milvus.Client.V2. - Bump the provider version to 1.1.0-preview: its public API changes. --- Directory.Packages.props | 2 +- MEVD/src/Milvus/Milvus.csproj | 2 +- MEVD/src/Milvus/MilvusCollection.cs | 6 +- MEVD/src/Milvus/README.md | 4 +- .../MilvusSearchResponseTests.cs | 114 ++++++++++++++++++ 5 files changed, 123 insertions(+), 5 deletions(-) create mode 100644 MEVD/test/Milvus.UnitTests/MilvusSearchResponseTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index bf00e5d..89dddc9 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ - + diff --git a/MEVD/src/Milvus/Milvus.csproj b/MEVD/src/Milvus/Milvus.csproj index 0082115..48ee643 100644 --- a/MEVD/src/Milvus/Milvus.csproj +++ b/MEVD/src/Milvus/Milvus.csproj @@ -1,7 +1,7 @@ - 1.0.0-preview + 1.1.0-preview CommunityToolkit.VectorData.Milvus $(AssemblyName) net10.0;net8.0;netstandard2.0;net462 diff --git a/MEVD/src/Milvus/MilvusCollection.cs b/MEVD/src/Milvus/MilvusCollection.cs index e3ca4e7..5362593 100644 --- a/MEVD/src/Milvus/MilvusCollection.cs +++ b/MEVD/src/Milvus/MilvusCollection.cs @@ -469,9 +469,13 @@ public async IAsyncEnumerable> HybridSearchAsync(StringComparer.Ordinal); + var row = rows[i]; row[keyName] = results.Ids.LongIds is { } longIds ? longIds[i] : results.Ids.StringIds![i]; yield return (row, results.Scores[i]); } diff --git a/MEVD/src/Milvus/README.md b/MEVD/src/Milvus/README.md index a89ff61..13ecea2 100644 --- a/MEVD/src/Milvus/README.md +++ b/MEVD/src/Milvus/README.md @@ -40,13 +40,13 @@ For more information, see the [Microsoft.Extensions.VectorData documentation](ht - `IsIndexed` does not create scalar indexes; Milvus can filter scalar fields without them. Supported vector indexes are automatic (default), Flat, and HNSW. - Field storage names must use ASCII letters, digits and underscores, starting with a letter or underscore. Reserved Milvus keywords are rejected during model construction. Varchar fields allow up to 65535 bytes. Schema changes on an existing collection require explicit management through the SDK. - Collection names must use ASCII letters, digits and underscores, start with a letter or underscore, and have at most 255 characters: Milvus rejects other names, such as `chathistory-local`. -- For NativeAOT, use dynamic dictionary collections with explicit definitions: the typed collection APIs use reflection. Publishing with trimming or NativeAOT shows the warnings `IL2104` and `IL3053` of the dependency `Milvus.Client.V2`. +- For NativeAOT, use dynamic dictionary collections with explicit definitions: the typed collection APIs use reflection. - On .NET Framework, `Milvus.Client.V2` calls Milvus over WinHTTP (`WinHttpHandler`, which `Grpc.Net.Client` brings in). This needs: - A TLS endpoint: `https: true` (the default) on the host-based registrations, or an `https://` URI in the `ConnectConfig` of a `MilvusClientV2`. A plaintext endpoint fails with `Response protocol downgraded to HTTP/1.1`. - A server certificate that Windows trusts. To validate it another way, set `ConnectConfig.ChannelOptions` to `GrpcChannelOptions` with a `WinHttpHandler` and pass that client to the provider. - Windows 11 or later. Windows Server 2019 and 2022 support gRPC over WinHTTP only partially. See [Microsoft's gRPC requirements for .NET Framework](https://learn.microsoft.com/aspnet/core/grpc/netstandard#net-framework). - Verified on Windows 11 with .NET Framework 4.7.2 against Milvus 2.6.25 over TLS with the V1 `Milvus.Client`; not yet re-verified with `Milvus.Client.V2`. + Verified on Windows 11 with .NET Framework 4.7.2 against Milvus 2.6.25 over TLS with `Milvus.Client.V2`, the certificate validated through `ConnectConfig.ChannelOptions`. Host-based registrations accept `database`, `username`/`password`, or `apiKey`. The two authentication modes are mutually exclusive. Keyed variants are also available: diff --git a/MEVD/test/Milvus.UnitTests/MilvusSearchResponseTests.cs b/MEVD/test/Milvus.UnitTests/MilvusSearchResponseTests.cs new file mode 100644 index 0000000..0dbce48 --- /dev/null +++ b/MEVD/test/Milvus.UnitTests/MilvusSearchResponseTests.cs @@ -0,0 +1,114 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.VectorData; +using Xunit; + +namespace CommunityToolkit.VectorData.Milvus.UnitTests; + +public sealed class MilvusSearchResponseTests +{ + [Fact] + public async Task SearchThrowsWhenTheResponseHasFewerRowsThanHits() + { + // Two hits, but the output fields hold a single row. + using var handler = new SearchHandler(ids: ["a", "b"], rowIds: ["a"]); + using var client = TestClients.FromHandler(handler); + using var collection = new MilvusCollection(client, "records", ownsClient: false); + + await Assert.ThrowsAsync( + async () => await collection.SearchAsync(new ReadOnlyMemory([1f, 0f, 0f]), 2).ToListAsync()); + } + + [Fact] + public async Task SearchReturnsOneRecordPerHit() + { + using var handler = new SearchHandler(ids: ["a", "b"], rowIds: ["a", "b"]); + using var client = TestClients.FromHandler(handler); + using var collection = new MilvusCollection(client, "records", ownsClient: false); + + var results = await collection.SearchAsync(new ReadOnlyMemory([1f, 0f, 0f]), 2).ToListAsync(); + + Assert.Equal(["a", "b"], results.Select(r => r.Record.Id)); + } + + public sealed class KeyOnlyRecord + { + [VectorStoreKey] + public string Id { get; set; } = string.Empty; + + [VectorStoreVector(3)] + public ReadOnlyMemory Vector { get; set; } + } + + // Answers Search with a SearchResults message built by hand, and every other gRPC call with an empty status. + private sealed class SearchHandler(string[] ids, string[] rowIds) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var method = request.RequestUri!.AbsolutePath.Split('/').Last(); + var message = method == "Search" ? SearchResults() : [10, 0, 16, 1]; + var frame = new byte[5 + message.Length]; + frame[1] = (byte)(message.Length >> 24); + frame[2] = (byte)(message.Length >> 16); + frame[3] = (byte)(message.Length >> 8); + frame[4] = (byte)message.Length; + message.CopyTo(frame, 5); + var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = new Version(2, 0), Content = new ByteArrayContent(frame) }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/grpc"); + response.TrailingHeaders.Add("grpc-status", "0"); + return Task.FromResult(response); + } + + // milvus.proto.milvus.SearchResults { status = 1; results = 2 } with + // milvus.proto.schema.SearchResultData { num_queries = 1; top_k = 2; fields_data = 3; scores = 4; ids = 5; topks = 6 }. + private byte[] SearchResults() + { + var keyColumn = Concat( + Field(1, Varint(21)), // type: VarChar + Field(2, Bytes(Encoding.UTF8.GetBytes("Id"))), // field_name + Field(3, Bytes(Field(6, Bytes(Strings(rowIds)))))); // scalars.string_data + var scores = Concat(ids.Select((_, i) => BitConverter.GetBytes(1f - (0.1f * i))).ToArray()); + var data = Concat( + Field(1, Varint(1)), + Field(2, Varint((ulong)ids.Length)), + Field(3, Bytes(keyColumn)), + Field(4, Bytes(scores)), + Field(5, Bytes(Field(2, Bytes(Strings(ids))))), // ids.str_id + Field(6, Bytes(Varint((ulong)ids.Length).Item2))); + return Concat(Field(1, Bytes([])), Field(2, Bytes(data))); + } + + private static byte[] Strings(IEnumerable values) + => Concat(values.Select(v => Field(1, Bytes(Encoding.UTF8.GetBytes(v)))).ToArray()); + + private static byte[] Field(int number, (int WireType, byte[] Payload) value) + => Concat(Varint((ulong)((number << 3) | value.WireType)).Item2, value.Payload); + + private static (int, byte[]) Varint(ulong value) + { + var bytes = new List(); + do + { + var b = (byte)(value & 0x7F); + value >>= 7; + bytes.Add(value == 0 ? b : (byte)(b | 0x80)); + } + while (value != 0); + return (0, bytes.ToArray()); + } + + private static (int, byte[]) Bytes(byte[] value) => (2, Concat(Varint((ulong)value.Length).Item2, value)); + + private static byte[] Concat(params byte[][] parts) => parts.SelectMany(p => p).ToArray(); + } +} From b147fc5124791ef67648a016f83feea2eade270a Mon Sep 17 00:00:00 2001 From: NEWTON MALLICK <38786893+N-E-W-T-O-N@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:34:30 +0530 Subject: [PATCH 3/4] fix:Adjust timeout calculation for LoadCollectionAsync Milvus V2 defines TimeoutMs = 0 as waiting forever, so a valid finite timeout can leave EnsureCollectionExistsAsync polling indefinitely unless canceled. Adding Math.Ceiling resolve the issue --- MEVD/src/Milvus/MilvusCollection.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MEVD/src/Milvus/MilvusCollection.cs b/MEVD/src/Milvus/MilvusCollection.cs index 5362593..043fd3f 100644 --- a/MEVD/src/Milvus/MilvusCollection.cs +++ b/MEVD/src/Milvus/MilvusCollection.cs @@ -583,7 +583,7 @@ private Task LoadAsync(CancellationToken cancellationToken) { CollectionName = Name, Sync = true, - TimeoutMs = (long)_loadTimeout.TotalMilliseconds, + TimeoutMs = (long)Math.Ceiling(_loadTimeout.TotalMilliseconds), }, cancellationToken); /// From 7c779046e509c6042761f9fe74f1f5b632d50ec7 Mon Sep 17 00:00:00 2001 From: N-E-W-T-O-N Date: Thu, 19 Nov 2026 23:18:25 +0530 Subject: [PATCH 4/4] Milvus: time the collection load wait with a Stopwatch Milvus.Client.V2 takes the load timeout in whole milliseconds, where 0 means no timeout, and adds it to DateTime.UtcNow: LoadTimeout = TimeSpan.MaxValue threw ArgumentOutOfRangeException even when the collection loaded at once. Load without the SDK's wait and poll GetLoadState here, timed with a Stopwatch as Milvus.Client did, so any positive LoadTimeout works: one below a millisecond times out, TimeSpan.MaxValue waits until the load ends. Tests cover both. --- MEVD/src/Milvus/MilvusCollection.cs | 42 ++++++++++++++++--- MEVD/src/Milvus/MilvusConstants.cs | 3 ++ .../MilvusEnsureCollectionTests.cs | 28 +++++++++++++ 3 files changed, 67 insertions(+), 6 deletions(-) diff --git a/MEVD/src/Milvus/MilvusCollection.cs b/MEVD/src/Milvus/MilvusCollection.cs index 043fd3f..04442df 100644 --- a/MEVD/src/Milvus/MilvusCollection.cs +++ b/MEVD/src/Milvus/MilvusCollection.cs @@ -578,13 +578,43 @@ private QueryParameters CreateQueryParameters(bool includeVectors) return MilvusFieldMapping.ReadRows(response.FieldsData); } - private Task LoadAsync(CancellationToken cancellationToken) - => _clientWrapper.Client.LoadCollectionAsync(new LoadCollectionReq + /// + /// Loads the collection and waits until Milvus reports it loaded, for at most . + /// + /// + /// The wait is timed here with a , as Milvus.Client did, rather than by the synchronous load of + /// Milvus.Client.V2: that one takes the timeout in whole milliseconds, where 0 means no timeout, and adds it to + /// , which throws for a timeout such as . + /// + private async Task LoadAsync(CancellationToken cancellationToken) + { + await _clientWrapper.Client.LoadCollectionAsync(new LoadCollectionReq { CollectionName = Name, Sync = false }, cancellationToken) + .ConfigureAwait(false); + + var stopwatch = Stopwatch.StartNew(); + while (true) { - CollectionName = Name, - Sync = true, - TimeoutMs = (long)Math.Ceiling(_loadTimeout.TotalMilliseconds), - }, cancellationToken); + var state = (await _clientWrapper.Client.GetLoadStateAsync(new GetLoadStateReq { CollectionName = Name }, cancellationToken) + .ConfigureAwait(false)).State; + if (state == LoadState.Loaded) + { + return; + } + if (state == LoadState.NotExist) + { + throw new MilvusException(MilvusErrorCode.UnexpectedError, $"Collection '{Name}' does not exist; load did not complete."); + } + + // NotLoad right after the load request is transient: Milvus registers the load asynchronously. + var remaining = _loadTimeout - stopwatch.Elapsed; + if (remaining <= TimeSpan.Zero) + { + throw new TimeoutException($"Timed out waiting for collection '{Name}' to load."); + } + await Task.Delay(remaining < MilvusConstants.LoadPollInterval ? remaining : MilvusConstants.LoadPollInterval, cancellationToken) + .ConfigureAwait(false); + } + } /// /// Run the given operation and wrap any with . diff --git a/MEVD/src/Milvus/MilvusConstants.cs b/MEVD/src/Milvus/MilvusConstants.cs index f119f7a..650b012 100644 --- a/MEVD/src/Milvus/MilvusConstants.cs +++ b/MEVD/src/Milvus/MilvusConstants.cs @@ -19,6 +19,9 @@ internal static class MilvusConstants internal const int DefaultPort = 19530; + // How often EnsureCollectionExistsAsync asks whether the collection has loaded, as Milvus.Client.V2 does. + internal static readonly TimeSpan LoadPollInterval = TimeSpan.FromMilliseconds(500); + internal const int DefaultHnswSearchEf = 64; internal const int MaxFieldNameLength = 255; diff --git a/MEVD/test/Milvus.UnitTests/MilvusEnsureCollectionTests.cs b/MEVD/test/Milvus.UnitTests/MilvusEnsureCollectionTests.cs index f7ab0fd..21109bb 100644 --- a/MEVD/test/Milvus.UnitTests/MilvusEnsureCollectionTests.cs +++ b/MEVD/test/Milvus.UnitTests/MilvusEnsureCollectionTests.cs @@ -64,6 +64,34 @@ public async Task ReportsALoadThatDoesNotEndAsAVectorStoreException() Assert.Equal("records", exception.CollectionName); } + [Fact(Timeout = 30000)] + public async Task AcceptsTheLargestLoadTimeout() + { + // Milvus.Client.V2 adds its load timeout to DateTime.UtcNow, which TimeSpan.MaxValue overflows. + using var handler = new RecordingHandler { CollectionExists = true }; + using var client = TestClients.FromHandler(handler); + using var collection = new MilvusCollection(client, "records", ownsClient: false, + options: new() { LoadTimeout = TimeSpan.MaxValue }); + + await collection.EnsureCollectionExistsAsync(TestContext.Current.CancellationToken); + + Assert.Contains("GetLoadState", handler.Methods); + } + + [Fact(Timeout = 30000)] + public async Task TimesOutALoadTimeoutBelowAMillisecond() + { + // In whole milliseconds the timeout would be 0, which Milvus.Client.V2 takes as no timeout. + using var handler = new RecordingHandler { CollectionExists = true, LoadingProgress = 1 }; + using var client = TestClients.FromHandler(handler); + using var collection = new MilvusCollection(client, "records", ownsClient: false, + options: new() { LoadTimeout = TimeSpan.FromTicks(1) }); + + var exception = await Assert.ThrowsAsync(() => collection.EnsureCollectionExistsAsync(TestContext.Current.CancellationToken)); + + Assert.IsType(exception.InnerException); + } + [Fact] public void WaitsForTheLoadLongerThanMilvusDoes() {