fix(retriever): Qdrant/Milvus 关键词检索整批失败返回 error,不再当成「没有匹配」 (#3847)

* fix(retriever): Qdrant/Milvus 关键词检索整批失败不再当成没有匹配

Qdrant 与 Milvus 的 KeywordsRetrieve 逐个 collection 检索,单个 collection 失败只降级成
一条日志后 continue。循环结束后按结果条数分支:全部 collection 失败与确实零命中都会打印
"No keyword matches found"、返回空结果与 nil error。上层只看第二个返回值,据此判定知识库
没有相关内容,用户与模型都无法区分"没有这个词"和"检索没有执行成功"。

改为在循环内累计匹配到的 collection 数与失败的 collection 数,全部匹配 collection 都失败
时返回带底层原因的聚合 error,例如
"qdrant keyword search failed in all 2 matched collections: <cause>"。计数放在 collection
名前缀/维度匹配之后,名字不匹配的 collection 不参与统计;匹配到的 collection 为 0 时维持
原行为,不报错。Milvus 的三处 continue(Search / convertResultSet /
buildMilvusIndexResults)全部计入,另有两处同样会跳过 collection 的失败路径(analyzer mode
探测、过滤器构建)一并计入,这三处的日志补上 collection 名。

部分失败时不再打印结论性的 "No keyword matches found":有结果时改为提示结果不完整,无结果
时说明有多少个 collection 应答过、多少个失败;只有本次调用没有发生任何错误时才继续打印该
结论。RetrieveResult.Error 保持原样(仓库内没有读取方),改动面最小、语义最清晰的暴露方式
是整批失败返回 error。

回归测试:
- Qdrant(repository_test.go):假 Qdrant gRPC 服务让 Scroll 全失败时返回 error 且不打印
  结论日志;只有一个 collection 失败时结果与 nil error 不变;全部成功且零命中时仍返回空结果
  + nil error 并保留结论日志。
- Milvus(新增 keywords_test.go):*client.Client 没有接口缝隙,改用进程内 Milvus gRPC 假
  服务(ShowCollections / DescribeCollection / Search)覆盖同样三种情形,走真实 Search 与
  结果转换路径。
- go.mod:milvus-proto 由新测试直接导入,去掉该依赖的 // indirect 标记。

反向验证:把两个 repository.go 改回原样后,两条"全部失败"用例分别以
"all-collections failure must surface as an error, got <nil>" 与
"An error is expected but got nil" 失败,部分失败与零命中两条用例保持通过;随后逐字节还原
修复。

* fix(retriever): 关键词检索部分失败随结果一起暴露,不再被当成完整结果

Qdrant/Milvus 的 KeywordsRetrieve 逐 collection 检索,部分 collection 失败时保留其余
collection 的结果并返回 nil error。上层拿到的是"结果 + nil error":既不知道少了几个
collection 的内容,也没有任何读取方,RetrieveResult.Error 因此长期是死字段。上一个
commit 只处理了"全部匹配 collection 都失败",部分失败仍然静默降级,模型与用户看到的
都是不完整结果。

让部分失败沿着结果走完这条链路:

- repository(qdrant/milvus):部分失败时把
  "… keyword search failed in N of M matched collections: <cause>" 写进
  RetrieveResult.Error —— 结果照常返回、调用级 error 仍为 nil;全部失败仍是调用级
  error,真正的零命中仍然 Error == nil;
- CompositeRetrieveEngine:读取每个结果集的 Error 并聚合,连同结果一起返回
  ("retrieve returned partial results: …");引擎级 error 仍然丢弃全部结果,
  all-or-nothing 策略不变;
- retrieveFromStores(该接口的唯一消费方):结果与 error 同时非空即"部分失败",打出
  带 store group 与原因的 WARN 并保留结果返回 —— 既不会把降级 store 升级成整次搜索
  失败,也不会让上层把不完整结果当完整结果;
- matched == 0(没有任何 collection 匹配 base name)单独打一条 Warn,与"检索成功但
  零命中"区分开;
- milvus/repository.go 的 allFields 块按 gofumpt 重排,四个包 gofumpt -l 干净。

回归测试:

- qdrant/milvus:部分失败(有命中 / 零命中)结果集带 Error 且调用 error 为 nil;全部
  成功零命中仍 Error == nil 且保留结论日志;全部失败仍是 error;matched == 0 打专属
  Warn 且不发任何 Scroll/Search;
- CompositeRetrieveEngine:结果集带 Error → (结果, error) 同时返回;结果集完整(含零
  命中)→ 无 error;引擎级 error → 丢弃全部结果;
- retrieveFromStores:单 store / 多 store 部分失败都打 WARN 且保留结果,完整零命中不
  打 partial 日志,引擎级 error 仍然失败。

反向验证:去掉四个源文件的可见性改动后,17 条新/改用例中 9 条失败(qdrant 3、milvus 3、
composite 1、retrieveFromStores 2),钉住"行为不变"的 8 条保持通过;还原后 diff 与
改动前逐字节一致。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
main
linus-liu-web 2026-10-07 23:59:38 +08:00 committed by GitHub
parent f9eeb8dc85
commit 5f5093b9f7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 1051 additions and 33 deletions

2
go.mod
View File

@ -239,7 +239,7 @@ require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.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.15
github.com/milvus-io/milvus/pkg/v2 v2.6.7-0.20251201120310-af64f2acba38 // indirect
github.com/minio/crc64nvme v1.1.1 // indirect
github.com/minio/md5-simd v1.1.2 // indirect

View File

@ -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")
}

