Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(retriever): Qdrant/Milvus 关键词检索整批失败返回 error,不再当成「没有匹配」 (#3847)
linus-liu-web5f5093b9f74e
diff --git a/go.mod b/go.modindex 20ae07003..02256d68d 100644--- a/go.mod+++ b/go.mod@@ -239,7 +239,7 @@ require (github.com/mattn/go-colorable v0.1.13 // indirectgithub.com/mattn/go-isatty v0.0.22 // indirectgithub.com/mattn/go-sqlite3 v1.14.24 // indirect- github.com/milvus-io/milvus-proto/go-api/v2 v2.6.15 // indirect+ github.com/milvus-io/milvus-proto/go-api/v2 v2.6.15github.com/milvus-io/milvus/pkg/v2 v2.6.7-0.20251201120310-af64f2acba38 // indirectgithub.com/minio/crc64nvme v1.1.1 // indirectgithub.com/minio/md5-simd v1.1.2 // indirectdiff --git a/internal/application/repository/retriever/milvus/keywords_test.go b/internal/application/repository/retriever/milvus/keywords_test.gonew file mode 100644index 000000000..7a2d89078--- /dev/null+++ b/internal/application/repository/retriever/milvus/keywords_test.go@@ -0,0 +1,282 @@+package milvus++import (+ "bytes"+ "context"+ "net"+ "os"+ "testing"++ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/milvus-io/milvus-proto/go-api/v2/commonpb"+ "github.com/milvus-io/milvus-proto/go-api/v2/milvuspb"+ "github.com/milvus-io/milvus-proto/go-api/v2/schemapb"+ client "github.com/milvus-io/milvus/client/v2/milvusclient"+ "github.com/stretchr/testify/require"+ "google.golang.org/grpc"+)++// fakeMilvusService answers the three RPCs KeywordsRetrieve needs. The+// repository holds a concrete *client.Client, so an in-process Milvus endpoint+// is the only seam that exercises the real search path instead of a stub.+type fakeMilvusService struct {+ milvuspb.UnimplementedMilvusServiceServer+ collections []string+ search func(collectionName string) (*milvuspb.SearchResults, error)+ searches []string+}++func (s *fakeMilvusService) ShowCollections(+ _ context.Context, _ *milvuspb.ShowCollectionsRequest,+) (*milvuspb.ShowCollectionsResponse, error) {+ return &milvuspb.ShowCollectionsResponse{+ Status: &commonpb.Status{},+ CollectionNames: s.collections,+ }, nil+}++func (s *fakeMilvusService) DescribeCollection(+ _ context.Context, request *milvuspb.DescribeCollectionRequest,+) (*milvuspb.DescribeCollectionResponse, error) {+ return &milvuspb.DescribeCollectionResponse{+ Status: &commonpb.Status{},+ Schema: &schemapb.CollectionSchema{+ Name: request.GetCollectionName(),+ Fields: []*schemapb.FieldSchema{+ {FieldID: 100, Name: fieldID, DataType: schemapb.DataType_VarChar, IsPrimaryKey: true},+ {FieldID: 101, Name: fieldContent, DataType: schemapb.DataType_VarChar},+ {FieldID: 102, Name: fieldContentSparse, DataType: schemapb.DataType_SparseFloatVector},+ },+ },+ }, nil+}++func (s *fakeMilvusService) Search(+ _ context.Context, request *milvuspb.SearchRequest,+) (*milvuspb.SearchResults, error) {+ name := request.GetCollectionName()+ s.searches = append(s.searches, name)+ return s.search(name)+}++type keywordsMilvusHarness struct {+ repo *milvusRepository+ fake *fakeMilvusService+}++func newKeywordsMilvusHarness(t *testing.T, collections []string,+ search func(collectionName string) (*milvuspb.SearchResults, error),+) *keywordsMilvusHarness {+ t.Helper()+ fake := &fakeMilvusService{collections: collections, search: search}++ lis, err := net.Listen("tcp", "127.0.0.1:0")+ require.NoError(t, err)+ grpcSrv := grpc.NewServer()+ milvuspb.RegisterMilvusServiceServer(grpcSrv, fake)+ go func() { _ = grpcSrv.Serve(lis) }()+ t.Cleanup(grpcSrv.Stop)++ // DisableConn skips the Connect handshake, which this fake does not serve.+ c, err := client.New(context.Background(), &client.ClientConfig{+ Address: lis.Addr().String(),+ DisableConn: true,+ })+ require.NoError(t, err)+ t.Cleanup(func() { _ = c.Close(context.Background()) })++ return &keywordsMilvusHarness{+ repo: &milvusRepository{client: c, collectionBaseName: "weknora_embeddings"},+ fake: fake,+ }+}++func failedMilvusSearch() *milvuspb.SearchResults {+ return &milvuspb.SearchResults{Status: &commonpb.Status{+ ErrorCode: commonpb.ErrorCode_UnexpectedError,+ Reason: "milvus keyword search unavailable",+ }}+}++func emptyMilvusSearch() *milvuspb.SearchResults {+ return &milvuspb.SearchResults{+ Status: &commonpb.Status{},+ Results: &schemapb.SearchResultData{+ NumQueries: 1,+ Topks: []int64{0},+ Ids: &schemapb.IDs{IdField: &schemapb.IDs_StrId{StrId: &schemapb.StringArray{}}},+ },+ }+}++func milvusSearchHits(chunkID, content string) *milvuspb.SearchResults {+ return &milvuspb.SearchResults{+ Status: &commonpb.Status{},+ Results: &schemapb.SearchResultData{+ NumQueries: 1,+ Topks: []int64{1},+ Scores: []float32{0.75},+ Ids: &schemapb.IDs{+ IdField: &schemapb.IDs_StrId{StrId: &schemapb.StringArray{Data: []string{chunkID}}},+ },+ FieldsData: []*schemapb.FieldData{+ milvusStringField(fieldContent, content),+ milvusStringField(fieldChunkID, chunkID),+ },+ },+ }+}++func milvusStringField(name, value string) *schemapb.FieldData {+ return &schemapb.FieldData{+ Type: schemapb.DataType_VarChar,+ FieldName: name,+ Field: &schemapb.FieldData_Scalars{Scalars: &schemapb.ScalarField{+ Data: &schemapb.ScalarField_StringData{+ StringData: &schemapb.StringArray{Data: []string{value}},+ },+ }},+ }+}++func keywordsMilvusParams() types.RetrieveParams {+ return types.RetrieveParams{+ Query: "invoice total",+ TopK: 10,+ KnowledgeBaseIDs: []string{"kb-1"},+ }+}++// captureMilvusLogs redirects the package logger for one test, so the+// "No keyword matches found" conclusion can be asserted on directly.+func captureMilvusLogs(t *testing.T) *bytes.Buffer {+ t.Helper()+ var buf bytes.Buffer+ logger.SetOutput(&buf)+ t.Cleanup(func() { logger.SetOutput(os.Stdout) })+ return &buf+}++// A batch in which every matching collection fails must reach the caller as an+// error. Returning an empty result set with a nil error is indistinguishable+// from a genuine zero-hit search, and the QA pipeline answers "no relevant+// content" on top of it (#3835).+func TestMilvusKeywordsRetrieveFailsWhenEveryMatchedCollectionFails(t *testing.T) {+ logs := captureMilvusLogs(t)+ harness := newKeywordsMilvusHarness(t,+ []string{"weknora_embeddings_1024", "weknora_embeddings_1536", "other_collection"},+ func(string) (*milvuspb.SearchResults, error) { return failedMilvusSearch(), nil },+ )++ results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsMilvusParams())++ require.Error(t, err, "all-collections failure must surface as an error")+ require.Contains(t, err.Error(), "all 2 matched collections")+ require.Contains(t, err.Error(), "milvus keyword search unavailable")+ require.Nil(t, results, "no result set may accompany the error")+ require.Equal(t,+ []string{"weknora_embeddings_1024", "weknora_embeddings_1536"}, harness.fake.searches,+ "only base-name collections are searched",+ )+ require.NotContains(t, logs.String(), "No keyword matches found",+ "a failed batch must not be logged as a search that found no matches")+}++// One failing collection must not fail the batch as long as another one+// answered: partial results are still results. The failure must travel with+// them though (RetrieveResult.Error) — otherwise callers treat the incomplete+// answer as a complete one (#3835).+func TestMilvusKeywordsRetrieveKeepsResultsWhenOnlySomeCollectionsFail(t *testing.T) {+ logs := captureMilvusLogs(t)+ harness := newKeywordsMilvusHarness(t,+ []string{"weknora_embeddings_1024", "weknora_embeddings_1536"},+ func(name string) (*milvuspb.SearchResults, error) {+ if name == "weknora_embeddings_1024" {+ return failedMilvusSearch(), nil+ }+ return milvusSearchHits("chunk-1", "invoice total 42"), nil+ },+ )++ results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsMilvusParams())++ require.NoError(t, err, "a partially failed batch must not fail the caller")+ require.Len(t, results, 1)+ require.Error(t, results[0].Error,+ "a partially failed batch must mark its result set with the failure")+ require.Contains(t, results[0].Error.Error(), "1 of 2 matched collections")+ require.Contains(t, results[0].Error.Error(), "milvus keyword search unavailable")+ require.Len(t, results[0].Results, 1)+ require.Equal(t, "chunk-1", results[0].Results[0].ChunkID)+ require.Equal(t, "invoice total 42", results[0].Results[0].Content)+ require.Equal(t, 0.75, results[0].Results[0].Score)+ require.Equal(t, types.KeywordsRetrieverType, results[0].RetrieverType)+ require.NotContains(t, logs.String(), "No keyword matches found",+ "a partially failed batch must not be logged as a search that found no matches")+}++// The genuine zero-hit outcome keeps its old shape: every collection answered,+// no token matched, so an empty result with a nil error is correct and the+// conclusion log still fires.+func TestMilvusKeywordsRetrieveReportsNoMatchesWhenNothingFailed(t *testing.T) {+ logs := captureMilvusLogs(t)+ harness := newKeywordsMilvusHarness(t, []string{"weknora_embeddings_1024"},+ func(string) (*milvuspb.SearchResults, error) { return emptyMilvusSearch(), nil },+ )++ results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsMilvusParams())++ require.NoError(t, err, "a successful search without matches must not error")+ require.Len(t, results, 1)+ require.Empty(t, results[0].Results)+ require.NoError(t, results[0].Error, "a complete zero-hit search must not mark an error")+ require.Contains(t, logs.String(), "No keyword matches found",+ "a successful zero-hit search must still be logged as such")+}++// A partial failure with zero hits is still a partial failure: the result set+// stays empty but must carry the error, and the conclusion log must stay off.+func TestMilvusKeywordsRetrieveMarksPartialFailureWhenNothingHit(t *testing.T) {+ logs := captureMilvusLogs(t)+ harness := newKeywordsMilvusHarness(t,+ []string{"weknora_embeddings_1024", "weknora_embeddings_1536"},+ func(name string) (*milvuspb.SearchResults, error) {+ if name == "weknora_embeddings_1024" {+ return failedMilvusSearch(), nil+ }+ return emptyMilvusSearch(), nil+ },+ )++ results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsMilvusParams())++ require.NoError(t, err, "a partially failed batch must not fail the caller")+ require.Len(t, results, 1)+ require.Empty(t, results[0].Results)+ require.Error(t, results[0].Error,+ "partial failure with zero hits must still be marked")+ require.NotContains(t, logs.String(), "No keyword matches found",+ "a partially failed batch must not be logged as a search that found no matches")+}++// No collection carries the repository's base name: nothing was searched at+// all, which must be distinguishable from a search that ran and hit nothing.+func TestMilvusKeywordsRetrieveWarnsWhenNoCollectionMatchesBaseName(t *testing.T) {+ logs := captureMilvusLogs(t)+ harness := newKeywordsMilvusHarness(t, []string{"other_collection"},+ func(string) (*milvuspb.SearchResults, error) { return emptyMilvusSearch(), nil },+ )++ results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsMilvusParams())++ require.NoError(t, err, "an empty collection list must not error")+ require.Len(t, results, 1)+ require.Empty(t, results[0].Results)+ require.NoError(t, results[0].Error, "no matching collection is not a partial failure")+ require.Empty(t, harness.fake.searches, "no Search may be issued without a matching collection")+ require.Contains(t, logs.String(), "No collection matched base name",+ "a search that never ran must be logged as such")+ require.NotContains(t, logs.String(), "No keyword matches found",+ "a search that never ran must not be logged as a search that found no matches")+}diff --git a/internal/application/repository/retriever/milvus/repository.go b/internal/application/repository/retriever/milvus/repository.goindex 5ddba22bc..8fed71f71 100644--- a/internal/application/repository/retriever/milvus/repository.go+++ b/internal/application/repository/retriever/milvus/repository.go@@ -36,10 +36,10 @@ const (fieldContentSparse = "content_sparse")-var (- allFields = []string{fieldID, fieldContent, fieldLanguage, fieldSourceID, fieldSourceType, fieldChunkID,- fieldKnowledgeID, fieldKnowledgeBaseID, fieldTagID, fieldIsEnabled, fieldEmbedding}-)+var allFields = []string{+ fieldID, fieldContent, fieldLanguage, fieldSourceID, fieldSourceType, fieldChunkID,+ fieldKnowledgeID, fieldKnowledgeBaseID, fieldTagID, fieldIsEnabled, fieldEmbedding,+}// NewMilvusRetrieveEngineRepository creates and initializes a new Milvus repository.// indexCfg is optional — pass nil to use env var / default values (env path).@@ -827,20 +827,33 @@ func (m *milvusRepository) KeywordsRetrieve(ctx context.Context,}var allResults []*types.IndexWithScore+ // A batch where every matching collection failed must not be reported as+ // "no matches": the caller cannot tell a genuine zero-hit search apart from+ // a search that never ran. Count both sides and fail loudly when the search+ // produced nothing but errors.+ matchedCollections := 0+ failedCollections := 0+ var lastFailedErr error// Search in all matching collectionsfor _, collectionName := range collections {if !matchesDimensionCollection(collectionName, m.collectionBaseName) {continue}+ matchedCollections+++collectionMode, modeErr := m.collectionAnalyzerMode(ctx, collectionName)if modeErr != nil {+ failedCollections+++ lastFailedErr = modeErrlog.Errorf("[Milvus] Failed to inspect collection %s analyzer mode: %v", collectionName, modeErr)continue}expr, paramsMap, err := m.getBaseFilterForQuery(params)if err != nil {+ failedCollections+++ lastFailedErr = errlog.Errorf("[Milvus] Failed to build base filter: %v", err)continue}@@ -864,22 +877,39 @@ func (m *milvusRepository) KeywordsRetrieve(ctx context.Context,searchOpt.WithOutputFields("*")resultSet, err := m.client.Search(ctx, searchOpt)if err != nil {- log.Errorf("[Milvus] Keywords search failed: %v", err)+ failedCollections+++ lastFailedErr = err+ log.Errorf("[Milvus] Keywords search failed in %s: %v", collectionName, err)continue}sets, scores, err := convertResultSet(resultSet)if err != nil {- log.Errorf("[Milvus] Failed to convert result set: %v", err)+ failedCollections+++ lastFailedErr = err+ log.Errorf("[Milvus] Failed to convert result set of %s: %v", collectionName, err)continue}results, scoreErr := buildMilvusIndexResults(sets, scores, types.MatchTypeKeywords)if scoreErr != nil {- log.Errorf("[Milvus] Failed to attach keyword scores: %v", scoreErr)+ failedCollections+++ lastFailedErr = scoreErr+ log.Errorf("[Milvus] Failed to attach keyword scores for %s: %v", collectionName, scoreErr)continue}allResults = append(allResults, results...)}+ // Every collection that matched the base name failed, so this call produced+ // no evidence at all about the knowledge base. Surface the failure instead+ // of letting callers treat it as "no relevant content".+ if matchedCollections > 0 && failedCollections == matchedCollections {+ return nil, fmt.Errorf(+ "milvus keyword search failed in all %d matched collections: %w",+ matchedCollections,+ lastFailedErr,+ )+ }+// Searches across multiple collections return one score-sorted page per// collection. Re-sort the combined list before applying the global TopK;// otherwise the first collection can crowd out better matches from later@@ -905,13 +935,52 @@ func (m *milvusRepository) KeywordsRetrieve(ctx context.Context,allResults = allResults[:params.TopK]}- if len(allResults) == 0 {- log.Warnf("[Milvus] No keyword matches found for query: %s", params.Query)- } else {+ // Some matched collections answered and others did not: these results are+ // real but incomplete. Carry the failure on the result set+ // (RetrieveResult.Error) instead of returning it as the call's error, which+ // would discard the partial evidence. CompositeRetrieveEngine turns it into+ // an error alongside the results so the gap stays visible upstream.+ var partialErr error+ if failedCollections > 0 && failedCollections < matchedCollections {+ partialErr = fmt.Errorf(+ "milvus keyword search failed in %d of %d matched collections: %w",+ failedCollections, matchedCollections, lastFailedErr,+ )+ }++ switch {+ case matchedCollections == 0:+ // No collection carries this base name, so nothing was searched. This+ // must not read as a search that ran and legitimately hit nothing.+ log.Warnf(+ "[Milvus] No collection matched base name %s among %d listed; keyword search did not run",+ m.collectionBaseName, len(collections),+ )+ case partialErr != nil:+ log.Warnf(+ "[Milvus] Keywords search failed in %d of %d matched collections; results are incomplete: %v",+ failedCollections, matchedCollections, lastFailedErr,+ )+ if len(allResults) > 0 {+ log.Infof("[Milvus] Keywords retrieval found %d results", len(allResults))+ break+ }+ // Partial failure with zero hits: the remaining collections did answer,+ // so this is a real zero-hit outcome, but it must not read as if the+ // search had succeeded everywhere.+ log.Warnf(+ "[Milvus] Keywords search returned no matches in the %d collections that answered",+ matchedCollections-failedCollections,+ )+ case len(allResults) > 0:log.Infof("[Milvus] Keywords retrieval found %d results", len(allResults))+ default:+ log.Warnf("[Milvus] No keyword matches found for query: %s", params.Query)}- return buildRetrieveResult(allResults, types.KeywordsRetrieverType), nil+ retrieved := buildRetrieveResult(allResults, types.KeywordsRetrieverType)+ retrieved[0].Error = partialErr+ return retrieved, nil}// CopyIndices copies index data from source knowledge base to target knowledge basediff --git a/internal/application/repository/retriever/qdrant/repository.go b/internal/application/repository/retriever/qdrant/repository.goindex 473731aef..d3c1008c3 100644--- a/internal/application/repository/retriever/qdrant/repository.go+++ b/internal/application/repository/retriever/qdrant/repository.go@@ -759,6 +759,13 @@ func (q *qdrantRepository) KeywordsRetrieve(ctx context.Context,var allResults []*types.IndexWithScorelimit := uint32(params.TopK)+ // A batch where every matching collection failed must not be reported as+ // "no matches": the caller cannot tell a genuine zero-hit search apart from+ // a search that never ran. Count both sides and fail loudly when the search+ // produced nothing but errors.+ matchedCollections := 0+ failedCollections := 0+ var lastFailedErr errorlog.Debugf("[Qdrant] Found %d collections, base name: %s", len(collections), q.collectionBaseName)@@ -775,6 +782,7 @@ func (q *qdrantRepository) KeywordsRetrieve(ctx context.Context,log.Debugf("[Qdrant] Skipping collection %s (doesn't match base name %s)", collectionName, q.collectionBaseName)continue}+ matchedCollections++filter := q.getBaseFilter(params)@@ -800,6 +808,8 @@ func (q *qdrantRepository) KeywordsRetrieve(ctx context.Context,WithPayload: qdrant.NewWithPayload(true),})if err != nil {+ failedCollections+++ lastFailedErr = errlog.Warnf("[Qdrant] Keywords search failed in %s: %v", collectionName, err)continue}@@ -826,18 +836,68 @@ func (q *qdrantRepository) KeywordsRetrieve(ctx context.Context,}}+ // Every collection that matched the base name failed, so this call produced+ // no evidence at all about the knowledge base. Surface the failure instead+ // of letting callers treat it as "no relevant content".+ if matchedCollections > 0 && failedCollections == matchedCollections {+ return nil, fmt.Errorf(+ "qdrant keyword search failed in all %d matched collections: %w",+ matchedCollections,+ lastFailedErr,+ )+ }+// Limit results to topKif len(allResults) > params.TopK {allResults = allResults[:params.TopK]}- if len(allResults) == 0 {- log.Warnf("[Qdrant] No keyword matches found for query: %s", params.Query)- } else {+ // Some matched collections answered and others did not: these results are+ // real but incomplete. Carry the failure on the result set+ // (RetrieveResult.Error) instead of returning it as the call's error, which+ // would discard the partial evidence. CompositeRetrieveEngine turns it into+ // an error alongside the results so the gap stays visible upstream.+ var partialErr error+ if failedCollections > 0 && failedCollections < matchedCollections {+ partialErr = fmt.Errorf(+ "qdrant keyword search failed in %d of %d matched collections: %w",+ failedCollections, matchedCollections, lastFailedErr,+ )+ }++ switch {+ case matchedCollections == 0:+ // No collection carries this base name, so nothing was searched. This+ // must not read as a search that ran and legitimately hit nothing.+ log.Warnf(+ "[Qdrant] No collection matched base name %s among %d listed; keyword search did not run",+ q.collectionBaseName, len(collections),+ )+ case partialErr != nil:+ log.Warnf(+ "[Qdrant] Keywords search failed in %d of %d matched collections; results are incomplete: %v",+ failedCollections, matchedCollections, lastFailedErr,+ )+ if len(allResults) > 0 {+ log.Infof("[Qdrant] Keywords retrieval found %d results", len(allResults))+ break+ }+ // Partial failure with zero hits: the remaining collections did answer,+ // so this is a real zero-hit outcome, but it must not read as if the+ // search had succeeded everywhere.+ log.Warnf(+ "[Qdrant] Keywords search returned no matches in the %d collections that answered",+ matchedCollections-failedCollections,+ )+ case len(allResults) > 0:log.Infof("[Qdrant] Keywords retrieval found %d results", len(allResults))+ default:+ log.Warnf("[Qdrant] No keyword matches found for query: %s", params.Query)}- return buildRetrieveResult(allResults, types.KeywordsRetrieverType), nil+ retrieved := buildRetrieveResult(allResults, types.KeywordsRetrieverType)+ retrieved[0].Error = partialErr+ return retrieved, nil}// CopyIndices copies index data from source knowledge base to target knowledge basediff --git a/internal/application/repository/retriever/qdrant/repository_test.go b/internal/application/repository/retriever/qdrant/repository_test.goindex 62b97995e..dcbfa69e4 100644--- a/internal/application/repository/retriever/qdrant/repository_test.go+++ b/internal/application/repository/retriever/qdrant/repository_test.go@@ -1,14 +1,18 @@package qdrantimport (+ "bytes""context""errors""fmt"+ "os"+ "slices""strings""testing""time""unicode/utf8"+ "github.com/Tencent/WeKnora/internal/logger""github.com/Tencent/WeKnora/internal/types""github.com/qdrant/go-client/qdrant""google.golang.org/grpc"@@ -519,3 +523,242 @@ func TestDeleteTreatsStaleCacheMissingCollectionAsNoOp(t *testing.T) {})}}++// errKeywordScroll makes every Scroll RPC fail the way an unreachable or+// overloaded Qdrant does.+var errKeywordScroll = errors.New("qdrant scroll unavailable")++type keywordsTestHarness struct {+ repo *qdrantRepository+ scrolls []string+}++// newKeywordsTestHarness wires KeywordsRetrieve to a fake Qdrant server. The+// collection list and the per-collection Scroll outcome are the only inputs the+// search loop has, so both are controlled here instead of stubbing the+// repository.+func newKeywordsTestHarness(t *testing.T, collections []string,+ scroll func(collectionName string) ([]*qdrant.RetrievedPoint, error),+) *keywordsTestHarness {+ t.Helper()+ harness := &keywordsTestHarness{}+ client := newInterceptedQdrantClient(t, func(+ _ context.Context, method string, req, reply any, _ *grpc.ClientConn,+ _ grpc.UnaryInvoker, _ ...grpc.CallOption,+ ) error {+ switch request := req.(type) {+ case *qdrant.ListCollectionsRequest:+ response := reply.(*qdrant.ListCollectionsResponse)+ for _, name := range collections {+ response.Collections = append(response.Collections, &qdrant.CollectionDescription{Name: name})+ }+ return nil+ case *qdrant.ScrollPoints:+ name := request.GetCollectionName()+ harness.scrolls = append(harness.scrolls, name)+ points, err := scroll(name)+ if err != nil {+ return err+ }+ reply.(*qdrant.ScrollResponse).Result = points+ return nil+ default:+ return fmt.Errorf("unexpected RPC %s", method)+ }+ })+ harness.repo = &qdrantRepository{client: client, collectionBaseName: "vectors"}+ return harness+}++func keywordsRetrieveParams() types.RetrieveParams {+ return types.RetrieveParams{+ Query: "invoice total",+ TopK: 10,+ KnowledgeBaseIDs: []string{"kb-1"},+ }+}++func keywordHitPoint(id, content string) *qdrant.RetrievedPoint {+ return &qdrant.RetrievedPoint{+ Id: &qdrant.PointId{PointIdOptions: &qdrant.PointId_Uuid{Uuid: id}},+ Payload: map[string]*qdrant.Value{+ fieldContent: qdrant.NewValueString(content),+ fieldChunkID: qdrant.NewValueString(id),+ fieldSourceID: qdrant.NewValueString("source-1"),+ fieldSourceType: qdrant.NewValueInt(2),+ },+ }+}++// captureLogs redirects the package logger for one test. The conclusion+// "No keyword matches found" is only legitimate when nothing failed, so the+// tests assert on the rendered log rather than on the counters alone.+func captureLogs(t *testing.T) *bytes.Buffer {+ t.Helper()+ var buf bytes.Buffer+ logger.SetOutput(&buf)+ t.Cleanup(func() { logger.SetOutput(os.Stdout) })+ return &buf+}++// A batch in which every matching collection fails must reach the caller as an+// error. Returning an empty result set with a nil error is indistinguishable+// from a genuine zero-hit search, and the QA pipeline answers "no relevant+// content" on top of it (#3835).+func TestKeywordsRetrieveFailsWhenEveryMatchedCollectionFails(t *testing.T) {+ logs := captureLogs(t)+ harness := newKeywordsTestHarness(t,+ []string{"vectors_1024", "vectors_1536", "other_2048"},+ func(string) ([]*qdrant.RetrievedPoint, error) {+ return nil, errKeywordScroll+ },+ )++ results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())++ if !errors.Is(err, errKeywordScroll) {+ t.Fatalf("all-collections failure must surface as an error, got %v", err)+ }+ if !strings.Contains(err.Error(), "all 2 matched collections") {+ t.Fatalf("error must state how many collections failed, got %q", err)+ }+ if results != nil {+ t.Fatalf("no result set may accompany the error, got %d sets", len(results))+ }+ if want := []string{"vectors_1024", "vectors_1536"}; !slices.Equal(harness.scrolls, want) {+ t.Fatalf("scroll attempts = %v, want %v: only base-name collections are searched", harness.scrolls, want)+ }+ if strings.Contains(logs.String(), "No keyword matches found") {+ t.Fatal("a failed batch must not be logged as a search that found no matches")+ }+}++// One failing collection must not fail the batch as long as another one+// answered: partial results are still results. The failure must travel with+// them though (RetrieveResult.Error) — otherwise callers treat the incomplete+// answer as a complete one (#3835).+func TestKeywordsRetrieveKeepsResultsWhenOnlySomeCollectionsFail(t *testing.T) {+ logs := captureLogs(t)+ harness := newKeywordsTestHarness(t, []string{"vectors_1024", "vectors_1536"},+ func(name string) ([]*qdrant.RetrievedPoint, error) {+ if name == "vectors_1024" {+ return nil, errKeywordScroll+ }+ return []*qdrant.RetrievedPoint{keywordHitPoint("chunk-1", "invoice total 42")}, nil+ },+ )++ results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())+ if err != nil {+ t.Fatalf("a partially failed batch must not fail the caller, got %v", err)+ }+ if len(results) != 1 {+ t.Fatalf("expected one result set, got %d", len(results))+ }+ if results[0].Error == nil {+ t.Fatal("a partially failed batch must mark its result set with the failure")+ }+ if !errors.Is(results[0].Error, errKeywordScroll) {+ t.Fatalf("partial error must keep the underlying cause, got %v", results[0].Error)+ }+ if !strings.Contains(results[0].Error.Error(), "1 of 2 matched collections") {+ t.Fatalf("partial error must state what failed, got %q", results[0].Error)+ }+ if len(results[0].Results) != 1 {+ t.Fatalf("expected the surviving collection's hit, got %d results", len(results[0].Results))+ }+ if got := results[0].Results[0].ChunkID; got != "chunk-1" {+ t.Fatalf("unexpected chunk id %q", got)+ }+ if results[0].RetrieverType != types.KeywordsRetrieverType {+ t.Fatalf("expected keywords retriever type, got %v", results[0].RetrieverType)+ }+ if strings.Contains(logs.String(), "No keyword matches found") {+ t.Fatal("a partially failed batch must not be logged as a search that found no matches")+ }+}++// The genuine zero-hit outcome keeps its old shape: every collection answered,+// no token matched, so an empty result with a nil error is correct and the+// conclusion log still fires.+func TestKeywordsRetrieveReportsNoMatchesWhenNothingFailed(t *testing.T) {+ logs := captureLogs(t)+ harness := newKeywordsTestHarness(t, []string{"vectors_1024"},+ func(string) ([]*qdrant.RetrievedPoint, error) {+ return nil, nil+ },+ )++ results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())+ if err != nil {+ t.Fatalf("a successful search without matches must not error, got %v", err)+ }+ if len(results) != 1 || len(results[0].Results) != 0 {+ t.Fatalf("expected one empty result set, got %#v", results)+ }+ if results[0].Error != nil {+ t.Fatalf("a complete zero-hit search must not mark an error, got %v", results[0].Error)+ }+ if !strings.Contains(logs.String(), "No keyword matches found") {+ t.Fatal("a successful zero-hit search must still be logged as such")+ }+}++// A partial failure with zero hits is still a partial failure: the result set+// stays empty but must carry the error, and the conclusion log must stay off.+func TestKeywordsRetrieveMarksPartialFailureWhenNothingHit(t *testing.T) {+ logs := captureLogs(t)+ harness := newKeywordsTestHarness(t, []string{"vectors_1024", "vectors_1536"},+ func(name string) ([]*qdrant.RetrievedPoint, error) {+ if name == "vectors_1024" {+ return nil, errKeywordScroll+ }+ return nil, nil+ },+ )++ results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())+ if err != nil {+ t.Fatalf("a partially failed batch must not fail the caller, got %v", err)+ }+ if len(results) != 1 || len(results[0].Results) != 0 {+ t.Fatalf("expected one empty result set, got %#v", results)+ }+ if !errors.Is(results[0].Error, errKeywordScroll) {+ t.Fatalf("partial failure with zero hits must still be marked, got %v", results[0].Error)+ }+ if strings.Contains(logs.String(), "No keyword matches found") {+ t.Fatal("a partially failed batch must not be logged as a search that found no matches")+ }+}++// No collection carries the repository's base name: nothing was searched at+// all, which must be distinguishable from a search that ran and hit nothing.+func TestKeywordsRetrieveWarnsWhenNoCollectionMatchesBaseName(t *testing.T) {+ logs := captureLogs(t)+ harness := newKeywordsTestHarness(t, []string{"other_1024"},+ func(string) ([]*qdrant.RetrievedPoint, error) {+ return nil, nil+ },+ )++ results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())+ if err != nil {+ t.Fatalf("an empty collection list must not error, got %v", err)+ }+ if len(results) != 1 || len(results[0].Results) != 0 {+ t.Fatalf("expected one empty result set, got %#v", results)+ }+ if results[0].Error != nil {+ t.Fatalf("no matching collection is not a partial failure, got %v", results[0].Error)+ }+ if len(harness.scrolls) != 0 {+ t.Fatalf("no Scroll may be issued without a matching collection, got %v", harness.scrolls)+ }+ if !strings.Contains(logs.String(), "No collection matched base name") {+ t.Fatal("a search that never ran must be logged as such")+ }+ if strings.Contains(logs.String(), "No keyword matches found") {+ t.Fatal("a search that never ran must not be logged as a search that found no matches")+ }+}diff --git a/internal/application/service/knowledgebase_search_fanout.go b/internal/application/service/knowledgebase_search_fanout.goindex c787006cc..b2abc8687 100644--- a/internal/application/service/knowledgebase_search_fanout.go+++ b/internal/application/service/knowledgebase_search_fanout.go@@ -29,11 +29,16 @@ const (// collected results span >1 engine type, the normalizer rescales vector// scores into [0, 1] before fusion.//-// Failure policy: all-or-nothing. The first group error fails the whole-// search and cancels siblings via errgroup, matching the existing single--// store behavior — chat/agent callers already treat "search failed" as-// abort. A future PR can extract a MergePolicy interface (open/closed)-// to add partial-result support without changing this function's callers.+// Failure policy: all-or-nothing for store-level failures. The first group+// error fails the whole search and cancels siblings via errgroup, matching the+// existing single-store behavior — chat/agent callers already treat "search+// failed" as abort. A retrieve call that returns results *and* an error is a+// different case: CompositeRetrieveEngine only does that when individual result+// sets carry a partial failure (RetrieveResult.Error), i.e. some collections+// answered and some did not. Those results are kept and the failure is logged+// at WARN by retainPartialResults; failing the whole search would throw away+// evidence that was retrieved successfully. A future PR can extract a+// MergePolicy interface (open/closed) to push partial results further up.//// Fast path: len(groups) == 1 → returns the single engine's Retrieve// directly with zero fan-out overhead. This is the dominant case today@@ -54,7 +59,8 @@ func (s *knowledgeBaseService) retrieveFromStores(return nil, nil}if len(groups) == 1 {- return groups[0].Engine.Retrieve(ctx, paramsWithTopK(groups[0]))+ res, err := groups[0].Engine.Retrieve(ctx, paramsWithTopK(groups[0]))+ return retainPartialResults(ctx, groups[0], res, err)}timeout := multiStoreRetrieveTimeout()@@ -72,6 +78,7 @@ func (s *knowledgeBaseService) retrieveFromStores(gcCtx, cancel := context.WithTimeout(gctx, timeout)defer cancel()res, err := grp.Engine.Retrieve(gcCtx, paramsWithTopK(grp))+ res, err = retainPartialResults(gcCtx, grp, res, err)if err != nil {logger.WarnWithFields(gctx, logger.Fields{"tenant_id": grp.OwnerTenantID,@@ -130,6 +137,32 @@ func (s *knowledgeBaseService) retrieveFromStores(return all, nil}+// retainPartialResults keeps results that arrive together with an error.+//+// CompositeRetrieveEngine returns a non-nil error alongside results only when+// individual result sets carry a partial failure (RetrieveResult.Error): some+// collections of the store answered, others did not. Dropping the results would+// turn a degraded store into a total search failure and lose the evidence that+// was retrieved; returning them without a trace would let callers treat an+// incomplete answer as complete. So the failure is logged at WARN — this is the+// closest consumer that still knows the store group — and the results are+// returned with a nil error, leaving the all-or-nothing policy for store-level+// failures untouched (those come back with no results, so err stays fatal).+func retainPartialResults(+ ctx context.Context, g *storeGroup, res []*types.RetrieveResult, err error,+) ([]*types.RetrieveResult, error) {+ if err == nil || len(res) == 0 {+ return res, err+ }+ logger.WarnWithFields(ctx, logger.Fields{+ "tenant_id": g.OwnerTenantID,+ "kb_count": len(g.KBIDs),+ "store_kind": storeKindLabel(g.StoreID),+ "result_sets": len(res),+ }, fmt.Sprintf("retrieve returned partial results: %v", err))+ return res, nil+}+// paramsWithTopK builds a fresh []RetrieveParams for a group. BaseParams// stay immutable; only TopK is overridden. This isolates iterative FAQ's// TopK mutation from the goroutines that read params inside Retrieve,diff --git a/internal/application/service/knowledgebase_search_fanout_test.go b/internal/application/service/knowledgebase_search_fanout_test.goindex 35031e05c..9786ffbfe 100644--- a/internal/application/service/knowledgebase_search_fanout_test.go+++ b/internal/application/service/knowledgebase_search_fanout_test.go@@ -379,12 +379,15 @@ func TestValidateSameEmbeddingModel_LogInjection_Sanitized(t *testing.T) {// engine, or returns an error. Only Retrieve, EngineType, and Support are// exercised; the rest panic.type fakeRetrieveEngineService struct {- engineType types.RetrieverEngineType- support []types.RetrieverType- canned []*types.IndexWithScore- cannedErr error- sleep time.Duration- retrieveCalls atomic.Int64+ engineType types.RetrieverEngineType+ support []types.RetrieverType+ canned []*types.IndexWithScore+ cannedErr error+ // cannedResultErr marks the returned result set as partially failed+ // (RetrieveResult.Error) without failing the call itself.+ cannedResultErr error+ sleep time.Duration+ retrieveCalls atomic.Int64}func (f *fakeRetrieveEngineService) EngineType() types.RetrieverEngineType {@@ -409,6 +412,7 @@ func (f *fakeRetrieveEngineService) Retrieve(ctx context.Context, p types.RetrieResults: f.canned,RetrieverEngineType: f.engineType,RetrieverType: p.RetrieverType,+ Error: f.cannedResultErr,}}, nil}diff --git a/internal/application/service/knowledgebase_search_partial_test.go b/internal/application/service/knowledgebase_search_partial_test.gonew file mode 100644index 000000000..63b5b7610--- /dev/null+++ b/internal/application/service/knowledgebase_search_partial_test.go@@ -0,0 +1,163 @@+package service++import (+ "bytes"+ "context"+ stderrors "errors"+ "os"+ "testing"++ "github.com/Tencent/WeKnora/internal/application/service/retriever"+ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// captureServiceLogs redirects the process logger for one test, so the WARN+// raised for a partial retrieve can be asserted on. Not parallel-safe: the+// logger output is process-wide.+func captureServiceLogs(t *testing.T) *bytes.Buffer {+ t.Helper()+ var buf bytes.Buffer+ logger.SetOutput(&buf)+ t.Cleanup(func() { logger.SetOutput(os.Stdout) })+ return &buf+}++func keywordsRetrieveParams(query string) []types.RetrieveParams {+ return []types.RetrieveParams{{+ Query: query,+ TopK: 50,+ RetrieverType: types.KeywordsRetrieverType,+ }}+}++// A store that answered only partially used to reach the search layer as a+// complete result: some collections failed, the hits from the rest came back+// with a nil error, and nothing said the answer was incomplete. The failure now+// travels with the results (RetrieveResult.Error -> CompositeRetrieveEngine)+// and is logged here, without discarding what was retrieved (#3835).+func TestRetrieveFromStores_LogsPartialFailureAndKeepsResults(t *testing.T) {+ logs := captureServiceLogs(t)+ cause := stderrors.New("qdrant keyword search failed in 1 of 2 matched collections")+ fake := &fakeRetrieveEngineService{+ engineType: types.QdrantRetrieverEngineType,+ support: []types.RetrieverType{types.KeywordsRetrieverType},+ canned: []*types.IndexWithScore{{ChunkID: "c1", Score: 0.5}},+ cannedResultErr: cause,+ }+ g := &storeGroup{+ StoreID: "store-x",+ KBIDs: []string{"kb-1"},+ Engine: buildBoundComposite(t, fake),+ BaseParams: keywordsRetrieveParams("q"),+ TopK: 50,+ }++ res, err := (&knowledgeBaseService{}).retrieveFromStores(+ context.Background(), []*storeGroup{g}, retriever.EngineAwareNormalizer{})++ require.NoError(t, err, "a partial failure must not fail the search")+ require.Len(t, res, 1)+ require.Len(t, res[0].Results, 1)+ assert.Equal(t, "c1", res[0].Results[0].ChunkID)+ assert.ErrorIs(t, res[0].Error, cause, "the result set must keep its partial failure")+ assert.Contains(t, logs.String(), "retrieve returned partial results")+ assert.Contains(t, logs.String(), "1 of 2 matched collections")+}++// The multi-store path must keep partial results too, instead of cancelling+// siblings and failing the whole search.+func TestRetrieveFromStores_MultiGroupKeepsPartialResults(t *testing.T) {+ logs := captureServiceLogs(t)+ cause := stderrors.New("milvus keyword search failed in 2 of 3 matched collections")+ partial := &fakeRetrieveEngineService{+ engineType: types.MilvusRetrieverEngineType,+ support: []types.RetrieverType{types.KeywordsRetrieverType},+ canned: []*types.IndexWithScore{{ChunkID: "partial-1", Score: 0.4}},+ cannedResultErr: cause,+ }+ clean := &fakeRetrieveEngineService{+ engineType: types.MilvusRetrieverEngineType,+ support: []types.RetrieverType{types.KeywordsRetrieverType},+ canned: []*types.IndexWithScore{{ChunkID: "clean-1", Score: 0.6}},+ }+ groups := []*storeGroup{+ {+ StoreID: "store-partial",+ KBIDs: []string{"kb-partial"},+ Engine: buildBoundComposite(t, partial),+ BaseParams: keywordsRetrieveParams("q"),+ TopK: 50,+ },+ {+ StoreID: "store-clean",+ KBIDs: []string{"kb-clean"},+ Engine: buildBoundComposite(t, clean),+ BaseParams: keywordsRetrieveParams("q"),+ TopK: 50,+ },+ }++ res, err := (&knowledgeBaseService{}).retrieveFromStores(+ context.Background(), groups, retriever.EngineAwareNormalizer{})++ require.NoError(t, err, "one degraded store must not fail the whole search")+ require.Len(t, res, 2)+ assert.Contains(t, logs.String(), "retrieve returned partial results")+ assert.Contains(t, logs.String(), "2 of 3 matched collections")+}++// A complete search that legitimately hit nothing must stay quiet: no partial+// warning, nil error.+func TestRetrieveFromStores_CompleteEmptySearchStaysQuiet(t *testing.T) {+ logs := captureServiceLogs(t)+ fake := &fakeRetrieveEngineService{+ engineType: types.QdrantRetrieverEngineType,+ support: []types.RetrieverType{types.KeywordsRetrieverType},+ }+ g := &storeGroup{+ StoreID: "store-x",+ KBIDs: []string{"kb-1"},+ Engine: buildBoundComposite(t, fake),+ BaseParams: keywordsRetrieveParams("q"),+ TopK: 50,+ }++ res, err := (&knowledgeBaseService{}).retrieveFromStores(+ context.Background(), []*storeGroup{g}, retriever.EngineAwareNormalizer{})++ require.NoError(t, err)+ require.Len(t, res, 1)+ assert.Empty(t, res[0].Results)+ assert.NoError(t, res[0].Error)+ assert.NotContains(t, logs.String(), "partial", "a complete zero-hit search must not warn")+}++// An engine-level failure still fails the search: exposing partial results must+// not weaken the all-or-nothing policy for stores that did not answer at all.+func TestRetrieveFromStores_EngineLevelErrorStillFails(t *testing.T) {+ logs := captureServiceLogs(t)+ cause := stderrors.New("vector store unavailable")+ fake := &fakeRetrieveEngineService{+ engineType: types.QdrantRetrieverEngineType,+ support: []types.RetrieverType{types.KeywordsRetrieverType},+ canned: []*types.IndexWithScore{{ChunkID: "never-returned", Score: 0.5}},+ cannedErr: cause,+ }+ g := &storeGroup{+ StoreID: "store-x",+ KBIDs: []string{"kb-1"},+ Engine: buildBoundComposite(t, fake),+ BaseParams: keywordsRetrieveParams("q"),+ TopK: 50,+ }++ res, err := (&knowledgeBaseService{}).retrieveFromStores(+ context.Background(), []*storeGroup{g}, retriever.EngineAwareNormalizer{})++ require.ErrorIs(t, err, cause)+ assert.Nil(t, res, "an engine-level failure still returns no results")+ assert.NotContains(t, logs.String(), "partial")+}diff --git a/internal/application/service/retriever/composite.go b/internal/application/service/retriever/composite.goindex cef6171a9..db1c7b47f 100644--- a/internal/application/service/retriever/composite.go+++ b/internal/application/service/retriever/composite.go@@ -2,6 +2,7 @@ package retrieverimport ("context"+ "errors""fmt""maps""slices"@@ -28,11 +29,20 @@ type CompositeRetrieveEngine struct {}// Retrieve performs retrieval operations by delegating to the appropriate engine-// based on the retriever type specified in the parameters+// based on the retriever type specified in the parameters.+//+// Error contract: a store-level failure is returned with no results, matching+// the long-standing all-or-nothing policy. A result set that reports a partial+// failure in RetrieveResult.Error is different — the hits it did return are+// kept and the failure is returned *alongside* them, so callers can log the+// gap without losing the evidence. Callers must therefore treat a non-nil+// error with non-nil results as "incomplete", not as "no results".func (c *CompositeRetrieveEngine) Retrieve(ctx context.Context,retrieveParams []types.RetrieveParams,) ([]*types.RetrieveResult, error) {- return concurrentRetrieve(ctx, retrieveParams,+ var partialMu sync.Mutex+ var partialErrs []error+ results, err := concurrentRetrieve(ctx, retrieveParams,func(ctx context.Context, param types.RetrieveParams, results *[]*types.RetrieveResult, mu *sync.Mutex) error {found := falsefor _, engineInfo := range c.engineInfos {@@ -44,6 +54,14 @@ func (c *CompositeRetrieveEngine) Retrieve(ctx context.Context,if err != nil {return err}+ for _, one := range result {+ if one == nil || one.Error == nil {+ continue+ }+ partialMu.Lock()+ partialErrs = append(partialErrs, one.Error)+ partialMu.Unlock()+ }mu.Lock()*results = append(*results, result...)mu.Unlock()@@ -57,6 +75,14 @@ func (c *CompositeRetrieveEngine) Retrieve(ctx context.Context,return nil},)+ if err != nil {+ // Engine-level failure: drop the results collected so far, unchanged.+ return nil, err+ }+ if len(partialErrs) > 0 {+ return results, fmt.Errorf("retrieve returned partial results: %w", errors.Join(partialErrs...))+ }+ return results, nil}// NewCompositeRetrieveEngine creates a new composite retrieve engine with the given parametersdiff --git a/internal/application/service/retriever/composite_partial_test.go b/internal/application/service/retriever/composite_partial_test.gonew file mode 100644index 000000000..f76cd30ac--- /dev/null+++ b/internal/application/service/retriever/composite_partial_test.go@@ -0,0 +1,131 @@+package retriever++import (+ "context"+ "errors"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/stretchr/testify/require"+)++// cannedEngine implements the three RetrieveEngineService methods the+// composite uses, returning one canned result set per retriever type. The+// embedded interface keeps the remaining methods out of this file; reaching+// one of them would panic on the nil interface, which is loud enough for a+// test.+type cannedEngine struct {+ interfaces.RetrieveEngineService+ engineType types.RetrieverEngineType+ support []types.RetrieverType+ results map[types.RetrieverType][]*types.RetrieveResult+ errs map[types.RetrieverType]error+}++func (e *cannedEngine) EngineType() types.RetrieverEngineType { return e.engineType }++func (e *cannedEngine) Support() []types.RetrieverType { return e.support }++func (e *cannedEngine) Retrieve(_ context.Context, p types.RetrieveParams,+) ([]*types.RetrieveResult, error) {+ if err := e.errs[p.RetrieverType]; err != nil {+ return nil, err+ }+ return e.results[p.RetrieverType], nil+}++func compositeWith(engine *cannedEngine) *CompositeRetrieveEngine {+ return &CompositeRetrieveEngine{engineInfos: []*engineInfo{{+ retrieveEngine: engine,+ retrieverType: engine.support,+ }}}+}++func keywordsParams(query string) []types.RetrieveParams {+ return []types.RetrieveParams{{+ Query: query,+ TopK: 10,+ RetrieverType: types.KeywordsRetrieverType,+ }}+}++// A result set that answered partially carries the failure in+// RetrieveResult.Error. The composite must hand both the results and the error+// to its caller: dropping the results loses evidence that was retrieved,+// swallowing the error makes the incomplete answer look complete (#3835).+func TestCompositeRetrieveExposesPartialResultError(t *testing.T) {+ cause := errors.New("qdrant keyword search failed in 1 of 2 matched collections")+ engine := &cannedEngine{+ engineType: types.QdrantRetrieverEngineType,+ support: []types.RetrieverType{types.KeywordsRetrieverType},+ results: map[types.RetrieverType][]*types.RetrieveResult{+ types.KeywordsRetrieverType: {{+ Results: []*types.IndexWithScore{{ChunkID: "chunk-1", Score: 1}},+ RetrieverEngineType: types.QdrantRetrieverEngineType,+ RetrieverType: types.KeywordsRetrieverType,+ Error: cause,+ }},+ },+ }++ results, err := compositeWith(engine).Retrieve(context.Background(), keywordsParams("q"))++ require.Error(t, err, "a partial result set must surface as an error")+ require.ErrorIs(t, err, cause, "the underlying cause must stay reachable")+ require.Len(t, results, 1, "partial results must survive alongside the error")+ require.Len(t, results[0].Results, 1)+ require.Equal(t, "chunk-1", results[0].Results[0].ChunkID)+ require.ErrorIs(t, results[0].Error, cause, "the result set keeps its own failure")+}++// A complete search — including a genuine zero-hit one — must stay quiet.+func TestCompositeRetrieveStaysSilentWhenResultSetsAreComplete(t *testing.T) {+ engine := &cannedEngine{+ engineType: types.QdrantRetrieverEngineType,+ support: []types.RetrieverType{types.KeywordsRetrieverType},+ results: map[types.RetrieverType][]*types.RetrieveResult{+ types.KeywordsRetrieverType: {{+ RetrieverEngineType: types.QdrantRetrieverEngineType,+ RetrieverType: types.KeywordsRetrieverType,+ }},+ },+ }++ results, err := compositeWith(engine).Retrieve(context.Background(), keywordsParams("q"))++ require.NoError(t, err, "an empty but complete result set is not a failure")+ require.Len(t, results, 1)+ require.Empty(t, results[0].Results)+ require.NoError(t, results[0].Error)+}++// An engine-level error is not a partial result: it still drops everything+// collected so far, so the existing all-or-nothing policy is unchanged.+func TestCompositeRetrieveDropsResultsOnEngineLevelError(t *testing.T) {+ cause := errors.New("vector store unavailable")+ engine := &cannedEngine{+ engineType: types.QdrantRetrieverEngineType,+ support: []types.RetrieverType{types.VectorRetrieverType, types.KeywordsRetrieverType},+ results: map[types.RetrieverType][]*types.RetrieveResult{+ types.VectorRetrieverType: {{+ Results: []*types.IndexWithScore{{ChunkID: "vector-1", Score: 0.9}},+ RetrieverEngineType: types.QdrantRetrieverEngineType,+ RetrieverType: types.VectorRetrieverType,+ }},+ },+ errs: map[types.RetrieverType]error{types.KeywordsRetrieverType: cause},+ }++ results, err := compositeWith(engine).Retrieve(context.Background(), []types.RetrieveParams{+ {Query: "q", TopK: 10, RetrieverType: types.VectorRetrieverType},+ {Query: "q", TopK: 10, RetrieverType: types.KeywordsRetrieverType},+ })++ require.ErrorIs(t, err, cause)+ require.Nil(t, results, "an engine-level failure still drops all results")+}++// The canned engine must stay usable wherever the registry hands out an+// engine service.+var _ interfaces.RetrieveEngineService = (*cannedEngine)(nil)diff --git a/internal/types/retriever.go b/internal/types/retriever.goindex afe5a4240..4c34e4300 100644--- a/internal/types/retriever.go+++ b/internal/types/retriever.go@@ -108,5 +108,12 @@ type RetrieveResult struct {Results []*IndexWithScore // Retrieval resultsRetrieverEngineType RetrieverEngineType // Retrieval source typeRetrieverType RetrieverType // Retrieval type- Error error // Retrieval error+ // Error reports a partial failure of this result set: Results holds what+ // answered, Error says what did not. It is nil for a complete retrieval,+ // including a genuine zero-hit search. A store-level failure is still+ // returned as the call's error with no result set at all.+ // CompositeRetrieveEngine surfaces a non-nil Error as an error alongside the+ // results, so a caller that reads the results must not ignore the error+ // without at least logging that the answer is incomplete.+ Error error // Retrieval error}