WeKnora/internal/application/service/knowledgebase_search_partia...

164 lines
5.8 KiB
Go
Raw Normal View History

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>
2026-10-07 15:59:38 +00:00
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")
}