View File

@ -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 collections
for _, collectionName := range collections {
if !matchesDimensionCollection(collectionName, m.collectionBaseName) {
continue
}
matchedCollections++
collectionMode, modeErr := m.collectionAnalyzerMode(ctx, collectionName)
if modeErr != nil {
failedCollections++
lastFailedErr = modeErr
log.Errorf("[Milvus] Failed to inspect collection %s analyzer mode: %v", collectionName, modeErr)
continue
}
expr, paramsMap, err := m.getBaseFilterForQuery(params)
if err != nil {
failedCollections++
lastFailedErr = err
log.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 {
log.Infof("[Milvus] Keywords retrieval found %d results", len(allResults))
// 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,
)
}
return buildRetrieveResult(allResults, types.KeywordsRetrieverType), nil
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)
}
retrieved := buildRetrieveResult(allResults, types.KeywordsRetrieverType)
retrieved[0].Error = partialErr
return retrieved, nil
}
// CopyIndices copies index data from source knowledge base to target knowledge base

View File

@ -759,6 +759,13 @@ func (q *qdrantRepository) KeywordsRetrieve(ctx context.Context,
var allResults []*types.IndexWithScore
limit := 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 error
log.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 = err
log.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 topK
if 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 {
log.Infof("[Qdrant] Keywords retrieval found %d results", len(allResults))
// 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,
)
}
return buildRetrieveResult(allResults, types.KeywordsRetrieverType), nil
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)
}
retrieved := buildRetrieveResult(allResults, types.KeywordsRetrieverType)
retrieved[0].Error = partialErr
return retrieved, nil
}
// CopyIndices copies index data from source knowledge base to target knowledge base

View File

@ -1,14 +1,18 @@
package qdrant
import (
"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")
}
}

View File

@ -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,

View File

@ -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.Retrie
Results: f.canned,
RetrieverEngineType: f.engineType,
RetrieverType: p.RetrieverType,
Error: f.cannedResultErr,
}}, nil
}

View File

@ -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")
}

View File

@ -2,6 +2,7 @@ package retriever
import (
"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 := false
for _, 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 parameters

View File

@ -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)

View File

@ -108,5 +108,12 @@ type RetrieveResult struct {
Results []*IndexWithScore // Retrieval results
RetrieverEngineType RetrieverEngineType // Retrieval source type
RetrieverType 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
}