diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml index e0dd221d..bf13fdac 100644 --- a/config/prompt_templates/agent_system_prompt.yaml +++ b/config/prompt_templates/agent_system_prompt.yaml @@ -46,7 +46,7 @@ templates: When the task calls for knowledge-base evidence: - Choose a relevant source from the current runtime directory and use a search or reader supported by its capabilities. A knowledge base's states what it is for and its (gist, topics, typical questions) states what it actually contains; when several are bound, prefer the ones whose profile matches the question and pass their ids to the search tool instead of searching all of them. - Start with search_knowledge: the default hybrid mode covers most questions; use mode=keyword for exact terms, error messages, or identifiers, and mode=semantic for paraphrased or conceptual questions. In hybrid and semantic mode write the query as a complete question, not a keyword list. Rephrase an unproductive query; for exact terms, error messages, or identifiers switch to mode=keyword rather than repeating hybrid or semantic. - - Use read_document(id=dN) when a returned passage is incomplete: page with offset, or pass query to find a passage inside the document. Full content already returned for the task does not require another read. list_documents shows what a knowledge base contains when the search surface is unclear. + - When a returned passage is incomplete, use read_document(id=cN, context=k) to read the chunks around it; use read_document(id=dN) to read a document from its start (page with offset), or pass query to find a passage inside it. Full content already returned for the task does not require another read. list_documents shows what a knowledge base contains when the search surface is unclear. - For exact quotes, numbers, or code, verify the underlying source passage rather than relying on document metadata or a generated overview. Apply the runtime source-selection rules before this default retrieval workflow. Other requested sources and deliverables are part of the user's task. diff --git a/frontend/src/views/agent/AgentEditorModal.test.mjs b/frontend/src/views/agent/AgentEditorModal.test.mjs index e63fcf42..f6f635ed 100644 --- a/frontend/src/views/agent/AgentEditorModal.test.mjs +++ b/frontend/src/views/agent/AgentEditorModal.test.mjs @@ -176,3 +176,12 @@ test('a skill whose previous version still runs stays selectable during and afte assert.match(source, /installsAnUpgrade\(skill\) \? \$t\('settings\.skills\.upgrade'\) : \$t\('agent\.editor\.installShort'\)/) assert.match(source, /return skill\.upgradable \|\| Boolean\(skill\.servedNote\)/) }) + +test('retrieval strategy settings are hidden in agent mode, where search_knowledge ignores them', () => { + // search_knowledge reads the global retrieval configuration; showing the + // per-agent thresholds in agent mode let users tune values with no effect. + assert.match(source, /v-show="currentSection === 'retrieval' && hasKnowledgeBase && !isAgentMode"/) + assert.match(source, /if \(hasKnowledgeBase\.value && !isAgentMode\.value\) \{\s*items\.push\(\{ key: 'retrieval'/) + const modeWatch = source.match(/watch\(isAgentMode, \(isAgent\) => \{([\s\S]*?)^\}\);/m)?.[1] ?? '' + assert.match(modeWatch, /isAgent && \([^)]*currentSection\.value === 'retrieval'/) +}) diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue index 8eddba52..3d4b96ea 100644 --- a/frontend/src/views/agent/AgentEditorModal.vue +++ b/frontend/src/views/agent/AgentEditorModal.vue @@ -1637,8 +1637,9 @@ - -
+ +

{{ $t('agent.editor.retrievalStrategy') }}

{{ $t('agentEditor.desc.retrievalSection') }}

@@ -2741,7 +2742,9 @@ const navItems = computed(() => { items.push({ key: 'conversation', icon: 'chat', label: t('agent.editor.conversationSettings') }); // 知识库与检索 items.push({ key: 'knowledge', icon: 'folder', label: t('agent.editor.knowledgeConfig') }); - if (hasKnowledgeBase.value) { + // 检索策略只作用于普通模式的问答流程;Agent 模式的检索工具不读这些设置, + // 显示出来只会让用户调了参数却没有任何效果。 + if (hasKnowledgeBase.value && !isAgentMode.value) { items.push({ key: 'retrieval', icon: 'search', label: t('agent.editor.retrievalStrategy') }); } items.push({ key: 'websearch', icon: 'internet', label: t('agent.editor.webSearchConfig') }); @@ -3914,8 +3917,8 @@ watch(hasKnowledgeBase, (hasKB, oldHasKB) => { // 监听运行模式变化,自动切换页面 watch(isAgentMode, (isAgent) => { - // 如果当前在高级设置页面但切换到了Agent模式,切换到基础设置 - if (isAgent && currentSection.value === 'advanced') { + // 如果当前在高级设置或检索策略页面但切换到了Agent模式,切换到基础设置 + if (isAgent && (currentSection.value === 'advanced' || currentSection.value === 'retrieval')) { currentSection.value = 'basic'; } if (!isAgent && (currentSection.value === 'skills' || currentSection.value === 'sandbox')) { diff --git a/internal/agent/tools/chunk_snippet_test.go b/internal/agent/tools/chunk_snippet_test.go index bc4183f5..6f354a25 100644 --- a/internal/agent/tools/chunk_snippet_test.go +++ b/internal/agent/tools/chunk_snippet_test.go @@ -104,3 +104,22 @@ func TestExtractChunkMatchSnippet_NonFAQUsesBodyContext(t *testing.T) { t.Fatalf("expected expanded body context: %s", snippet) } } + +// A Chinese question has no spaces; it is segmented into words so the +// snippet lands on the matching passage instead of the chunk's opening. +func TestExtractSnippetForChineseQuery(t *testing.T) { + content := strings.Repeat("无关的开头内容。", 60) + "退款申请需要在收货后七天内提交。" + strings.Repeat("其他内容。", 20) + snippet := extractSnippetForQueries(content, []string{"退款申请的时限是多久?"}) + if !strings.Contains(snippet, "退款申请") { + t.Fatalf("snippet did not reach the matching passage: %q", snippet) + } +} + +func TestSearchQueryTokensSkipsStopwords(t *testing.T) { + tokens := searchQueryTokens([]string{"How does the engine start?"}) + for _, tok := range tokens { + if tok == "the" || tok == "does" || tok == "how" { + t.Fatalf("stopword %q kept: %v", tok, tokens) + } + } +} diff --git a/internal/agent/tools/faq_snippet.go b/internal/agent/tools/faq_snippet.go index 7a9ab3ca..610f286b 100644 --- a/internal/agent/tools/faq_snippet.go +++ b/internal/agent/tools/faq_snippet.go @@ -5,6 +5,7 @@ import ( "regexp" "strings" + "github.com/Tencent/WeKnora/internal/searchutil" "github.com/Tencent/WeKnora/internal/types" ) @@ -208,20 +209,46 @@ func faqMatchedQuestionFromRegex(meta *types.FAQChunkMetadata, compiled []*regex return meta.StandardQuestion } +// faqMatchedQuestionFromQueries picks the question the queries match best: +// one containing a whole query beats term matches, and more matched terms +// beat fewer. Ties go to similar questions in order, then the standard one. +// With word-level terms (Chinese queries are segmented) "the first question +// sharing any term" picked a loosely related similar question. func faqMatchedQuestionFromQueries(meta *types.FAQChunkMetadata, queries []string) string { if meta == nil { return "" } tokens := searchQueryTokens(queries) - for _, sq := range meta.SimilarQuestions { - if textMatchesSearchQueries(sq, queries, tokens) { - return sq + best, bestScore := meta.StandardQuestion, 0 + candidates := append(append([]string(nil), meta.SimilarQuestions...), meta.StandardQuestion) + for _, q := range candidates { + if score := searchQueryMatchScore(q, queries, tokens); score > bestScore { + best, bestScore = q, score } } - if textMatchesSearchQueries(meta.StandardQuestion, queries, tokens) { - return meta.StandardQuestion + return best +} + +// searchQueryMatchScore rates how well text matches the queries: a whole +// query contained in text counts more than any number of single terms. +func searchQueryMatchScore(text string, queries []string, tokens []string) int { + if text == "" { + return 0 } - return meta.StandardQuestion + lowered := strings.ToLower(text) + score := 0 + for _, q := range queries { + q = strings.ToLower(strings.TrimSpace(q)) + if q != "" && strings.Contains(lowered, q) { + score += 1000 + } + } + for _, tok := range tokens { + if strings.Contains(lowered, tok) { + score++ + } + } + return score } func faqAnswersForSnippet(answers []string) string { @@ -241,41 +268,12 @@ func faqAnswersForSnippet(answers []string) string { return truncateRunes(strings.Join(parts, " | "), snippetMaxAnswerRunes) } -func textMatchesSearchQueries(text string, queries []string, tokens []string) bool { - if text == "" { - return false - } - lowered := strings.ToLower(text) - for _, q := range queries { - q = strings.ToLower(strings.TrimSpace(q)) - if q != "" && strings.Contains(lowered, q) { - return true - } - } - for _, tok := range tokens { - if strings.Contains(lowered, tok) { - return true - } - } - return false -} - func searchQueryTokens(queries []string) []string { tokens := make([]string, 0, 8) seen := make(map[string]struct{}) for _, q := range queries { - for _, tok := range strings.FieldsFunc(q, func(r rune) bool { - switch r { - case ' ', '\t', '\n', '\r', ',', '.', ';', ':', '?', '!', - '(', ')', '[', ']', '{', '}', '"', '\'': - return true - } - return false - }) { - tok = strings.ToLower(strings.TrimSpace(tok)) - if len([]rune(tok)) < 2 { - continue - } + for _, tok := range queryTerms(q) { + tok = strings.ToLower(tok) if _, ok := seen[tok]; ok { continue } @@ -285,3 +283,55 @@ func searchQueryTokens(queries []string) []string { } return tokens } + +// queryTerms splits a query into candidate terms, keeping their case: words +// split on whitespace and punctuation, Chinese fields segmented into words, +// dropping single characters and stopwords. Terms may repeat. +func queryTerms(query string) []string { + var terms []string + add := func(word string) { + word = strings.TrimSpace(word) + if len([]rune(word)) < 2 { + return + } + if _, stop := snippetStopwords[strings.ToLower(word)]; stop { + return + } + terms = append(terms, word) + } + for _, field := range strings.FieldsFunc(query, isSnippetSeparator) { + // A Chinese question has no spaces, so the whole question was one + // token that never occurred in any chunk and every snippet fell + // back to the chunk's opening. Segment it into words instead. + if searchutil.ContainsChinese(field) { + for _, word := range types.Jieba.CutForSearch(field, true) { + add(word) + } + continue + } + add(field) + } + return terms +} + +// isSnippetSeparator splits a query into candidate terms on whitespace and +// ASCII or full-width punctuation. +func isSnippetSeparator(r rune) bool { + switch r { + case ' ', '\t', '\n', '\r', ',', '.', ';', ':', '?', '!', + '(', ')', '[', ']', '{', '}', '"', '\'', + ',', '。', ';', ':', '?', '!', '、', '(', ')', '【', '】', '“', '”', '‘', '’': + return true + } + return false +} + +// snippetStopwords are function words that occur in almost every chunk; as +// the earliest match they placed the snippet at an arbitrary position. +var snippetStopwords = map[string]struct{}{ + "the": {}, "and": {}, "or": {}, "of": {}, "to": {}, "in": {}, "on": {}, "for": {}, "with": {}, + "is": {}, "are": {}, "was": {}, "be": {}, "do": {}, "does": {}, "did": {}, "an": {}, "at": {}, + "by": {}, "it": {}, "its": {}, "as": {}, "from": {}, "that": {}, "this": {}, "what": {}, "how": {}, + "why": {}, "when": {}, "which": {}, "who": {}, "can": {}, "if": {}, + "什么": {}, "怎么": {}, "如何": {}, "哪些": {}, "是否": {}, "可以": {}, "一个": {}, "我们": {}, "你们": {}, +} diff --git a/internal/agent/tools/query_knowledge_graph.go b/internal/agent/tools/query_knowledge_graph.go index 44f42422..04e6af56 100644 --- a/internal/agent/tools/query_knowledge_graph.go +++ b/internal/agent/tools/query_knowledge_graph.go @@ -3,8 +3,10 @@ package tools import ( "context" "encoding/json" + "errors" "fmt" "sort" + "strings" "sync" "github.com/Tencent/WeKnora/internal/types" @@ -20,9 +22,10 @@ type graphConfigSummary struct { var queryKnowledgeGraphTool = BaseTool{ name: ToolQueryKnowledgeGraph, description: "Query the knowledge graph of graph-enabled knowledge bases to explore how entities relate " + - "(for example \"relationship between Docker and Kubernetes\"). Returns the chunks that carry those " + - "relationships with cN handles.\nUse search_knowledge for ordinary text retrieval and " + - "read_document(id=dN) to read a source in full.", + "(for example \"relationship between Docker and Kubernetes\"). Put the entity names in query. Returns " + + "the matching entities' relations and the chunks they were extracted from, then chunks found by text " + + "search, with cN handles.\nUse search_knowledge for ordinary text retrieval and " + + "read_document(id=cN, context=k) to read around a chunk.", schema: utils.GenerateSchema[QueryKnowledgeGraphInput](), } @@ -39,6 +42,65 @@ type QueryKnowledgeGraphTool struct { scopeKnowledgeService interfaces.KnowledgeService searchTargets types.SearchTargets scopeEnforced bool + graphRepo interfaces.RetrieveGraphRepository + chunkRepo interfaces.ChunkRepository +} + +// WithGraph lets the tool query the graph store for entities and relations. +// Without it the tool only has text search, which is what it used to do in +// every case: the tool never touched the graph, so a graph-only knowledge +// base always answered "no relevant graph information". +func (t *QueryKnowledgeGraphTool) WithGraph( + graphRepo interfaces.RetrieveGraphRepository, chunkRepo interfaces.ChunkRepository, +) *QueryKnowledgeGraphTool { + t.graphRepo = graphRepo + t.chunkRepo = chunkRepo + return t +} + +const ( + // graphQueryMaxTerms bounds the entity-name terms sent to the graph store. + graphQueryMaxTerms = 8 + // graphQueryMaxChunks bounds the evidence chunks loaded per knowledge base. + graphQueryMaxChunks = 10 + // graphQueryMaxRelations bounds the relations returned to the model. + graphQueryMaxRelations = 30 +) + +// graphSearchTerms turns the query into entity-name terms. The graph store +// matches node names by case-sensitive substring, so the whole query only +// matches when it is itself an entity name; its words catch the entities a +// question mentions ("Docker 和 Kubernetes 的关系" → Docker, Kubernetes). +// Words keep their case: lowercased terms never matched "Docker". +func graphSearchTerms(query string) []string { + query = strings.TrimSpace(query) + if query == "" { + return nil + } + seen := map[string]bool{query: true} + var tokens []string + for _, word := range queryTerms(query) { + if !seen[word] { + seen[word] = true + tokens = append(tokens, word) + } + } + // Longer tokens are more specific entity candidates; sort for stability. + sort.SliceStable(tokens, func(i, j int) bool { + li, lj := len([]rune(tokens[i])), len([]rune(tokens[j])) + if li != lj { + return li > lj + } + return tokens[i] < tokens[j] + }) + terms := []string{query} + for _, token := range tokens { + if len(terms) >= graphQueryMaxTerms { + break + } + terms = append(terms, token) + } + return terms } // WithKnowledgeScope enables document/tag-level result filtering for Agent @@ -111,117 +173,174 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess // Concurrently query all knowledge bases type graphQueryResult struct { - kbID string - kb *types.KnowledgeBase - results []*types.SearchResult - err error + kbID string + kb *types.KnowledgeBase + graphResults []*types.SearchResult // chunks the matched entities come from + textResults []*types.SearchResult + relations []*types.GraphRelation + warnings []string // failures of one source while the other returned results + err error } var wg sync.WaitGroup var mu sync.Mutex kbResults := make(map[string]*graphQueryResult) + terms := graphSearchTerms(query) searchParams := types.SearchParams{ - QueryText: query, - MatchCount: 10, + QueryText: query, + MatchCount: 10, + SkipContextEnrichment: true, } for _, kbID := range input.KnowledgeBaseIDs { wg.Add(1) go func(id string) { defer wg.Done() + res := &graphQueryResult{kbID: id} + defer func() { + mu.Lock() + kbResults[id] = res + mu.Unlock() + }() // Get knowledge base to check graph configuration kb, err := t.knowledgeService.GetKnowledgeBaseByIDOnly(ctx, id) if err != nil { - mu.Lock() - kbResults[id] = &graphQueryResult{kbID: id, err: fmt.Errorf("failed to get knowledge base: %v", err)} - mu.Unlock() + res.err = fmt.Errorf("failed to get knowledge base: %v", err) return } + res.kb = kb // Check if graph extraction is enabled if kb.ExtractConfig == nil || (len(kb.ExtractConfig.Nodes) == 0 && len(kb.ExtractConfig.Relations) == 0) { - mu.Lock() - kbResults[id] = &graphQueryResult{kbID: id, err: fmt.Errorf("graph extraction not configured")} - mu.Unlock() + res.err = fmt.Errorf("graph extraction not configured") return } - // Query graph - results, err := t.knowledgeService.HybridSearch(ctx, id, searchParams) + var errs []string + graphResults, graph, err := t.queryGraph(ctx, id, terms) if err != nil { - mu.Lock() - kbResults[id] = &graphQueryResult{kbID: id, kb: kb, err: fmt.Errorf("query failed: %v", err)} - mu.Unlock() - return + errs = append(errs, fmt.Sprintf("graph query failed: %v", err)) + } + var relations []*types.GraphRelation + if graph != nil { + relations = graph.Relation + } + // Text search complements the graph: relations say how entities + // connect, text hits carry statements the extraction missed. A KB + // with no text index returns nothing here rather than an error. + textResults, err := t.knowledgeService.HybridSearch(ctx, id, searchParams) + if err != nil { + errs = append(errs, fmt.Sprintf("text search failed: %v", err)) } if t.scopeEnforced { - results, err = filterSearchResultsInSearchTargets( - ctx, t.searchTargets, id, results, t.scopeKnowledgeService, - ) - if err != nil { - mu.Lock() - kbResults[id] = &graphQueryResult{kbID: id, kb: kb, err: err} - mu.Unlock() + if graphResults, err = filterSearchResultsInSearchTargets( + ctx, t.searchTargets, id, graphResults, t.scopeKnowledgeService, + ); err != nil { + res.err = err return } + if textResults, err = filterSearchResultsInSearchTargets( + ctx, t.searchTargets, id, textResults, t.scopeKnowledgeService, + ); err != nil { + res.err = err + return + } + // The graph namespace is the whole knowledge base, so under a + // document or tag scope only relations between entities backed + // by an in-scope chunk may reach the model. + if !searchTargetsCoverWholeKB(t.searchTargets, id) { + relations = relationsBackedBy(graph, graphResults) + } + } + res.graphResults, res.textResults, res.relations = graphResults, textResults, relations + if len(errs) > 0 && len(graphResults) == 0 && len(textResults) == 0 { + res.err = errors.New(strings.Join(errs, "; ")) + } else { + res.warnings = errs } - - mu.Lock() - kbResults[id] = &graphQueryResult{kbID: id, kb: kb, results: results} - mu.Unlock() }(kbID) } wg.Wait() - // Collect and deduplicate results - seenChunks := make(map[string]*types.SearchResult) - var errors []string + // Collect and deduplicate results: graph evidence first (in entity + // order), then text hits by score. + seenChunks := make(map[string]bool) + var errs []string graphConfigs := make(map[string]graphConfigSummary) kbCounts := make(map[string]int) + var graphHits, textHits []*types.SearchResult + var relations []*types.GraphRelation + seenRelations := make(map[string]bool) for _, kbID := range input.KnowledgeBaseIDs { result := kbResults[kbID] if result.err != nil { - errors = append(errors, fmt.Sprintf("KB %s: %v", kbID, result.err)) + errs = append(errs, fmt.Sprintf("KB %s: %v", kbID, result.err)) continue } + for _, warning := range result.warnings { + errs = append(errs, fmt.Sprintf("KB %s: %s", kbID, warning)) + } if result.kb != nil && result.kb.ExtractConfig != nil { graphConfigs[kbID] = summarizeGraphConfig(result.kb.ExtractConfig) } - kbCounts[kbID] = len(result.results) - for _, r := range result.results { - if _, seen := seenChunks[r.ID]; !seen { - seenChunks[r.ID] = r + kbCounts[kbID] = len(result.graphResults) + len(result.textResults) + for _, r := range result.graphResults { + if !seenChunks[r.ID] { + seenChunks[r.ID] = true + graphHits = append(graphHits, r) + } + } + for _, r := range result.textResults { + if !seenChunks[r.ID] { + seenChunks[r.ID] = true + textHits = append(textHits, r) + } + } + for _, rel := range result.relations { + key := rel.Node1 + "\x00" + rel.Type + "\x00" + rel.Node2 + if !seenRelations[key] && len(relations) < graphQueryMaxRelations { + seenRelations[key] = true + relations = append(relations, rel) } } } - // Convert map to slice and sort by score - allResults := make([]*types.SearchResult, 0, len(seenChunks)) - for _, result := range seenChunks { - allResults = append(allResults, result) + sort.SliceStable(textHits, func(i, j int) bool { + return textHits[i].Score > textHits[j].Score + }) + allResults := append(graphHits, textHits...) + relationData := make([]map[string]interface{}, 0, len(relations)) + for _, rel := range relations { + relationData = append(relationData, map[string]interface{}{ + "source": rel.Node1, "type": rel.Type, "target": rel.Node2, + }) } - sort.Slice(allResults, func(i, j int) bool { - return allResults[i].Score > allResults[j].Score - }) - - if len(allResults) == 0 { + if len(allResults) == 0 && len(relations) == 0 { + // The model reads an empty result from Output alone, so failures + // must be stated here or they read as "the graph has no such entity". + output := "No relevant graph information found." + if len(errs) > 0 { + output += " Some knowledge bases could not be queried: " + strings.Join(errs, "; ") + "." + } return &types.ToolResult{ Success: true, - Output: "No relevant graph information found.", + Output: output, Data: map[string]interface{}{ "knowledge_base_ids": input.KnowledgeBaseIDs, "query": query, "results": []interface{}{}, + "relations": relationData, "graph_configs": graphConfigsToData(graphConfigs), "graph_config": aggregateGraphConfig(graphConfigs), - "errors": errors, + "errors": errs, + "display_type": "graph_query_results", }, }, nil } @@ -230,16 +349,25 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess output := "=== Knowledge Graph Query ===\n\n" output += fmt.Sprintf("📊 Query: %s\n", query) output += fmt.Sprintf("🎯 Target Knowledge Bases: %v\n", input.KnowledgeBaseIDs) - output += fmt.Sprintf("✓ Found %d relevant results (deduplicated)\n\n", len(allResults)) + output += fmt.Sprintf("✓ Found %d relations and %d relevant chunks (deduplicated)\n\n", + len(relations), len(allResults)) - if len(errors) > 0 { + if len(errs) > 0 { output += "=== ⚠️ Partial Failures ===\n" - for _, errMsg := range errors { + for _, errMsg := range errs { output += fmt.Sprintf(" - %s\n", errMsg) } output += "\n" } + if len(relations) > 0 { + output += "=== 🔗 Relations ===\n" + for _, rel := range relations { + output += fmt.Sprintf(" - %s --[%s]--> %s\n", rel.Node1, rel.Type, rel.Node2) + } + output += "\n" + } + // Display graph configuration status hasGraphConfig := false output += "=== 📈 Graph Configuration Status ===\n\n" @@ -314,7 +442,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess } // Build structured graph data for frontend visualization - graphData := buildGraphVisualizationData(allResults) + graphData := buildGraphVisualizationData(allResults, relations) return &types.ToolResult{ Success: true, @@ -323,18 +451,156 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess "knowledge_base_ids": input.KnowledgeBaseIDs, "query": query, "results": formattedResults, + "relations": relationData, "count": len(allResults), "kb_counts": kbCounts, "graph_configs": graphConfigsToData(graphConfigs), "graph_config": aggregateGraphConfig(graphConfigs), "graph_data": graphData, "has_graph_config": hasGraphConfig, - "errors": errors, + "errors": errs, "display_type": "graph_query_results", }, }, nil } +// queryGraph looks the query's entity terms up in kbID's graph and returns +// the chunks the matched entities were extracted from, plus the matched graph +// (entities and relations). With no graph store wired, or none configured +// (the store answers nil), it returns nothing. +func (t *QueryKnowledgeGraphTool) queryGraph( + ctx context.Context, kbID string, terms []string, +) ([]*types.SearchResult, *types.GraphData, error) { + if t.graphRepo == nil || len(terms) == 0 { + return nil, nil, nil + } + graph, err := t.graphRepo.SearchNode(ctx, types.NameSpace{KnowledgeBase: kbID}, terms) + if err != nil || graph == nil { + return nil, nil, err + } + chunkIDs := make([]string, 0, graphQueryMaxChunks) + seen := make(map[string]bool) + for _, node := range graph.Node { + for _, id := range node.Chunks { + if len(chunkIDs) >= graphQueryMaxChunks { + break + } + if id != "" && !seen[id] { + seen[id] = true + chunkIDs = append(chunkIDs, id) + } + } + } + if len(chunkIDs) == 0 || t.chunkRepo == nil { + return nil, graph, nil + } + // The graph namespace is the knowledge base, which the caller already + // authorized; a chunk ID is only trusted when its row belongs to it. + chunks, err := t.chunkRepo.ListChunksByIDOnly(ctx, chunkIDs) + if err != nil { + return nil, graph, err + } + byID := make(map[string]*types.Chunk, len(chunks)) + knowledgeIDs := make([]string, 0, len(chunks)) + for _, c := range chunks { + if c != nil && c.KnowledgeBaseID == kbID && c.IsEnabled { + byID[c.ID] = c + knowledgeIDs = append(knowledgeIDs, c.KnowledgeID) + } + } + titles, err := t.knowledgeTitles(ctx, knowledgeIDs) + if err != nil { + return nil, graph, err + } + results := make([]*types.SearchResult, 0, len(byID)) + for _, id := range chunkIDs { + c := byID[id] + if c == nil { + continue + } + // A chunk can outlive its soft-deleted document; titles holds only + // documents that still exist (nil when there is no way to check). + if _, exists := titles[c.KnowledgeID]; titles != nil && !exists { + continue + } + results = append(results, &types.SearchResult{ + ID: c.ID, + Content: c.Content, + KnowledgeID: c.KnowledgeID, + KnowledgeBaseID: c.KnowledgeBaseID, + KnowledgeTitle: titles[c.KnowledgeID], + ChunkIndex: c.ChunkIndex, + ChunkType: string(c.ChunkType), + ParentChunkID: c.ParentChunkID, + MatchType: types.MatchTypeGraph, + }) + } + return results, graph, nil +} + +// knowledgeTitles returns the titles of the knowledge IDs that still exist. +// It returns nil when no knowledge service is wired to look them up. +func (t *QueryKnowledgeGraphTool) knowledgeTitles(ctx context.Context, ids []string) (map[string]string, error) { + if t.scopeKnowledgeService == nil { + return nil, nil + } + titles := make(map[string]string, len(ids)) + if len(ids) == 0 { + return titles, nil + } + tenantID, _ := types.TenantIDFromContext(ctx) + knowledges, err := t.scopeKnowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, tenantID, ids) + if err != nil { + return nil, fmt.Errorf("failed to load documents: %w", err) + } + for _, k := range knowledges { + if k != nil { + titles[k.ID] = k.Title + } + } + return titles, nil +} + +// searchTargetsCoverWholeKB reports whether targets grant the whole of kbID +// rather than some of its documents or tags. +func searchTargetsCoverWholeKB(targets types.SearchTargets, kbID string) bool { + for _, target := range targets { + if target != nil && target.KnowledgeBaseID == kbID && searchTargetIsWholeKB(target) { + return true + } + } + return false +} + +// relationsBackedBy keeps the graph's relations whose two entities were both +// extracted from one of the evidence chunks. Entities whose chunks are not +// among them cannot be shown to be in scope, so their relations are dropped. +func relationsBackedBy(graph *types.GraphData, evidence []*types.SearchResult) []*types.GraphRelation { + if graph == nil || len(evidence) == 0 { + return nil + } + allowedChunks := make(map[string]bool, len(evidence)) + for _, r := range evidence { + allowedChunks[r.ID] = true + } + allowedNodes := make(map[string]bool) + for _, node := range graph.Node { + for _, id := range node.Chunks { + if allowedChunks[id] { + allowedNodes[node.Name] = true + break + } + } + } + var relations []*types.GraphRelation + for _, rel := range graph.Relation { + if allowedNodes[rel.Node1] && allowedNodes[rel.Node2] { + relations = append(relations, rel) + } + } + return relations +} + func summarizeGraphConfig(config *types.ExtractConfig) graphConfigSummary { if config == nil { return graphConfigSummary{} @@ -429,14 +695,29 @@ func uniqueStrings(values []string) []string { return result } -// buildGraphVisualizationData builds structured data for graph visualization -func buildGraphVisualizationData(results []*types.SearchResult) map[string]interface{} { - // Build a simple graph structure for frontend visualization +// buildGraphVisualizationData builds structured data for graph visualization: +// the entities and relations the graph returned, and the chunks. +func buildGraphVisualizationData( + results []*types.SearchResult, relations []*types.GraphRelation, +) map[string]interface{} { nodes := make([]map[string]interface{}, 0) edges := make([]map[string]interface{}, 0) - // Create nodes from results seenEntities := make(map[string]bool) + addEntity := func(name string) { + if name == "" || seenEntities["entity:"+name] { + return + } + seenEntities["entity:"+name] = true + nodes = append(nodes, map[string]interface{}{"id": "entity:" + name, "label": name, "type": "entity"}) + } + for _, rel := range relations { + addEntity(rel.Node1) + addEntity(rel.Node2) + edges = append(edges, map[string]interface{}{ + "source": "entity:" + rel.Node1, "target": "entity:" + rel.Node2, "label": rel.Type, + }) + } for i, result := range results { if !seenEntities[result.ID] { nodes = append(nodes, map[string]interface{}{ diff --git a/internal/agent/tools/query_knowledge_graph_graph_test.go b/internal/agent/tools/query_knowledge_graph_graph_test.go new file mode 100644 index 00000000..747a7e95 --- /dev/null +++ b/internal/agent/tools/query_knowledge_graph_graph_test.go @@ -0,0 +1,133 @@ +package tools + +import ( + "context" + "encoding/json" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type stubGraphRepo struct { + interfaces.RetrieveGraphRepository + graph *types.GraphData + terms []string +} + +func (s *stubGraphRepo) SearchNode(_ context.Context, _ types.NameSpace, nodes []string) (*types.GraphData, error) { + s.terms = nodes + return s.graph, nil +} + +type stubGraphChunkRepo struct { + interfaces.ChunkRepository + chunks map[string]*types.Chunk +} + +func (s *stubGraphChunkRepo) ListChunksByIDOnly(_ context.Context, ids []string) ([]*types.Chunk, error) { + var out []*types.Chunk + for _, id := range ids { + if c := s.chunks[id]; c != nil { + out = append(out, c) + } + } + return out, nil +} + +// The tool used to run plain text search only. It now looks the entities up +// in the graph, returns their relations, and puts the chunks they came from +// first — only chunks of the queried, authorized knowledge base. +func TestQueryKnowledgeGraph_QueriesTheGraph(t *testing.T) { + graphRepo := &stubGraphRepo{graph: &types.GraphData{ + Node: []*types.GraphNode{ + {Name: "Docker", Chunks: []string{"c-docker", "c-foreign", "c-disabled"}}, + {Name: "Kubernetes", Chunks: []string{"c-k8s"}}, + }, + Relation: []*types.GraphRelation{{Node1: "Kubernetes", Node2: "Docker", Type: "orchestrates"}}, + }} + chunkRepo := &stubGraphChunkRepo{chunks: map[string]*types.Chunk{ + "c-docker": { + ID: "c-docker", KnowledgeBaseID: "kb-1", KnowledgeID: "doc", + Content: "Docker runs containers", IsEnabled: true, + }, + "c-k8s": { + ID: "c-k8s", KnowledgeBaseID: "kb-1", KnowledgeID: "doc", + Content: "Kubernetes schedules pods", IsEnabled: true, + }, + "c-foreign": {ID: "c-foreign", KnowledgeBaseID: "kb-other", Content: "foreign", IsEnabled: true}, + "c-disabled": {ID: "c-disabled", KnowledgeBaseID: "kb-1", Content: "disabled", IsEnabled: false}, + }} + tool := NewQueryKnowledgeGraphTool(&stubKnowledgeBaseService{ + kb: &types.KnowledgeBase{ID: "kb-1", ExtractConfig: &types.ExtractConfig{ + Enabled: true, Nodes: []*types.GraphNode{{Name: "技术"}}, + }}, + results: []*types.SearchResult{{ID: "c-text", KnowledgeID: "doc", Content: "text hit", Score: 0.9}}, + }).WithGraph(graphRepo, chunkRepo) + + args, err := json.Marshal(QueryKnowledgeGraphInput{KnowledgeBaseIDs: []string{"kb-1"}, Query: "Docker Kubernetes"}) + require.NoError(t, err) + result, err := tool.Execute(context.Background(), args) + require.NoError(t, err) + + assert.Equal(t, []string{"Docker Kubernetes", "Kubernetes", "Docker"}, graphRepo.terms, + "terms keep case: Neo4j CONTAINS is case-sensitive") + rows, ok := result.Data["results"].([]map[string]interface{}) + require.True(t, ok) + ids := make([]interface{}, 0, len(rows)) + for _, row := range rows { + ids = append(ids, row["chunk_id"]) + } + assert.Equal(t, []interface{}{"c-docker", "c-k8s", "c-text"}, ids, + "graph evidence first, foreign and disabled chunks dropped") + relations, ok := result.Data["relations"].([]map[string]interface{}) + require.True(t, ok) + require.Len(t, relations, 1) + assert.Equal(t, "orchestrates", relations[0]["type"]) + assert.Contains(t, result.Output, "Kubernetes --[orchestrates]--> Docker") +} + +// The graph namespace is the whole knowledge base. Under a document scope, +// relations between entities from out-of-scope documents must not reach the +// model, and a failed text search is reported next to the graph evidence. +func TestQueryKnowledgeGraph_ScopesRelationsToDocuments(t *testing.T) { + graphRepo := &stubGraphRepo{graph: &types.GraphData{ + Node: []*types.GraphNode{ + {Name: "Docker", Chunks: []string{"c-a"}}, + {Name: "Kubernetes", Chunks: []string{"c-a"}}, + {Name: "Secret", Chunks: []string{"c-b"}}, + }, + Relation: []*types.GraphRelation{ + {Node1: "Kubernetes", Node2: "Docker", Type: "orchestrates"}, + {Node1: "Secret", Node2: "Docker", Type: "leaks"}, + }, + }} + chunkRepo := &stubGraphChunkRepo{chunks: map[string]*types.Chunk{ + "c-a": {ID: "c-a", KnowledgeBaseID: "kb-1", KnowledgeID: "doc-a", Content: "in scope", IsEnabled: true}, + "c-b": {ID: "c-b", KnowledgeBaseID: "kb-1", KnowledgeID: "doc-b", Content: "out of scope", IsEnabled: true}, + }} + tool := NewQueryKnowledgeGraphTool(&stubKnowledgeBaseService{ + kb: &types.KnowledgeBase{ID: "kb-1", ExtractConfig: &types.ExtractConfig{ + Enabled: true, Nodes: []*types.GraphNode{{Name: "技术"}}, + }}, + err: assert.AnError, + }, types.SearchTargets{{ + Type: types.SearchTargetTypeKnowledge, KnowledgeBaseID: "kb-1", KnowledgeIDs: []string{"doc-a"}, + }}).WithGraph(graphRepo, chunkRepo) + + args, err := json.Marshal(QueryKnowledgeGraphInput{KnowledgeBaseIDs: []string{"kb-1"}, Query: "Docker"}) + require.NoError(t, err) + result, err := tool.Execute(context.Background(), args) + require.NoError(t, err) + + relations, ok := result.Data["relations"].([]map[string]interface{}) + require.True(t, ok) + require.Len(t, relations, 1) + assert.Equal(t, "orchestrates", relations[0]["type"]) + assert.NotContains(t, result.Output, "Secret") + errs, _ := result.Data["errors"].([]string) + require.Len(t, errs, 1, "the failed text search is reported beside the graph hits") + assert.Contains(t, errs[0], "text search failed") +} diff --git a/internal/agent/tools/query_knowledge_graph_test.go b/internal/agent/tools/query_knowledge_graph_test.go index c72d2eee..8a67f17b 100644 --- a/internal/agent/tools/query_knowledge_graph_test.go +++ b/internal/agent/tools/query_knowledge_graph_test.go @@ -15,6 +15,7 @@ import ( type stubKnowledgeBaseService struct { kb *types.KnowledgeBase results []*types.SearchResult + err error } func (s *stubKnowledgeBaseService) CreateKnowledgeBase(context.Context, *types.KnowledgeBase) (*types.KnowledgeBase, error) { @@ -64,7 +65,7 @@ func (s *stubKnowledgeBaseService) TogglePinKnowledgeBase(context.Context, strin } func (s *stubKnowledgeBaseService) HybridSearch(context.Context, string, types.SearchParams) ([]*types.SearchResult, error) { - return s.results, nil + return s.results, s.err } func (s *stubKnowledgeBaseService) HybridSearchWithRerank( @@ -178,7 +179,7 @@ func TestQueryKnowledgeGraph_ReportsConfiguredEntityAndRelationTypes(t *testing. assert.Contains(t, result.Output, "审批流程") assert.Contains(t, result.Output, "管理") assert.Contains(t, result.Output, "审批") - assert.Contains(t, result.Output, "✓ Found 3 relevant results (deduplicated)") + assert.Contains(t, result.Output, "✓ Found 0 relations and 3 relevant chunks (deduplicated)") assert.Contains(t, result.Output, "Result #1:") assert.Contains(t, result.Output, "Result #2:") assert.Contains(t, result.Output, "Result #3:") diff --git a/internal/agent/tools/read_document.go b/internal/agent/tools/read_document.go index 8b9f9af8..410e9f29 100644 --- a/internal/agent/tools/read_document.go +++ b/internal/agent/tools/read_document.go @@ -30,7 +30,8 @@ var readDocumentTool = BaseTool{ "chunk; set context to include neighbouring chunks on each side).\n" + "query finds passages inside the document: matching chunks come back with one chunk of context on each " + "side. By default query is case-insensitive and split on whitespace: a chunk matches when it contains " + - "every word, in any order. Set regex=true to match query as one POSIX regular expression instead.\n" + + "every word, in any order. Set regex=true to match query as one POSIX regular expression instead. " + + "When a query result is truncated, repeat it with offset=next_offset to get the following matches.\n" + "Page through long documents with offset and limit: offset counts chunks in reading order from 0 and is " + "not a chunk index, so continue with the returned next_offset, and use id=cN with context to read around " + "a specific chunk. A page holds fewer than limit chunks when they would exceed the output size budget; " + @@ -179,7 +180,7 @@ func (t *ReadDocumentTool) Execute(ctx context.Context, args json.RawMessage) (* // chunk: silently returning the single chunk would read as "no match". switch { case len(matchers) > 0: - return t.readByQuery(ctx, knowledge, query, matchers) + return t.readByQuery(ctx, knowledge, query, matchers, offset) case chunk != nil: return t.readAroundChunk(ctx, knowledge, chunk, contextChunks) default: @@ -395,11 +396,14 @@ func (t *ReadDocumentTool) readAroundChunk( }, nil } -// readByQuery scans the document in order and returns chunks matched by -// every matcher, with one chunk of context on each side, capped at -// readDocumentMaxMatches. +// readByQuery scans the document in order from offset and returns chunks +// matched by every matcher, with one chunk of context on each side, capped at +// readDocumentMaxMatches and the output budget. A truncated result carries +// next_offset, the reading-order position of the first match it left out; +// without it matches past the cap could only be reached by paging the whole +// document. func (t *ReadDocumentTool) readByQuery( - ctx context.Context, knowledge *types.Knowledge, query string, matchers []*regexp.Regexp, + ctx context.Context, knowledge *types.Knowledge, query string, matchers []*regexp.Regexp, offset int, ) (*types.ToolResult, error) { var rows []readChunkRow emitted := make(map[string]bool) @@ -408,7 +412,10 @@ func (t *ReadDocumentTool) readByQuery( var total int64 var prev *types.Chunk forceNext := false - page := 1 + // Start one chunk before offset so a match at offset still gets its + // preceding context, also when offset is the first chunk of a page. + page := max(offset-1, 0)/readDocumentScanPageSize + 1 + nextOffset := -1 tenantID := t.tenantFor(knowledge) // Stop collecting before the registry's head/tail truncation would cut // rows in the middle; the header and tags take the remaining share. @@ -426,14 +433,18 @@ scan: if err != nil { return &types.ToolResult{Success: false, Error: err.Error()}, err } - if page == 1 { - total = pageTotal - } + total = pageTotal if len(chunks) == 0 { break } enrichChunkImageInfo(ctx, t.chunkService.GetRepository(), tenantID, chunks) - for _, c := range chunks { + for i, c := range chunks { + position := (page-1)*readDocumentScanPageSize + i + if position < offset { + // Before the requested start: only its text as context. + prev = c + continue + } haystack := enrichChunkContent(c) if q := faqStandardQuestion(c); q != "" { haystack += "\n" + q @@ -441,6 +452,7 @@ scan: if matchesAll(matchers, haystack) { if matchCount >= readDocumentMaxMatches || used >= budget { truncated = true + nextOffset = position break scan } matchCount++ @@ -469,6 +481,9 @@ scan: data["query"] = query data["match_count"] = matchCount data["truncated"] = truncated + if nextOffset >= 0 { + data["next_offset"] = nextOffset + } return &types.ToolResult{ Success: true, Output: t.buildOutput(knowledge, total, rows, query), diff --git a/internal/agent/tools/read_document_test.go b/internal/agent/tools/read_document_test.go index 42c7872f..fe113aa8 100644 --- a/internal/agent/tools/read_document_test.go +++ b/internal/agent/tools/read_document_test.go @@ -525,3 +525,39 @@ func TestReadDocumentFAQChunkExposesQuestion(t *testing.T) { t.Fatalf("output = %s", res.Output) } } + +// A truncated query result says where to continue, and offset resumes the +// scan there; matches past the cap used to be reachable only by paging the +// whole document. +func TestReadDocumentQueryContinuesFromNextOffset(t *testing.T) { + tool, repo := newReadDocumentFixture(12) + for _, c := range repo.ordered { + c.Content = "needle " + strings.Repeat("x", 400) + } + ctx := WithOutputBudget(context.Background(), 1500) + first, err := tool.Execute(ctx, json.RawMessage(`{"id":"doc-1","query":"needle"}`)) + if err != nil || !first.Success || first.Data["truncated"] != true { + t.Fatalf("first=%+v err=%v", first, err) + } + next, ok := first.Data["next_offset"].(int) + if !ok || next <= 0 || next >= 12 { + t.Fatalf("next_offset = %v", first.Data["next_offset"]) + } + firstIDs := chunkIDsFromData(t, first.Data) + + second, err := tool.Execute(ctx, json.RawMessage(fmt.Sprintf(`{"id":"doc-1","query":"needle","offset":%d}`, next))) + if err != nil || !second.Success { + t.Fatalf("second=%+v err=%v", second, err) + } + secondIDs := chunkIDsFromData(t, second.Data) + if len(secondIDs) == 0 { + t.Fatal("continuation returned nothing") + } + for _, id := range secondIDs { + for _, seen := range firstIDs { + if id == seen && id != secondIDs[0] { + t.Fatalf("continuation repeated %s: first=%v second=%v", id, firstIDs, secondIDs) + } + } + } +} diff --git a/internal/agent/tools/search_knowledge.go b/internal/agent/tools/search_knowledge.go index 73533b8e..a43ceee3 100644 --- a/internal/agent/tools/search_knowledge.go +++ b/internal/agent/tools/search_knowledge.go @@ -4,10 +4,12 @@ import ( "context" "encoding/json" "fmt" + "math" "regexp" "sort" "strings" "sync" + "unicode/utf8" "github.com/Tencent/WeKnora/internal/config" "github.com/Tencent/WeKnora/internal/logger" @@ -44,8 +46,9 @@ var searchKnowledgeTool = BaseTool{ "profile fits the question. When nothing passes the relevance check, rephrase with terms the documents " + "would use; repeating the same query in another mode usually does not help. For identifiers, error " + "codes or exact names retry with mode=keyword.\n" + - "Every chunk carries a cN handle and belongs to a dN document. Use read_document(id=dN) to read the " + - "surrounding context or the whole document. Retrieval matches chunk text; the relevance model also " + + "Every chunk carries a cN handle and belongs to a dN document. Use read_document(id=cN, context=k) to " + + "read the text around a chunk, and read_document(id=dN) to read a document from its start. Retrieval " + + "matches chunk text; the relevance model also " + "sees the document title. To find a document by its title or file name use list_documents(keyword=...).", schema: json.RawMessage(`{ "type": "object", @@ -228,15 +231,28 @@ func (t *SearchKnowledgeTool) Execute(ctx context.Context, args json.RawMessage) "[Tool][SearchKnowledge] query=%q mode=%s limit=%d top_k=%d targets=%d kbs=%d", query, mode, limit, topK, len(searchTargets), len(kbIDs)) - allResults := t.concurrentSearchByTargets(ctx, query, mode, kbModes, searchTargets, kbList, - topK, vectorThreshold, keywordThreshold, kbTypeMap) + allResults, searchFailures, searchCalls, embedFallbacks := t.concurrentSearchByTargets(ctx, query, mode, + kbModes, searchTargets, kbList, topK, vectorThreshold, keywordThreshold, kbTypeMap) + // A hybrid search that ran keyword-only is reported like any other mode + // fallback, so an empty result is not read as "no semantic match". + for kbID, reason := range embedFallbacks { + kbModes[kbID] = kbSearchMode{mode: SearchModeKeyword, fallback: true, reason: reason} + } + // A failed search is not an empty one. Reporting "no matching chunks" + // when the vector store timed out or the embedding call failed made the + // model conclude the knowledge base has no answer. + if searchCalls > 0 && len(searchFailures) >= searchCalls { + msg := "Knowledge search failed: " + strings.Join(searchFailures, "; ") + + ". The knowledge bases were not searched, so this is not evidence that they lack the answer." + return &types.ToolResult{Success: false, Output: msg, Error: msg}, nil + } deduplicated := t.deduplicateResults(allResults) ranked := deduplicated rerankRejected := 0 if t.rerankModel != nil && len(deduplicated) > 0 { - reranked, err := t.rerankResults(ctx, query, deduplicated) + reranked, err := t.rerankResults(ctx, query, deduplicated, mode == SearchModeKeyword) if err != nil { logger.Warnf(ctx, "[Tool][SearchKnowledge] Rerank failed, using retrieval order: %v", err) } else { @@ -288,7 +304,13 @@ func (t *SearchKnowledgeTool) Execute(ctx context.Context, args json.RawMessage) } } - result := t.formatOutput(ctx, final, kbIDs, query, mode) + result, omitted := t.formatWithinBudget(ctx, final, kbIDs, query, mode) + if omitted > 0 { + result.Data["omitted_for_budget"] = omitted + } + if len(searchFailures) > 0 { + result.Data["partial_failures"] = searchFailures + } annotateModeFallback(result.Data, mode, kbModes) if rerankRejected > 0 { result.Data["rerank_rejected"] = rerankRejected @@ -299,6 +321,33 @@ func (t *SearchKnowledgeTool) Execute(ctx context.Context, args json.RawMessage) return result, nil } +// formatWithinBudget renders results, dropping the lowest-ranked ones until +// the rendering fits in four fifths of the tool output budget, and reports +// how many were dropped. The model reads a view rebuilt from Data, which the +// registry's output truncation does not reach, so 30 full chunks used to go +// into the context whatever the budget. The best result is always kept. +func (t *SearchKnowledgeTool) formatWithinBudget( + ctx context.Context, + results []*searchResultWithMeta, + kbIDs []string, + query, mode string, +) (*types.ToolResult, int) { + budget := OutputBudget(ctx) * 4 / 5 + kept := results + result := t.formatOutput(ctx, kept, kbIDs, query, mode) + for len(kept) > 1 { + size := utf8.RuneCountInString(result.Output) + if size <= budget { + break + } + // Shrink in proportion to the overshoot, at least one row per round. + n := min(len(kept)-1, max(1, len(kept)*budget/size)) + kept = kept[:n] + result = t.formatOutput(ctx, kept, kbIDs, query, mode) + } + return result, len(results) - len(kept) +} + // emptySearchStatement describes an empty result, including any mode // fallback, so the model does not read "no semantic neighbours" as "the // exact term does not occur". When retrieval found candidates and the rerank @@ -312,14 +361,26 @@ func emptySearchStatement(query string, data map[string]interface{}, kbCount int msg = fmt.Sprintf("No chunk passed the relevance check for %q (mode=%s) in %d knowledge base(s): "+ "retrieval found %d candidate chunks but the relevance model scored none of them as answering the "+ "query. Repeating the same query in another mode usually will not help; rephrase with terms the "+ - "documents would use. For identifiers, error codes or exact names retry with mode=keyword.", + "documents would use.", query, mode, kbCount, rejected) + if mode != SearchModeKeyword { + msg += " For identifiers, error codes or exact names retry with mode=keyword." + } + } else if mode == SearchModeKeyword { + msg += " No chunk contains these exact terms; try the terms the documents would use, or mode=hybrid " + + "with a natural-language question." } fallbacks, _ := data["mode_fallbacks"].([]map[string]interface{}) for _, fb := range fallbacks { msg += fmt.Sprintf(" Knowledge base %v was searched with mode=%v (%v).", fb["knowledge_base_id"], fb["mode"], fb["reason"]) } + // An empty result renders from this text alone, so a failed search in + // part of the scope must be stated here, or it reads as "not found". + if failures, _ := data["partial_failures"].([]string); len(failures) > 0 { + msg += " Some knowledge bases could not be searched, so this is not evidence that they lack the " + + "answer: " + strings.Join(failures, "; ") + "." + } return msg } @@ -442,7 +503,7 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( topK int, vectorThreshold, keywordThreshold float64, kbTypeMap map[string]string, -) []*searchResultWithMeta { +) (_ []*searchResultWithMeta, failures []string, calls int, embedFallbacks map[string]string) { // Filter out non-searchable KBs (wiki-only / graph-only). Feeding a // wiki-only KB into HybridSearch causes spurious "model ID cannot be // empty" errors because such KBs have no EmbeddingModelID configured. @@ -474,7 +535,7 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( st.KnowledgeBaseID) } if len(filteredTargets) == 0 { - return nil + return nil, nil, 0, nil } searchTargets = filteredTargets @@ -490,6 +551,28 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( var wg sync.WaitGroup var mu sync.Mutex allResults := make([]*searchResultWithMeta, 0) + // fail records one search that returned an error, or a search that + // could not run; calls counts every search attempted. + fail := func(kbIDs []string, err error) { + mu.Lock() + defer mu.Unlock() + failures = append(failures, fmt.Sprintf("%v: %v", kbIDs, err)) + } + attempt := func() { + mu.Lock() + defer mu.Unlock() + calls++ + } + // fallBack records a hybrid knowledge base searched by keyword only + // because the query embedding failed. + fallBack := func(kbID string, err error) { + mu.Lock() + defer mu.Unlock() + if embedFallbacks == nil { + embedFallbacks = make(map[string]string) + } + embedFallbacks[kbID] = fmt.Sprintf("query embedding failed, semantic search skipped: %v", err) + } collect := func(rows []*types.SearchResult, usedMode string) { mu.Lock() defer mu.Unlock() @@ -518,15 +601,41 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( } // Compute embedding once for this (model, query) pair var queryEmbedding []float32 + var embedErr error if modelKey != "" && needsEmbedding { emb, err := t.knowledgeBaseService.GetQueryEmbedding(ctx, targets[0].KnowledgeBaseID, query) if err != nil { logger.Warnf(ctx, "[Tool][SearchKnowledge] Failed to pre-compute embedding for model %s: %v", modelKey, err) + embedErr = err } else { queryEmbedding = emb } } + // Without a query embedding every vector search would re-embed + // (with retries) and fail again. Hybrid targets fall back to + // keyword search, as the chat pipeline does; vector-only targets + // cannot run and are reported as failed. + groupModeFor := func(kbID string) (string, bool) { + m, ok := modeFor(kbID) + if embedErr != nil && m == SearchModeHybrid { + return SearchModeKeyword, ok + } + return m, ok + } + runnable := targets[:0:0] + for _, st := range targets { + if m, _ := groupModeFor(st.KnowledgeBaseID); embedErr != nil && m == SearchModeSemantic { + attempt() + fail([]string{st.KnowledgeBaseID}, fmt.Errorf("query embedding failed: %w", embedErr)) + continue + } + if m, _ := modeFor(st.KnowledgeBaseID); embedErr != nil && m == SearchModeHybrid { + fallBack(st.KnowledgeBaseID, embedErr) + } + runnable = append(runnable, st) + } + targets = runnable // Separate full-KB targets (combinable per retrieval mode) from // specific-knowledge targets. @@ -534,7 +643,7 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( var knowledgeTargets []*types.SearchTarget for _, st := range targets { if st.Type == types.SearchTargetTypeKnowledgeBase && len(st.TagIDs) == 0 { - m, _ := modeFor(st.KnowledgeBaseID) + m, _ := groupModeFor(st.KnowledgeBaseID) fullKBIDsByMode[m] = append(fullKBIDsByMode[m], st.KnowledgeBaseID) } else { knowledgeTargets = append(knowledgeTargets, st) @@ -546,6 +655,7 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( innerWg.Add(1) go func(usedMode string, fullKBIDs []string) { defer innerWg.Done() + attempt() kbResults, err := t.knowledgeBaseService.HybridSearch(ctx, fullKBIDs[0], types.SearchParams{ QueryText: query, QueryEmbedding: queryEmbedding, @@ -555,10 +665,16 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( KeywordThreshold: keywordThreshold, DisableVectorMatch: usedMode == SearchModeKeyword, DisableKeywordsMatch: usedMode == SearchModeSemantic, + // Neighbor, parent and related chunks came back as + // extra rows that were never retrieved, tripling the + // rerank input; read_document(cN, context=k) serves + // surrounding text on demand. + SkipContextEnrichment: true, }) if err != nil { logger.Warnf(ctx, "[Tool][SearchKnowledge] Combined search failed for KBs %v: %v", fullKBIDs, err) + fail(fullKBIDs, err) return } collect(kbResults, usedMode) @@ -570,7 +686,8 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( innerWg.Add(1) go func() { defer innerWg.Done() - usedMode, _ := modeFor(st.KnowledgeBaseID) + attempt() + usedMode, _ := groupModeFor(st.KnowledgeBaseID) stVectorThreshold, stKeywordThreshold := st.RecallThresholds(vectorThreshold, keywordThreshold) kbResults, err := t.knowledgeBaseService.HybridSearch(ctx, st.KnowledgeBaseID, types.SearchParams{ QueryText: query, @@ -583,9 +700,15 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( ScopeTagIDs: st.ScopeTagIDs, DisableVectorMatch: usedMode == SearchModeKeyword, DisableKeywordsMatch: usedMode == SearchModeSemantic, + // Neighbor, parent and related chunks came back as + // extra rows that were never retrieved, tripling the + // rerank input; read_document(cN, context=k) serves + // surrounding text on demand. + SkipContextEnrichment: true, }) if err != nil { logger.Warnf(ctx, "[Tool][SearchKnowledge] Failed to search KB %s: %v", st.KnowledgeBaseID, err) + fail([]string{st.KnowledgeBaseID}, err) return } collect(kbResults, usedMode) @@ -595,7 +718,7 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( }(modelKey, targets) } wg.Wait() - return allResults + return allResults, failures, calls, embedFallbacks } // rerankResults scores all search results (including FAQ entries) with the @@ -605,10 +728,16 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets( // A failed rerank call degrades to the raw retrieval order. An empty result // is kept empty: the shared stage already preserves the top candidate down to // its fallback floor, so reaching zero means even the best match is below it. +// +// In keyword mode the rerank model only orders the hits. The exact-term +// match is the evidence, and rerank models score a bare identifier such as +// ERR_4012 low against the chunk that defines it, so filtering rejected +// every hit and the empty result sent the model back to keyword mode again. func (t *SearchKnowledgeTool) rerankResults( ctx context.Context, query string, results []*searchResultWithMeta, + orderOnly bool, ) ([]*searchResultWithMeta, error) { if len(results) == 0 || t.rerankModel == nil { return results, nil @@ -619,9 +748,13 @@ func (t *SearchKnowledgeTool) rerankResults( rows[i] = r.SearchResult } threshold := t.rerankThreshold() + if orderOnly { + threshold = math.Inf(-1) + } res := reranking.Rerank(ctx, t.rerankModel, query, rows, reranking.Options{ Threshold: threshold, FallbackMinScore: reranking.FallbackMinScore(t.searchTargets.HasRecallThresholdOverride()), + MaxCandidates: reranking.DefaultMaxCandidates, }) if res.Diagnostics.Outcome == types.RerankOutcomeModelError { logger.Warnf(ctx, "[Tool][SearchKnowledge] Rerank model failed, using raw retrieval results: %s", @@ -640,33 +773,16 @@ func (t *SearchKnowledgeTool) rerankResults( return reranked, nil } -func (t *SearchKnowledgeTool) getFAQMetadata( - ctx context.Context, - chunkID string, - cache map[string]*types.FAQChunkMetadata, -) (*types.FAQChunkMetadata, error) { - if chunkID == "" || t.chunkService == nil { +// faqMetadataFromResult parses FAQ metadata carried on the search result. +// Retrieval already loaded the chunk, including its metadata; re-reading it +// per hit cost one query each and, being tenant scoped, failed for FAQ KBs +// shared from another workspace, which then rendered as plain chunks without +// their answers. +func faqMetadataFromResult(result *types.SearchResult) (*types.FAQChunkMetadata, error) { + if result == nil || len(result.ChunkMetadata) == 0 { return nil, nil } - if meta, ok := cache[chunkID]; ok { - return meta, nil - } - chunk, err := t.chunkService.GetChunkByID(ctx, chunkID) - if err != nil { - cache[chunkID] = nil - return nil, err - } - if chunk == nil { - cache[chunkID] = nil - return nil, nil - } - meta, err := chunk.FAQMetadata() - if err != nil { - cache[chunkID] = nil - return nil, err - } - cache[chunkID] = meta - return meta, nil + return (&types.Chunk{Metadata: result.ChunkMetadata}).FAQMetadata() } func (t *SearchKnowledgeTool) rerankThreshold() float64 { @@ -676,23 +792,34 @@ func (t *SearchKnowledgeTool) rerankThreshold() float64 { return reranking.DefaultThreshold } -// deduplicateResults removes duplicate chunks, keeping the first occurrence. -// Uses multiple keys (ID, parent chunk ID, knowledge+index) and a content -// signature for near-duplicate detection. Input order is preserved. +// deduplicateResults removes duplicate chunks. Uses the chunk ID, the +// document position of text chunks and a content signature for near-duplicate +// detection, and returns the survivors best score first. +// +// Rows are visited best score first (stable), so of two duplicates the +// better-scored one survives rather than whichever search returned first. +// Sibling chunks under one parent are distinct text and are kept: keying on +// the parent dropped the child that held the answer whenever a sibling +// arrived first. The document-position key applies to text chunks only; +// image and FAQ chunks all carry chunk_index 0, so it collapsed every image +// chunk of a document, and the document's first text chunk, into one row. func (t *SearchKnowledgeTool) deduplicateResults(results []*searchResultWithMeta) []*searchResultWithMeta { seen := make(map[string]bool) contentSig := make(map[string]bool) uniqueResults := make([]*searchResultWithMeta, 0, len(results)) + ordered := make([]*searchResultWithMeta, 0, len(results)) for _, r := range results { - if r == nil || r.SearchResult == nil { - continue + if r != nil && r.SearchResult != nil { + ordered = append(ordered, r) } + } + sort.SliceStable(ordered, func(i, j int) bool { return ordered[i].Score > ordered[j].Score }) + + for _, r := range ordered { keys := []string{r.ID} - if r.ParentChunkID != "" { - keys = append(keys, "parent:"+r.ParentChunkID) - } - if r.KnowledgeID != "" { + isText := r.ChunkType == "" || r.ChunkType == string(types.ChunkTypeText) + if r.KnowledgeID != "" && isText { keys = append(keys, fmt.Sprintf("kb:%s#%d", r.KnowledgeID, r.ChunkIndex)) } dup := false @@ -792,13 +919,12 @@ func (t *SearchKnowledgeTool) formatOutput( writeKnowledgeMetadataHeader(&ob, results) formattedResults := make([]map[string]interface{}, 0, len(results)) - faqMetadataCache := make(map[string]*types.FAQChunkMetadata) queries := []string{query} for i, result := range results { var faqMeta *types.FAQChunkMetadata if result.KnowledgeBaseType == types.KnowledgeBaseTypeFAQ { - meta, err := t.getFAQMetadata(ctx, result.ID, faqMetadataCache) + meta, err := faqMetadataFromResult(result.SearchResult) if err != nil { logger.Warnf(ctx, "[Tool][SearchKnowledge] Failed to load FAQ metadata for chunk %s: %v", result.ID, err) diff --git a/internal/agent/tools/search_knowledge_rerank_test.go b/internal/agent/tools/search_knowledge_rerank_test.go index 9ce9f971..a0d73a5f 100644 --- a/internal/agent/tools/search_knowledge_rerank_test.go +++ b/internal/agent/tools/search_knowledge_rerank_test.go @@ -67,7 +67,7 @@ func TestRerankResults_modelErrorKeepsRawResults(t *testing.T) { tool := newRerankTestTool(model) results := newRerankTestResults() - out, err := tool.rerankResults(context.Background(), "query", results) + out, err := tool.rerankResults(context.Background(), "query", results, false) if err != nil { t.Fatalf("rerankResults returned error: %v", err) } @@ -90,7 +90,7 @@ func TestRerankResults_allBelowFallbackFloorReturnsEmpty(t *testing.T) { t.Parallel() tool := newRerankTestTool(&stubReranker{scores: []float64{0.10, 0.04}}) - out, err := tool.rerankResults(context.Background(), "query", newRerankTestResults()) + out, err := tool.rerankResults(context.Background(), "query", newRerankTestResults(), false) if err != nil { t.Fatalf("rerankResults returned error: %v", err) } @@ -103,7 +103,7 @@ func TestRerankResults_keepsCandidatesAboveThreshold(t *testing.T) { t.Parallel() tool := newRerankTestTool(&stubReranker{scores: []float64{0.9, 0.05}}) - out, err := tool.rerankResults(context.Background(), "query", newRerankTestResults()) + out, err := tool.rerankResults(context.Background(), "query", newRerankTestResults(), false) if err != nil { t.Fatalf("rerankResults returned error: %v", err) } @@ -117,7 +117,7 @@ func TestRerankResults_withoutModelIsPassthrough(t *testing.T) { tool := newRerankTestTool(nil) results := newRerankTestResults() - out, err := tool.rerankResults(context.Background(), "query", results) + out, err := tool.rerankResults(context.Background(), "query", results, false) if err != nil { t.Fatalf("rerankResults returned error: %v", err) } @@ -177,3 +177,56 @@ func TestRerankThreshold_default(t *testing.T) { t.Fatalf("default threshold = %v, want %v", got, reranking.DefaultThreshold) } } + +type failingSearchKBService struct { + stubKnowledgeBaseService + err error +} + +func (s *failingSearchKBService) HybridSearch( + context.Context, string, types.SearchParams, +) ([]*types.SearchResult, error) { + return nil, s.err +} + +// A search that failed is not an empty search: the model must not read a +// vector-store outage as "the knowledge base has no answer". +func TestExecuteReportsSearchFailure(t *testing.T) { + t.Parallel() + tool := NewSearchKnowledgeTool( + &failingSearchKBService{err: errors.New("vector store unavailable")}, nil, nil, + types.SearchTargets{{Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-1", TenantID: 1}}, + nil, &config.Config{Conversation: &config.ConversationConfig{}}, + ) + res, err := tool.Execute(context.Background(), json.RawMessage(`{"query":"refund policy"}`)) + if err != nil || res == nil { + t.Fatalf("Execute: res=%+v err=%v", res, err) + } + if res.Success || !strings.Contains(res.Error, "vector store unavailable") || + !strings.Contains(res.Error, "not evidence") { + t.Fatalf("failure not reported: %+v", res) + } +} + +// In keyword mode the rerank model orders exact-term hits but does not reject +// them: identifiers score low with rerank models. +func TestRerankResults_keywordModeOrdersWithoutFiltering(t *testing.T) { + t.Parallel() + tool := newRerankTestTool(&stubReranker{scores: []float64{0.01, 0.05}}) + + out, err := tool.rerankResults(context.Background(), "ERR_4012", newRerankTestResults(), true) + if err != nil { + t.Fatalf("rerankResults returned error: %v", err) + } + if len(out) != 2 || out[0].ID != "c2" { + t.Fatalf("expected both hits ordered by model score, got %#v", out) + } +} + +func TestEmptySearchStatementDoesNotSendKeywordModeBackToKeyword(t *testing.T) { + t.Parallel() + msg := emptySearchStatement("ERR_4012", map[string]interface{}{"mode": SearchModeKeyword}, 1) + if strings.Contains(msg, "retry with mode=keyword") { + t.Fatalf("keyword-mode statement suggests keyword mode: %q", msg) + } +} diff --git a/internal/agent/tools/search_knowledge_test.go b/internal/agent/tools/search_knowledge_test.go index 3c73329a..fd40d03a 100644 --- a/internal/agent/tools/search_knowledge_test.go +++ b/internal/agent/tools/search_knowledge_test.go @@ -3,8 +3,10 @@ package tools import ( "context" "encoding/json" + "fmt" "strings" "testing" + "unicode/utf8" "github.com/Tencent/WeKnora/internal/config" "github.com/Tencent/WeKnora/internal/types" @@ -254,3 +256,112 @@ func TestFormatOutputRowsCarryHandlesAndSnippets(t *testing.T) { t.Fatalf("legacy annotations must be gone: %s", res.Output) } } + +// A shared FAQ KB belongs to another workspace, so re-reading the chunk with +// the caller's tenant fails. The answers must come from the metadata the +// retrieval result already carries; the tool has no chunk service here. +func TestFormatOutputRendersFAQFromResultMetadata(t *testing.T) { + chunk := &types.Chunk{} + if err := chunk.SetFAQMetadata(&types.FAQChunkMetadata{ + StandardQuestion: "How do refunds work?", + Answers: []string{"Refunds are issued within 7 days."}, + }); err != nil { + t.Fatal(err) + } + tool := &SearchKnowledgeTool{} + results := []*searchResultWithMeta{ + { + SearchResult: &types.SearchResult{ + ID: "faq-1", KnowledgeID: "faq-doc", Content: "How do refunds work?", Score: 0.9, + ChunkMetadata: chunk.Metadata, + }, + KnowledgeBaseID: "kb-faq", KnowledgeBaseType: types.KnowledgeBaseTypeFAQ, + }, + } + res := tool.formatOutput(context.Background(), results, []string{"kb-faq"}, "refunds", SearchModeHybrid) + rows, ok := res.Data["results"].([]map[string]interface{}) + if !ok || len(rows) != 1 { + t.Fatalf("results rows = %#v", res.Data["results"]) + } + answers, _ := rows[0]["faq_answers"].([]string) + if len(answers) != 1 || answers[0] != "Refunds are issued within 7 days." { + t.Fatalf("faq answers = %#v", rows[0]["faq_answers"]) + } + if !strings.Contains(res.Output, ": %q", res.Output) + } +} + +// The model reads a view rebuilt from Data, which registry truncation does not +// reach, so the tool fits its own rows to the output budget, keeps the best +// ones, and says how many it left out. +func TestFormatWithinBudgetDropsLowestRankedRows(t *testing.T) { + tool := &SearchKnowledgeTool{} + results := make([]*searchResultWithMeta, 10) + for i := range results { + results[i] = &searchResultWithMeta{ + SearchResult: &types.SearchResult{ + ID: fmt.Sprintf("c%d", i), KnowledgeID: "doc", ChunkIndex: i, + Content: strings.Repeat("内容", 500), Score: 1 - float64(i)/10, + }, + KnowledgeBaseID: "kb-1", + } + } + ctx := WithOutputBudget(context.Background(), 5000) + + res, omitted := tool.formatWithinBudget(ctx, results, []string{"kb-1"}, "q", SearchModeHybrid) + rows, _ := res.Data["results"].([]map[string]interface{}) + if omitted == 0 || len(rows)+omitted != 10 { + t.Fatalf("rows=%d omitted=%d", len(rows), omitted) + } + if rows[0]["chunk_id"] != "c0" { + t.Fatalf("best row not kept first: %v", rows[0]["chunk_id"]) + } + if n := utf8.RuneCountInString(res.Output); n > 4000 && len(rows) > 1 { + t.Fatalf("output has %d runes with %d rows, over the 4000-rune share of the budget", n, len(rows)) + } + + // A single row is always kept, even over budget. + single, omittedSingle := tool.formatWithinBudget(ctx, results[:1], []string{"kb-1"}, "q", SearchModeHybrid) + if omittedSingle != 0 || single.Data["count"] != 1 { + t.Fatalf("single row dropped: omitted=%d count=%v", omittedSingle, single.Data["count"]) + } +} + +func TestDeduplicateResultsKeepsSiblingsImagesAndBestScore(t *testing.T) { + tool := &SearchKnowledgeTool{} + row := func( + id, knowledgeID string, index int, chunkType, parent, content string, score float64, + ) *searchResultWithMeta { + return &searchResultWithMeta{SearchResult: &types.SearchResult{ + ID: id, KnowledgeID: knowledgeID, ChunkIndex: index, ChunkType: chunkType, + ParentChunkID: parent, Content: content, Score: score, + }} + } + ocr := string(types.ChunkTypeImageOCR) + in := []*searchResultWithMeta{ + // Siblings under one parent are different text. + row("child-a", "d1", 3, "", "p1", "first child", 0.4), + row("child-b", "d1", 4, "", "p1", "second child", 0.9), + // Image chunks all carry chunk_index 0. + row("img-1", "d1", 0, ocr, "", "ocr one", 0.5), + row("img-2", "d1", 0, ocr, "", "ocr two", 0.5), + row("text-0", "d1", 0, "", "", "intro", 0.3), + // The same chunk from two searches: the better score wins. + row("dup", "d2", 1, "", "", "dup text", 0.2), + row("dup", "d2", 1, "", "", "dup text", 0.8), + } + out := tool.deduplicateResults(in) + got := map[string]float64{} + for _, r := range out { + got[r.ID] = r.Score + } + for _, id := range []string{"child-a", "child-b", "img-1", "img-2", "text-0", "dup"} { + if _, ok := got[id]; !ok { + t.Fatalf("%s dropped; kept %v", id, got) + } + } + if len(out) != 6 || got["dup"] != 0.8 || out[0].ID != "child-b" { + t.Fatalf("dedup = %v (first %s)", got, out[0].ID) + } +} diff --git a/internal/agent/tools/wiki_search_scope_test.go b/internal/agent/tools/wiki_search_scope_test.go new file mode 100644 index 00000000..36278388 --- /dev/null +++ b/internal/agent/tools/wiki_search_scope_test.go @@ -0,0 +1,61 @@ +package tools + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +// limitingWikiService returns at most limit pages, like the real store. +type limitingWikiService struct { + *fakeWikiPageService + limits []int +} + +func (s *limitingWikiService) SearchPages( + ctx context.Context, kbID, query string, limit int, +) ([]*types.WikiPage, error) { + s.limits = append(s.limits, limit) + pages, err := s.fakeWikiPageService.SearchPages(ctx, kbID, query, limit) + if len(pages) > limit { + pages = pages[:limit] + } + return pages, err +} + +// Under a document scope, out-of-scope pages ranked first used to fill the +// limit and hide the in-scope page ranked just below them. +func TestWikiSearchScopedOverfetchesBeforeFiltering(t *testing.T) { + var pages []*types.WikiPage + for i := 0; i < 3; i++ { + pages = append(pages, &types.WikiPage{ + KnowledgeBaseID: "kb-1", Slug: fmt.Sprintf("other-%d", i), Title: "Other", Content: "engine", + PageType: "entity", SourceRefs: types.StringArray{"doc-other|Other"}, + }) + } + pages = append(pages, &types.WikiPage{ + KnowledgeBaseID: "kb-1", Slug: "wanted", Title: "Wanted", Content: "engine", + PageType: "entity", SourceRefs: types.StringArray{"doc-wanted|Wanted"}, + }) + service := &limitingWikiService{fakeWikiPageService: &fakeWikiPageService{ + searchResults: map[string][]*types.WikiPage{"kb-1": pages}, + }} + tool := NewWikiSearchTool(service, nil, + []WikiScope{{KnowledgeBaseID: "kb-1", KnowledgeIDs: []string{"doc-wanted"}}}, NewWikiRouteResolver()) + + args, _ := json.Marshal(map[string]any{"query": "engine", "limit": 2}) + res, err := tool.Execute(context.Background(), args) + if err != nil || res == nil || !res.Success { + t.Fatalf("Execute: res=%+v err=%v", res, err) + } + if !strings.Contains(res.Output, "wanted") { + t.Fatalf("in-scope page below the limit was not found: %s", res.Output) + } + if len(service.limits) == 0 || service.limits[0] <= 2 { + t.Fatalf("scoped search did not over-fetch: limits=%v", service.limits) + } +} diff --git a/internal/agent/tools/wiki_tools.go b/internal/agent/tools/wiki_tools.go index 400be4c2..be1784fd 100644 --- a/internal/agent/tools/wiki_tools.go +++ b/internal/agent/tools/wiki_tools.go @@ -260,6 +260,13 @@ func pageIntersectsKnowledgeIDs(page *types.WikiPage, allowed map[string]bool) b return false } +const ( + // wikiScopedSearchOverfetch and wikiScopedSearchMaxFetch bound how many + // pages a scoped wiki_search asks for before filtering by scope. + wikiScopedSearchOverfetch = 5 + wikiScopedSearchMaxFetch = 100 +) + func pagePassesWikiScope( ctx context.Context, page *types.WikiPage, @@ -878,14 +885,23 @@ func (t *wikiSearchTool) Execute(ctx context.Context, args json.RawMessage) (*ty if kbID == "" { continue } - pages, err := t.wikiService.SearchPages(ctx, kbID, pattern, params.Limit) + // A document- or tag-scoped search filters pages after the store + // returns them, so asking for exactly limit pages let + // out-of-scope pages fill the page and hide in-scope ones ranked + // just below. Over-fetch, then keep the first limit in scope. + fetchLimit := params.Limit + if _, hasKnowledgeFilter := scopeKnowledgeFilter(sc); hasKnowledgeFilter || len(sc.TagIDs) > 0 { + fetchLimit = max(params.Limit, min(params.Limit*wikiScopedSearchOverfetch, wikiScopedSearchMaxFetch)) + } + kept := 0 + pages, err := t.wikiService.SearchPages(ctx, kbID, pattern, fetchLimit) if err != nil { searchErrors = append(searchErrors, fmt.Sprintf("Wiki search %q failed in KB %s: %v", query, kbID, err)) continue } successfulSearchCalls++ for _, p := range pages { - if p == nil { + if p == nil || kept >= params.Limit { continue } passesScope, scopeErr := pagePassesWikiScope(ctx, p, sc, fetchTags) @@ -907,6 +923,7 @@ func (t *wikiSearchTool) Execute(ctx context.Context, args json.RawMessage) (*ty continue } actualKBID := kbID + kept++ allHits = append(allHits, searchHit{page: p, kbID: actualKBID}) t.routes.rememberPage(p, actualKBID) foundKBs[p.Slug] = append(foundKBs[p.Slug], actualKBID) @@ -915,9 +932,15 @@ func (t *wikiSearchTool) Execute(ctx context.Context, args json.RawMessage) (*ty registerLinkedSlugs(foundKBs, p, actualKBID) } } - _ = filteredCount // reserved for future debug surface - if len(allHits) == 0 { + if filteredCount > 0 { + // Say why the result is empty: pages matched, but none cites + // the selected documents or tags. + allOutputs = append(allOutputs, fmt.Sprintf( + "", + query, filteredCount)) + continue + } allOutputs = append(allOutputs, fmt.Sprintf("", query)) continue } diff --git a/internal/application/repository/knowledge.go b/internal/application/repository/knowledge.go index bf036a50..bfc5ebe9 100644 --- a/internal/application/repository/knowledge.go +++ b/internal/application/repository/knowledge.go @@ -391,7 +391,7 @@ func (r *knowledgeRepository) GetKnowledgeBatch( ctx context.Context, tenantID uint64, ids []string, ) ([]*types.Knowledge, error) { var knowledge []*types.Knowledge - if err := r.db.WithContext(ctx).Debug(). + if err := r.db.WithContext(ctx). Where("tenant_id = ? AND id IN ?", tenantID, ids). Find(&knowledge).Error; err != nil { return nil, err @@ -399,6 +399,20 @@ func (r *knowledgeRepository) GetKnowledgeBatch( return knowledge, nil } +// GetKnowledgeBatchByIDOnly gets knowledge in batch without a tenant filter. +func (r *knowledgeRepository) GetKnowledgeBatchByIDOnly( + ctx context.Context, ids []string, +) ([]*types.Knowledge, error) { + if len(ids) == 0 { + return nil, nil + } + var knowledge []*types.Knowledge + if err := r.db.WithContext(ctx).Where("id IN ?", ids).Find(&knowledge).Error; err != nil { + return nil, err + } + return knowledge, nil +} + // CheckKnowledgeExists checks if knowledge already exists func (r *knowledgeRepository) CheckKnowledgeExists( ctx context.Context, diff --git a/internal/application/repository/retriever/milvus/repository.go b/internal/application/repository/retriever/milvus/repository.go index ce39fe57..5ddba22b 100644 --- a/internal/application/repository/retriever/milvus/repository.go +++ b/internal/application/repository/retriever/milvus/repository.go @@ -770,7 +770,7 @@ func (m *milvusRepository) VectorRetrieve(ctx context.Context, var sp *index.CustomAnnParam if params.Threshold > 0 { ann := index.NewCustomAnnParam() - ann.WithRadius(params.Threshold) + ann.WithRadius(m.similarityToMetric(params.Threshold)) sp = &ann } searchOption := client.NewSearchOption(collectionName, params.TopK, []entity.Vector{entity.FloatVector(params.Embedding)}) @@ -795,6 +795,9 @@ func (m *milvusRepository) VectorRetrieve(ctx context.Context, log.Errorf("[Milvus] Failed to convert result set: %v", err) return nil, fmt.Errorf("failed to convert result set: %w", err) } + for i := range scores { + scores[i] = m.metricToSimilarity(scores[i]) + } results, err := buildMilvusIndexResults(sets, scores, types.MatchTypeEmbedding) if err != nil { log.Errorf("[Milvus] Failed to attach vector scores: %v", err) @@ -1330,3 +1333,25 @@ func convertResultSet(resultSet []client.ResultSet) ([]*MilvusVectorEmbeddingWit } return docs, scores, nil } + +// metricToSimilarity converts a raw vector-search score into cosine +// similarity, the scale callers rank and threshold on. IP and COSINE already +// are for the L2-normalized embeddings WeKnora indexes. Milvus L2 returns +// the squared Euclidean distance (smaller is better), which for unit vectors +// is 2 - 2cos; passing it through ranked the farthest hits first. +func (m *milvusRepository) metricToSimilarity(score float64) float64 { + if m.metricType == entity.L2 { + return 1 - score/2 + } + return score +} + +// similarityToMetric converts a cosine-similarity threshold into the range +// search radius of the configured metric: a lower bound on IP / COSINE, an +// upper bound on the squared L2 distance. +func (m *milvusRepository) similarityToMetric(similarity float64) float64 { + if m.metricType == entity.L2 { + return 2 * (1 - similarity) + } + return similarity +} diff --git a/internal/application/repository/retriever/milvus/score_test.go b/internal/application/repository/retriever/milvus/score_test.go new file mode 100644 index 00000000..8b9c04c4 --- /dev/null +++ b/internal/application/repository/retriever/milvus/score_test.go @@ -0,0 +1,29 @@ +package milvus + +import ( + "testing" + + "github.com/milvus-io/milvus/client/v2/entity" + "github.com/stretchr/testify/require" +) + +// Milvus L2 reports the squared distance of unit vectors, 2 - 2cos. Scores +// leave the driver as cosine similarity and thresholds map onto the radius. +func TestMetricConversionL2(t *testing.T) { + t.Parallel() + m := &milvusRepository{metricType: entity.L2} + require.InDelta(t, 1.0, m.metricToSimilarity(0), 1e-9) + require.InDelta(t, 0.5, m.metricToSimilarity(1), 1e-9) + require.Greater(t, m.metricToSimilarity(0.2), m.metricToSimilarity(0.8), "nearer must score higher") + require.InDelta(t, 1.0, m.similarityToMetric(0.5), 1e-9) + require.InDelta(t, 0.5, m.metricToSimilarity(m.similarityToMetric(0.5)), 1e-9) +} + +func TestMetricConversionIPAndCosinePassThrough(t *testing.T) { + t.Parallel() + for _, metric := range []entity.MetricType{entity.IP, entity.COSINE} { + m := &milvusRepository{metricType: metric} + require.InDelta(t, 0.73, m.metricToSimilarity(0.73), 1e-9) + require.InDelta(t, 0.4, m.similarityToMetric(0.4), 1e-9) + } +} diff --git a/internal/application/repository/retriever/opensearch/query.go b/internal/application/repository/retriever/opensearch/query.go index ae306889..fab16784 100644 --- a/internal/application/repository/retriever/opensearch/query.go +++ b/internal/application/repository/retriever/opensearch/query.go @@ -100,8 +100,9 @@ func (f *retrieveFilters) toBoolMust() []map[string]any { // // Applies `min_score` when threshold > 0. The OpenSearch k-NN plugin's // SpaceType.COSINESIMIL.scoreTranslation produces (1 + cos) / 2 ∈ [0, 1] -// at the client, so the caller's Threshold value passes through to -// min_score directly without further scaling. +// at the client, while callers pass a cosine-similarity threshold (the +// scale every other engine uses), so the threshold is mapped onto the +// plugin's scale; wrapResults maps scores back. // // Signature returns ([]byte, error) so callers can propagate // json.Marshal failures (reachable for NaN / +/-Inf in embedding). @@ -120,7 +121,7 @@ func buildKNNQuery(embedding []float32, topK int, threshold float64, f *retrieve "query": map[string]any{"knn": knn}, } if threshold > 0 { - body["min_score"] = threshold + body["min_score"] = cosineToKNNScore(threshold) } out, err := json.Marshal(body) if err != nil { @@ -152,3 +153,16 @@ func buildKeywordQuery(queryText string, topK int, threshold float64, f *retriev } return out, nil } + +// cosineToKNNScore maps a cosine similarity onto the k-NN plugin's +// cosinesimil score, (1 + cos) / 2. +func cosineToKNNScore(cos float64) float64 { + return (1 + cos) / 2 +} + +// knnScoreToCosine inverts cosineToKNNScore. Vector scores leave the driver +// as cosine similarity so they compare with the other engines' scores and +// with thresholds; the raw (1 + cos) / 2 put a 0.5 threshold at cos >= 0. +func knnScoreToCosine(score float64) float64 { + return 2*score - 1 +} diff --git a/internal/application/repository/retriever/opensearch/repository_test.go b/internal/application/repository/retriever/opensearch/repository_test.go index 687f0cd4..7d9d9c1f 100644 --- a/internal/application/repository/retriever/opensearch/repository_test.go +++ b/internal/application/repository/retriever/opensearch/repository_test.go @@ -423,8 +423,9 @@ func TestBuildKNNQuery_AppliesMinScoreWhenThreshold(t *testing.T) { } var parsed map[string]any _ = json.Unmarshal(body, &parsed) - if ms, ok := parsed["min_score"]; !ok || ms.(float64) != 0.75 { - t.Errorf("min_score: want 0.75, got %v (present=%v)", ms, ok) + // A cosine threshold of 0.75 is (1 + 0.75) / 2 on the k-NN plugin's scale. + if ms, ok := parsed["min_score"]; !ok || ms.(float64) != 0.875 { + t.Errorf("min_score: want 0.875, got %v (present=%v)", ms, ok) } } diff --git a/internal/application/repository/retriever/opensearch/retrieve.go b/internal/application/repository/retriever/opensearch/retrieve.go index d2202c58..733f7c8b 100644 --- a/internal/application/repository/retriever/opensearch/retrieve.go +++ b/internal/application/repository/retriever/opensearch/retrieve.go @@ -179,6 +179,10 @@ func wrapResults(ctx context.Context, hits []hit, rt types.RetrieverType, mt typ log := logger.GetLogger(ctx) out := make([]*types.IndexWithScore, 0, len(hits)) for _, h := range hits { + score := h.Score + if rt == types.VectorRetrieverType { + score = knnScoreToCosine(score) + } if h.ID != h.Source.ChunkID { log.Warnf("[OpenSearch] hit._id=%q != _source.chunk_id=%q (D12 invariant violation)", h.ID, h.Source.ChunkID) @@ -192,7 +196,7 @@ func wrapResults(ctx context.Context, hits []hit, rt types.RetrieverType, mt typ SourceType: types.SourceType(h.Source.SourceType), TagID: h.Source.TagID, Content: h.Source.Content, - Score: h.Score, + Score: score, MatchType: mt, IsEnabled: h.Source.IsEnabled, }) diff --git a/internal/application/repository/retriever/opensearch/score_test.go b/internal/application/repository/retriever/opensearch/score_test.go new file mode 100644 index 00000000..5b0424f6 --- /dev/null +++ b/internal/application/repository/retriever/opensearch/score_test.go @@ -0,0 +1,25 @@ +package opensearch + +import ( + "context" + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +// The k-NN plugin reports (1 + cos) / 2; vector hits leave the driver as +// cosine similarity, keyword hits keep their BM25 score. +func TestWrapResultsReportsCosineForVectorHits(t *testing.T) { + t.Parallel() + hits := []hit{{ID: "c1", Score: 0.9}} + hits[0].Source.ChunkID = "c1" + + vector := wrapResults(context.Background(), hits, types.VectorRetrieverType, types.MatchTypeEmbedding) + if got := vector[0].Results[0].Score; got < 0.8-1e-9 || got > 0.8+1e-9 { + t.Fatalf("vector score = %v, want cosine 0.8", got) + } + keyword := wrapResults(context.Background(), hits, types.KeywordsRetrieverType, types.MatchTypeKeywords) + if got := keyword[0].Results[0].Score; got != 0.9 { + t.Fatalf("keyword score = %v, want 0.9 unchanged", got) + } +} diff --git a/internal/application/repository/retriever/postgres/repository.go b/internal/application/repository/retriever/postgres/repository.go index f89b9463..4d1829ec 100644 --- a/internal/application/repository/retriever/postgres/repository.go +++ b/internal/application/repository/retriever/postgres/repository.go @@ -76,11 +76,23 @@ func (g *pgRepository) EstimateStorageSize( return totalStorageSize } +// upsertBySource makes a re-index of an existing (source_id, source_type) +// replace the stored row. Callers such as FAQ edits re-index under the old +// source ID and rely on the new content winning; DO NOTHING kept the stale +// content and vector. +var upsertBySource = clause.OnConflict{ + Columns: []clause.Column{{Name: "source_id"}, {Name: "source_type"}}, + DoUpdates: clause.AssignmentColumns([]string{ + "chunk_id", "knowledge_id", "knowledge_base_id", "tag_id", + "content", "dimension", "embedding", "is_enabled", "updated_at", + }), +} + // Save stores a single index entry func (g *pgRepository) Save(ctx context.Context, indexInfo *types.IndexInfo, additionalParams map[string]any) error { logger.GetLogger(ctx).Debugf("[Postgres] Saving index for source ID: %s", indexInfo.SourceID) embeddingDB := toDBVectorEmbedding(indexInfo, additionalParams) - err := g.db.WithContext(ctx).Create(embeddingDB).Error + err := g.db.WithContext(ctx).Clauses(upsertBySource).Create(embeddingDB).Error if err != nil { logger.GetLogger(ctx).Errorf("[Postgres] Failed to save index: %v", err) return err @@ -94,11 +106,25 @@ func (g *pgRepository) BatchSave( ctx context.Context, indexInfoList []*types.IndexInfo, additionalParams map[string]any, ) error { logger.GetLogger(ctx).Infof("[Postgres] Batch saving %d indices", len(indexInfoList)) - indexInfoDBList := make([]*pgVector, len(indexInfoList)) - for i := range indexInfoList { - indexInfoDBList[i] = toDBVectorEmbedding(indexInfoList[i], additionalParams) + // ON CONFLICT DO UPDATE rejects a statement that touches the same row + // twice, so a source repeated in one batch keeps only its last entry. + type sourceKey struct { + id string + typ int } - err := g.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(indexInfoDBList).Error + positions := make(map[sourceKey]int, len(indexInfoList)) + indexInfoDBList := make([]*pgVector, 0, len(indexInfoList)) + for _, indexInfo := range indexInfoList { + row := toDBVectorEmbedding(indexInfo, additionalParams) + key := sourceKey{id: row.SourceID, typ: row.SourceType} + if i, ok := positions[key]; ok { + indexInfoDBList[i] = row + continue + } + positions[key] = len(indexInfoDBList) + indexInfoDBList = append(indexInfoDBList, row) + } + err := g.db.WithContext(ctx).Clauses(upsertBySource).Create(indexInfoDBList).Error if err != nil { logger.GetLogger(ctx).Errorf("[Postgres] Batch save failed: %v", err) return err @@ -210,7 +236,7 @@ func (g *pgRepository) KeywordsRetrieve(ctx context.Context, }}) var embeddingDBList []pgVectorWithScore - err := g.db.WithContext(ctx).Clauses(conds...).Debug(). + err := g.db.WithContext(ctx).Clauses(conds...). Select([]string{ "paradedb.score(id) as score", "id", @@ -501,18 +527,28 @@ func (g *pgRepository) CopyIndices(ctx context.Context, return nil } + // Only the mapped knowledge is copied (callers clone one document at a + // time), so filter on it instead of paging the whole source knowledge + // base. Keyset pagination on id keeps pages stable; OFFSET without an + // ORDER BY could skip or repeat rows. + sourceKnowledgeIDs := make([]string, 0, len(sourceToTargetKBIDMap)) + for sourceKnowledgeID := range sourceToTargetKBIDMap { + sourceKnowledgeIDs = append(sourceKnowledgeIDs, sourceKnowledgeID) + } + // Batch processing parameters batchSize := 500 // Number of records to process per batch - offset := 0 // Offset for pagination + var lastID uint // Keyset cursor totalCopied := 0 // Total number of copied records for { // Paginated query for source data var sourceVectors []*pgVector if err := g.db.WithContext(ctx). - Where("knowledge_base_id = ?", sourceKnowledgeBaseID). + Where("knowledge_base_id = ? AND knowledge_id IN ? AND id > ?", + sourceKnowledgeBaseID, sourceKnowledgeIDs, lastID). + Order("id"). Limit(batchSize). - Offset(offset). Find(&sourceVectors).Error; err != nil { logger.GetLogger(ctx).Errorf("[Postgres] Failed to query source index data: %v", err) return err @@ -520,7 +556,7 @@ func (g *pgRepository) CopyIndices(ctx context.Context, // If no more data, exit the loop if len(sourceVectors) == 0 { - if offset == 0 { + if lastID == 0 { logger.GetLogger(ctx).Warnf("[Postgres] No source index data found") } break @@ -528,8 +564,8 @@ func (g *pgRepository) CopyIndices(ctx context.Context, batchCount := len(sourceVectors) logger.GetLogger(ctx).Infof( - "[Postgres] Found %d source index data, batch start position: %d", - batchCount, offset, + "[Postgres] Found %d source index data, batch start after id: %d", + batchCount, lastID, ) // Create target vector index @@ -581,6 +617,7 @@ func (g *pgRepository) CopyIndices(ctx context.Context, KnowledgeBaseID: targetKnowledgeBaseID, // Update to target knowledge base ID Dimension: sourceVector.Dimension, Embedding: sourceVector.Embedding, // Copy the vector embedding directly, avoid recalculation + IsEnabled: sourceVector.IsEnabled, } targetVectors = append(targetVectors, targetVector) @@ -603,7 +640,7 @@ func (g *pgRepository) CopyIndices(ctx context.Context, } // Move to the next batch - offset += batchCount + lastID = sourceVectors[batchCount-1].ID // If the number of returned records is less than the requested size, it means the last page has been reached if batchCount < batchSize { diff --git a/internal/application/repository/retriever/postgres/structs.go b/internal/application/repository/retriever/postgres/structs.go index 1653771b..8e002ef4 100644 --- a/internal/application/repository/retriever/postgres/structs.go +++ b/internal/application/repository/retriever/postgres/structs.go @@ -25,7 +25,9 @@ type pgVector struct { Content string `json:"content" gorm:"column:content;not null"` Dimension int `json:"dimension" gorm:"column:dimension;not null"` Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"` - IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;default:true;index"` + // No GORM default tag: GORM swaps a zero bool for the tag's default on + // insert, which indexed disabled chunks as enabled. Writers always set it. + IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;index"` } // pgVectorWithScore extends pgVector with similarity score field diff --git a/internal/application/repository/retriever/sqlite/fts_query_test.go b/internal/application/repository/retriever/sqlite/fts_query_test.go new file mode 100644 index 00000000..9b23c083 --- /dev/null +++ b/internal/application/repository/retriever/sqlite/fts_query_test.go @@ -0,0 +1,32 @@ +package sqlite + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSanitizeFTS5QueryScopesToContent(t *testing.T) { + t.Parallel() + assert.Equal(t, `content : ("2023")`, sanitizeFTS5Query("2023")) + // Quotes never reach an FTS string unescaped. + assert.Equal(t, `content : ("say" OR "hi")`, sanitizeFTS5Query(`say"hi"`)) + // A lone Han character matches bigrams that start with it. + assert.Equal(t, `content : ("A" OR "股"*)`, sanitizeFTS5Query("A股")) + assert.Equal(t, "", sanitizeFTS5Query(" ")) +} + +// Only the content column is searched: IDs indexed alongside it must not +// match a query. +func TestKeywordsRetrieveIgnoresIDColumns(t *testing.T) { + repository := newSQLiteRetrieverTestRepository(t) + if !repository.db.Migrator().HasTable("lite_embeddings_fts") { + t.Skip("FTS5 unavailable (build without sqlite_fts5)") + } + info := sqliteTestIndex("chunk-2023", "kb", "knowledge", "", true) + info.Content = "quarterly report" + saveSQLiteTestVector(t, repository, info, []float32{1, 0}) + + assert.Empty(t, keywordSearch(t, repository, "2023")) + assert.Len(t, keywordSearch(t, repository, "quarterly"), 1) +} diff --git a/internal/application/repository/retriever/sqlite/repository.go b/internal/application/repository/retriever/sqlite/repository.go index 2496d99d..b0177b19 100644 --- a/internal/application/repository/retriever/sqlite/repository.go +++ b/internal/application/repository/retriever/sqlite/repository.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "strings" + "sync" "time" "unicode" @@ -14,7 +15,6 @@ import ( sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo" "github.com/google/uuid" "gorm.io/gorm" - "gorm.io/gorm/clause" ) // sqliteEmbedding stores metadata alongside the vec0 virtual table rows @@ -36,7 +36,10 @@ type sqliteEmbedding struct { func (sqliteEmbedding) TableName() string { return "lite_embeddings" } type sqliteRepository struct { - db *gorm.DB + db *gorm.DB + // vecMu guards vecTables: concurrent BatchSave and retrieval goroutines + // all consult it, and an unguarded map write is a fatal runtime error. + vecMu sync.RWMutex vecTables map[int]bool // tracks which vec0 tables have been created (keyed by dimension) } @@ -48,6 +51,7 @@ func NewSQLiteRetrieveEngineRepository(db *gorm.DB) interfaces.RetrieveEngineRep } initFTS5(db) + enableImageChunkIndexes(db) repo := &sqliteRepository{ db: db, @@ -59,6 +63,28 @@ func NewSQLiteRetrieveEngineRepository(db *gorm.DB) interfaces.RetrieveEngineRep return repo } +// enableImageChunkIndexes repairs image OCR/caption rows that were indexed +// with is_enabled = 0 because the multimodal indexer never set IsEnabled. +// Retrieval filters on is_enabled, so those rows were never searchable. +// Only rows whose chunk is itself enabled are touched, which leaves chunks a +// user disabled alone; after the first run the statement matches nothing. +func enableImageChunkIndexes(db *gorm.DB) { + result := db.Exec(`UPDATE lite_embeddings SET is_enabled = 1 + WHERE is_enabled = 0 AND chunk_id IN ( + SELECT id FROM chunks + WHERE chunk_type IN (?, ?) AND is_enabled = 1 + )`, string(types.ChunkTypeImageOCR), string(types.ChunkTypeImageCaption)) + if result.Error != nil { + logger.GetLogger(context.Background()).Warnf( + "[SQLite] Failed to re-enable image chunk indexes: %v", result.Error) + return + } + if result.RowsAffected > 0 { + logger.GetLogger(context.Background()).Infof( + "[SQLite] Re-enabled %d image OCR/caption index rows", result.RowsAffected) + } +} + func initFTS5(db *gorm.DB) { var sqlStr string db.Raw("SELECT sql FROM sqlite_master WHERE type='table' AND name='lite_embeddings_fts'").Scan(&sqlStr) @@ -105,8 +131,20 @@ func vecTableName(dim int) string { return fmt.Sprintf("vec_embeddings_%d", dim) } +func (r *sqliteRepository) hasVecTable(dim int) bool { + r.vecMu.RLock() + defer r.vecMu.RUnlock() + return r.vecTables[dim] +} + +func (r *sqliteRepository) markVecTable(dim int) { + r.vecMu.Lock() + defer r.vecMu.Unlock() + r.vecTables[dim] = true +} + func (r *sqliteRepository) ensureVecTable(dim int) { - if dim <= 0 || r.vecTables[dim] { + if dim <= 0 || r.hasVecTable(dim) { return } tbl := vecTableName(dim) @@ -116,13 +154,13 @@ func (r *sqliteRepository) ensureVecTable(dim int) { ) if err := r.db.Exec(createSQL).Error; err != nil { if strings.Contains(err.Error(), "already exists") { - r.vecTables[dim] = true + r.markVecTable(dim) return } logger.GetLogger(context.Background()).Errorf("[SQLite] Failed to create vec0 table for dim %d: %v", dim, err) return } - r.vecTables[dim] = true + r.markVecTable(dim) } func (r *sqliteRepository) ensureExistingVecTables() { @@ -142,45 +180,84 @@ func (r *sqliteRepository) Support() []types.RetrieverType { } func (r *sqliteRepository) Save(ctx context.Context, indexInfo *types.IndexInfo, params map[string]any) error { - row := toSQLiteEmbedding(indexInfo) - emb := extractEmbedding(params, indexInfo.SourceID) - if len(emb) > 0 { - row.Dimension = len(emb) - } - if err := r.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(row).Error; err != nil { - return err - } - r.syncFTS5Insert(ctx, row) - if len(emb) > 0 && row.ID > 0 { - r.insertVec(ctx, row.ID, row.Dimension, emb) - } - return nil + return r.BatchSave(ctx, []*types.IndexInfo{indexInfo}, params) } +// BatchSave upserts by (source_id, source_type): rows already indexed for a +// source are replaced together with their FTS and vec0 entries. Callers +// re-index an edited FAQ entry under its old source ID and expect the new +// content to win; ON CONFLICT DO NOTHING kept the stale row instead, and the +// skipped rows also shifted the RETURNING ids GORM assigns back to the slice, +// attaching vectors and FTS entries to the wrong rows. func (r *sqliteRepository) BatchSave(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) error { if len(indexInfoList) == 0 { return nil } - rows := make([]*sqliteEmbedding, len(indexInfoList)) - embs := make([][]float32, len(indexInfoList)) - for i, info := range indexInfoList { - rows[i] = toSQLiteEmbedding(info) + type sourceKey struct { + id string + typ int + } + positions := make(map[sourceKey]int, len(indexInfoList)) + rows := make([]*sqliteEmbedding, 0, len(indexInfoList)) + embs := make([][]float32, 0, len(indexInfoList)) + for _, info := range indexInfoList { + row := toSQLiteEmbedding(info) emb := extractEmbedding(params, info.SourceID) - embs[i] = emb if len(emb) > 0 { - rows[i].Dimension = len(emb) + row.Dimension = len(emb) } - } - if err := r.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(rows).Error; err != nil { - return err - } - for i, row := range rows { - r.syncFTS5Insert(ctx, row) - if len(embs[i]) > 0 && row.ID > 0 { - r.insertVec(ctx, row.ID, row.Dimension, embs[i]) + // A source repeated inside one batch keeps its last entry, as an + // upsert would. + key := sourceKey{id: row.SourceID, typ: row.SourceType} + if i, ok := positions[key]; ok { + rows[i], embs[i] = row, emb + continue } + positions[key] = len(rows) + rows = append(rows, row) + embs = append(embs, emb) } - return nil + + sourceIDs := make([]string, 0, len(rows)) + for _, row := range rows { + sourceIDs = append(sourceIDs, row.SourceID) + // vec0 tables are created outside the transaction below: production + // SQLite runs on one connection, which the transaction holds. + r.ensureVecTable(row.Dimension) + } + // Replacing a source is one transaction, so a failed insert cannot + // leave the source with its old rows deleted and no new ones. + return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + var candidates []sqliteEmbedding + if err := tx.Where("source_id IN ?", sourceIDs).Find(&candidates).Error; err != nil { + return err + } + existing := make([]sqliteEmbedding, 0, len(candidates)) + existingIDs := make([]uint, 0, len(candidates)) + for _, c := range candidates { + if _, ok := positions[sourceKey{id: c.SourceID, typ: c.SourceType}]; ok { + existing = append(existing, c) + existingIDs = append(existingIDs, c.ID) + } + } + if len(existing) > 0 { + r.deleteRowsAndVecs(tx, existing) + if err := tx.Where("id IN ?", existingIDs).Delete(&sqliteEmbedding{}).Error; err != nil { + return err + } + } + + if err := tx.Create(rows).Error; err != nil { + return err + } + for i, row := range rows { + r.syncFTS5Insert(tx, row) + if len(embs[i]) > 0 && row.ID > 0 { + r.insertVec(tx, row.ID, row.Dimension, embs[i]) + } + } + return nil + }) } func (r *sqliteRepository) EstimateStorageSize(_ context.Context, indexInfoList []*types.IndexInfo, _ map[string]any) int64 { @@ -194,21 +271,21 @@ func (r *sqliteRepository) EstimateStorageSize(_ context.Context, indexInfoList func (r *sqliteRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, _ int, _ string) error { var rows []sqliteEmbedding r.db.WithContext(ctx).Where("chunk_id IN ?", chunkIDList).Find(&rows) - r.deleteRowsAndVecs(ctx, rows) + r.deleteRowsAndVecs(r.db.WithContext(ctx), rows) return r.db.WithContext(ctx).Where("chunk_id IN ?", chunkIDList).Delete(&sqliteEmbedding{}).Error } func (r *sqliteRepository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, _ int, _ string) error { var rows []sqliteEmbedding r.db.WithContext(ctx).Where("source_id IN ?", sourceIDList).Find(&rows) - r.deleteRowsAndVecs(ctx, rows) + r.deleteRowsAndVecs(r.db.WithContext(ctx), rows) return r.db.WithContext(ctx).Where("source_id IN ?", sourceIDList).Delete(&sqliteEmbedding{}).Error } func (r *sqliteRepository) DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, _ int, _ string) error { var rows []sqliteEmbedding r.db.WithContext(ctx).Where("knowledge_id IN ?", knowledgeIDList).Find(&rows) - r.deleteRowsAndVecs(ctx, rows) + r.deleteRowsAndVecs(r.db.WithContext(ctx), rows) return r.db.WithContext(ctx).Where("knowledge_id IN ?", knowledgeIDList).Delete(&sqliteEmbedding{}).Error } @@ -219,34 +296,62 @@ func (r *sqliteRepository) CopyIndices(ctx context.Context, targetKnowledgeBaseID string, _ int, _ string, ) error { - for sourceChunkID, targetChunkID := range sourceToTargetChunkIDMap { - var src sqliteEmbedding - if err := r.db.WithContext(ctx).Where("chunk_id = ?", sourceChunkID).First(&src).Error; err != nil { - continue + sourceChunkIDs := make([]string, 0, len(sourceToTargetChunkIDMap)) + for sourceChunkID := range sourceToTargetChunkIDMap { + sourceChunkIDs = append(sourceChunkIDs, sourceChunkID) + } + const batchSize = 500 + for start := 0; start < len(sourceChunkIDs); start += batchSize { + end := min(start+batchSize, len(sourceChunkIDs)) + // Every row of a chunk is copied: besides the chunk itself, generated + // questions are indexed as extra rows under the same chunk_id. + var sources []sqliteEmbedding + if err := r.db.WithContext(ctx). + Where("chunk_id IN ?", sourceChunkIDs[start:end]). + Order("id"). + Find(&sources).Error; err != nil { + return err } - newRow := sqliteEmbedding{ - SourceID: uuid.New().String(), - SourceType: src.SourceType, - ChunkID: targetChunkID, - KnowledgeID: sourceToTargetKBIDMap[src.KnowledgeID], - KnowledgeBaseID: targetKnowledgeBaseID, - TagID: src.TagID, - Content: src.Content, - Dimension: src.Dimension, - IsEnabled: src.IsEnabled, - } - if err := r.db.WithContext(ctx).Create(&newRow).Error; err != nil { - logger.GetLogger(ctx).Warnf("[SQLite] CopyIndices: failed to copy chunk %s: %v", sourceChunkID, err) - continue - } - r.syncFTS5Insert(ctx, &newRow) - if src.Dimension > 0 && newRow.ID > 0 { - r.copyVec(ctx, src.ID, newRow.ID, src.Dimension) + for _, src := range sources { + targetChunkID := sourceToTargetChunkIDMap[src.ChunkID] + newRow := sqliteEmbedding{ + SourceID: copiedSourceID(src.SourceID, src.ChunkID, targetChunkID), + SourceType: src.SourceType, + ChunkID: targetChunkID, + KnowledgeID: sourceToTargetKBIDMap[src.KnowledgeID], + KnowledgeBaseID: targetKnowledgeBaseID, + TagID: src.TagID, + Content: src.Content, + Dimension: src.Dimension, + IsEnabled: src.IsEnabled, + } + if err := r.db.WithContext(ctx).Create(&newRow).Error; err != nil { + logger.GetLogger(ctx).Warnf("[SQLite] CopyIndices: failed to copy source %s: %v", src.SourceID, err) + continue + } + r.syncFTS5Insert(r.db.WithContext(ctx), &newRow) + if src.Dimension > 0 && newRow.ID > 0 { + r.copyVec(ctx, src.ID, newRow.ID, src.Dimension) + } } } return nil } +// copiedSourceID maps a source row's SourceID onto the target chunk the way +// the Postgres engine does, so the copy can later be deleted or re-indexed by +// source ID: a chunk row uses the chunk ID and a generated question keeps its +// "{chunkID}-{questionID}" suffix. +func copiedSourceID(sourceID, sourceChunkID, targetChunkID string) string { + if sourceID == sourceChunkID { + return targetChunkID + } + if questionID, ok := strings.CutPrefix(sourceID, sourceChunkID+"-"); ok { + return targetChunkID + "-" + questionID + } + return uuid.New().String() +} + func (r *sqliteRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error { for chunkID, enabled := range chunkStatusMap { r.db.WithContext(ctx).Model(&sqliteEmbedding{}).Where("chunk_id = ?", chunkID).Update("is_enabled", enabled) @@ -490,17 +595,18 @@ func extractEmbedding(params map[string]any, sourceID string) []float32 { return embMap[sourceID] } -func (r *sqliteRepository) insertVec(_ context.Context, rowID uint, dim int, emb []float32) { - r.ensureVecTable(dim) +// insertVec writes a row's vector through db. The vec0 table for dim must +// already exist (ensureVecTable), since db may be a transaction. +func (r *sqliteRepository) insertVec(db *gorm.DB, rowID uint, dim int, emb []float32) { blob, err := sqlite_vec.SerializeFloat32(emb) if err != nil { return } sql := fmt.Sprintf("INSERT INTO %s(rowid, embedding) VALUES (?, ?)", vecTableName(dim)) - r.db.Exec(sql, rowID, blob) + db.Exec(sql, rowID, blob) } -func (r *sqliteRepository) deleteRowsAndVecs(_ context.Context, rows []sqliteEmbedding) { +func (r *sqliteRepository) deleteRowsAndVecs(db *gorm.DB, rows []sqliteEmbedding) { dimIDs := make(map[int][]uint) for _, row := range rows { if row.Dimension > 0 { @@ -508,21 +614,21 @@ func (r *sqliteRepository) deleteRowsAndVecs(_ context.Context, rows []sqliteEmb } } for dim, ids := range dimIDs { - if !r.vecTables[dim] { + if !r.hasVecTable(dim) { continue } tbl := vecTableName(dim) for _, id := range ids { - r.db.Exec(fmt.Sprintf("DELETE FROM %s WHERE rowid = ?", tbl), id) + db.Exec(fmt.Sprintf("DELETE FROM %s WHERE rowid = ?", tbl), id) } } for _, row := range rows { - r.db.Exec("DELETE FROM lite_embeddings_fts WHERE rowid = ?", row.ID) + db.Exec("DELETE FROM lite_embeddings_fts WHERE rowid = ?", row.ID) } } func (r *sqliteRepository) copyVec(_ context.Context, srcID, dstID uint, dim int) { - if !r.vecTables[dim] { + if !r.hasVecTable(dim) { return } tbl := vecTableName(dim) @@ -532,13 +638,13 @@ func (r *sqliteRepository) copyVec(_ context.Context, srcID, dstID uint, dim int ), dstID, srcID) } -func (r *sqliteRepository) syncFTS5Insert(_ context.Context, row *sqliteEmbedding) { +func (r *sqliteRepository) syncFTS5Insert(db *gorm.DB, row *sqliteEmbedding) { if row.ID == 0 { return } tokenizedContent := tokenizeCJKBigram(row.Content) sql := `INSERT INTO lite_embeddings_fts(rowid, content, source_id, chunk_id, knowledge_id, knowledge_base_id) VALUES(?, ?, ?, ?, ?, ?)` - r.db.Exec(sql, row.ID, tokenizedContent, row.SourceID, row.ChunkID, row.KnowledgeID, row.KnowledgeBaseID) + db.Exec(sql, row.ID, tokenizedContent, row.SourceID, row.ChunkID, row.KnowledgeID, row.KnowledgeBaseID) } type whereClause struct { @@ -647,15 +753,25 @@ func sanitizeFTS5Query(q string) string { var parts []string for _, f := range fields { - if f != "" { - parts = append(parts, `"`+f+`"`) + if f == "" { + continue } + term := `"` + strings.ReplaceAll(f, `"`, `""`) + `"` + // The index holds CJK text as bigrams, so a lone Han character + // (the 股 of "A股") was never a token; match bigrams starting with it. + if runes := []rune(f); len(runes) == 1 && unicode.Is(unicode.Han, runes[0]) { + term += "*" + } + parts = append(parts, term) } if len(parts) == 0 { return "" } - // Use OR because we want fuzzy match across multiple bigrams/words - return strings.Join(parts, " OR ") + // Use OR because we want fuzzy match across multiple bigrams/words. + // Only the content column is searched: the FTS table also indexes + // source, chunk, knowledge and KB IDs, so a query for "2023" could match + // a UUID fragment. + return "content : (" + strings.Join(parts, " OR ") + ")" } diff --git a/internal/application/repository/retriever/sqlite/save_test.go b/internal/application/repository/retriever/sqlite/save_test.go new file mode 100644 index 00000000..a39697a2 --- /dev/null +++ b/internal/application/repository/retriever/sqlite/save_test.go @@ -0,0 +1,209 @@ +package sqlite + +import ( + "context" + "fmt" + "sync" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func vectorSearch(t *testing.T, repository *sqliteRepository, embedding []float32) []*types.IndexWithScore { + t.Helper() + results, err := repository.vectorRetrieve(context.Background(), types.RetrieveParams{ + Embedding: embedding, + TopK: 10, + RetrieverType: types.VectorRetrieverType, + }) + require.NoError(t, err) + require.Len(t, results, 1) + return results[0].Results +} + +func keywordSearch(t *testing.T, repository *sqliteRepository, query string) []*types.IndexWithScore { + t.Helper() + results, err := repository.keywordsRetrieve(context.Background(), types.RetrieveParams{ + Query: query, + TopK: 10, + RetrieverType: types.KeywordsRetrieverType, + }) + require.NoError(t, err) + require.Len(t, results, 1) + return results[0].Results +} + +func TestBatchSaveReplacesExistingSource(t *testing.T) { + repository := newSQLiteRetrieverTestRepository(t) + info := sqliteTestIndex("faq", "kb", "knowledge", "", true) + info.Content = "oldanswer" + saveSQLiteTestVector(t, repository, info, []float32{1, 0}) + + edited := *info + edited.Content = "newanswer" + saveSQLiteTestVector(t, repository, &edited, []float32{0, 1}) + + var count int64 + require.NoError(t, repository.db.Model(&sqliteEmbedding{}).Count(&count).Error) + assert.Equal(t, int64(1), count, "re-indexing a source must replace its row") + + hits := vectorSearch(t, repository, []float32{0, 1}) + require.Len(t, hits, 1) + assert.Equal(t, "newanswer", hits[0].Content) + assert.InDelta(t, 1.0, hits[0].Score, 1e-3, "the vector must be the re-indexed one") + + if !repository.db.Migrator().HasTable("lite_embeddings_fts") { + t.Log("FTS5 unavailable (build without sqlite_fts5); skipping keyword checks") + return + } + assert.Empty(t, keywordSearch(t, repository, "oldanswer"), "stale FTS entry must be gone") + require.Len(t, keywordSearch(t, repository, "newanswer"), 1) +} + +func TestBatchSaveKeepsVectorsAlignedWhenSomeSourcesExist(t *testing.T) { + repository := newSQLiteRetrieverTestRepository(t) + existing := sqliteTestIndex("existing", "kb", "knowledge", "", true) + saveSQLiteTestVector(t, repository, existing, []float32{1, 0}) + + fresh := sqliteTestIndex("fresh", "kb", "knowledge", "", true) + require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{existing, fresh}, map[string]any{ + "embedding": map[string][]float32{ + existing.SourceID: {1, 0}, + fresh.SourceID: {0, 1}, + }, + })) + + hits := vectorSearch(t, repository, []float32{0, 1}) + require.Len(t, hits, 2) + assert.Equal(t, "fresh", hits[0].ChunkID, "the fresh row must carry its own vector") + assert.InDelta(t, 1.0, hits[0].Score, 1e-3) +} + +func TestBatchSaveKeepsLastDuplicateInBatch(t *testing.T) { + repository := newSQLiteRetrieverTestRepository(t) + first := sqliteTestIndex("chunk", "kb", "knowledge", "", true) + first.Content = "firstversion" + second := *first + second.Content = "secondversion" + require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{first, &second}, map[string]any{ + "embedding": map[string][]float32{first.SourceID: {1, 0}}, + })) + + hits := vectorSearch(t, repository, []float32{1, 0}) + require.Len(t, hits, 1) + assert.Equal(t, "secondversion", hits[0].Content) +} + +func TestConcurrentBatchSaveNewDimensions(t *testing.T) { + repository := newSQLiteRetrieverTestRepository(t) + sqlDB, err := repository.db.DB() + require.NoError(t, err) + // Production runs SQLite on a single connection. + sqlDB.SetMaxOpenConns(1) + + var wg sync.WaitGroup + errs := make(chan error, 16) + for i := range 16 { + wg.Add(1) + go func() { + defer wg.Done() + dim := 2 + i%4 + info := sqliteTestIndex(fmt.Sprintf("chunk-%d", i), "kb", "knowledge", "", true) + embedding := make([]float32, dim) + embedding[0] = 1 + errs <- repository.BatchSave(context.Background(), []*types.IndexInfo{info}, map[string]any{ + "embedding": map[string][]float32{info.SourceID: embedding}, + }) + }() + } + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } + for dim := 2; dim < 6; dim++ { + assert.True(t, repository.hasVecTable(dim)) + } +} + +func TestCopyIndicesCopiesEveryRowOfAChunk(t *testing.T) { + repository := newSQLiteRetrieverTestRepository(t) + chunk := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", true) + chunk.SourceID = "src-chunk" + question := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", false) + question.SourceID = "src-chunk-q1" + question.Content = "generated question" + require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{chunk, question}, map[string]any{ + "embedding": map[string][]float32{ + chunk.SourceID: {1, 0}, + question.SourceID: {0, 1}, + }, + })) + + require.NoError(t, repository.CopyIndices(context.Background(), "kb-src", + map[string]string{"knowledge-src": "knowledge-dst"}, + map[string]string{"src-chunk": "dst-chunk"}, + "kb-dst", 2, string(types.KnowledgeTypeManual), + )) + + var copied []sqliteEmbedding + require.NoError(t, repository.db.Where("knowledge_base_id = ?", "kb-dst").Order("source_id").Find(&copied).Error) + require.Len(t, copied, 2) + assert.Equal(t, "dst-chunk", copied[0].SourceID) + assert.True(t, *copied[0].IsEnabled) + assert.Equal(t, "dst-chunk-q1", copied[1].SourceID) + assert.False(t, *copied[1].IsEnabled, "enabled state must be copied") + for _, row := range copied { + assert.Equal(t, "dst-chunk", row.ChunkID) + assert.Equal(t, "knowledge-dst", row.KnowledgeID) + } +} + +func TestEnableImageChunkIndexesRepairsOnlyEnabledImageChunks(t *testing.T) { + repository := newSQLiteRetrieverTestRepository(t) + require.NoError(t, repository.db.Exec( + `CREATE TABLE chunks (id TEXT PRIMARY KEY, chunk_type TEXT, is_enabled BOOLEAN)`).Error) + require.NoError(t, repository.db.Exec(`INSERT INTO chunks (id, chunk_type, is_enabled) VALUES + ('ocr', 'image_ocr', 1), ('caption', 'image_caption', 1), + ('ocr-off', 'image_ocr', 0), ('text-off', 'text', 1)`).Error) + for _, id := range []string{"ocr", "caption", "ocr-off", "text-off"} { + saveSQLiteTestVector(t, repository, sqliteTestIndex(id, "kb", "knowledge", "", false), []float32{1, 0}) + } + + enableImageChunkIndexes(repository.db) + + enabled := map[string]bool{} + var rows []sqliteEmbedding + require.NoError(t, repository.db.Find(&rows).Error) + for _, row := range rows { + enabled[row.ChunkID] = *row.IsEnabled + } + assert.Equal(t, map[string]bool{ + "ocr": true, "caption": true, "ocr-off": false, "text-off": false, + }, enabled) +} + +// Replacing a source is atomic: when the insert fails, the old row stays. +func TestBatchSaveKeepsOldRowWhenInsertFails(t *testing.T) { + repository := newSQLiteRetrieverTestRepository(t) + info := sqliteTestIndex("faq", "kb", "knowledge", "", true) + info.Content = "old answer" + saveSQLiteTestVector(t, repository, info, []float32{1, 0}) + + require.NoError(t, repository.db.Exec(`CREATE TRIGGER reject_boom BEFORE INSERT ON lite_embeddings + WHEN NEW.content = 'boom' BEGIN SELECT RAISE(ABORT, 'rejected'); END`).Error) + edited := *info + edited.Content = "boom" + require.Error(t, repository.BatchSave(context.Background(), []*types.IndexInfo{&edited}, map[string]any{ + "embedding": map[string][]float32{edited.SourceID: {0, 1}}, + })) + + var rows []sqliteEmbedding + require.NoError(t, repository.db.Find(&rows).Error) + require.Len(t, rows, 1) + assert.Equal(t, "old answer", rows[0].Content) + hits := vectorSearch(t, repository, []float32{1, 0}) + require.Len(t, hits, 1, "the old vector must survive the failed replace") +} diff --git a/internal/application/repository/retriever/tencentvectordb/repository.go b/internal/application/repository/retriever/tencentvectordb/repository.go index 54f6a19f..3b0296c9 100644 --- a/internal/application/repository/retriever/tencentvectordb/repository.go +++ b/internal/application/repository/retriever/tencentvectordb/repository.go @@ -266,8 +266,10 @@ func (r *repository) VectorRetrieve(ctx context.Context, params types.RetrievePa limit = 10 } searchParams := &tcvectordb.SearchDocumentParams{ - Filter: r.baseFilter(params), - Params: &tcvectordb.SearchDocParams{Ef: 100}, + Filter: r.baseFilter(params), + // HNSW returns at most ef candidates; a fixed 100 capped recall + // below TopK, which reaches 500. + Params: &tcvectordb.SearchDocParams{Ef: uint32(max(limit, 100))}, RetrieveVector: false, OutputFields: outputFields(), Limit: limit, diff --git a/internal/application/repository/retriever/weaviate/repository.go b/internal/application/repository/retriever/weaviate/repository.go index f3dcc162..d5fd2d32 100644 --- a/internal/application/repository/retriever/weaviate/repository.go +++ b/internal/application/repository/retriever/weaviate/repository.go @@ -561,7 +561,13 @@ func (w *weaviateRepository) VectorRetrieve(ctx context.Context, where := w.getBaseFilter(params) limit := params.TopK - scoreThreshold := float32(params.Threshold) + // Weaviate's certainty is (1 + cos) / 2; callers pass a cosine + // similarity threshold, the scale every other engine uses. A zero + // threshold means no filtering, so it stays 0 rather than becoming 0.5. + var scoreThreshold float32 + if params.Threshold > 0 { + scoreThreshold = float32((1 + params.Threshold) / 2) + } fields := getEmbeddingFields() result, err := w.client.GraphQL().Get().WithClassName(collectionName). WithWhere(where). @@ -928,7 +934,9 @@ func parseGraphQLResponse(items []interface{}, collectionName string, matchType if matchType == types.MatchTypeKeywords { score = 1.0 } else { - score = s + // certainty = (1 + cos) / 2; report cosine similarity so + // scores compare with the other engines and thresholds. + score = 2*s - 1 } } diff --git a/internal/application/repository/retriever/weaviate/score_test.go b/internal/application/repository/retriever/weaviate/score_test.go new file mode 100644 index 00000000..dc648998 --- /dev/null +++ b/internal/application/repository/retriever/weaviate/score_test.go @@ -0,0 +1,23 @@ +package weaviate + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +// Weaviate certainty is (1 + cos) / 2; vector hits leave the driver as +// cosine similarity. +func TestParseGraphQLResponseReportsCosine(t *testing.T) { + t.Parallel() + items := []interface{}{ + map[string]interface{}{ + "_additional": map[string]interface{}{"id": "p1", "certainty": 0.9}, + "chunk_id": "c1", + }, + } + got := parseGraphQLResponse(items, "Coll", types.MatchTypeEmbedding) + if len(got) != 1 || got[0].Score < 0.8-1e-9 || got[0].Score > 0.8+1e-9 { + t.Fatalf("scores = %+v, want cosine 0.8", got) + } +} diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go index c595e4d0..94de08e3 100644 --- a/internal/application/service/agent_service.go +++ b/internal/application/service/agent_service.go @@ -95,6 +95,7 @@ func knowledgeBaseScopesForPrompt(config *types.AgentConfig) ([]string, map[stri type agentService struct { browserSkill *browserskill.Manager userRepo interfaces.UserRepository + graphRepo interfaces.RetrieveGraphRepository cfg *config.Config modelService interfaces.ModelService mcpServiceService interfaces.MCPServiceService @@ -151,10 +152,12 @@ func NewAgentService( hostSandbox HostSandboxManager, browserSkill *browserskill.Manager, userRepo interfaces.UserRepository, + graphRepo interfaces.RetrieveGraphRepository, ) interfaces.AgentService { svc := &agentService{ browserSkill: browserSkill, userRepo: userRepo, + graphRepo: graphRepo, cfg: cfg, modelService: modelService, knowledgeBaseService: knowledgeBaseService, @@ -1235,8 +1238,13 @@ func (s *agentService) registerTools( case tools.ToolListDocuments: toolToRegister = tools.NewListDocumentsTool(s.knowledgeService, config.SearchTargets) case tools.ToolQueryKnowledgeGraph: + var chunkRepo interfaces.ChunkRepository + if s.chunkService != nil { + chunkRepo = s.chunkService.GetRepository() + } toolToRegister = tools.NewQueryKnowledgeGraphTool(s.knowledgeBaseService, config.SearchTargets). - WithKnowledgeScope(s.knowledgeService) + WithKnowledgeScope(s.knowledgeService). + WithGraph(s.graphRepo, chunkRepo) case tools.ToolSearchConversations: // The owner is captured from the caller's identity here, not read // from the model's arguments, so no prompt can redirect the search diff --git a/internal/application/service/chat_pipeline/chat_pipeline.go b/internal/application/service/chat_pipeline/chat_pipeline.go index 2c8544a2..c3896914 100644 --- a/internal/application/service/chat_pipeline/chat_pipeline.go +++ b/internal/application/service/chat_pipeline/chat_pipeline.go @@ -98,10 +98,6 @@ var ( Description: "Reranking failed", ErrorType: "rerank_failed", } - ErrGetRerankModel = &PluginError{ - Description: "Failed to get rerank model", - ErrorType: "get_rerank_model_failed", - } ErrGetChatModel = &PluginError{ Description: "Failed to get chat model", ErrorType: "get_chat_model_failed", diff --git a/internal/application/service/chat_pipeline/extract_entity.go b/internal/application/service/chat_pipeline/extract_entity.go index 3bfa881b..e756fd5c 100644 --- a/internal/application/service/chat_pipeline/extract_entity.go +++ b/internal/application/service/chat_pipeline/extract_entity.go @@ -61,8 +61,20 @@ func (p *PluginExtractEntity) OnEvent(ctx context.Context, logger.Debugf(ctx, "skipping extract entity, neo4j is disabled") return next() } + // QUERY_UNDERSTAND has already classified the turn. Entities only feed the + // knowledge-base graph search, so a greeting or chit-chat turn that skips + // KB retrieval must not pay for this second LLM call. + if !chatManage.NeedsRetrieval() { + logger.Debugf(ctx, "skipping extract entity, intent %q needs no KB retrieval", chatManage.Intent) + return next() + } + // Prefer the rewritten query: it resolves pronouns and ellipsis from the + // conversation, which the raw follow-up question lacks. query := chatManage.Query + if rewritten := strings.TrimSpace(chatManage.RewriteQuery); rewritten != "" { + query = rewritten + } model, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID) if err != nil { diff --git a/internal/application/service/chat_pipeline/faq_direct_answer_test.go b/internal/application/service/chat_pipeline/faq_direct_answer_test.go new file mode 100644 index 00000000..37721ec8 --- /dev/null +++ b/internal/application/service/chat_pipeline/faq_direct_answer_test.go @@ -0,0 +1,49 @@ +package chatpipeline + +import ( + "context" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +// The direct-answer threshold is compared against the score before boosts, +// and the FAQ that cleared it is the one marked exact — not whichever FAQ +// happens to rank first after boosting. +func TestIntoChatMessage_ExactFAQUsesPreBoostScore(t *testing.T) { + cm := &types.ChatManage{ + PipelineRequest: types.PipelineRequest{ + Query: "refund policy", + SummaryConfig: types.SummaryConfig{ + ContextTemplate: "{{contexts}}", + }, + }, + PipelineState: types.PipelineState{ + MergeResult: []*types.SearchResult{ + { + ID: "boosted", Content: "boosted but middling", ChunkType: string(types.ChunkTypeFAQ), Score: 1.02, + Metadata: map[string]string{"composite_score": "0.8500"}, + }, + { + ID: "strong", Content: "strong match", ChunkType: string(types.ChunkTypeFAQ), Score: 0.98, + Metadata: map[string]string{"composite_score": "0.9300"}, + }, + }, + }, + } + cm.FAQPriorityEnabled = true + cm.FAQDirectAnswerThreshold = 0.9 + + plugin := &PluginIntoChatMessage{} + next := func() *PluginError { return nil } + if err := plugin.OnEvent(context.Background(), types.INTO_CHAT_MESSAGE, cm, next); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if strings.Contains(cm.UserContent, `id="FAQ-1" match="exact"`) { + t.Fatalf("boosted FAQ below the threshold was marked exact: %s", cm.UserContent) + } + if !strings.Contains(cm.UserContent, `id="FAQ-2" match="exact"`) { + t.Fatalf("the FAQ that cleared the threshold was not marked exact: %s", cm.UserContent) + } +} diff --git a/internal/application/service/chat_pipeline/into_chat_message.go b/internal/application/service/chat_pipeline/into_chat_message.go index e8f923ce..2e51dcd9 100644 --- a/internal/application/service/chat_pipeline/into_chat_message.go +++ b/internal/application/service/chat_pipeline/into_chat_message.go @@ -6,6 +6,7 @@ import ( "html" "strings" + "github.com/Tencent/WeKnora/internal/reranking" "github.com/Tencent/WeKnora/internal/searchutil" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" @@ -42,17 +43,25 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context, // Separate FAQ and document results when FAQ priority is enabled var faqResults, docResults []*types.SearchResult var hasHighConfidenceFAQ bool + // exactFAQ is the position in faqResults of the FAQ that cleared the + // direct-answer threshold; only that entry is marked as an exact match. + exactFAQ := -1 if chatManage.FAQPriorityEnabled { for _, result := range chatManage.MergeResult { if result.ChunkType == string(types.ChunkTypeFAQ) { faqResults = append(faqResults, result) - // Check if this FAQ has high confidence (above direct answer threshold) - if result.Score >= chatManage.FAQDirectAnswerThreshold && !hasHighConfidenceFAQ { + // Check if this FAQ has high confidence (above direct answer + // threshold). Compare the score before boosts: the FAQ boost + // exists to rank FAQs above documents, and letting it (or the + // wiki/memory boosts) lift an FAQ over the threshold marked + // middling matches as exact. + if reranking.PreBoostScore(result) >= chatManage.FAQDirectAnswerThreshold && !hasHighConfidenceFAQ { hasHighConfidenceFAQ = true + exactFAQ = len(faqResults) - 1 pipelineInfo(ctx, "IntoChatMessage", "high_confidence_faq", map[string]interface{}{ "chunk_id": result.ID, - "score": fmt.Sprintf("%.4f", result.Score), + "score": fmt.Sprintf("%.4f", reranking.PreBoostScore(result)), "threshold": chatManage.FAQDirectAnswerThreshold, }) } @@ -136,7 +145,7 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context, contextsBuilder.WriteString("\n") for i, result := range faqResults { passage := getEnrichedPassageForChat(ctx, result) - if hasHighConfidenceFAQ && i == 0 { + if i == exactFAQ { contextsBuilder.WriteString(fmt.Sprintf("%s\n", i+1, passage)) } else { contextsBuilder.WriteString(fmt.Sprintf("%s\n", i+1, passage)) diff --git a/internal/application/service/chat_pipeline/load_history.go b/internal/application/service/chat_pipeline/load_history.go index a9a6dd0a..c749fa92 100644 --- a/internal/application/service/chat_pipeline/load_history.go +++ b/internal/application/service/chat_pipeline/load_history.go @@ -61,6 +61,7 @@ func (p *PluginLoadHistory) OnEvent(ctx context.Context, } chatManage.History = historyList + chatManage.HistoryLoaded = true pipelineInfo(ctx, "LoadHistory", "output", map[string]interface{}{ "session_id": chatManage.SessionID, diff --git a/internal/application/service/chat_pipeline/merge.go b/internal/application/service/chat_pipeline/merge.go index 21263c8a..1b370db3 100644 --- a/internal/application/service/chat_pipeline/merge.go +++ b/internal/application/service/chat_pipeline/merge.go @@ -80,10 +80,10 @@ func (p *PluginMerge) OnEvent(ctx context.Context, mergedChunks := p.groupAndMergeCurrentContent(ctx, searchResult) // Step 6: Populate FAQ answers - mergedChunks = p.populateFAQAnswers(ctx, chatManage, mergedChunks) + mergedChunks = p.populateFAQAnswers(ctx, mergedChunks) // Step 7: Expand short contexts - mergedChunks = p.expandShortContextWithNeighbors(ctx, chatManage, mergedChunks) + mergedChunks = p.expandShortContextWithNeighbors(ctx, mergedChunks) // Step 7.5: Re-merge overlapping ranges introduced by expansion mergedChunks = p.groupAndMergeCurrentContent(ctx, mergedChunks) @@ -97,18 +97,35 @@ func (p *PluginMerge) OnEvent(ctx context.Context, } // selectInputResults picks rerank results if available, falling back to search -// results sorted by score descending. +// results sorted by score descending and cut to RerankTopK. Without the cut, +// a turn whose rerank did not run (no model, model unavailable, API error) +// resolved parents, FAQ answers and neighbors for every search hit — up to +// hundreds with query expansion and per-document targets — before top-k +// dropped most of them. func (p *PluginMerge) selectInputResults(ctx context.Context, chatManage *types.ChatManage) []*types.SearchResult { if len(chatManage.RerankResult) > 0 { return chatManage.RerankResult } - pipelineWarn(ctx, "Merge", "fallback", map[string]interface{}{ - "reason": "empty_rerank_result", - }) result := chatManage.SearchResult - sort.Slice(result, func(i, j int) bool { + sort.SliceStable(result, func(i, j int) bool { return result[i].Score > result[j].Score }) + if k := chatManage.RerankTopK; k > 0 && len(result) > k { + // Graph hits have no retrieval score (0) and would always fall + // below the cut; entity search already bounds how many it adds. + kept := result[:k:k] + for _, r := range result[k:] { + if r.MatchType == types.MatchTypeGraph { + kept = append(kept, r) + } + } + result = kept + } + pipelineWarn(ctx, "Merge", "fallback", map[string]interface{}{ + "reason": "empty_rerank_result", + "input_cnt": len(chatManage.SearchResult), + "kept_cnt": len(result), + }) return result } diff --git a/internal/application/service/chat_pipeline/merge_expand.go b/internal/application/service/chat_pipeline/merge_expand.go index e459e96c..66b82521 100644 --- a/internal/application/service/chat_pipeline/merge_expand.go +++ b/internal/application/service/chat_pipeline/merge_expand.go @@ -7,10 +7,15 @@ import ( "github.com/Tencent/WeKnora/internal/types" ) -// expandShortContextWithNeighbors expands the short context with neighbors +// expandShortContextWithNeighbors expands the short context with neighbors. +// +// Lookups are not tenant scoped: hits from an org-shared KB belong to the +// sharing workspace, and a caller-tenant filter silently skipped their +// expansion. The base IDs come from retrieval results and neighbors are only +// accepted from the same knowledge, the same rule parent resolution uses +// (#3342). func (p *PluginMerge) expandShortContextWithNeighbors( ctx context.Context, - chatManage *types.ChatManage, results []*types.SearchResult, ) []*types.SearchResult { const ( @@ -22,17 +27,6 @@ func (p *PluginMerge) expandShortContextWithNeighbors( return results } - tenantID, _ := types.TenantIDFromContext(ctx) - if tenantID == 0 && chatManage != nil { - tenantID = chatManage.TenantID - } - if tenantID == 0 { - pipelineWarn(ctx, "Merge", "expand_skip", map[string]interface{}{ - "reason": "missing_tenant", - }) - return results - } - type targetInfo struct { result *types.SearchResult } @@ -70,7 +64,7 @@ func (p *PluginMerge) expandShortContextWithNeighbors( } chunkMap := make(map[string]*types.Chunk, len(baseIDs)) - chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, baseIDs) + chunks, err := p.chunkRepo.ListChunksByIDOnly(ctx, baseIDs) if err != nil { pipelineWarn(ctx, "Merge", "expand_list_base_failed", map[string]interface{}{ "error": err.Error(), @@ -103,7 +97,7 @@ func (p *PluginMerge) expandShortContextWithNeighbors( for id := range neighborIDsSet { neighborIDs = append(neighborIDs, id) } - neighbors, err := p.chunkRepo.ListChunksByID(ctx, tenantID, neighborIDs) + neighbors, err := p.chunkRepo.ListChunksByIDOnly(ctx, neighborIDs) if err != nil { pipelineWarn(ctx, "Merge", "expand_list_neighbor_failed", map[string]interface{}{ "error": err.Error(), @@ -123,7 +117,7 @@ func (p *PluginMerge) expandShortContextWithNeighbors( for _, target := range targets { res := target.result - p.fetchChunksIfMissing(ctx, tenantID, chunkMap, res.ID) + p.fetchChunksIfMissing(ctx, chunkMap, res.ID) baseChunk := chunkMap[res.ID] if baseChunk == nil || baseChunk.Content == "" || baseChunk.ChunkType != types.ChunkTypeText { continue @@ -137,7 +131,7 @@ func (p *PluginMerge) expandShortContextWithNeighbors( prevCursor := baseChunk.PreChunkID nextCursor := baseChunk.NextChunkID - p.fetchChunksIfMissing(ctx, tenantID, chunkMap, prevCursor, nextCursor) + p.fetchChunksIfMissing(ctx, chunkMap, prevCursor, nextCursor) if prevCursor != "" { if prevChunk := chunkMap[prevCursor]; prevChunk != nil && prevChunk.KnowledgeID == baseChunk.KnowledgeID { @@ -174,7 +168,7 @@ func (p *PluginMerge) expandShortContextWithNeighbors( expanded := false if prevCursor != "" { - p.fetchChunksIfMissing(ctx, tenantID, chunkMap, prevCursor) + p.fetchChunksIfMissing(ctx, chunkMap, prevCursor) if prevChunk := chunkMap[prevCursor]; prevChunk != nil && prevChunk.KnowledgeID == baseChunk.KnowledgeID { prevContent = searchutil.JoinChunkContent(prevChunk.Content, prevContent, "\n\n") @@ -192,7 +186,7 @@ func (p *PluginMerge) expandShortContextWithNeighbors( } if nextCursor != "" { - p.fetchChunksIfMissing(ctx, tenantID, chunkMap, nextCursor) + p.fetchChunksIfMissing(ctx, chunkMap, nextCursor) if nextChunk := chunkMap[nextCursor]; nextChunk != nil && nextChunk.KnowledgeID == baseChunk.KnowledgeID { nextContent = searchutil.JoinChunkContent(nextContent, nextChunk.Content, "\n\n") @@ -250,18 +244,25 @@ func runeLen(s string) int { return len([]rune(s)) } -// mergeOrderedContent merges ordered content +// mergeOrderedContent joins prev, base and next in document order within +// roughly maxLen runes. base is the retrieval hit and is never cut; the budget +// left after it goes to the end of prev and the start of next, the text +// adjacent to the hit, with any share one side cannot use passed to the other. +// Truncating the joined string instead let a long previous neighbor push the +// hit out of the context entirely. func mergeOrderedContent(prev, base, next string, maxLen int) string { + prevRunes, nextRunes := []rune(prev), []rune(next) + budget := max(maxLen-runeLen(base), 0) + prevKeep := min(len(prevRunes), budget/2) + nextKeep := min(len(nextRunes), budget-prevKeep) + prevKeep = min(len(prevRunes), budget-nextKeep) + content := base - if prev != "" { - content = searchutil.JoinChunkContent(prev, content, "\n\n") + if prevKeep > 0 { + content = searchutil.JoinChunkContent(string(prevRunes[len(prevRunes)-prevKeep:]), content, "\n\n") } - if next != "" { - content = searchutil.JoinChunkContent(content, next, "\n\n") - } - runes := []rune(content) - if len(runes) > maxLen { - return string(runes[:maxLen]) + if nextKeep > 0 { + content = searchutil.JoinChunkContent(content, string(nextRunes[:nextKeep]), "\n\n") } return content } @@ -277,7 +278,6 @@ func containsID(ids []string, target string) bool { func (p *PluginMerge) fetchChunksIfMissing( ctx context.Context, - tenantID uint64, chunkMap map[string]*types.Chunk, chunkIDs ...string, ) { @@ -294,7 +294,7 @@ func (p *PluginMerge) fetchChunksIfMissing( return } - chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, missing) + chunks, err := p.chunkRepo.ListChunksByIDOnly(ctx, missing) if err != nil { pipelineWarn(ctx, "Merge", "expand_fetch_missing_failed", map[string]interface{}{ "missing_cnt": len(missing), diff --git a/internal/application/service/chat_pipeline/merge_expand_edit_test.go b/internal/application/service/chat_pipeline/merge_expand_edit_test.go index 5d6b83d3..deeb125e 100644 --- a/internal/application/service/chat_pipeline/merge_expand_edit_test.go +++ b/internal/application/service/chat_pipeline/merge_expand_edit_test.go @@ -72,7 +72,7 @@ func TestExpandShortContextKeepsSourceCoordinates(t *testing.T) { Content: "edited base body", StartAt: 100, EndAt: 120, } - got := plugin.expandShortContextWithNeighbors(ctx, &types.ChatManage{}, []*types.SearchResult{result}) + got := plugin.expandShortContextWithNeighbors(ctx, []*types.SearchResult{result}) if len(got) != 1 { t.Fatalf("result count = %d, want 1", len(got)) } diff --git a/internal/application/service/chat_pipeline/merge_faq.go b/internal/application/service/chat_pipeline/merge_faq.go index be85e80e..ed56e537 100644 --- a/internal/application/service/chat_pipeline/merge_faq.go +++ b/internal/application/service/chat_pipeline/merge_faq.go @@ -7,27 +7,20 @@ import ( "github.com/Tencent/WeKnora/internal/types" ) -// populateFAQAnswers populates FAQ answers for the search results +// populateFAQAnswers populates FAQ answers for the search results. +// +// The chunk lookup is not tenant scoped: FAQ hits from an org-shared KB +// belong to the sharing workspace, and in question-only index mode their +// answers exist only in chunk metadata, so a caller-tenant filter left the +// model with bare questions. The IDs come from retrieval results (#3342). func (p *PluginMerge) populateFAQAnswers( ctx context.Context, - chatManage *types.ChatManage, results []*types.SearchResult, ) []*types.SearchResult { if len(results) == 0 || p.chunkRepo == nil { return results } - tenantID, _ := types.TenantIDFromContext(ctx) - if tenantID == 0 && chatManage != nil { - tenantID = chatManage.TenantID - } - if tenantID == 0 { - pipelineWarn(ctx, "Merge", "faq_enrich_skip", map[string]interface{}{ - "reason": "missing_tenant", - }) - return results - } - chunkResultMap := make(map[string][]*types.SearchResult) chunkIDSet := make(map[string]struct{}) for _, r := range results { @@ -52,7 +45,7 @@ func (p *PluginMerge) populateFAQAnswers( chunkIDs = append(chunkIDs, id) } - chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs) + chunks, err := p.chunkRepo.ListChunksByIDOnly(ctx, chunkIDs) if err != nil { pipelineWarn(ctx, "Merge", "faq_chunk_fetch_failed", map[string]interface{}{ "error": err.Error(), diff --git a/internal/application/service/chat_pipeline/merge_history.go b/internal/application/service/chat_pipeline/merge_history.go index 8341028a..025b2f9f 100644 --- a/internal/application/service/chat_pipeline/merge_history.go +++ b/internal/application/service/chat_pipeline/merge_history.go @@ -10,19 +10,24 @@ import ( ) // filterHistoryResults retrieves history references and filters them by -// textual similarity to the current query. Only references that are above -// a Jaccard similarity threshold are kept, and their scores are discounted -// to reflect that they were not directly retrieved for the current query. -// Results already present in currentResults (by chunk ID) are excluded. +// how much of the current query they cover. Only references whose token +// overlap with the query reaches a threshold are kept, and their scores are +// discounted to reflect that they were not directly retrieved for the +// current query. Results already present in currentResults (by chunk ID) +// are excluded. +// +// Overlap is measured against the smaller token set (in practice the query). +// Jaccard divided by the union, so a query of about 8 terms against a chunk of +// a few hundred never passed 0.05 and the 0.15 threshold kept nothing. func filterHistoryResults( ctx context.Context, chatManage *types.ChatManage, currentResults []*types.SearchResult, ) []*types.SearchResult { const ( - // minSimilarity is the minimum Jaccard similarity between the current - // query and a history chunk's content for it to be injected. - minSimilarity = 0.15 + // minSimilarity is the minimum share of query terms (overlap + // coefficient) a history chunk must contain to be injected. + minSimilarity = 0.3 // historyScoreDiscount reduces the original score of history results // to rank them below freshly-retrieved results of similar relevance. historyScoreDiscount = 0.6 @@ -56,7 +61,7 @@ func filterHistoryResults( continue } contentTokens := searchutil.TokenizeSimple(r.Content) - sim := searchutil.Jaccard(queryTokens, contentTokens) + sim := searchutil.TokenOverlapRatio(queryTokens, contentTokens) if sim < minSimilarity { pipelineInfo(ctx, "Merge", "history_filter_drop", map[string]interface{}{ "chunk_id": r.ID, diff --git a/internal/application/service/chat_pipeline/merge_history_test.go b/internal/application/service/chat_pipeline/merge_history_test.go new file mode 100644 index 00000000..cac9cf29 --- /dev/null +++ b/internal/application/service/chat_pipeline/merge_history_test.go @@ -0,0 +1,36 @@ +package chatpipeline + +import ( + "context" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +// A follow-up question shares a few terms with last turn's long reference. +// Jaccard over the union never reached the threshold for chunk-sized text, +// so no history reference was ever injected. +func TestFilterHistoryResultsKeepsReferenceCoveringTheQuery(t *testing.T) { + longChunk := "refund policy: customers may request a refund within seven days of delivery. " + + strings.Repeat("unrelated operational detail about warehouses and shipping partners. ", 30) + cm := &types.ChatManage{ + PipelineState: types.PipelineState{ + RewriteQuery: "refund within seven days delivery", + History: []*types.History{{ + KnowledgeReferences: []*types.SearchResult{ + {ID: "ref-1", Content: longChunk, Score: 0.8}, + {ID: "ref-2", Content: strings.Repeat("completely different topic text. ", 30), Score: 0.9}, + }, + }}, + }, + } + got := filterHistoryResults(context.Background(), cm, nil) + if len(got) != 1 || got[0].ID != "ref-1" { + ids := make([]string, 0, len(got)) + for _, r := range got { + ids = append(ids, r.ID) + } + t.Fatalf("history references kept = %v, want [ref-1]", ids) + } +} diff --git a/internal/application/service/chat_pipeline/merge_shared_lookup_test.go b/internal/application/service/chat_pipeline/merge_shared_lookup_test.go new file mode 100644 index 00000000..b59ffbd9 --- /dev/null +++ b/internal/application/service/chat_pipeline/merge_shared_lookup_test.go @@ -0,0 +1,107 @@ +package chatpipeline + +import ( + "context" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +// Hits from an org-shared KB belong to the sharing workspace (tenant 2) +// while the caller is tenant 1. The merge stage must still fill FAQ answers +// and expand neighbors for them, as parent resolution already does. + +func TestPopulateFAQAnswersResolvesSharedKBChunks(t *testing.T) { + faq := &types.Chunk{ID: "faq", TenantID: 2, ChunkType: types.ChunkTypeFAQ, Content: "How do refunds work?"} + if err := faq.SetFAQMetadata(&types.FAQChunkMetadata{ + StandardQuestion: "How do refunds work?", + Answers: []string{"Refunds are issued within 7 days."}, + }); err != nil { + t.Fatal(err) + } + repo := &tenantScopedChunkRepo{expandChunkRepo: &expandChunkRepo{ + chunks: map[string]*types.Chunk{"faq": faq}, + }} + plugin := &PluginMerge{chunkRepo: repo} + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) + result := &types.SearchResult{ID: "faq", ChunkType: string(types.ChunkTypeFAQ), Content: faq.Content} + + got := plugin.populateFAQAnswers(ctx, []*types.SearchResult{result}) + if !strings.Contains(got[0].Content, "Refunds are issued within 7 days.") { + t.Fatalf("shared FAQ answer was not filled in: %q", got[0].Content) + } +} + +func TestExpandShortContextResolvesSharedKBNeighbors(t *testing.T) { + repo := &tenantScopedChunkRepo{expandChunkRepo: &expandChunkRepo{chunks: map[string]*types.Chunk{ + "prev": { + ID: "prev", TenantID: 2, KnowledgeID: "doc", ChunkType: types.ChunkTypeText, + Content: "shared previous body", NextChunkID: "base", + }, + "base": { + ID: "base", TenantID: 2, KnowledgeID: "doc", ChunkType: types.ChunkTypeText, + Content: "shared base body", PreChunkID: "prev", NextChunkID: "next", + }, + "next": { + ID: "next", TenantID: 2, KnowledgeID: "doc", ChunkType: types.ChunkTypeText, + Content: "shared next body", PreChunkID: "base", + }, + }}} + plugin := &PluginMerge{chunkRepo: repo} + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) + result := &types.SearchResult{ + ID: "base", KnowledgeID: "doc", ChunkType: string(types.ChunkTypeText), Content: "shared base body", + } + + got := plugin.expandShortContextWithNeighbors(ctx, []*types.SearchResult{result}) + for _, want := range []string{"shared previous body", "shared base body", "shared next body"} { + if !strings.Contains(got[0].Content, want) { + t.Fatalf("shared neighbor expansion missing %q: %q", want, got[0].Content) + } + } +} + +func TestExpandShortContextKeepsHitWhenNeighborIsLong(t *testing.T) { + longPrev := strings.Repeat("p", 2000) + longNext := strings.Repeat("n", 2000) + repo := &expandChunkRepo{chunks: map[string]*types.Chunk{ + "prev": { + ID: "prev", KnowledgeID: "doc", ChunkType: types.ChunkTypeText, + Content: longPrev, NextChunkID: "base", + }, + "base": { + ID: "base", KnowledgeID: "doc", ChunkType: types.ChunkTypeText, + Content: "the matched heading", PreChunkID: "prev", NextChunkID: "next", + }, + "next": {ID: "next", KnowledgeID: "doc", ChunkType: types.ChunkTypeText, Content: longNext, PreChunkID: "base"}, + }} + plugin := &PluginMerge{chunkRepo: repo} + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) + result := &types.SearchResult{ + ID: "base", KnowledgeID: "doc", ChunkType: string(types.ChunkTypeText), Content: "the matched heading", + } + + got := plugin.expandShortContextWithNeighbors(ctx, []*types.SearchResult{result}) + content := got[0].Content + if !strings.Contains(content, "the matched heading") { + t.Fatalf("the retrieval hit was cut out of the expanded context: %d runes", runeLen(content)) + } + if !strings.Contains(content, "p\n\nthe matched heading\n\nn") { + t.Fatalf("expanded context should keep the text adjacent to the hit: %q...", content[:40]) + } + if n := runeLen(content); n > 850+4 { + t.Fatalf("expanded context has %d runes, want about 850", n) + } +} + +func TestMergeOrderedContentGivesUnusedBudgetToOtherSide(t *testing.T) { + got := mergeOrderedContent("short prev", "base", strings.Repeat("n", 100), 60) + if !strings.HasPrefix(got, "short prev\n\nbase\n\n") { + t.Fatalf("short prev should be kept whole: %q", got) + } + // 60 - len("base") = 56; prev uses 10, so next gets the remaining 46. + if n := strings.Count(got, "n"); n != 46 { + t.Fatalf("next kept %d runes, want 46", n) + } +} diff --git a/internal/application/service/chat_pipeline/overlap_dedup_test.go b/internal/application/service/chat_pipeline/overlap_dedup_test.go new file mode 100644 index 00000000..501dc948 --- /dev/null +++ b/internal/application/service/chat_pipeline/overlap_dedup_test.go @@ -0,0 +1,36 @@ +package chatpipeline + +import ( + "context" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +// Near-duplicates of similar size collapse to the better-scored one, but a +// short chunk is not dropped just because a much longer text on the same +// topic happens to contain most of its words. +func TestRemovePartialOverlapsSizeGuard(t *testing.T) { + near := []*types.SearchResult{ + {ID: "a", Content: "alpha beta gamma delta epsilon zeta eta theta", Score: 0.9}, + {ID: "b", Content: "alpha beta gamma delta epsilon zeta eta theta iota", Score: 0.5}, + } + if got := removePartialOverlaps(context.Background(), near); len(got) != 1 || got[0].ID != "a" { + t.Fatalf("near-duplicates not collapsed: %+v", got) + } + + var page strings.Builder + for i := 0; i < 20; i++ { + page.WriteString("alpha beta gamma delta epsilon zeta eta theta kappa lambda mu nu xi omicron pi rho ") + page.WriteString("filler" + string(rune('a'+i)) + " ") + } + mixed := []*types.SearchResult{ + {ID: "chunk", Content: "alpha beta gamma delta epsilon zeta eta theta sigma", Score: 0.4}, + {ID: "page", Content: page.String() + " word1 word2 word3 word4 word5 word6 word7 word8 word9 word10" + + " word11 word12 word13 word14 word15 word16 word17 word18 word19 word20", Score: 0.9}, + } + if got := removePartialOverlaps(context.Background(), mixed); len(got) != 2 { + t.Fatalf("short chunk dropped against a much longer text: %+v", got) + } +} diff --git a/internal/application/service/chat_pipeline/query_expansion.go b/internal/application/service/chat_pipeline/query_expansion.go index f5f1a642..e6ca1271 100644 --- a/internal/application/service/chat_pipeline/query_expansion.go +++ b/internal/application/service/chat_pipeline/query_expansion.go @@ -13,11 +13,23 @@ import ( // runQueryExpansion performs query expansion when initial recall is low. // It generates query variants and runs concurrent retrieval across search targets. +// +// The variants are local rewrites of the query (stopwords dropped, words +// reordered), so they only add recall on the keyword side: their embeddings +// sit next to the original query's, and the vector half of each search +// re-embedded the variant and repeated the main search. Expansion therefore +// searches keywords only, and does nothing when keyword matching is off. func (p *PluginSearch) runQueryExpansion(ctx context.Context, chatManage *types.ChatManage) []*types.SearchResult { pipelineInfo(ctx, "Search", "recall_low", map[string]interface{}{ "current": len(chatManage.SearchResult), "threshold": chatManage.EmbeddingTopK, }) + if chatManage.DisableKeywordsMatch { + pipelineInfo(ctx, "Search", "expansion_skip", map[string]interface{}{ + "reason": "keyword_match_disabled", + }) + return nil + } expansions := p.expandQueries(ctx, chatManage) if len(expansions) == 0 { return nil @@ -67,8 +79,7 @@ func (p *PluginSearch) runQueryExpansion(ctx context.Context, chatManage *types. MatchCount: expTopK, TagIDs: t.TagIDs, ScopeTagIDs: t.ScopeTagIDs, - DisableVectorMatch: chatManage.DisableVectorMatch, - DisableKeywordsMatch: chatManage.DisableKeywordsMatch, + DisableVectorMatch: true, SkipContextEnrichment: true, // Pipeline handles context assembly in merge stage } // Apply knowledge ID filter if this is a partial KB search diff --git a/internal/application/service/chat_pipeline/query_expansion_test.go b/internal/application/service/chat_pipeline/query_expansion_test.go index 77011689..4aeddf30 100644 --- a/internal/application/service/chat_pipeline/query_expansion_test.go +++ b/internal/application/service/chat_pipeline/query_expansion_test.go @@ -3,10 +3,12 @@ package chatpipeline import ( "context" "strings" + "sync" "testing" "unicode/utf8" "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/stretchr/testify/assert" ) @@ -63,3 +65,49 @@ func containsToken(values []string, want string) bool { } return false } + +type recordingExpansionKBService struct { + interfaces.KnowledgeBaseService + mu sync.Mutex + params []types.SearchParams +} + +func (s *recordingExpansionKBService) HybridSearch( + _ context.Context, _ string, params types.SearchParams, +) ([]*types.SearchResult, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.params = append(s.params, params) + return nil, nil +} + +// Expansion variants only add keyword recall, so they must not re-embed and +// repeat the vector search; with keyword matching off there is nothing to do. +func TestRunQueryExpansionSearchesKeywordsOnly(t *testing.T) { + kbService := &recordingExpansionKBService{} + plugin := &PluginSearch{knowledgeBaseService: kbService} + cm := &types.ChatManage{ + PipelineRequest: types.PipelineRequest{ + EmbeddingTopK: 10, + SearchTargets: types.SearchTargets{{KnowledgeBaseID: "kb-1", Type: types.SearchTargetTypeKnowledgeBase}}, + }, + PipelineState: types.PipelineState{RewriteQuery: "如何配置向量数据库的索引参数"}, + } + + plugin.runQueryExpansion(context.Background(), cm) + if len(kbService.params) == 0 { + t.Fatal("expected expansion searches") + } + for _, p := range kbService.params { + if !p.DisableVectorMatch || p.DisableKeywordsMatch { + t.Fatalf("expansion search params = %+v, want keyword-only", p) + } + } + + kbService.params = nil + cm.DisableKeywordsMatch = true + plugin.runQueryExpansion(context.Background(), cm) + if len(kbService.params) != 0 { + t.Fatalf("expansion ran %d searches with keyword matching off", len(kbService.params)) + } +} diff --git a/internal/application/service/chat_pipeline/query_understand.go b/internal/application/service/chat_pipeline/query_understand.go index c8c29777..ec1bd0c0 100644 --- a/internal/application/service/chat_pipeline/query_understand.go +++ b/internal/application/service/chat_pipeline/query_understand.go @@ -83,7 +83,7 @@ func (p *PluginQueryUnderstand) OnEvent(ctx context.Context, // --- Load and prepare conversation history --- var historyList []*types.History - if len(chatManage.History) > 0 { + if len(chatManage.History) > 0 || chatManage.HistoryLoaded { historyList = chatManage.History pipelineInfo(ctx, "QueryUnderstand", "history_reused", map[string]interface{}{ "session_id": chatManage.SessionID, @@ -112,7 +112,10 @@ func (p *PluginQueryUnderstand) OnEvent(ctx context.Context, maxTokens := 150 if useImages { - maxTokens = 500 + // The image prompt asks for the full OCR text in image_description. + // At 500 tokens a text-heavy screenshot cut the JSON off, the parse + // failed, and the turn lost its rewrite, intent and description. + maxTokens = 2048 } // --- Call model --- @@ -214,6 +217,7 @@ func (p *PluginQueryUnderstand) loadHistory(ctx context.Context, chatManage *typ } chatManage.History = historyList + chatManage.HistoryLoaded = true if len(historyList) > 0 { pipelineInfo(ctx, "QueryUnderstand", "history_ready", map[string]interface{}{ @@ -383,7 +387,13 @@ func (p *PluginQueryUnderstand) parseOutput(chatManage *types.ChatManage, raw st return } - if output, ok := parseStructuredQueryOutput(content); ok { + output, ok := parseStructuredQueryOutput(content) + if !ok { + // A reply cut off by the token cap is not valid JSON, but the fields + // the model wrote before the cut are still usable. + output, ok = salvageStructuredQueryOutput(content) + } + if ok { if rewrite := strings.TrimSpace(output.RewriteQuery); rewrite != "" { chatManage.RewriteQuery = rewrite } @@ -395,6 +405,45 @@ func (p *PluginQueryUnderstand) parseOutput(chatManage *types.ChatManage, raw st // On parse failure, keep the original query and intent. } +// salvageFieldPattern captures a JSON string field and its value, closed or +// cut off at the end of the reply. +var salvageFieldPattern = regexp.MustCompile(`"([a-z_]+)"\s*:\s*"((?:[^"\\]|\\.)*)("?)`) + +// salvageStructuredQueryOutput recovers the string fields of a truncated +// structured reply. Complete fields are taken as they are. A field the reply +// was cut inside keeps the text written so far only when it is the image +// description, where a partial transcript still helps; a cut-off rewrite or +// intent is dropped, since it would replace the user's complete query. +func salvageStructuredQueryOutput(content string) (queryUnderstandOutput, bool) { + fields := make(map[string]json.RawMessage) + for _, m := range salvageFieldPattern.FindAllStringSubmatch(content, -1) { + if closed := m[3] != ""; !closed && !isImageDescriptionField(m[1]) { + continue + } + value := strings.TrimSuffix(m[2], "\\") + var decoded string + if err := json.Unmarshal([]byte(`"`+value+`"`), &decoded); err != nil { + continue + } + encoded, _ := json.Marshal(decoded) + fields[m[1]] = encoded + } + if len(fields) == 0 { + return queryUnderstandOutput{}, false + } + encoded, err := json.Marshal(fields) + if err != nil { + return queryUnderstandOutput{}, false + } + return parseStructuredQueryOutputJSON(string(encoded)) +} + +// isImageDescriptionField reports whether key is one of the image description +// aliases parseStructuredQueryOutputJSON accepts. +func isImageDescriptionField(key string) bool { + return strings.HasPrefix(key, "image_") || key == "description" +} + func parseStructuredQueryOutput(raw string) (queryUnderstandOutput, bool) { content := strings.TrimSpace(raw) if content == "" { @@ -429,10 +478,7 @@ func parseStructuredQueryOutputJSON(content string) (queryUnderstandOutput, bool "rewrite_query", "rewritten_query", "query", "question")), } - intentStr := strings.TrimSpace(firstStringField(obj, "intent")) - if intentStr != "" { - out.Intent = types.QueryIntent(intentStr) - } + out.Intent = types.NormalizeQueryIntent(firstStringField(obj, "intent")) desc := strings.TrimSpace(firstStringField(obj, "image_description", "image_desc", "image_text", "image_ocr_text", "description")) diff --git a/internal/application/service/chat_pipeline/query_understand_test.go b/internal/application/service/chat_pipeline/query_understand_test.go index ac2382f8..b9df755a 100644 --- a/internal/application/service/chat_pipeline/query_understand_test.go +++ b/internal/application/service/chat_pipeline/query_understand_test.go @@ -149,3 +149,51 @@ func TestParseOutput_ValidJSONStillAppliesRewrite(t *testing.T) { t.Errorf("Intent = %q, want summarize", cm.Intent) } } + +// A reply cut off by the token cap still yields the fields written before +// the cut, including the partial image description. +func TestParseOutputSalvagesTruncatedReply(t *testing.T) { + p := &PluginQueryUnderstand{} + cm := &types.ChatManage{PipelineRequest: types.PipelineRequest{Query: ""}} + p.parseOutput(cm, `{"rewrite_query":"如何处理 ERR_4012 错误","intent":"kb_search",`+ + `"image_description":"截图显示了错误信息 \"ERR_4012\" 以及重试按`) + if cm.RewriteQuery != "如何处理 ERR_4012 错误" || cm.Intent != types.IntentKBSearch { + t.Fatalf("rewrite=%q intent=%q", cm.RewriteQuery, cm.Intent) + } + if cm.ImageDescription != `截图显示了错误信息 "ERR_4012" 以及重试按` { + t.Fatalf("image description = %q", cm.ImageDescription) + } +} + +// A rewrite cut off by the token cap must not replace the user's query. +func TestParseOutputDropsTruncatedRewrite(t *testing.T) { + p := &PluginQueryUnderstand{} + cm := &types.ChatManage{} + p.parseOutput(cm, `{"intent":"kb_search","rewrite_query":"How do I configure the retention policy for arch`) + if cm.RewriteQuery != "" { + t.Fatalf("truncated rewrite adopted: %q", cm.RewriteQuery) + } + if cm.Intent != types.IntentKBSearch { + t.Fatalf("intent = %q", cm.Intent) + } +} + +// An unexpected intent label no longer turns retrieval off. +func TestParseOutputNormalizesIntent(t *testing.T) { + p := &PluginQueryUnderstand{} + for raw, want := range map[string]types.QueryIntent{ + "KB_SEARCH": types.IntentKBSearch, + "kb-search": types.IntentKBSearch, + "search": "", + "Greeting": types.IntentGreeting, + } { + cm := &types.ChatManage{} + p.parseOutput(cm, `{"rewrite_query":"q","intent":"`+raw+`"}`) + if cm.Intent != want { + t.Fatalf("intent %q -> %q, want %q", raw, cm.Intent, want) + } + } + if !(&types.ChatManage{PipelineState: types.PipelineState{Intent: ""}}).NeedsRetrieval() { + t.Fatal("an unknown intent must still retrieve") + } +} diff --git a/internal/application/service/chat_pipeline/rerank.go b/internal/application/service/chat_pipeline/rerank.go index feca29bb..7d5e048f 100644 --- a/internal/application/service/chat_pipeline/rerank.go +++ b/internal/application/service/chat_pipeline/rerank.go @@ -66,16 +66,18 @@ func (p *PluginRerank) OnEvent(ctx context.Context, return next() } - // Get rerank model from service + // Get rerank model from service. A model that cannot be loaded (deleted, + // misconfigured) degrades to retrieval order like a failed rerank call, + // as the search APIs do, rather than failing every turn of the session. rerankModel, err := p.modelService.GetRerankModel(ctx, chatManage.RerankModelID) if err != nil { diag.Outcome = types.RerankOutcomeModelUnavailable diag.Error = err.Error() - pipelineError(ctx, "Rerank", "get_model", map[string]interface{}{ + pipelineWarn(ctx, "Rerank", "get_model_fallback", map[string]interface{}{ "model_id": chatManage.RerankModelID, "error": err.Error(), }) - return ErrGetRerankModel.WithError(err) + return next() } rerankCtx, rerankSpan := langfuse.GetManager().StartSpan(ctx, langfuse.SpanOptions{ @@ -100,6 +102,7 @@ func (p *PluginRerank) OnEvent(ctx context.Context, opts := reranking.Options{ Threshold: chatManage.RerankThreshold, TopK: max(1, chatManage.RerankTopK), + MaxCandidates: max(reranking.DefaultMaxCandidates, chatManage.RerankTopK), FallbackMinScore: reranking.FallbackMinScore(chatManage.SearchTargets.HasRecallThresholdOverride()), } if chatManage.FAQPriorityEnabled { diff --git a/internal/application/service/chat_pipeline/rerank_test.go b/internal/application/service/chat_pipeline/rerank_test.go index aa428e76..628064f4 100644 --- a/internal/application/service/chat_pipeline/rerank_test.go +++ b/internal/application/service/chat_pipeline/rerank_test.go @@ -2,6 +2,7 @@ package chatpipeline import ( "context" + "errors" "sync" "testing" @@ -182,3 +183,44 @@ func TestSearchHonorsRecallPathSwitches(t *testing.T) { }) } } + +type failingRerankModelService struct { + interfaces.ModelService +} + +func (failingRerankModelService) GetRerankModel(context.Context, string) (rerank.Reranker, error) { + return nil, errors.New("model deleted") +} + +// A rerank model that cannot be loaded degrades to retrieval order instead of +// failing the turn, like a failed rerank call. +func TestPluginRerankDegradesWhenModelUnavailable(t *testing.T) { + plugin := &PluginRerank{modelService: failingRerankModelService{}} + cm := rerankChatManage(0.3) + + nextCalled := false + err := plugin.OnEvent(context.Background(), types.CHUNK_RERANK, cm, func() *PluginError { + nextCalled = true + return nil + }) + if err != nil || !nextCalled { + t.Fatalf("err=%v nextCalled=%v", err, nextCalled) + } + if cm.RerankDiagnostics.Outcome != types.RerankOutcomeModelUnavailable || len(cm.SearchResult) != 2 { + t.Fatalf("diagnostics=%+v search=%d", cm.RerankDiagnostics, len(cm.SearchResult)) + } +} + +// Without rerank results the merge input is cut to RerankTopK, best first. +func TestMergeFallbackKeepsRerankTopK(t *testing.T) { + cm := &types.ChatManage{ + PipelineRequest: types.PipelineRequest{RerankTopK: 2}, + PipelineState: types.PipelineState{SearchResult: []*types.SearchResult{ + {ID: "low", Score: 0.1}, {ID: "high", Score: 0.9}, {ID: "mid", Score: 0.5}, + }}, + } + got := (&PluginMerge{}).selectInputResults(context.Background(), cm) + if len(got) != 2 || got[0].ID != "high" || got[1].ID != "mid" { + t.Fatalf("fallback input = %+v", got) + } +} diff --git a/internal/application/service/chat_pipeline/search.go b/internal/application/service/chat_pipeline/search.go index 1e6a66da..4b2f9504 100644 --- a/internal/application/service/chat_pipeline/search.go +++ b/internal/application/service/chat_pipeline/search.go @@ -218,13 +218,23 @@ func buildContentSignature(content string) string { // - Substring containment: if the normalized short text is a literal substring // of the normalized long text, the shorter chunk is removed. // - Token overlap coefficient >= 0.85: if 85%+ of the smaller chunk's tokens -// appear in the larger chunk, the smaller one is redundant. +// appear in the larger chunk, the smaller one is redundant. Only applied +// when the two token sets are within maxOverlapSizeRatio of each other: +// near-duplicates are of similar size, while a long web page or parent +// chunk shares most words with any short chunk on its topic. +// +// Each text is tokenized once; tokenizing both sides of every pair ran jieba +// O(n²) times over parent- and page-sized texts before the first token of +// the answer. // // The input slice MUST already be deduplicated by ID/signature. Within each // pair the chunk with the lower score is the candidate for removal; ties are // broken by content length (longer wins). func removePartialOverlaps(ctx context.Context, results []*types.SearchResult) []*types.SearchResult { - const overlapThreshold = 0.85 + const ( + overlapThreshold = 0.85 + maxOverlapSizeRatio = 3 + ) if len(results) <= 1 { return results @@ -233,6 +243,13 @@ func removePartialOverlaps(ctx context.Context, results []*types.SearchResult) [ type normEntry struct { norm string result *types.SearchResult + tokens map[string]struct{} // built on first use + } + tokensOf := func(e *normEntry) map[string]struct{} { + if e.tokens == nil { + e.tokens = searchutil.TokenizeSimple(e.result.Content) + } + return e.tokens } entries := make([]normEntry, 0, len(results)) @@ -266,11 +283,10 @@ func removePartialOverlaps(ctx context.Context, results []*types.SearchResult) [ ) if !contained { - ratio := searchutil.ContentOverlapRatio( - entries[shortIdx].result.Content, - entries[longIdx].result.Content, - ) - if ratio < overlapThreshold { + shortTokens, longTokens := tokensOf(&entries[shortIdx]), tokensOf(&entries[longIdx]) + small, large := min(len(shortTokens), len(longTokens)), max(len(shortTokens), len(longTokens)) + if small*maxOverlapSizeRatio < large || + searchutil.TokenOverlapRatio(shortTokens, longTokens) < overlapThreshold { continue } } diff --git a/internal/application/service/chat_pipeline/search_entity.go b/internal/application/service/chat_pipeline/search_entity.go index 85cecd40..3ab64c83 100644 --- a/internal/application/service/chat_pipeline/search_entity.go +++ b/internal/application/service/chat_pipeline/search_entity.go @@ -139,20 +139,32 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context, logger.Infof(ctx, "No new chunk found") return next() } - chunks, err := p.chunkRepo.ListChunksByID(ctx, types.MustTenantIDFromContext(ctx), chunkIDs) + // Graph hits from an org-shared KB belong to the sharing workspace, so + // the lookups are not tenant scoped (as for parents, #3342). The graph + // namespaces are the KBs in this turn's scope; a chunk is only used when + // its row belongs to one of them. + allowedKBs := make(map[string]bool, len(knowledgeBaseIDs)+len(entityKnowledge)) + for _, id := range knowledgeBaseIDs { + allowedKBs[id] = true + } + for _, kbID := range entityKnowledge { + allowedKBs[kbID] = true + } + listed, err := p.chunkRepo.ListChunksByIDOnly(ctx, chunkIDs) if err != nil { logger.Errorf(ctx, "Failed to list chunks, session_id: %s, error: %v", chatManage.SessionID, err) return next() } + chunks := make([]*types.Chunk, 0, len(listed)) knowledgeIDs := []string{} - for _, chunk := range chunks { + for _, chunk := range listed { + if chunk == nil || !allowedKBs[chunk.KnowledgeBaseID] { + continue + } + chunks = append(chunks, chunk) knowledgeIDs = append(knowledgeIDs, chunk.KnowledgeID) } - knowledges, err := p.knowledgeRepo.GetKnowledgeBatch( - ctx, - types.MustTenantIDFromContext(ctx), - knowledgeIDs, - ) + knowledges, err := p.knowledgeRepo.GetKnowledgeBatchByIDOnly(ctx, knowledgeIDs) if err != nil { logger.Errorf(ctx, "Failed to list knowledge, session_id: %s, error: %v", chatManage.SessionID, err) return next() @@ -164,10 +176,15 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context, } var entityResults []*types.SearchResult for _, chunk := range chunks { - searchResult := chunk2SearchResult(chunk, knowledgeMap[chunk.KnowledgeID]) - entityResults = append(entityResults, searchResult) + // A chunk can outlive its soft-deleted document, and a disabled + // chunk must not come back through the graph either. + knowledge := knowledgeMap[chunk.KnowledgeID] + if knowledge == nil || !chunk.IsEnabled { + continue + } + entityResults = append(entityResults, chunk2SearchResult(chunk, knowledge)) } - searchutil.EnrichSearchResultsImageInfo(ctx, p.chunkRepo, types.MustTenantIDFromContext(ctx), entityResults) + searchutil.EnrichSearchResultsImageInfoOnly(ctx, p.chunkRepo, entityResults) chatManage.SearchResult = append(chatManage.SearchResult, entityResults...) // remove duplicate results chatManage.SearchResult = removeDuplicateResults(chatManage.SearchResult) @@ -184,6 +201,9 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context, return next() } +// maxEntityChunks bounds the chunks graph entity search adds to a turn. +const maxEntityChunks = 30 + // filterSeenChunk filters seen chunks from the graph func filterSeenChunk(ctx context.Context, graph *types.GraphData, searchResult []*types.SearchResult) []string { seen := map[string]bool{} @@ -195,6 +215,12 @@ func filterSeenChunk(ctx context.Context, graph *types.GraphData, searchResult [ chunkIDs := []string{} for _, node := range graph.Node { for _, chunkID := range node.Chunks { + // Every chunk of every matched node was fetched and passed on; + // entity search runs on an empty result list, so nothing was + // ever filtered as seen. Cap it. + if len(chunkIDs) >= maxEntityChunks { + break + } if seen[chunkID] { continue } @@ -206,7 +232,13 @@ func filterSeenChunk(ctx context.Context, graph *types.GraphData, searchResult [ return chunkIDs } -// chunk2SearchResult converts a chunk to a search result +// chunk2SearchResult converts a chunk to a search result. +// +// Graph hits come from entity lookups, not similarity search, so they have no +// retrieval score. They used to carry a fixed 1.0, which ranked them above +// every scored hit whenever rerank did not run. With 0 they fill the slots +// scored hits leave; when rerank runs, CompositeScore substitutes the model +// score for the missing retrieval score. func chunk2SearchResult(chunk *types.Chunk, knowledge *types.Knowledge) *types.SearchResult { return &types.SearchResult{ ID: chunk.ID, @@ -218,7 +250,7 @@ func chunk2SearchResult(chunk *types.Chunk, knowledge *types.Knowledge) *types.S StartAt: chunk.StartAt, EndAt: chunk.EndAt, Seq: chunk.ChunkIndex, - Score: 1.0, + Score: 0, MatchType: types.MatchTypeGraph, Metadata: knowledge.GetMetadata(), ChunkType: string(chunk.ChunkType), diff --git a/internal/application/service/chat_pipeline/search_entity_scope_test.go b/internal/application/service/chat_pipeline/search_entity_scope_test.go new file mode 100644 index 00000000..521175ae --- /dev/null +++ b/internal/application/service/chat_pipeline/search_entity_scope_test.go @@ -0,0 +1,70 @@ +package chatpipeline + +import ( + "context" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +type entityGraphRepo struct { + interfaces.RetrieveGraphRepository + graph *types.GraphData +} + +func (r *entityGraphRepo) SearchNode(context.Context, types.NameSpace, []string) (*types.GraphData, error) { + return r.graph, nil +} + +type entityKnowledgeRepo struct { + interfaces.KnowledgeRepository + knowledge map[string]*types.Knowledge +} + +func (r *entityKnowledgeRepo) GetKnowledgeBatchByIDOnly(_ context.Context, ids []string) ([]*types.Knowledge, error) { + var out []*types.Knowledge + for _, id := range ids { + if k := r.knowledge[id]; k != nil { + out = append(out, k) + } + } + return out, nil +} + +// Graph hits resolve across workspaces for the KBs in scope, never outside +// them, and a chunk whose document is gone is skipped instead of panicking. +func TestSearchEntityResolvesSharedChunksWithinScope(t *testing.T) { + plugin := &PluginSearchEntity{ + graphRepo: &entityGraphRepo{graph: &types.GraphData{Node: []*types.GraphNode{ + {Name: "Docker", Chunks: []string{"shared", "outside", "orphan"}}, + }}}, + chunkRepo: &expandChunkRepo{chunks: map[string]*types.Chunk{ + "shared": entityChunk("shared", 2, "kb-shared", "doc"), + "outside": entityChunk("outside", 3, "kb-other", "doc-x"), + "orphan": entityChunk("orphan", 2, "kb-shared", "gone"), + }}, + knowledgeRepo: &entityKnowledgeRepo{knowledge: map[string]*types.Knowledge{ + "doc": {ID: "doc", KnowledgeBaseID: "kb-shared", Title: "Shared doc"}, + "doc-x": {ID: "doc-x", KnowledgeBaseID: "kb-other", Title: "Other"}, + }}, + } + cm := &types.ChatManage{PipelineState: types.PipelineState{ + Entity: []string{"Docker"}, EntityKBIDs: []string{"kb-shared"}, + }} + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) + + if err := plugin.OnEvent(ctx, types.ENTITY_SEARCH, cm, func() *PluginError { return nil }); err != nil { + t.Fatalf("OnEvent: %v", err) + } + if len(cm.SearchResult) != 1 || cm.SearchResult[0].ID != "shared" || + cm.SearchResult[0].KnowledgeTitle != "Shared doc" { + t.Fatalf("entity results = %+v", cm.SearchResult) + } +} + +func entityChunk(id string, tenantID uint64, kbID, knowledgeID string) *types.Chunk { + return &types.Chunk{ + ID: id, TenantID: tenantID, KnowledgeBaseID: kbID, KnowledgeID: knowledgeID, IsEnabled: true, Content: id, + } +} diff --git a/internal/application/service/chat_pipeline/web_fetch.go b/internal/application/service/chat_pipeline/web_fetch.go index ccd20867..4ef1efeb 100644 --- a/internal/application/service/chat_pipeline/web_fetch.go +++ b/internal/application/service/chat_pipeline/web_fetch.go @@ -96,10 +96,11 @@ func (p *PluginWebFetch) OnEvent( if fr.content == "" { continue } - // Truncate to reasonable size for LLM context + // Truncate to reasonable size for LLM context. Cut on a rune + // boundary: slicing bytes split multi-byte characters. content := fr.content - if len(content) > 8000 { - content = content[:8000] + "\n...(truncated)" + if runes := []rune(content); len(runes) > webFetchMaxRunes { + content = string(runes[:webFetchMaxRunes]) + "\n...(truncated)" } webResults[fr.idx].Content = content fetchedCount++ @@ -111,3 +112,6 @@ func (p *PluginWebFetch) OnEvent( }) return next() } + +// webFetchMaxRunes caps the fetched page text kept per web result. +const webFetchMaxRunes = 8000 diff --git a/internal/application/service/image_multimodal.go b/internal/application/service/image_multimodal.go index bd873440..67b9fc4e 100644 --- a/internal/application/service/image_multimodal.go +++ b/internal/application/service/image_multimodal.go @@ -497,6 +497,10 @@ func (s *ImageMultimodalService) indexChunks(ctx context.Context, payload types. ChunkID: chunk.ID, KnowledgeID: chunk.KnowledgeID, KnowledgeBaseID: chunk.KnowledgeBaseID, + // Engines other than Postgres store the zero value verbatim and + // filter on is_enabled = true, so leaving this unset made OCR and + // caption chunks unsearchable there. + IsEnabled: chunk.IsEnabled, }) } diff --git a/internal/application/service/knowledge_faq.go b/internal/application/service/knowledge_faq.go index 1331f6ef..01e288fe 100644 --- a/internal/application/service/knowledge_faq.go +++ b/internal/application/service/knowledge_faq.go @@ -423,29 +423,12 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context, return nil, err } } else { - // Combined 模式或首次创建,使用全量索引 - // 增量删除:只删除被移除的相似问索引 - oldSimilarQuestionCount := len(oldSimilarQuestions) - newSimilarQuestionCount := len(meta.SimilarQuestions) - if questionIndexMode == types.FAQQuestionIndexModeSeparate && oldSimilarQuestionCount > newSimilarQuestionCount { - retrieveEngine, engineErr := retriever.CreateRetrieveEngineForKB( - ctx, s.retrieveEngine, s.ownership, types.MustTenantIDFromContext(ctx), kb.VectorStoreID) - if engineErr == nil { - sourceIDsToDelete := make([]string, 0, oldSimilarQuestionCount-newSimilarQuestionCount) - for i := newSimilarQuestionCount; i < oldSimilarQuestionCount; i++ { - sourceIDsToDelete = append(sourceIDsToDelete, fmt.Sprintf("%s-%d", chunk.ID, i)) - } - if len(sourceIDsToDelete) > 0 { - logger.Debugf(ctx, "UpdateFAQEntry: incremental delete %d obsolete source IDs", len(sourceIDsToDelete)) - if delErr := retrieveEngine.DeleteBySourceIDList(ctx, sourceIDsToDelete, embeddingModel.GetDimensions(), types.KnowledgeTypeFAQ); delErr != nil { - logger.Warnf(ctx, "UpdateFAQEntry: failed to delete obsolete source IDs: %v", delErr) - } - } - } - } - - // 使用 needDelete=false,因为 EFPutDocument 会自动覆盖相同 SourceID 的文档 - if err := s.indexFAQChunks(ctx, kb, faqKnowledge, []*types.Chunk{chunk}, embeddingModel, false, false); err != nil { + // Combined 模式或首次创建,使用全量索引。needDelete=true 按 chunk + // 删除该条目的全部旧索引(含已移除的相似问),再整体重建。 + // 同一 SourceID 重建索引并非所有引擎都会覆盖(ES v8、Qdrant 每次写入 + // 生成新文档 ID),不先删会留下过期内容。 + err := s.indexFAQChunks(ctx, kb, faqKnowledge, []*types.Chunk{chunk}, embeddingModel, false, true) + if err != nil { return nil, err } } @@ -599,8 +582,10 @@ func (s *knowledgeService) AddSimilarQuestions(ctx context.Context, return nil, err } } else { - // Combined mode, re-index the whole entry - if err := s.indexFAQChunks(ctx, kb, faqKnowledge, []*types.Chunk{chunk}, embeddingModel, false, false); err != nil { + // Combined mode, re-index the whole entry. Delete first: not every + // engine overwrites an existing SourceID on re-index. + err := s.indexFAQChunks(ctx, kb, faqKnowledge, []*types.Chunk{chunk}, embeddingModel, false, true) + if err != nil { return nil, err } } diff --git a/internal/application/service/knowledge_faq_import.go b/internal/application/service/knowledge_faq_import.go index ec4b2c1d..6bcdd5bb 100644 --- a/internal/application/service/knowledge_faq_import.go +++ b/internal/application/service/knowledge_faq_import.go @@ -1975,7 +1975,12 @@ func (s *knowledgeService) incrementalIndexFAQEntry( logger.Debugf(ctx, "incrementalIndexFAQEntry: updated similar questions (answers changed): %v", updatedQuestions) } - // 3. 删除不再存在的相似问索引 + // 3. 删除不再存在的相似问索引,以及即将重建的旧索引。 + // 不能依赖 BatchIndex 覆盖同一 SourceID:ES v8、Qdrant 等引擎每次写入 + // 生成新文档 ID,不先删会留下内容过期的重复条目。 + for _, info := range indexInfoToUpdate { + sourceIDsToDelete = append(sourceIDsToDelete, info.SourceID) + } if len(sourceIDsToDelete) > 0 { logger.Debugf(ctx, "incrementalIndexFAQEntry: deleting %d obsolete sourceIDs: %v", len(sourceIDsToDelete), sourceIDsToDelete) if delErr := retrieveEngine.DeleteBySourceIDList(ctx, sourceIDsToDelete, embeddingModel.GetDimensions(), types.KnowledgeTypeFAQ); delErr != nil { @@ -2675,8 +2680,8 @@ func (s *knowledgeService) executeFAQMergeOperations( return mergedCount, fmt.Errorf("failed to batch save merged chunks: %w", err) } - // 4. 重建索引(EFPutDocument 会自动覆盖相同 SourceID) - if err := s.indexFAQChunks(ctx, kb, faqKnowledge, mergedChunks, embeddingModel, false, false); err != nil { + // 4. 重建索引。先删旧索引:ES v8、Qdrant 等引擎不会覆盖相同 SourceID。 + if err := s.indexFAQChunks(ctx, kb, faqKnowledge, mergedChunks, embeddingModel, false, true); err != nil { return mergedCount, fmt.Errorf("failed to re-index merged chunks: %w", err) } diff --git a/internal/application/service/knowledge_shared_storage_failure_test.go b/internal/application/service/knowledge_shared_storage_failure_test.go index cac55cc1..5d91944a 100644 --- a/internal/application/service/knowledge_shared_storage_failure_test.go +++ b/internal/application/service/knowledge_shared_storage_failure_test.go @@ -24,6 +24,15 @@ func (r *failingSharedKnowledgeRepo) GetKnowledgeByIDOnly(context.Context, strin return nil, r.err } +// GetKnowledgeBatchByIDOnly mirrors a batch query: a missing row is simply +// absent, while a storage failure is an error. +func (r *failingSharedKnowledgeRepo) GetKnowledgeBatchByIDOnly(context.Context, []string) ([]*types.Knowledge, error) { + if errors.Is(r.err, repository.ErrKnowledgeNotFound) { + return nil, nil + } + return nil, r.err +} + func TestSharedDocumentReadsPropagateStorageFailure(t *testing.T) { for _, failure := range []error{errors.New("database unavailable"), repository.ErrKnowledgeNotFound} { repo := &failingSharedKnowledgeRepo{err: failure} diff --git a/internal/application/service/knowledgebase_search.go b/internal/application/service/knowledgebase_search.go index bc03d388..18462f27 100644 --- a/internal/application/service/knowledgebase_search.go +++ b/internal/application/service/knowledgebase_search.go @@ -225,10 +225,18 @@ func (s *knowledgeBaseService) hybridSearchCandidates(ctx context.Context, // Skip when params already carries an embedding (e.g. the agent // pre-computed it) or when the primary KB has no vector indexing // configured. - if len(params.QueryEmbedding) == 0 && - kb.IsVectorEnabled() && kb.EmbeddingModelID != "" && - !params.DisableVectorMatch { - emb, embErr := s.GetQueryEmbedding(ctx, kb.ID, params.QueryText) + embeddingKB := kb + if !hasEmbeddingModel(embeddingKB) { + embeddingKB = nil + for _, candidate := range kbs { + if hasEmbeddingModel(candidate) { + embeddingKB = candidate + break + } + } + } + if len(params.QueryEmbedding) == 0 && embeddingKB != nil && !params.DisableVectorMatch { + emb, embErr := s.GetQueryEmbedding(ctx, embeddingKB.ID, params.QueryText) if embErr != nil { return nil, embErr } @@ -285,7 +293,8 @@ func (s *knowledgeBaseService) hybridSearchCandidates(ctx context.Context, } // Separate and fuse retrieval results. - vectorResults, keywordResults := classifyRetrievalResults(ctx, retrieveResults) + vectorLists, keywordLists := classifyRetrievalResults(ctx, retrieveResults) + vectorResults, keywordResults := flattenLists(vectorLists), flattenLists(keywordLists) if len(vectorResults) == 0 && len(keywordResults) == 0 { logger.Info(ctx, "No search results found") return nil, nil @@ -297,7 +306,7 @@ func (s *knowledgeBaseService) hybridSearchCandidates(ctx context.Context, if tenantInfo != nil { retrievalCfg = tenantInfo.RetrievalConfig } - deduplicatedChunks := fuseOrDeduplicate(ctx, vectorResults, keywordResults, retrievalCfg) + deduplicatedChunks := fuseOrDeduplicate(ctx, vectorLists, keywordLists, retrievalCfg) kb.EnsureDefaults() @@ -307,7 +316,7 @@ func (s *knowledgeBaseService) hybridSearchCandidates(ctx context.Context, // timeout surfaced as ErrVectorStoreUnavailable) must surface to the // caller rather than be silently converted to a truncated chunk list. return s.applyFAQPostProcessing( - ctx, kb, deduplicatedChunks, vectorResults, groups, params, matchCount) + ctx, kb, kbs, deduplicatedChunks, vectorLists, groups, params, matchCount) } // normalizedMatchCount resolves the effective primary-match cap for a search. @@ -328,7 +337,17 @@ func normalizedMatchCount(requested int) int { if requested <= 0 { return types.DefaultRetrievalTopK } - return requested + // A search never returns more than the pool it draws from, so capping here + // changes no result; it keeps the over-retrieval arithmetic + // (MatchCount*5*len(KBs), the FAQ path's MatchCount*3) from overflowing + // into a negative TopK on absurd input. + return min(requested, maxRetrievalPoolSize) +} + +// hasEmbeddingModel reports whether kb is vector-indexed with a configured +// embedding model, i.e. whether it can embed a query for vector retrieval. +func hasEmbeddingModel(kb *types.KnowledgeBase) bool { + return kb != nil && kb.IsVectorEnabled() && kb.EmbeddingModelID != "" } // pickPrimary returns the KB whose ID matches id, or nil if id is not in @@ -409,8 +428,19 @@ func (s *knowledgeBaseService) buildRetrievalParams( // scope happens to include them (e.g. KBSelectionMode=all picking up a // wiki-only KB). var faqVectorKBIDs, docVectorKBIDs, docKeywordKBIDs []string + // The query is embedded with the primary's model, or with the first + // vector KB of the group when the primary has none (a wiki primary + // searched together with document KBs): asking the primary for its empty + // model ID failed the whole search. + embeddingKB := primary + if !hasEmbeddingModel(primary) { + embeddingKB = nil + } for _, kb := range groupKBs { - if kb.IsVectorEnabled() && kb.EmbeddingModelID != "" { + if hasEmbeddingModel(kb) { + if embeddingKB == nil { + embeddingKB = kb + } if kb.Type == types.KnowledgeBaseTypeFAQ { faqVectorKBIDs = append(faqVectorKBIDs, kb.ID) } else { @@ -430,7 +460,7 @@ func (s *knowledgeBaseService) buildRetrievalParams( (len(faqVectorKBIDs) > 0 || len(docVectorKBIDs) > 0) { logger.Info(ctx, "Vector retrieval supported, preparing vector retrieval parameters") - queryEmbedding, err := s.resolveQueryEmbedding(ctx, primary, params, currentTenantID) + queryEmbedding, err := s.resolveQueryEmbedding(ctx, embeddingKB, params, currentTenantID) if err != nil { return nil, err } diff --git a/internal/application/service/knowledgebase_search_embedding_kb_test.go b/internal/application/service/knowledgebase_search_embedding_kb_test.go new file mode 100644 index 00000000..f9540ff2 --- /dev/null +++ b/internal/application/service/knowledgebase_search_embedding_kb_test.go @@ -0,0 +1,46 @@ +package service + +import ( + "context" + "testing" + + "github.com/Tencent/WeKnora/internal/models/embedding" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/stretchr/testify/require" +) + +type recordingEmbeddingModelService struct { + interfaces.ModelService + requested []string +} + +func (s *recordingEmbeddingModelService) GetEmbeddingModel(_ context.Context, id string) (embedding.Embedder, error) { + s.requested = append(s.requested, id) + return dimensionTestEmbedder{dimensions: 768}, nil +} + +// A wiki primary has no embedding model. Searched together with a document +// KB, the query used to be embedded with the primary's empty model ID and +// the whole search failed; it is now embedded with the vector KB's model. +func TestBuildRetrievalParamsEmbedsWithAVectorKB(t *testing.T) { + models := &recordingEmbeddingModelService{} + s := &knowledgeBaseService{modelService: models} + engine := buildBoundComposite(t, &fakeRetrieveEngineService{ + engineType: types.PostgresRetrieverEngineType, + support: []types.RetrieverType{types.VectorRetrieverType}, + }) + wiki := &types.KnowledgeBase{ID: "kb-wiki", TenantID: 1} + docs := &types.KnowledgeBase{ + ID: "kb-docs", TenantID: 1, EmbeddingModelID: "embed-1", + IndexingStrategy: types.IndexingStrategy{VectorEnabled: true}, + } + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) + + params, err := s.buildRetrievalParams(ctx, engine, wiki, []*types.KnowledgeBase{wiki, docs}, + types.SearchParams{QueryText: "q"}, 50) + require.NoError(t, err) + require.Equal(t, []string{"embed-1"}, models.requested) + require.NotEmpty(t, params) + require.Len(t, params[0].Embedding, 768) +} diff --git a/internal/application/service/knowledgebase_search_fanout_test.go b/internal/application/service/knowledgebase_search_fanout_test.go index 79bbd3ee..35031e05 100644 --- a/internal/application/service/knowledgebase_search_fanout_test.go +++ b/internal/application/service/knowledgebase_search_fanout_test.go @@ -587,18 +587,10 @@ func TestRetrieveFromStores_MultiGroupParallel_Concat(t *testing.T) { func TestRetrieveFromStores_MixedEngine_Normalizes(t *testing.T) { t.Parallel() - // EngineAwareNormalizer policy in effect: - // - ES / ElasticFaiss / OpenSearch / Weaviate / Postgres / SQLite / - // Qdrant / TencentVectorDB / Doris surface non-negative cosine in - // [0, 1] when the value reaches the normalizer (Lucene script_score - // non-negative invariant for ES; k-NN plugin SpaceType.COSINESIMIL - // pre-translation for OpenSearch; engine-internal conversions for - // the rest) → passthrough via clamp01. - // - Milvus is the only engine in this codebase that still surfaces - // the raw signed cosine in [-1, 1] → cosine-shift via (score + 1) / 2. - // - // First sub-case below pins the ES passthrough; the Milvus sub-case - // pins the cosine-shift path so the [-1, 1] branch stays under coverage. + // EngineAwareNormalizer policy in effect: every driver reports cosine + // similarity (OpenSearch / Weaviate / Milvus L2 convert in the driver), + // so vector scores pass through clamp01, which only floors a negative + // cosine at 0 and guards NaN/Inf. fakeES := &fakeRetrieveEngineService{ engineType: types.ElasticsearchRetrieverEngineType, support: []types.RetrieverType{types.VectorRetrieverType}, @@ -657,14 +649,16 @@ func TestRetrieveFromStores_MixedEngine_Normalizes(t *testing.T) { assert.InDelta(t, 0.3, scoresByChunk2["es2"], 1e-9) assert.InDelta(t, 0.8, scoresByChunk2["pg2"], 1e-9) - // Milvus cosine-shift coverage: raw -0.4 → (−0.4 + 1) / 2 = 0.3. - // Milvus is now the only engine in this switch that still uses the - // signed-cosine branch; without this case the [-1, 1] arm would be - // uncovered by the mixed-engine integration test. + // Milvus reports cosine like every other engine: 0.3 stays 0.3 (it used + // to be shifted to (0.3 + 1) / 2 = 0.65 and out-rank a PG hit at 0.6), + // and a negative cosine is floored at 0. fakeMilvus := &fakeRetrieveEngineService{ engineType: types.MilvusRetrieverEngineType, support: []types.RetrieverType{types.VectorRetrieverType}, - canned: []*types.IndexWithScore{{ChunkID: "mv1", Score: -0.4}}, + canned: []*types.IndexWithScore{ + {ChunkID: "mv1", Score: 0.3}, + {ChunkID: "mv2", Score: -0.4}, + }, } fakePG3 := &fakeRetrieveEngineService{ engineType: types.PostgresRetrieverEngineType, @@ -684,6 +678,7 @@ func TestRetrieveFromStores_MixedEngine_Normalizes(t *testing.T) { } } assert.InDelta(t, 0.3, scoresByChunk3["mv1"], 1e-9) + assert.InDelta(t, 0.0, scoresByChunk3["mv2"], 1e-9) assert.InDelta(t, 0.8, scoresByChunk3["pg3"], 1e-9) } @@ -890,7 +885,7 @@ func TestIterativeRetrieve_PropagatesTypedAppError(t *testing.T) { } s := &knowledgeBaseService{} ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) - results, err := s.iterativeRetrieveWithDeduplication(ctx, groups, 10, "q") + results, err := s.iterativeRetrieveWithDeduplication(ctx, groups, 10, "q", 50) require.Error(t, err) assert.Nil(t, results, "results must be nil so HybridSearch returns a clean error response") app, ok := apperrors.IsAppError(err) @@ -928,7 +923,8 @@ func TestApplyFAQPostProcessing_PropagatesError(t *testing.T) { vectorResults[i] = &types.IndexWithScore{ChunkID: fmt.Sprintf("v%d", i)} } params := types.SearchParams{QueryText: "q", MatchCount: 10} - out, err := s.applyFAQPostProcessing(ctx, kb, chunks, vectorResults, groups, params, 5) + vectorLists := [][]*types.IndexWithScore{vectorResults} + out, err := s.applyFAQPostProcessing(ctx, kb, []*types.KnowledgeBase{kb}, chunks, vectorLists, groups, params, 5) require.Error(t, err) assert.Nil(t, out) _, ok := apperrors.IsAppError(err) @@ -1004,3 +1000,41 @@ func TestRetrieveFromStores_IterativePattern_NoInternalRace(t *testing.T) { assert.Equal(t, 50, g.BaseParams[0].TopK, "BaseParams TopK must stay immutable") } } + +// The iterative FAQ path triggers when one vector list came back full, judged +// per list: two short lists that together exceed matchCount must not trigger +// it, and one full list must. The failing engine makes the iterative path +// observable through its error. +func TestApplyFAQPostProcessing_TriggerJudgesEachList(t *testing.T) { + t.Parallel() + bad := &fakeRetrieveEngineService{ + engineType: types.PostgresRetrieverEngineType, + support: []types.RetrieverType{types.VectorRetrieverType}, + cannedErr: stderrors.New("simulated retrieve failure"), + } + groups := []*storeGroup{ + {Engine: buildBoundComposite(t, bad), BaseParams: vectorParams("q"), TopK: 5, KBIDs: []string{"kb-a"}}, + {Engine: buildBoundComposite(t, bad), BaseParams: vectorParams("q"), TopK: 5, KBIDs: []string{"kb-b"}}, + } + s := &knowledgeBaseService{chunkRepo: &tenantScopedFAQChunkRepo{}} + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) + kb := &types.KnowledgeBase{ID: "kb-a", Type: types.KnowledgeBaseTypeFAQ, TenantID: 1} + chunks := []*types.IndexWithScore{{ChunkID: "c1", Score: 0.5}} + params := types.SearchParams{QueryText: "q", MatchCount: 10} + list := func(n int, prefix string) []*types.IndexWithScore { + out := make([]*types.IndexWithScore, n) + for i := range out { + out[i] = &types.IndexWithScore{ChunkID: fmt.Sprintf("%s%d", prefix, i)} + } + return out + } + + short := [][]*types.IndexWithScore{list(3, "a"), list(3, "b")} + out, err := s.applyFAQPostProcessing(ctx, kb, []*types.KnowledgeBase{kb}, chunks, short, groups, params, 5) + require.NoError(t, err, "no list is full, so no deeper search") + assert.Equal(t, chunks, out) + + full := [][]*types.IndexWithScore{list(5, "a"), list(1, "b")} + _, err = s.applyFAQPostProcessing(ctx, kb, []*types.KnowledgeBase{kb}, chunks, full, groups, params, 5) + require.Error(t, err, "a full list must trigger the iterative path") +} diff --git a/internal/application/service/knowledgebase_search_faq.go b/internal/application/service/knowledgebase_search_faq.go index e6f28a6f..cb9aa920 100644 --- a/internal/application/service/knowledgebase_search_faq.go +++ b/internal/application/service/knowledgebase_search_faq.go @@ -13,7 +13,10 @@ import ( // applyFAQPostProcessing handles FAQ-specific post-processing: iterative retrieval // when not enough unique chunks are found, or negative question filtering otherwise. -// For non-FAQ knowledge bases, returns the input unchanged. +// Iterative retrieval follows the primary KB's type; negative questions are +// filtered whenever any KB in scope is an FAQ KB, so an FAQ searched alongside +// a document KB still honours them. Without an FAQ KB in scope the input is +// returned unchanged. // // The iterative retrieval path fans out across the supplied storeGroups so // multi-store FAQ searches grow TopK uniformly across every bound vector @@ -24,20 +27,28 @@ import ( func (s *knowledgeBaseService) applyFAQPostProcessing( ctx context.Context, kb *types.KnowledgeBase, + scopeKBs []*types.KnowledgeBase, chunks []*types.IndexWithScore, - vectorResults []*types.IndexWithScore, + vectorLists [][]*types.IndexWithScore, groups []*storeGroup, params types.SearchParams, matchCount int, ) ([]*types.IndexWithScore, error) { - if kb.Type != types.KnowledgeBaseTypeFAQ { + isFAQ := func(k *types.KnowledgeBase) bool { return k != nil && k.Type == types.KnowledgeBaseTypeFAQ } + if !isFAQ(kb) && !slices.ContainsFunc(scopeKBs, isFAQ) { return chunks, nil } // Check if we need iterative retrieval for FAQ with separate indexing. // Only use iterative retrieval if we don't have enough unique chunks - // after first deduplication. - needsIterativeRetrieval := len(chunks) < params.MatchCount && len(vectorResults) == matchCount + // after first deduplication, some vector list came back full (so a + // deeper search can find more), and the depth can still grow. A full + // list is judged per list: the concatenation of several lists is larger + // than matchCount whenever more than one vector list exists, which kept + // this from ever triggering in multi-list searches. + listFull := slices.ContainsFunc(vectorLists, func(l []*types.IndexWithScore) bool { return len(l) >= matchCount }) + needsIterativeRetrieval := isFAQ(kb) && len(chunks) < params.MatchCount && listFull && + matchCount < maxRetrievalPoolSize if needsIterativeRetrieval { logger.Info(ctx, "Not enough unique chunks, using iterative retrieval for FAQ") return s.iterativeRetrieveWithDeduplication( @@ -45,11 +56,18 @@ func (s *knowledgeBaseService) applyFAQPostProcessing( groups, params.MatchCount, params.QueryText, + matchCount, ) } // Filter by negative questions if not using iterative retrieval. - result := s.filterByNegativeQuestions(ctx, chunks, params.QueryText) + faqKBIDs := make(map[string]bool) + for _, k := range append([]*types.KnowledgeBase{kb}, scopeKBs...) { + if isFAQ(k) { + faqKBIDs[k.ID] = true + } + } + result := s.filterByNegativeQuestions(ctx, chunks, params.QueryText, faqKBIDs) logger.Infof(ctx, "Result count after negative question filtering: %d", len(result)) return result, nil } @@ -58,6 +76,12 @@ func (s *knowledgeBaseService) applyFAQPostProcessing( // This is used for FAQ knowledge bases with separate indexing mode. // Negative question filtering is applied after each iteration with chunk data caching. // +// Each round searches twice as deep as the one before, starting at twice +// initialDepth (the depth the first search already used), and fuses its +// lists exactly like the first search (fuseOrDeduplicate), so the scores it +// returns are on the same scale. A deeper round returns a superset of the +// previous one, so each round's fused list replaces the last. +// // Each iteration only updates group.TopK; the underlying BaseParams stays // immutable so the fan-out goroutines inside retrieveFromStores never // observe a mid-mutation slice. Engines and grouping are computed once @@ -74,15 +98,14 @@ func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Co groups []*storeGroup, matchCount int, queryText string, + initialDepth int, ) ([]*types.IndexWithScore, error) { maxIterations := 5 - // Start with a larger TopK since we're called when first retrieval wasn't enough - // The first retrieval already used matchCount*3, so start from there. // matchCount is caller-supplied, so both the seed and the per-iteration // doubling are bounded by maxRetrievalPoolSize — otherwise a single request // could drive the vector-store query depth arbitrarily deep. - currentTopK := min(matchCount*3, maxRetrievalPoolSize) - uniqueChunks := make(map[string]*types.IndexWithScore) + currentTopK := min(max(matchCount*3, initialDepth*2), maxRetrievalPoolSize) + var uniqueChunks []*types.IndexWithScore // Cache chunk data to avoid repeated DB queries across iterations chunkDataCache := make(map[string]*types.Chunk) // Track chunks that have been filtered out by negative questions @@ -90,6 +113,10 @@ func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Co queryTextLower := strings.ToLower(strings.TrimSpace(queryText)) tenantID := types.MustTenantIDFromContext(ctx) + var retrievalCfg *types.RetrievalConfig + if tenantInfo, _ := types.TenantInfoFromContext(ctx); tenantInfo != nil { + retrievalCfg = tenantInfo.RetrievalConfig + } for i := 0; i < maxIterations; i++ { // Bump only the per-group TopK. BaseParams is immutable and read @@ -119,22 +146,20 @@ func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Co break } - // Collect results - iterationResults := []*types.IndexWithScore{} - for _, retrieveResult := range retrieveResults { - iterationResults = append(iterationResults, retrieveResult.Results...) - } - - if len(iterationResults) == 0 { + vectorLists, keywordLists := classifyRetrievalResults(ctx, retrieveResults) + if len(vectorLists) == 0 && len(keywordLists) == 0 { logger.Infof(ctx, "No results found at iteration %d", i+1) break } - - totalRetrieved := len(iterationResults) + // A list shorter than the requested depth is exhausted; when every + // list is, searching deeper cannot find anything new. + exhausted := !slices.ContainsFunc(append(vectorLists, keywordLists...), + func(l []*types.IndexWithScore) bool { return len(l) >= currentTopK }) + fused := fuseOrDeduplicate(ctx, vectorLists, keywordLists, retrievalCfg) // Collect new chunk IDs that need to be fetched from DB newChunkIDs := make([]string, 0) - for _, result := range iterationResults { + for _, result := range fused { if _, cached := chunkDataCache[result.ChunkID]; !cached { if _, filtered := filteredOutChunks[result.ChunkID]; !filtered { newChunkIDs = append(newChunkIDs, result.ChunkID) @@ -144,7 +169,7 @@ func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Co // Batch fetch only new chunks if len(newChunkIDs) > 0 { - newChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, newChunkIDs) + newChunks, err := s.listChunksByIDWithShared(ctx, tenantID, newChunkIDs) if err != nil { logger.Warnf(ctx, "Failed to fetch chunks at iteration %d: %v", i+1, err) } else { @@ -154,37 +179,27 @@ func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Co } } - // Deduplicate, merge, and filter in one pass - for _, result := range iterationResults { - // Skip if already filtered out + // Filter negative questions using cached data + uniqueChunks = uniqueChunks[:0] + for _, result := range fused { if _, filtered := filteredOutChunks[result.ChunkID]; filtered { continue } - - // Check negative questions using cached data - if chunkData, ok := chunkDataCache[result.ChunkID]; ok { - if chunkData.ChunkType == types.ChunkTypeFAQ { - if meta, err := chunkData.FAQMetadata(); err == nil && meta != nil { - if s.matchesNegativeQuestions(queryTextLower, meta.NegativeQuestions) { - filteredOutChunks[result.ChunkID] = struct{}{} - delete(uniqueChunks, result.ChunkID) - continue - } - } + if chunkData, ok := chunkDataCache[result.ChunkID]; ok && chunkData.ChunkType == types.ChunkTypeFAQ { + if meta, err := chunkData.FAQMetadata(); err == nil && meta != nil && + s.matchesNegativeQuestions(queryTextLower, meta.NegativeQuestions) { + filteredOutChunks[result.ChunkID] = struct{}{} + continue } } - - // Keep highest score for each chunk - if existing, ok := uniqueChunks[result.ChunkID]; !ok || result.Score > existing.Score { - uniqueChunks[result.ChunkID] = result - } + uniqueChunks = append(uniqueChunks, result) } logger.Infof( ctx, - "After iteration %d: retrieved %d results, found %d valid unique chunks (target: %d)", + "After iteration %d: depth %d, found %d valid unique chunks (target: %d)", i+1, - totalRetrieved, + currentTopK, len(uniqueChunks), matchCount, ) @@ -195,9 +210,9 @@ func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Co break } - // Early stop: If we got fewer results than TopK, there are no more results to retrieve - if totalRetrieved < currentTopK { - logger.Infof(ctx, "No more results available (got %d < %d), stopping iteration", totalRetrieved, currentTopK) + // Early stop: If every list came back short, there are no more results to retrieve + if exhausted { + logger.Infof(ctx, "No more results available at depth %d, stopping iteration", currentTopK) break } @@ -210,22 +225,18 @@ func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Co currentTopK = min(currentTopK*2, maxRetrievalPoolSize) } - // Convert map to slice and sort by score - result := make([]*types.IndexWithScore, 0, len(uniqueChunks)) - for _, chunk := range uniqueChunks { - result = append(result, chunk) - } - - slices.SortFunc(result, sortByScoreDesc) - - logger.Infof(ctx, "Iterative retrieval completed: %d unique chunks found after filtering", len(result)) - return result, nil + logger.Infof(ctx, "Iterative retrieval completed: %d unique chunks found after filtering", len(uniqueChunks)) + return uniqueChunks, nil } // filterByNegativeQuestions filters out chunks that match negative questions for FAQ knowledge bases. +// Only candidates of the FAQ knowledge bases in faqKBIDs (or of an unknown +// knowledge base) are looked up; document chunks in a mixed scope cannot carry +// negative questions and are kept without loading their rows. func (s *knowledgeBaseService) filterByNegativeQuestions(ctx context.Context, chunks []*types.IndexWithScore, queryText string, + faqKBIDs map[string]bool, ) []*types.IndexWithScore { if len(chunks) == 0 { return chunks @@ -241,11 +252,18 @@ func (s *knowledgeBaseService) filterByNegativeQuestions(ctx context.Context, // Collect chunk IDs chunkIDs := make([]string, 0, len(chunks)) for _, chunk := range chunks { - chunkIDs = append(chunkIDs, chunk.ChunkID) + if chunk.KnowledgeBaseID == "" || faqKBIDs[chunk.KnowledgeBaseID] { + chunkIDs = append(chunkIDs, chunk.ChunkID) + } + } + if len(chunkIDs) == 0 { + return chunks } - // Batch fetch chunks to get negative questions - allChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs) + // Batch fetch chunks to get negative questions. Shared-KB chunks belong to + // the sharing workspace; a tenant-scoped lookup missed them and the + // "not found, keep it" branch below let them bypass the filter. + allChunks, err := s.listChunksByIDWithShared(ctx, tenantID, chunkIDs) if err != nil { logger.Warnf(ctx, "Failed to fetch chunks for negative question filtering: %v", err) // If we can't fetch chunks, return original results @@ -263,7 +281,7 @@ func (s *knowledgeBaseService) filterByNegativeQuestions(ctx context.Context, for _, chunk := range chunks { chunkData, ok := chunkMap[chunk.ChunkID] if !ok { - // If chunk not found, keep it (shouldn't happen, but be safe) + // Not an FAQ candidate (not looked up), or not found: keep it filteredChunks = append(filteredChunks, chunk) continue } diff --git a/internal/application/service/knowledgebase_search_faq_negative_test.go b/internal/application/service/knowledgebase_search_faq_negative_test.go new file mode 100644 index 00000000..83e157b9 --- /dev/null +++ b/internal/application/service/knowledgebase_search_faq_negative_test.go @@ -0,0 +1,96 @@ +package service + +import ( + "context" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/stretchr/testify/require" +) + +// tenantScopedFAQChunkRepo mimics the SQL repository: ListChunksByID filters +// on the caller's tenant, ListChunksByIDOnly does not. +type tenantScopedFAQChunkRepo struct { + interfaces.ChunkRepository + chunks map[string]*types.Chunk +} + +func (r *tenantScopedFAQChunkRepo) ListChunksByID( + _ context.Context, tenantID uint64, ids []string, +) ([]*types.Chunk, error) { + var out []*types.Chunk + for _, id := range ids { + if c := r.chunks[id]; c != nil && c.TenantID == tenantID { + out = append(out, c) + } + } + return out, nil +} + +func (r *tenantScopedFAQChunkRepo) ListChunksByIDOnly(_ context.Context, ids []string) ([]*types.Chunk, error) { + var out []*types.Chunk + for _, id := range ids { + if c := r.chunks[id]; c != nil { + out = append(out, c) + } + } + return out, nil +} + +func faqChunkWithNegative(t *testing.T, id string, tenantID uint64, kbID, negative string) *types.Chunk { + t.Helper() + c := &types.Chunk{ID: id, TenantID: tenantID, KnowledgeBaseID: kbID, ChunkType: types.ChunkTypeFAQ} + require.NoError(t, c.SetFAQMetadata(&types.FAQChunkMetadata{ + StandardQuestion: "How do refunds work?", + Answers: []string{"Within 7 days."}, + NegativeQuestions: []string{negative}, + })) + return c +} + +// An FAQ KB searched together with a document KB (document KB primary), and +// an FAQ KB shared from another workspace, must both honour negative +// questions. Before, the filter ran only when the primary KB was an FAQ KB and +// looked chunks up in the caller's workspace only; a chunk it could not find +// was kept. +func TestApplyFAQPostProcessingFiltersNegativeQuestionsAcrossScope(t *testing.T) { + repo := &tenantScopedFAQChunkRepo{chunks: map[string]*types.Chunk{ + "own-faq": faqChunkWithNegative(t, "own-faq", 1, "kb-faq", "refund for gift cards"), + "shared-faq": faqChunkWithNegative(t, "shared-faq", 2, "kb-shared-faq", "refund for gift cards"), + "doc": {ID: "doc", TenantID: 1, KnowledgeBaseID: "kb-doc", ChunkType: types.ChunkTypeText}, + }} + s := &knowledgeBaseService{ + chunkRepo: repo, + kbShareService: &fakeKBShareService{allowedKBs: map[string]bool{"kb-shared-faq": true}}, + } + docKB := &types.KnowledgeBase{ID: "kb-doc", TenantID: 1, Type: types.KnowledgeBaseTypeDocument} + scope := []*types.KnowledgeBase{ + docKB, + {ID: "kb-faq", TenantID: 1, Type: types.KnowledgeBaseTypeFAQ}, + {ID: "kb-shared-faq", TenantID: 2, Type: types.KnowledgeBaseTypeFAQ}, + } + chunks := []*types.IndexWithScore{ + {ChunkID: "own-faq", Score: 0.9}, + {ChunkID: "shared-faq", Score: 0.8}, + {ChunkID: "doc", Score: 0.7}, + } + + out, err := s.applyFAQPostProcessing(newSharedAccessContext(), docKB, scope, chunks, nil, nil, + types.SearchParams{QueryText: "Refund for gift cards", MatchCount: 10}, 50) + require.NoError(t, err) + require.Len(t, out, 1) + require.Equal(t, "doc", out[0].ChunkID) +} + +func TestApplyFAQPostProcessingSkipsScopeWithoutFAQ(t *testing.T) { + s := &knowledgeBaseService{} + docKB := &types.KnowledgeBase{ID: "kb-doc", Type: types.KnowledgeBaseTypeDocument} + chunks := []*types.IndexWithScore{{ChunkID: "doc", Score: 0.7}} + + scope := []*types.KnowledgeBase{docKB} + out, err := s.applyFAQPostProcessing(newSharedAccessContext(), docKB, scope, chunks, nil, nil, + types.SearchParams{QueryText: "anything", MatchCount: 10}, 50) + require.NoError(t, err) + require.Equal(t, chunks, out) +} diff --git a/internal/application/service/knowledgebase_search_fusion.go b/internal/application/service/knowledgebase_search_fusion.go index b8870298..fe96a89c 100644 --- a/internal/application/service/knowledgebase_search_fusion.go +++ b/internal/application/service/knowledgebase_search_fusion.go @@ -9,9 +9,13 @@ import ( "github.com/Tencent/WeKnora/internal/types" ) -// classifyRetrievalResults separates retrieval results by retriever type (vector vs keyword). +// classifyRetrievalResults separates retrieval results by retriever type +// (vector vs keyword). Each RetrieveResult stays its own list: they come from +// different engines, store groups and parameter sets (document vs FAQ), are +// appended in goroutine completion order, and their positions are only +// meaningful within the list. func classifyRetrievalResults(ctx context.Context, retrieveResults []*types.RetrieveResult) ( - vectorResults, keywordResults []*types.IndexWithScore, + vectorLists, keywordLists [][]*types.IndexWithScore, ) { for _, retrieveResult := range retrieveResults { logger.Infof(ctx, "Retrieval results, engine: %v, retriever: %v, count: %v", @@ -19,35 +23,62 @@ func classifyRetrievalResults(ctx context.Context, retrieveResults []*types.Retr retrieveResult.RetrieverType, len(retrieveResult.Results), ) + if len(retrieveResult.Results) == 0 { + continue + } if retrieveResult.RetrieverType == types.VectorRetrieverType { - vectorResults = append(vectorResults, retrieveResult.Results...) + vectorLists = append(vectorLists, retrieveResult.Results) } else { - keywordResults = append(keywordResults, retrieveResult.Results...) + keywordLists = append(keywordLists, retrieveResult.Results) } } return } -// fuseOrDeduplicate either fuses vector+keyword results via RRF or deduplicates vector-only results. +// flattenLists concatenates retrieval lists. +func flattenLists(lists [][]*types.IndexWithScore) []*types.IndexWithScore { + var out []*types.IndexWithScore + for _, list := range lists { + out = append(out, list...) + } + return out +} + +// fuseOrDeduplicate either fuses vector+keyword results via RRF or deduplicates +// single-retriever results. Every path returns scores in [0, 1] so results of +// separate searches (per-document targets, embedding-model groups, FAQ vs +// document calls) can be ranked together downstream: +// - vector only: the engines' cosine similarity, unchanged (FAQ thresholds +// depend on it); +// - keyword only: BM25 divided by the best score of its own list; +// - hybrid: weighted RRF divided by its maximum (a chunk ranked first by +// both retrievers scores 1). +// // retrievalCfg may be nil — defaults are then used for RRF parameters. -func fuseOrDeduplicate(ctx context.Context, vectorResults, keywordResults []*types.IndexWithScore, retrievalCfg *types.RetrievalConfig) []*types.IndexWithScore { - if len(keywordResults) == 0 { +func fuseOrDeduplicate( + ctx context.Context, vectorLists, keywordLists [][]*types.IndexWithScore, retrievalCfg *types.RetrievalConfig, +) []*types.IndexWithScore { + if len(keywordLists) == 0 { // Vector-only: keep original embedding scores (important for FAQ) - result := deduplicateByScore(vectorResults) + result := deduplicateByScore(flattenLists(vectorLists)) logger.Infof(ctx, "Result count after deduplication: %d", len(result)) return result } - if len(vectorResults) == 0 { + if len(vectorLists) == 0 { // Keyword-only: keep relative BM25 order, but fold unbounded // scores into [0, 1] before they reach rerank/MMR. Raw BM25 - // (often >10) saturates compositeScore's 0.3*base term. - result := deduplicateByScore(keywordResults) - rescaleUnboundedScores(result) + // (often >10) saturates compositeScore's 0.3*base term. BM25 from + // different engines or indexes is not comparable, so each list is + // scaled by its own best score. + for _, list := range keywordLists { + rescaleUnboundedScores(list) + } + result := deduplicateByScore(flattenLists(keywordLists)) logger.Infof(ctx, "Result count after deduplication: %d", len(result)) return result } // Hybrid: use RRF fusion to merge vector + keyword results - result := fuseWithRRF(ctx, vectorResults, keywordResults, retrievalCfg) + result := fuseWithRRF(ctx, vectorLists, keywordLists, retrievalCfg) logger.Infof(ctx, "Result count after RRF fusion: %d", len(result)) return result } @@ -123,35 +154,37 @@ func rescaleUnboundedScores(results []*types.IndexWithScore) { } // fuseWithRRF merges vector and keyword retrieval results using Reciprocal Rank Fusion. -// RRF score = vectorWeight/(k+vectorRank) + keywordWeight/(k+keywordRank). +// RRF score = vectorWeight/(k+vectorRank) + keywordWeight/(k+keywordRank), +// divided by its maximum (vectorWeight+keywordWeight)/(k+1) so it lands in +// [0, 1] like the single-retriever paths. Raw RRF tops out near 0.016, which +// made hybrid hits lose to any vector-only or keyword-only result they were +// ranked against and left rerank's base-score term and MMR's relevance term +// with nothing to work with. +// +// A chunk's rank for a retriever is its best position in any one list of +// that retriever, each list ordered by its own score. Positions in the +// concatenation of several lists are arbitrary: the second list's best hit +// would otherwise rank behind every hit of the first. // k, vectorWeight and keywordWeight are sourced from retrievalCfg (with defaults). // The merged results are sorted by RRF score descending. -func fuseWithRRF(ctx context.Context, vectorResults, keywordResults []*types.IndexWithScore, retrievalCfg *types.RetrievalConfig) []*types.IndexWithScore { +func fuseWithRRF( + ctx context.Context, vectorLists, keywordLists [][]*types.IndexWithScore, retrievalCfg *types.RetrievalConfig, +) []*types.IndexWithScore { rrfK := retrievalCfg.GetEffectiveRRFK() vectorWeight, keywordWeight := retrievalCfg.GetEffectiveRRFWeights() + maxRRF := (vectorWeight + keywordWeight) / float64(rrfK+1) - // Build rank maps for each retriever (already sorted by score from retriever) - vectorRanks := make(map[string]int, len(vectorResults)) - for i, r := range vectorResults { - if _, exists := vectorRanks[r.ChunkID]; !exists { - vectorRanks[r.ChunkID] = i + 1 // 1-indexed rank - } - } - keywordRanks := make(map[string]int, len(keywordResults)) - for i, r := range keywordResults { - if _, exists := keywordRanks[r.ChunkID]; !exists { - keywordRanks[r.ChunkID] = i + 1 - } - } + vectorRanks := bestRanks(vectorLists) + keywordRanks := bestRanks(keywordLists) // Collect all unique chunks — prefer vector result's metadata for each chunk chunkInfoMap := make(map[string]*types.IndexWithScore) - for _, r := range vectorResults { + for _, r := range flattenLists(vectorLists) { if existing, exists := chunkInfoMap[r.ChunkID]; !exists || r.Score > existing.Score { chunkInfoMap[r.ChunkID] = r } } - for _, r := range keywordResults { + for _, r := range flattenLists(keywordLists) { if _, exists := chunkInfoMap[r.ChunkID]; !exists { chunkInfoMap[r.ChunkID] = r } @@ -167,7 +200,7 @@ func fuseWithRRF(ctx context.Context, vectorResults, keywordResults []*types.Ind if rank, ok := keywordRanks[chunkID]; ok { rrfScore += keywordWeight / float64(rrfK+rank) } - info.Score = rrfScore + info.Score = rrfScore / maxRRF result = append(result, info) } slices.SortFunc(result, sortByScoreDesc) @@ -185,3 +218,17 @@ func fuseWithRRF(ctx context.Context, vectorResults, keywordResults []*types.Ind return result } + +// bestRanks returns each chunk's best 1-based rank across lists, ranking every +// list on its own by score (a chunk repeated in a list keeps its best score). +func bestRanks(lists [][]*types.IndexWithScore) map[string]int { + ranks := make(map[string]int) + for _, list := range lists { + for i, r := range deduplicateByScore(list) { + if current, ok := ranks[r.ChunkID]; !ok || i+1 < current { + ranks[r.ChunkID] = i + 1 + } + } + } + return ranks +} diff --git a/internal/application/service/knowledgebase_search_fusion_test.go b/internal/application/service/knowledgebase_search_fusion_test.go index 0bc35249..3c251a61 100644 --- a/internal/application/service/knowledgebase_search_fusion_test.go +++ b/internal/application/service/knowledgebase_search_fusion_test.go @@ -12,11 +12,11 @@ import ( func TestFuseOrDeduplicate_KeywordOnlyRescalesUnboundedBM25(t *testing.T) { t.Parallel() - got := fuseOrDeduplicate(context.Background(), nil, []*types.IndexWithScore{ + got := fuseOrDeduplicate(context.Background(), nil, [][]*types.IndexWithScore{{ {ChunkID: "strong", Score: 16.1239}, {ChunkID: "mid", Score: 8.06195}, {ChunkID: "weak", Score: 4.030975}, - }, nil) + }}, nil) require.Len(t, got, 3) require.Equal(t, "strong", got[0].ChunkID) @@ -32,18 +32,18 @@ func TestFuseOrDeduplicate_KeywordOnlyRescalesUnboundedBM25(t *testing.T) { func TestFuseOrDeduplicate_KeywordOnlyLeavesUnitIntervalScores(t *testing.T) { t.Parallel() - flat := fuseOrDeduplicate(context.Background(), nil, []*types.IndexWithScore{ + flat := fuseOrDeduplicate(context.Background(), nil, [][]*types.IndexWithScore{{ {ChunkID: "a", Score: 1.0}, {ChunkID: "b", Score: 1.0}, - }, nil) + }}, nil) require.Len(t, flat, 2) require.InDelta(t, 1.0, flat[0].Score, 1e-9) require.InDelta(t, 1.0, flat[1].Score, 1e-9) - bounded := fuseOrDeduplicate(context.Background(), nil, []*types.IndexWithScore{ + bounded := fuseOrDeduplicate(context.Background(), nil, [][]*types.IndexWithScore{{ {ChunkID: "high", Score: 0.8}, {ChunkID: "low", Score: 0.4}, - }, nil) + }}, nil) require.Equal(t, "high", bounded[0].ChunkID) require.InDelta(t, 0.8, bounded[0].Score, 1e-9) require.InDelta(t, 0.4, bounded[1].Score, 1e-9) @@ -52,10 +52,10 @@ func TestFuseOrDeduplicate_KeywordOnlyLeavesUnitIntervalScores(t *testing.T) { func TestFuseOrDeduplicate_VectorOnlyKeepsEmbeddingScores(t *testing.T) { t.Parallel() - got := fuseOrDeduplicate(context.Background(), []*types.IndexWithScore{ + got := fuseOrDeduplicate(context.Background(), [][]*types.IndexWithScore{{ {ChunkID: "near", Score: 0.91}, {ChunkID: "far", Score: 0.22}, - }, nil, nil) + }}, nil, nil) require.Equal(t, "near", got[0].ChunkID) require.InDelta(t, 0.91, got[0].Score, 1e-9) @@ -66,8 +66,8 @@ func TestFuseOrDeduplicate_HybridUsesRRFNotRawBM25(t *testing.T) { t.Parallel() got := fuseOrDeduplicate(context.Background(), - []*types.IndexWithScore{{ChunkID: "vec", Score: 0.9}}, - []*types.IndexWithScore{{ChunkID: "kw", Score: 16.1239}}, + [][]*types.IndexWithScore{{{ChunkID: "vec", Score: 0.9}}}, + [][]*types.IndexWithScore{{{ChunkID: "kw", Score: 16.1239}}}, nil, ) @@ -77,6 +77,69 @@ func TestFuseOrDeduplicate_HybridUsesRRFNotRawBM25(t *testing.T) { require.Less(t, hit.Score, 1.0) require.NotEqual(t, 16.1239, hit.Score) } + // Normalized RRF: rank 1 for one retriever only scores that retriever's + // share of the total weight (defaults 0.7 / 0.3). + require.Equal(t, "vec", got[0].ChunkID) + require.InDelta(t, 0.7, got[0].Score, 1e-9) + require.InDelta(t, 0.3, got[1].Score, 1e-9) +} + +func TestFuseOrDeduplicate_HybridTopOfBothScoresOne(t *testing.T) { + t.Parallel() + + got := fuseOrDeduplicate(context.Background(), + [][]*types.IndexWithScore{{{ChunkID: "both", Score: 0.9}, {ChunkID: "vec", Score: 0.8}}}, + [][]*types.IndexWithScore{{{ChunkID: "both", Score: 12}}}, + nil, + ) + require.Equal(t, "both", got[0].ChunkID) + require.InDelta(t, 1.0, got[0].Score, 1e-9) +} + +// Lists are ranked on their own. The FAQ list arrives second (goroutine +// completion order), but its best hit is still vector rank 1 — not rank 4 +// behind every document hit. +func TestFuseOrDeduplicate_HybridRanksEachListOnItsOwn(t *testing.T) { + t.Parallel() + + docList := []*types.IndexWithScore{ + {ChunkID: "doc-1", Score: 0.81}, {ChunkID: "doc-2", Score: 0.8}, {ChunkID: "doc-3", Score: 0.79}, + } + // Engines return lists sorted, but nothing guarantees it; ranks follow score. + faqList := []*types.IndexWithScore{{ChunkID: "faq-2", Score: 0.7}, {ChunkID: "faq-1", Score: 0.93}} + keywordList := []*types.IndexWithScore{{ChunkID: "faq-1", Score: 7}, {ChunkID: "doc-3", Score: 3}} + + got := fuseOrDeduplicate(context.Background(), + [][]*types.IndexWithScore{docList, faqList}, + [][]*types.IndexWithScore{keywordList}, + nil, + ) + require.Equal(t, "faq-1", got[0].ChunkID, "vector rank 1 in its list plus keyword rank 1") + require.InDelta(t, 1.0, got[0].Score, 1e-9) + + scores := map[string]float64{} + for _, hit := range got { + scores[hit.ChunkID] = hit.Score + } + // doc-1 and faq-2 hold rank 1 and 2 of their own lists. + require.InDelta(t, 0.7, scores["doc-1"], 1e-9) + require.InDelta(t, 0.7*61.0/62.0, scores["faq-2"], 1e-9) +} + +func TestFuseOrDeduplicate_KeywordOnlyScalesEachList(t *testing.T) { + t.Parallel() + + got := fuseOrDeduplicate(context.Background(), nil, [][]*types.IndexWithScore{ + {{ChunkID: "pg-top", Score: 20}, {ChunkID: "pg-low", Score: 10}}, + {{ChunkID: "es-top", Score: 4}}, + }, nil) + scores := map[string]float64{} + for _, hit := range got { + scores[hit.ChunkID] = hit.Score + } + require.InDelta(t, 1.0, scores["pg-top"], 1e-9) + require.InDelta(t, 0.5, scores["pg-low"], 1e-9) + require.InDelta(t, 1.0, scores["es-top"], 1e-9, "each engine's BM25 is scaled by its own best score") } func TestRescaleUnboundedScores_IgnoresNonFiniteWhenFindingMax(t *testing.T) { diff --git a/internal/application/service/knowledgebase_search_matchcount_test.go b/internal/application/service/knowledgebase_search_matchcount_test.go index da8df5f7..101dea47 100644 --- a/internal/application/service/knowledgebase_search_matchcount_test.go +++ b/internal/application/service/knowledgebase_search_matchcount_test.go @@ -31,7 +31,8 @@ func TestNormalizedMatchCount(t *testing.T) { {name: "omitted arrives as zero", requested: 0, want: types.DefaultRetrievalTopK}, {name: "negative cannot index a slice", requested: -1, want: types.DefaultRetrievalTopK}, {name: "explicit value is honored", requested: 3, want: 3}, - {name: "large explicit value is not clamped here", requested: 10000, want: 10000}, + {name: "large explicit value is clamped to the pool", requested: 10000, want: maxRetrievalPoolSize}, + {name: "overflow-sized value is clamped", requested: 1 << 62, want: maxRetrievalPoolSize}, } for _, tt := range tests { @@ -65,7 +66,7 @@ func TestIterativeRetrieve_CapsSeedTopK(t *testing.T) { s := &knowledgeBaseService{} ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) - results, err := s.iterativeRetrieveWithDeduplication(ctx, groups, 100000, "q") + results, err := s.iterativeRetrieveWithDeduplication(ctx, groups, 100000, "q", 50) require.NoError(t, err) assert.Empty(t, results) assert.Equal(t, maxRetrievalPoolSize, groups[0].TopK, diff --git a/internal/application/service/knowledgebase_search_rerank.go b/internal/application/service/knowledgebase_search_rerank.go index d9a7c802..8833b1d3 100644 --- a/internal/application/service/knowledgebase_search_rerank.go +++ b/internal/application/service/knowledgebase_search_rerank.go @@ -118,6 +118,9 @@ func (s *knowledgeBaseService) HybridSearchWithRerank(ctx context.Context, } out := &types.RetrievalResult{Meta: types.RetrievalMeta{Rerank: diag}} + // Recall at least as deep as the rerank asks for: with match_count=5 and + // rerank.top_k=200 the pool used to stop at the 50-hit floor. + params.MatchCount = max(params.MatchCount, topK) chunks, err := s.hybridSearchCandidates(ctx, id, params) if err != nil { return nil, err diff --git a/internal/application/service/knowledgebase_search_results.go b/internal/application/service/knowledgebase_search_results.go index 85780736..6930e3cd 100644 --- a/internal/application/service/knowledgebase_search_results.go +++ b/internal/application/service/knowledgebase_search_results.go @@ -84,7 +84,10 @@ func (s *knowledgeBaseService) processSearchResults(ctx context.Context, // Build final search results searchResults := s.assembleSearchResults(ctx, chunks, chunkMap, knowledgeMap, index, skipEnrichment) - searchutil.EnrichSearchResultsImageInfo(ctx, s.chunkRepo, tenantID, searchResults) + // Results can come from org-shared KBs owned by another workspace; the + // chunks above were already permission checked, so look up their image + // children without the caller-tenant filter (#3342). + searchutil.EnrichSearchResultsImageInfoOnly(ctx, s.chunkRepo, searchResults) logger.Infof(ctx, "Search results processed, total: %d", len(searchResults)) return searchResults, nil @@ -353,6 +356,7 @@ func (s *knowledgeBaseService) buildSearchResult(chunk *types.Chunk, KnowledgeDescription: knowledge.Description, KnowledgeCustomMetadata: knowledge.CustomMetadataText(), ChunkMetadata: chunk.Metadata, + ContextHeader: chunk.ContextHeader, MatchedContent: matchedContent, KnowledgeBaseID: knowledge.KnowledgeBaseID, } diff --git a/internal/application/service/knowledgebase_search_shared.go b/internal/application/service/knowledgebase_search_shared.go index a47bbb12..95a8d887 100644 --- a/internal/application/service/knowledgebase_search_shared.go +++ b/internal/application/service/knowledgebase_search_shared.go @@ -2,9 +2,7 @@ package service import ( "context" - "errors" - "github.com/Tencent/WeKnora/internal/application/repository" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" ) @@ -56,17 +54,18 @@ func (s *knowledgeBaseService) fetchKnowledgeDataWithShared(ctx context.Context, for _, k := range rows { appendAllowed(k) } - for _, id := range knowledgeIDs { - if rows[id] != nil { - continue - } - k, err := s.kgRepo.GetKnowledgeByIDOnly(ctx, id) - if err != nil && !errors.Is(err, repository.ErrKnowledgeNotFound) { - return nil, err - } - if err == nil { - appendAllowed(k) - } + // Knowledge of org-shared KBs lives in the sharing workspace. Fetch all + // of it in one query; it used to be one query per ID, serially. + missing := s.findMissingIDs(knowledgeIDs, func(id string) bool { return rows[id] != nil }) + if len(missing) == 0 { + return knowledgeMap, nil + } + crossRows, err := s.kgRepo.GetKnowledgeBatchByIDOnly(ctx, missing) + if err != nil { + return nil, err + } + for _, k := range crossRows { + appendAllowed(k) } return knowledgeMap, nil } diff --git a/internal/application/service/retriever/normalizer.go b/internal/application/service/retriever/normalizer.go index 00363eb6..fb5ac324 100644 --- a/internal/application/service/retriever/normalizer.go +++ b/internal/application/service/retriever/normalizer.go @@ -25,70 +25,25 @@ type ScoreNormalizer interface { ) float64 } -// EngineAwareNormalizer applies the documented per-engine cosine-score -// formula. The caller (HybridSearch) enforces a same-embedding-model -// precondition via ResolveEmbeddingModelKeys, so post-normalization values -// are semantically comparable across engines. +// EngineAwareNormalizer maps vector scores onto [0, 1]. Every driver reports +// vector scores as cosine similarity: pgvector and sqlite-vec compute +// 1 - cosine distance, Qdrant, TencentVectorDB, Doris and Milvus (IP or +// COSINE over L2-normalized embeddings) return the similarity itself, the +// Milvus L2 path converts the squared distance, Elasticsearch v8 runs a +// cosineSimilarity script_score, and OpenSearch and Weaviate convert the +// (1 + cos) / 2 their APIs return (k-NN cosinesimil score, certainty). The +// caller (HybridSearch) enforces a same-embedding-model precondition via +// ResolveEmbeddingModelKeys, so the values are comparable across engines, +// and the same scale holds on single-store searches, which skip this step. // -// Source formulas (verified against repository implementations on -// upstream/main 3214e3d9, OpenSearch 2.17 / 3.5 docs, the k-NN plugin's -// SpaceType.java source, the Tencent VectorDB Go SDK base_document.go, -// pgvector / sqlite-vec / Qdrant / Weaviate docs, and the Lucene -// script_score non-negative invariant). Engines are grouped by the -// effective score range observed at the normalizer's input: +// Cosine similarity is theoretically [-1, 1], but the L2-normalized, +// positive-component IR embeddings WeKnora targets (sentence-transformers, +// BGE, OpenAI text-embedding-3, Cohere, E5, ...) keep it in [0, 1] in +// practice; clamp01 floors the rare negative value at 0. // -// Range [-1, 1] (raw cosine, normalized via (score + 1) / 2): -// - Milvus (COSINE metric mode). Milvus docs explicitly state the -// COSINE metric "has a range of [-1, 1]". -// -// Range [0, 1] (passthrough — already on the target scale): -// - Elasticsearch v8 — driver issues `cosineSimilarity(query, 'embedding')` -// as a script_score script. Lucene rejects negative final scores -// ("Final relevance scores from the script_score query cannot be -// negative") so the effective range observed here is [0, 1] for -// IR-normalized embeddings (see IR-normalization note below). If -// a future driver swap inserts `1.0 + cosineSimilarity(...)` (the -// pattern recommended by ES docs) this group will need to move out. -// - OpenSearch — the k-NN plugin's SpaceType.COSINESIMIL.scoreTranslation -// applies Math.max((2.0F - rawScore) / 2.0F, 0.0F) where rawScore is -// the distance (1 - cosine) from Lucene/Faiss, so the score returned -// to the client is (1 + cosine) / 2 ∈ [0, 1]. The OpenSearch driver -// itself ships in a later Phase 3 PR (see #1440); this branch is -// unreachable from production retrieval paths until then, but the -// unit tests pin the formula in advance. Source: -// github.com/opensearch-project/k-NN at -// src/main/java/org/opensearch/knn/index/SpaceType.java (COSINESIMIL -// enum, scoreTranslation method). -// - Weaviate — driver requests `certainty`, defined by Weaviate as -// (2 - distance) / 2 = (1 + cosine) / 2, intrinsically ∈ [0, 1]. -// - Postgres pgvector — driver computes `(1 - distance) as score` -// where `<=>` is cosine distance ∈ [0, 2]; the theoretical range -// is therefore [-1, 1] but IR-normalized embeddings (see below) -// keep the observed range in [0, 1]. -// - SQLite sqlite-vec — driver computes `1 - v.Distance` where the -// vec0 `distance_metric=cosine` returns distance ∈ [0, 2] (per -// sqlite-vec docs: "0 for identical, 2 for opposite"). Same IR -// caveat as pgvector. -// - Qdrant — Distance.Cosine; Qdrant normalizes vectors at insert -// time and the score returned by ScoredPoint.score is the dot -// product of the normalized vectors = raw cosine ∈ [-1, 1] in -// theory, [0, 1] under the IR caveat. -// - TencentVectorDB — MetricType COSINE; per the SDK godoc -// (tcvectordb base_document.go): "COSINE: return when score >= -// radius, value range [-1, 1]." Same IR caveat. -// - Doris — driver runs `inner_product_approximate` against -// L2-normalized embeddings (or legacy `(1 - cosine_distance_approximate)`), -// which equals raw cosine ∈ [-1, 1]. Same IR caveat. -// -// IR-normalization caveat (applies to pgvector, sqlite-vec, Qdrant, -// TencentVectorDB, Doris): modern RAG embeddings are L2-normalized -// positive-component unit vectors (sentence-transformers, BGE, OpenAI -// text-embedding-3, Cohere, E5, etc.) that empirically keep cosine in -// [0, 1]. Theoretical [-1, 1] inputs would clamp to 0 below — silent -// information loss only for embedding models that produce negative -// cosines (rare in IR workloads but possible for centered word2vec, -// GloVe, or non-IR embeddings). If a future use case violates this, -// the affected engines should move into the [-1, 1] group. +// Milvus used to be mapped through (score + 1) / 2 here, which put its hits +// on a different scale from every other engine in a multi-store search, and +// from its own single-store results. // // Dead enum references (kept as RetrieverEngineType constants but // without a driver implementation — see internal/types/vectorstore.go @@ -97,9 +52,6 @@ type ScoreNormalizer interface { // - InfinityRetrieverEngineType // - ElasticFaissRetrieverEngineType // -// Their case labels below route to clamp01(score) defensively, but -// production code never returns these engine types. -// // Unknown engines clamp to [0, 1]; the fan-out caller emits a single WARN // per request via warnIfUnknownEngine so Normalize itself stays lock-free // and panic-free even on nil ctx. @@ -113,7 +65,7 @@ func (EngineAwareNormalizer) Normalize( _ context.Context, score float64, retrieverType types.RetrieverType, - engineType types.RetrieverEngineType, + _ types.RetrieverEngineType, ) float64 { if retrieverType != types.VectorRetrieverType { // BM25 and other non-vector retrievers: passthrough. RRF rank-based @@ -121,41 +73,9 @@ func (EngineAwareNormalizer) Normalize( return score } - switch engineType { - case types.MilvusRetrieverEngineType: - // Raw cosine in [-1, 1] → [0, 1]. Milvus is the only engine in - // this codebase whose driver surfaces the raw cosine signed range - // to the normalizer. Pass through clamp01 once more so that a - // misbehaving engine returning 1.0000002 does not leak past the - // [0, 1] envelope (caller sorts by score afterwards). - return clamp01((score + 1) / 2) - case types.ElasticsearchRetrieverEngineType, - types.ElasticFaissRetrieverEngineType, - types.OpenSearchRetrieverEngineType, - types.WeaviateRetrieverEngineType, - types.PostgresRetrieverEngineType, - types.SQLiteRetrieverEngineType, - types.QdrantRetrieverEngineType, - types.InfinityRetrieverEngineType, - types.TencentVectorDBRetrieverEngineType, - types.DorisRetrieverEngineType: - // Already in [0, 1] when the value reaches us. See struct godoc - // above for the per-engine derivation: Elasticsearch's Lucene - // script_score non-negative invariant; OpenSearch's k-NN plugin - // SpaceType.COSINESIMIL.scoreTranslation pre-translation; - // Weaviate's certainty intrinsic; and the IR-normalization - // caveat covering pgvector / sqlite-vec / Qdrant / - // TencentVectorDB / Doris (theoretical [-1, 1] but observed - // [0, 1] for L2-normalized positive-component IR embeddings). - // - // ElasticFaiss and Infinity are dead enum references — their - // case labels are kept so the switch is exhaustive over the - // declared engine constants, but no driver returns these. - return clamp01(score) - default: - // Unknown engine. Clamp defensively; the caller emits WARN with ctx. - return clamp01(score) - } + // Every engine reports cosine similarity (see the type comment); the + // clamp only guards the [0, 1] envelope and NaN/Inf. + return clamp01(score) } // clamp01 maps any float64 into [0, 1] safely, including NaN/Inf inputs that diff --git a/internal/application/service/retriever/normalizer_test.go b/internal/application/service/retriever/normalizer_test.go index 94e2299c..1dab67f0 100644 --- a/internal/application/service/retriever/normalizer_test.go +++ b/internal/application/service/retriever/normalizer_test.go @@ -26,40 +26,28 @@ func TestEngineAwareNormalizer_KeywordPassthrough(t *testing.T) { } } -func TestEngineAwareNormalizer_CosineRange(t *testing.T) { +// Milvus reports cosine similarity like every other engine (IP / COSINE over +// normalized embeddings, L2 converted in the driver). It used to be mapped +// through (score + 1) / 2, which put a multi-store Milvus hit at 0.75 for a +// cosine of 0.5 while every other engine reported 0.5. +func TestEngineAwareNormalizer_MilvusIsCosine(t *testing.T) { t.Parallel() n := EngineAwareNormalizer{} - // Only Milvus surfaces the raw cosine signed range [-1, 1] to the - // normalizer in this codebase. Elasticsearch v8 used to be in this - // group, but the driver issues a script_score cosineSimilarity script - // and Lucene rejects negative final scores ("Final relevance scores - // from the script_score query cannot be negative" — ES docs), so the - // score observed by the normalizer is already in [0, 1]; ES is now - // part of the passthrough group below. ElasticFaiss is a dead enum - // (no driver) and follows ES. cases := []struct { score float64 want float64 }{ - {-1.0, 0}, - {-0.5, 0.25}, - {0, 0.5}, - {0.5, 0.75}, + {-0.5, 0}, + {0, 0}, + {0.5, 0.5}, {1.0, 1.0}, - // Drift beyond [-1, 1] is clamped. - {-1.5, 0}, {1.5, 1.0}, } - for _, engine := range []types.RetrieverEngineType{ - types.MilvusRetrieverEngineType, - } { - for _, tc := range cases { - got := n.Normalize(context.Background(), tc.score, - types.VectorRetrieverType, engine) - if math.Abs(got-tc.want) > 1e-9 { - t.Fatalf("cosine[%s] score=%v: want %v, got %v", - engine, tc.score, tc.want, got) - } + for _, tc := range cases { + got := n.Normalize(context.Background(), tc.score, + types.VectorRetrieverType, types.MilvusRetrieverEngineType) + if math.Abs(got-tc.want) > 1e-9 { + t.Fatalf("milvus score=%v: want %v, got %v", tc.score, tc.want, got) } } } diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.go index 1a57773a..7fbb9123 100644 --- a/internal/application/service/session_agent_qa.go +++ b/internal/application/service/session_agent_qa.go @@ -343,6 +343,12 @@ func (s *sessionService) buildAgentConfig( MaxCompletionTokens: customAgent.Config.MaxCompletionTokens, RetainRetrievalHistory: customAgent.Config.RetainRetrievalHistory, SharedAgentReadOnly: req.SharedAgentReadOnly, + // The model is always told it may call tools in parallel; without + // this the engine still ran them one by one, so three searches in + // one reply cost three sequential embed/retrieve/rerank rounds. + // Only read-only tools overlap (agenttools.CanRunConcurrently); + // anything else is a barrier that runs alone, in model order. + ParallelToolCalls: true, } applyRequestReasoningEffort(req.ReasoningEffort, &agentConfig.Thinking, &agentConfig.ReasoningEffort) // An unset MCP mode means "all" at runtime, but the share scope and the diff --git a/internal/handler/session/knowledge_search_options_test.go b/internal/handler/session/knowledge_search_options_test.go new file mode 100644 index 00000000..39ec3028 --- /dev/null +++ b/internal/handler/session/knowledge_search_options_test.go @@ -0,0 +1,25 @@ +package session + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/internal/types" +) + +// knowledge-search runs one search per scoped target and reranks every +// candidate, so result counts are bounded. +func TestKnowledgeSearchOptionsBoundsCounts(t *testing.T) { + t.Parallel() + _, err := knowledgeSearchOptions(&SearchKnowledgeRequest{MatchCount: types.MaxRequestedResults}) + require.NoError(t, err) + + _, err = knowledgeSearchOptions(&SearchKnowledgeRequest{MatchCount: types.MaxRequestedResults + 1}) + require.ErrorContains(t, err, "match_count must not exceed") + + _, err = knowledgeSearchOptions(&SearchKnowledgeRequest{ + Rerank: &types.RerankOptions{TopK: types.MaxRequestedResults + 1}, + }) + require.ErrorContains(t, err, "rerank.top_k must not exceed") +} diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index e96f1352..63aa971c 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -931,6 +931,9 @@ func knowledgeSearchOptions(request *SearchKnowledgeRequest) (*types.KnowledgeSe if request.MatchCount < 0 { return nil, fmt.Errorf("match_count must not be negative") } + if request.MatchCount > types.MaxRequestedResults { + return nil, fmt.Errorf("match_count must not exceed %d", types.MaxRequestedResults) + } if request.DisableVectorMatch && request.DisableKeywordsMatch { return nil, fmt.Errorf("disable_vector_match and disable_keywords_match cannot both be true") } diff --git a/internal/modelcontext/model_output.go b/internal/modelcontext/model_output.go index 84e369d5..6e0a2026 100644 --- a/internal/modelcontext/model_output.go +++ b/internal/modelcontext/model_output.go @@ -49,13 +49,14 @@ func (r *sourceRegistry) ModelOutput(result *types.ToolResult) string { mode = "semantic" } output := r.modelKnowledgeOutput(mode, mapsValue(result.Data["results"]), result.Output) - return r.annotateModeFallbacks(output, result.Data) + return annotateSearchNotes(r.annotateModeFallbacks(output, result.Data), result.Data) case "knowledge_chunks_list": return r.modelKnowledgeChunksOutput(result.Data, result.Output) case "document_info": return r.modelDocumentInfoOutput(result.Data, result.Output) case "graph_query_results": - return r.modelKnowledgeOutput("graph", mapsValue(result.Data["results"]), result.Output) + return annotateGraphResult( + r.modelKnowledgeOutput("graph", mapsValue(result.Data["results"]), result.Output), result.Data) case "web_search_results": return r.modelWebSearchOutput(mapsValue(result.Data["results"]), result.Output) case "database_query": @@ -291,6 +292,66 @@ func (r *sourceRegistry) annotateModeFallbacks(output string, data map[string]in return strings.TrimSuffix(output, "") + b.String() + "" } +// matchAddsToContent reports whether a match snippet tells the model +// anything the chunk's content does not: it does when there is no content +// (a snippet-only view), or when the snippet is not an excerpt of it. +// Rendering an excerpt next to the full content repeated up to 800 +// characters per row. +func matchAddsToContent(match, content string) bool { + if content == "" { + return true + } + excerpt := strings.TrimSpace(match) + for _, marker := range []string{"...", "…"} { + excerpt = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(excerpt, marker), marker)) + } + return excerpt != "" && !strings.Contains(content, excerpt) +} + +// annotateGraphResult adds the graph relations and any per-knowledge-base +// failures to a graph query's chunk view. Both lived only in Output, which +// the model never sees once there are chunk rows to render. +func annotateGraphResult(output string, data map[string]interface{}) string { + relations := mapsValue(data["relations"]) + failures := stringSliceValue(data["errors"]) + if (len(relations) == 0 && len(failures) == 0) || !strings.HasSuffix(output, "") { + return output + } + var b strings.Builder + for _, rel := range relations { + fmt.Fprintf(&b, " \n", + escapeAttr(stringValue(rel, "source")), escapeAttr(stringValue(rel, "type")), + escapeAttr(stringValue(rel, "target"))) + } + for _, failure := range failures { + fmt.Fprintf(&b, " %s\n", escapeText(failure)) + } + return strings.TrimSuffix(output, "") + b.String() + "" +} + +// annotateSearchNotes tells the model what a search result does not show: +// how many lower-ranked results were left out to fit the tool output budget +// (so it narrows the query or lowers the limit instead of concluding nothing +// else matched), and which knowledge bases could not be searched (so a +// failure is not read as an absence of evidence). +func annotateSearchNotes(output string, data map[string]interface{}) string { + omitted := intValue(data, "omitted_for_budget") + failures := stringSliceValue(data["partial_failures"]) + if (omitted <= 0 && len(failures) == 0) || !strings.HasSuffix(output, "") { + return output + } + var b strings.Builder + if omitted > 0 { + fmt.Fprintf(&b, " Lower-ranked results were left out to "+ + "fit the output size. Narrow the query or lower limit to see them.\n", omitted) + } + for _, failure := range failures { + fmt.Fprintf(&b, " %s — these knowledge bases were not searched.\n", + escapeText(failure)) + } + return strings.TrimSuffix(output, "") + b.String() + "" +} + func viewForRow(row map[string]interface{}, mode string) string { if stringValue(row, "content") != "" { return "full" @@ -357,6 +418,9 @@ func (r *sourceRegistry) modelKnowledgeChunksOutput(data map[string]interface{}, fmt.Fprintf(&footer, " \n") } else if _, ok := data["next_offset"]; ok { @@ -480,7 +544,10 @@ func renderKnowledgeChunks(mode string, chunks []modelChunk, info map[string]int if chunk.question != "" { fmt.Fprintf(&b, " %s\n", escapeText(chunk.question)) } - if chunk.match != "" { + // Deep reads keep the snippet: it locates the hit inside a long + // chunk. Search rows are chunk-sized, so an excerpt of the content + // shown beside it only repeats it. + if chunk.match != "" && (mode == "deep_read" || matchAddsToContent(chunk.match, chunk.content)) { fmt.Fprintf(&b, " %s\n", escapeText(chunk.match)) } if chunk.content != "" { diff --git a/internal/modelcontext/omitted_results_test.go b/internal/modelcontext/omitted_results_test.go new file mode 100644 index 00000000..c82184cd --- /dev/null +++ b/internal/modelcontext/omitted_results_test.go @@ -0,0 +1,57 @@ +package modelcontext + +import ( + "strings" + "testing" +) + +func TestAnnotateSearchNotes(t *testing.T) { + t.Parallel() + base := "\n" + got := annotateSearchNotes(base, map[string]interface{}{ + "omitted_for_budget": 4, + "partial_failures": []string{"[kb-2]: vector store unavailable"}, + }) + if !strings.Contains(got, ``) || + !strings.Contains(got, "[kb-2]: vector store unavailable") || + !strings.HasSuffix(got, "") { + t.Fatalf("annotated = %q", got) + } + if annotateSearchNotes(base, map[string]interface{}{}) != base { + t.Fatal("nothing to add must leave the output unchanged") + } +} + +func TestAnnotateGraphResult(t *testing.T) { + t.Parallel() + base := "\n" + got := annotateGraphResult(base, map[string]interface{}{ + "relations": []map[string]interface{}{{"source": "Kubernetes", "type": "orchestrates", "target": "Docker"}}, + "errors": []string{"KB b2: graph extraction not configured"}, + }) + for _, want := range []string{ + ``, + "KB b2: graph extraction not configured", + } { + if !strings.Contains(got, want) { + t.Fatalf("missing %q in %q", want, got) + } + } + if annotateGraphResult(base, map[string]interface{}{}) != base { + t.Fatal("nothing to add must leave the output unchanged") + } +} + +func TestMatchAddsToContent(t *testing.T) { + t.Parallel() + content := "Install the engine, then configure psionic drive parameters." + if matchAddsToContent("... configure psionic drive ...", content) { + t.Fatal("an excerpt of the content adds nothing") + } + if !matchAddsToContent("How do I tune the drive?", content) { + t.Fatal("a matched question absent from the content adds information") + } + if !matchAddsToContent("anything", "") { + t.Fatal("a snippet-only row keeps its snippet") + } +} diff --git a/internal/models/api/rerank_settings.go b/internal/models/api/rerank_settings.go index 48bf64c7..f6fbf975 100644 --- a/internal/models/api/rerank_settings.go +++ b/internal/models/api/rerank_settings.go @@ -49,9 +49,8 @@ type RerankSettings struct { // MaxConcurrency bounds in-flight batches when the input is split. 0 // means the caller's default. MaxConcurrency int - // RequestTimeout caps one request, in seconds. 0 leaves the HTTP client - // without its own deadline and lets the caller's context govern, which is - // what every vendor but WeKnora Cloud has always done here. + // RequestTimeout caps one request, in seconds. 0 uses the rerank + // client's default (see rerank.newRerankHTTPClient). RequestTimeout int // AcceptsTruncatePromptTokens reports that this vendor is a vLLM-class // runtime, which is the only kind that implements the diff --git a/internal/models/rerank/langfuse_wrapper.go b/internal/models/rerank/langfuse_wrapper.go index a61580f6..7cd07e88 100644 --- a/internal/models/rerank/langfuse_wrapper.go +++ b/internal/models/rerank/langfuse_wrapper.go @@ -23,6 +23,9 @@ type langfuseReranker struct { func (l *langfuseReranker) GetModelName() string { return l.inner.GetModelName() } func (l *langfuseReranker) GetModelID() string { return l.inner.GetModelID() } +// MaxPassageRunes forwards the wrapped reranker's limit. +func (l *langfuseReranker) MaxPassageRunes(query string) int { return MaxPassageRunes(l.inner, query) } + func (l *langfuseReranker) Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error) { mgr := langfuse.GetManager() if !mgr.Enabled() { diff --git a/internal/models/rerank/llm_debug.go b/internal/models/rerank/llm_debug.go index 5abc2731..2656c1c1 100644 --- a/internal/models/rerank/llm_debug.go +++ b/internal/models/rerank/llm_debug.go @@ -24,6 +24,9 @@ func (d *debugReranker) Rerank(ctx context.Context, query string, documents []st func (d *debugReranker) GetModelName() string { return d.inner.GetModelName() } func (d *debugReranker) GetModelID() string { return d.inner.GetModelID() } +// MaxPassageRunes forwards the wrapped reranker's limit. +func (d *debugReranker) MaxPassageRunes(query string) int { return MaxPassageRunes(d.inner, query) } + func logRerankDebug(ctx context.Context, model string, query string, documents []string, results []RankResult, callErr error, dur time.Duration) { if !logger.LLMDebugEnabled() { return diff --git a/internal/models/rerank/passage_limit_test.go b/internal/models/rerank/passage_limit_test.go new file mode 100644 index 00000000..1887eb2f --- /dev/null +++ b/internal/models/rerank/passage_limit_test.go @@ -0,0 +1,40 @@ +package rerank + +import ( + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/models/api" + "github.com/stretchr/testify/assert" +) + +func TestMaxPassageRunesFromSettings(t *testing.T) { + t.Parallel() + cases := []struct { + name string + settings api.RerankSettings + query string + want int + }{ + {"no limits", api.RerankSettings{}, "query", 0}, + {"per document", api.RerankSettings{MaxDocumentChars: 4096}, "query", 4096}, + {"request budget minus query", api.RerankSettings{MaxRequestChars: 2000}, "查询内容", 1996}, + {"tighter of the two", api.RerankSettings{MaxDocumentChars: 500, MaxRequestChars: 2000}, "q", 500}, + {"request budget tighter", api.RerankSettings{MaxDocumentChars: 4096, MaxRequestChars: 2000}, "q", 1999}, + {"query fills the budget", api.RerankSettings{MaxRequestChars: 3}, "long query", 1}, + } + for _, tc := range cases { + r := newWrapped(&fakeProtocol{}, tc.settings) + assert.Equal(t, tc.want, r.MaxPassageRunes(tc.query), tc.name) + // Wrappers must not hide the limit. + for _, wrapped := range []Reranker{&debugReranker{inner: r}, &langfuseReranker{inner: r}} { + assert.Equal(t, tc.want, MaxPassageRunes(wrapped, tc.query), tc.name+" via %T", wrapped) + } + } +} + +func TestRerankHTTPClientHasDefaultTimeout(t *testing.T) { + t.Parallel() + assert.Equal(t, defaultRerankRequestTimeout, newRerankHTTPClient(0).Timeout) + assert.Equal(t, 5*time.Second, newRerankHTTPClient(5*time.Second).Timeout) +} diff --git a/internal/models/rerank/protocol.go b/internal/models/rerank/protocol.go index 2ed81da3..d872cc7d 100644 --- a/internal/models/rerank/protocol.go +++ b/internal/models/rerank/protocol.go @@ -111,6 +111,22 @@ func (r *protocolReranker) Rerank( return results, nil } +// MaxPassageRunes implements PassageLimiter from the documented per-document +// and per-request ceilings; the query is charged against the latter because +// every request repeats it. +func (r *protocolReranker) MaxPassageRunes(query string) int { + limit := r.settings.MaxDocumentChars + if total := r.settings.MaxRequestChars; total > 0 { + // A query that leaves no room fails in Rerank with its own error; + // 1 keeps the limit meaningful rather than reading as "no limit". + room := max(total-utf8.RuneCountInString(query), 1) + if limit <= 0 || room < limit { + limit = room + } + } + return max(limit, 0) +} + func (r *protocolReranker) concurrency() int { if r.settings.MaxConcurrency > 0 { return r.settings.MaxConcurrency diff --git a/internal/models/rerank/reranker.go b/internal/models/rerank/reranker.go index 1e4f6d60..b60c75a0 100644 --- a/internal/models/rerank/reranker.go +++ b/internal/models/rerank/reranker.go @@ -33,6 +33,26 @@ type Reranker interface { GetModelID() string } +// PassageLimiter is implemented by rerankers whose vendor documents how large +// a document may be. The rerank stage builds its passages itself (title, +// chunk body, captions, OCR text, generated questions), so it can fit them to +// the limit instead of letting one oversized candidate fail the whole +// request, which the protocol layer rightly refuses to truncate on its own. +type PassageLimiter interface { + // MaxPassageRunes returns the longest document, in runes, one request + // can carry beside query. 0 means no documented limit. + MaxPassageRunes(query string) int +} + +// MaxPassageRunes reports r's passage limit for query, or 0 when r documents +// none. +func MaxPassageRunes(r Reranker, query string) int { + if limiter, ok := r.(PassageLimiter); ok { + return limiter.MaxPassageRunes(query) + } + return 0 +} + type RankResult struct { Index int `json:"index"` Document DocumentInfo `json:"document"` diff --git a/internal/models/rerank/transport.go b/internal/models/rerank/transport.go index 5161360c..1cd19d86 100644 --- a/internal/models/rerank/transport.go +++ b/internal/models/rerank/transport.go @@ -26,11 +26,20 @@ var sharedRerankHTTPTransport = secutils.NewSSRFSafeTransport( secutils.DefaultSSRFSafeHTTPClientConfig(), ) +// defaultRerankRequestTimeout caps one rerank request when the catalog sets +// no timeout. Chat and agent contexts carry no deadline of their own, so a +// stalled self-hosted rerank server used to hold the turn open until the +// client disconnected. A failed call degrades to retrieval order. +const defaultRerankRequestTimeout = 60 * time.Second + // newRerankHTTPClient returns an HTTP client with connection-level SSRF // protection and redirect validation. All clients share // sharedRerankHTTPTransport so keep-alive connections are pooled globally, // while each keeps its own timeout. func newRerankHTTPClient(timeout time.Duration) *http.Client { + if timeout <= 0 { + timeout = defaultRerankRequestTimeout + } cfg := secutils.DefaultSSRFSafeHTTPClientConfig() cfg.Timeout = timeout return secutils.NewSSRFSafeHTTPClientWithTransport(cfg, sharedRerankHTTPTransport) diff --git a/internal/reranking/passage.go b/internal/reranking/passage.go index d705216a..364d3c13 100644 --- a/internal/reranking/passage.go +++ b/internal/reranking/passage.go @@ -120,6 +120,14 @@ func CleanPassage(text string) string { func EnrichedPassage(ctx context.Context, result *types.SearchResult) string { combinedText := CleanPassage(result.Content) var enrichments []string + // An image OCR or caption chunk's body is that same text, and its + // image_info repeats it; appending it again doubled the passage. + body := strings.TrimSpace(result.Content) + addImageText := func(text string) { + if text != "" && strings.TrimSpace(text) != body { + enrichments = append(enrichments, text) + } + } if result.ImageInfo != "" { var imageInfos []types.ImageInfo @@ -127,12 +135,8 @@ func EnrichedPassage(ctx context.Context, result *types.SearchResult) string { logger.Warnf(ctx, "[Rerank] Failed to parse image info of chunk %s: %v", result.ID, err) } else { for _, img := range imageInfos { - if img.Caption != "" { - enrichments = append(enrichments, img.Caption) - } - if img.OCRText != "" { - enrichments = append(enrichments, img.OCRText) - } + addImageText(img.Caption) + addImageText(img.OCRText) } } } @@ -163,11 +167,21 @@ func EnrichedPassage(ctx context.Context, result *types.SearchResult) string { // // An empty enriched body stays empty: a title alone is not evidence that // the chunk answers anything. +// +// The chunk's heading breadcrumb (ContextHeader) goes between the two for the +// same reason: it was embedded with the chunk, so vector search can find +// "7 天内可申请" under "## 退款政策" while a model scoring the bare body +// rejects it. func ModelPassage(ctx context.Context, result *types.SearchResult) string { passage := EnrichedPassage(ctx, result) - title := strings.TrimSpace(result.KnowledgeTitle) - if strings.TrimSpace(passage) == "" || title == "" || result.ChunkType == string(types.ChunkTypeFAQ) { + if strings.TrimSpace(passage) == "" || result.ChunkType == string(types.ChunkTypeFAQ) { return passage } - return title + "\n\n" + passage + if header := strings.TrimSpace(result.ContextHeader); header != "" { + passage = header + "\n\n" + passage + } + if title := strings.TrimSpace(result.KnowledgeTitle); title != "" { + passage = title + "\n\n" + passage + } + return passage } diff --git a/internal/reranking/passage_test.go b/internal/reranking/passage_test.go index a8c1b9fd..50fee35f 100644 --- a/internal/reranking/passage_test.go +++ b/internal/reranking/passage_test.go @@ -178,3 +178,14 @@ func TestCleanPassageForRerank(t *testing.T) { }) } } + +func TestModelPassage_includesHeadingBreadcrumb(t *testing.T) { + t.Parallel() + got := ModelPassage(context.Background(), &types.SearchResult{ + Content: "7 天内可申请", KnowledgeTitle: "售后手册", ContextHeader: "退款政策 > 申请条件", + ChunkType: string(types.ChunkTypeText), + }) + if got != "售后手册\n\n退款政策 > 申请条件\n\n7 天内可申请" { + t.Fatalf("passage = %q", got) + } +} diff --git a/internal/reranking/rerank.go b/internal/reranking/rerank.go index 4b7e9e74..a64b81b5 100644 --- a/internal/reranking/rerank.go +++ b/internal/reranking/rerank.go @@ -11,6 +11,7 @@ import ( "sort" "strconv" "strings" + "unicode/utf8" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/models/rerank" @@ -30,6 +31,12 @@ const ( // at degradeFactor times itself, but never below degradeFloor. degradeFloor = 0.3 degradeFactor = 0.7 + + // DefaultMaxCandidates bounds how many candidates the chat pipeline and + // the agent tool send to the rerank model. Query expansion and + // per-document or per-tag targets each add a full retrieval list, and + // every candidate is a billed passage and a share of the latency. + DefaultMaxCandidates = 200 ) // FallbackMinScore returns the score the best candidate needs to survive an @@ -54,8 +61,14 @@ type Options struct { // FallbackMinScore is the score the best candidate needs to be kept when // nothing passes the threshold. See FallbackMinScore(). FallbackMinScore float64 + // MaxCandidates, when positive, reranks only the MaxCandidates rows with + // the highest retrieval score. Retrieval scores share one [0, 1] scale + // across searches, so the cut keeps the strongest candidates of each. + MaxCandidates int // FAQScoreBoost, when above 1, multiplies the composite score of FAQ - // entries (capped at 1). + // entries, capped at 1 so scores stay on the [0, 1] scale. FAQs tied at + // the cap are ordered by their pre-boost score. Compare absolute + // thresholds against PreBoostScore. FAQScoreBoost float64 } @@ -98,9 +111,10 @@ func Rerank( }, } + keep := topByScore(results, opts.MaxCandidates) candidateIdx := make([]int, 0, len(results)) for i, r := range results { - if r == nil { + if r == nil || (keep != nil && !keep[i]) { continue } passage := ModelPassage(ctx, r) @@ -116,6 +130,7 @@ func Rerank( res.Diagnostics.Outcome = types.RerankOutcomeNoCandidates return res } + fitPassages(ctx, res.Passages, rerank.MaxPassageRunes(model, query)) scores, err := model.Rerank(ctx, query, res.Passages) if err != nil { @@ -158,7 +173,14 @@ func Rerank( for i := range order { order[i] = i } - sort.SliceStable(order, func(a, b int) bool { return scored[order[a]].Score > scored[order[b]].Score }) + sort.SliceStable(order, func(a, b int) bool { + sa, sb := scored[order[a]], scored[order[b]] + if sa.Score != sb.Score { + return sa.Score > sb.Score + } + // Boosted FAQs capped at 1 tie; keep them in relevance order. + return PreBoostScore(sa) > PreBoostScore(sb) + }) res.Scored = make([]*types.SearchResult, len(order)) sortedIdx := make([]int, len(order)) for i, o := range order { @@ -186,6 +208,58 @@ func Rerank( return res } +// topByScore returns the positions of the limit highest-scoring rows, or nil +// when limit is not positive or every row fits. Ties keep the earlier row. +// Graph hits are always kept outside the limit: they carry no retrieval score +// (CompositeScore substitutes the model score) and would otherwise always be +// cut; their number is bounded where they are added. +func topByScore(results []*types.SearchResult, limit int) map[int]bool { + if limit <= 0 || len(results) <= limit { + return nil + } + keep := make(map[int]bool, limit) + order := make([]int, 0, len(results)) + for i, r := range results { + switch { + case r == nil: + case r.MatchType == types.MatchTypeGraph: + keep[i] = true + default: + order = append(order, i) + } + } + if len(order) <= limit { + return nil + } + sort.SliceStable(order, func(a, b int) bool { return results[order[a]].Score > results[order[b]].Score }) + for _, i := range order[:limit] { + keep[i] = true + } + return keep +} + +// fitPassages trims passages longer than limit runes (0 = no limit). A +// passage is the title, then the chunk body, then captions, OCR text and +// generated questions, so trimming the tail drops the least essential text +// first. Vendors reject an oversized document, and the protocol layer fails +// the whole request rather than truncate it, so a single chunk with a large +// screenshot's OCR text used to cost every candidate its rerank score. +func fitPassages(ctx context.Context, passages []string, limit int) { + if limit <= 0 { + return + } + trimmed := 0 + for i, p := range passages { + if utf8.RuneCountInString(p) > limit { + passages[i] = string([]rune(p)[:limit]) + trimmed++ + } + } + if trimmed > 0 { + logger.Infof(ctx, "[Rerank] Trimmed %d passages to the model's %d-character limit", trimmed, limit) + } +} + // applyThreshold keeps the scores at or above opts.Threshold. When none // pass, a threshold above degradeFloor is lowered once; when still none // pass, the best candidate is kept if it reaches opts.FallbackMinScore. @@ -234,18 +308,24 @@ func bestScore(scores []rerank.RankResult) (rerank.RankResult, bool) { return top, true } +// CompositeScoreKey is the Metadata key holding a reranked row's composite +// score before any boost (FAQ boost here, wiki or memory boosts later in the +// chat pipeline) changes Score. +const CompositeScoreKey = "composite_score" + // scoredCopy returns a copy of r whose Score is the composite of the model // score and its retrieval score, recording both in Metadata. func scoredCopy(r *types.SearchResult, modelScore, faqBoost float64) *types.SearchResult { c := *r c.Metadata = maps.Clone(r.Metadata) if c.Metadata == nil { - c.Metadata = make(map[string]string, 2) + c.Metadata = make(map[string]string, 3) } base := r.Score c.Metadata["base_score"] = strconv.FormatFloat(base, 'f', 4, 64) c.Metadata["model_score"] = strconv.FormatFloat(modelScore, 'f', 4, 64) c.Score = CompositeScore(&c, modelScore, base) + c.Metadata[CompositeScoreKey] = strconv.FormatFloat(c.Score, 'f', 4, 64) if faqBoost > 1.0 && c.ChunkType == string(types.ChunkTypeFAQ) { c.Metadata["faq_boosted"] = "true" c.Metadata["faq_original_score"] = strconv.FormatFloat(c.Score, 'f', 4, 64) @@ -255,12 +335,32 @@ func scoredCopy(r *types.SearchResult, modelScore, faqBoost float64) *types.Sear } // CompositeScore blends the rerank model score with the retrieval score and a -// source weight, clamped to [0, 1]. +// source weight, clamped to [0, 1]. Graph hits carry no retrieval score (they +// come from entity lookups, not similarity search), so the model score stands +// in for it rather than a made-up constant. func CompositeScore(r *types.SearchResult, modelScore, baseScore float64) float64 { sourceWeight := 1.0 if strings.EqualFold(r.KnowledgeSource, "web_search") { sourceWeight = 0.95 } + if r.MatchType == types.MatchTypeGraph { + baseScore = modelScore + } composite := 0.6*modelScore + 0.3*baseScore + 0.1*sourceWeight return math.Min(math.Max(composite, 0), 1) } + +// PreBoostScore returns the score to compare against absolute thresholds such +// as the FAQ direct-answer threshold: the composite score before any boost +// when the row was reranked, and its retrieval score otherwise. +func PreBoostScore(r *types.SearchResult) float64 { + if r == nil { + return 0 + } + if v, ok := r.Metadata[CompositeScoreKey]; ok { + if f, err := strconv.ParseFloat(v, 64); err == nil { + return f + } + } + return r.Score +} diff --git a/internal/reranking/rerank_test.go b/internal/reranking/rerank_test.go index 98b833e8..af1c77b5 100644 --- a/internal/reranking/rerank_test.go +++ b/internal/reranking/rerank_test.go @@ -164,9 +164,57 @@ func TestRerank_topKAppliesMMRAndFAQBoost(t *testing.T) { if len(res.Results) != 2 || len(res.Scored) != 3 { t.Fatalf("results=%d scored=%d", len(res.Results), len(res.Scored)) } - // The FAQ entry is boosted from 0.67 to 1.0 and ranks first. - if res.Results[0].ID != "c3" || res.Results[0].Metadata["faq_boosted"] != "true" || res.Results[0].Score != 1 { - t.Fatalf("FAQ boost not applied: %+v", res.Results[0]) + // The FAQ entry is boosted from 0.67 to 1.005, capped at 1, and ranks + // first; its pre-boost score stays available for absolute thresholds. + top := res.Results[0] + if top.ID != "c3" || top.Metadata["faq_boosted"] != "true" || math.Abs(top.Score-1.0) > 1e-9 { + t.Fatalf("FAQ boost not applied: %+v", top) + } + if got := PreBoostScore(top); math.Abs(got-0.67) > 1e-9 { + t.Fatalf("pre-boost score = %v, want 0.67", got) + } +} + +// Strong FAQ entries are capped at 1 and tie; their order must still follow +// relevance, and the boost must not leave the [0, 1] scale. +func TestRerank_boostedFAQsKeepRelevanceOrder(t *testing.T) { + t.Parallel() + in := rows("faq weaker", "faq stronger") + for _, r := range in { + r.ChunkType = string(types.ChunkTypeFAQ) + } + res := Rerank(context.Background(), &stubReranker{scores: []float64{0.9, 0.95}}, "q", in, + Options{Threshold: 0.3, FAQScoreBoost: 1.5}) + if len(res.Results) != 2 || res.Results[0].ID != "c2" { + t.Fatalf("boosted FAQs lost their order: %+v / %+v", res.Results[0], res.Results[1]) + } + for _, r := range res.Results { + if r.Score > 1 { + t.Fatalf("boosted score %v exceeds 1", r.Score) + } + } +} + +// Graph hits have no retrieval score; the model score stands in for it. +func TestCompositeScore_graphHitUsesModelScoreAsBase(t *testing.T) { + t.Parallel() + graph := &types.SearchResult{MatchType: types.MatchTypeGraph} + if got := CompositeScore(graph, 0.8, 0); math.Abs(got-(0.9*0.8+0.1)) > 1e-9 { + t.Fatalf("graph composite = %v", got) + } + vector := &types.SearchResult{MatchType: types.MatchTypeEmbedding} + if got := CompositeScore(vector, 0.8, 0); math.Abs(got-(0.6*0.8+0.1)) > 1e-9 { + t.Fatalf("vector composite = %v", got) + } +} + +func TestPreBoostScore_fallsBackToScore(t *testing.T) { + t.Parallel() + if got := PreBoostScore(&types.SearchResult{Score: 0.42}); got != 0.42 { + t.Fatalf("PreBoostScore without rerank metadata = %v", got) + } + if got := PreBoostScore(nil); got != 0 { + t.Fatalf("PreBoostScore(nil) = %v", got) } } @@ -200,3 +248,65 @@ func TestFallbackMinScore(t *testing.T) { t.Fatalf("explicit-scope fallback minimum = %v, want -Inf", got) } } + +// limitedReranker is a stubReranker whose vendor documents a passage limit. +type limitedReranker struct { + stubReranker + limit int +} + +func (l *limitedReranker) MaxPassageRunes(string) int { return l.limit } + +// An oversized passage used to fail the whole request, costing every +// candidate its score. Passages are now fitted to the documented limit, +// keeping the title and body ahead of the appended enrichments. +func TestRerank_fitsPassagesToModelLimit(t *testing.T) { + t.Parallel() + long := strings.Repeat("长", 50) + model := &limitedReranker{stubReranker: stubReranker{scores: []float64{0.9, 0.8}}, limit: 20} + res := Rerank(context.Background(), model, "q", rows(long, "short"), Options{Threshold: 0.3}) + if len(model.documents) != 2 { + t.Fatalf("documents sent = %d", len(model.documents)) + } + if n := len([]rune(model.documents[0])); n != 20 { + t.Fatalf("long passage has %d runes, want 20", n) + } + if model.documents[1] != "short" { + t.Fatalf("short passage changed: %q", model.documents[1]) + } + if len(res.Results) != 2 { + t.Fatalf("results = %d", len(res.Results)) + } +} + +// An OCR chunk's body is the OCR text and its image_info repeats it. +func TestEnrichedPassage_skipsImageTextRepeatingTheBody(t *testing.T) { + t.Parallel() + r := &types.SearchResult{ + Content: "Invoice total 42", + ChunkType: string(types.ChunkTypeImageOCR), + ImageInfo: `[{"url":"u","ocr_text":"Invoice total 42","caption":"a scanned invoice"}]`, + } + got := EnrichedPassage(context.Background(), r) + if strings.Count(got, "Invoice total 42") != 1 || !strings.Contains(got, "a scanned invoice") { + t.Fatalf("passage = %q", got) + } +} + +// MaxCandidates sends only the best-scored rows to the model, and indices +// still point into the caller's slice. +func TestRerank_maxCandidatesKeepsBestRetrievalScores(t *testing.T) { + t.Parallel() + in := rows("a", "b", "c", "d") + for i, s := range []float64{0.2, 0.9, 0.1, 0.8} { + in[i].Score = s + } + model := &stubReranker{scores: []float64{0.7, 0.6}} + res := Rerank(context.Background(), model, "q", in, Options{Threshold: 0.3, MaxCandidates: 2}) + if strings.Join(model.documents, ",") != "b,d" { + t.Fatalf("documents sent = %v, want the two best-scored rows in input order", model.documents) + } + if len(res.Indices) != 2 || res.Indices[0] != 1 || res.Indices[1] != 3 { + t.Fatalf("indices = %v, want [1 3]", res.Indices) + } +} diff --git a/internal/searchutil/imageinfo.go b/internal/searchutil/imageinfo.go index 3cae5442..d2c5b96d 100644 --- a/internal/searchutil/imageinfo.go +++ b/internal/searchutil/imageinfo.go @@ -189,6 +189,29 @@ func EnrichSearchResultsImageInfo( chunkRepo interfaces.ChunkRepository, tenantID uint64, results []*types.SearchResult, +) { + enrichSearchResultsImageInfo(results, func(chunkIDs []string) map[string]string { + return CollectImageInfoByChunkIDs(ctx, chunkRepo, tenantID, chunkIDs) + }) +} + +// EnrichSearchResultsImageInfoOnly is the shared-KB variant of +// EnrichSearchResultsImageInfo for results that may come from an org-shared +// KB owned by another workspace. The result IDs must already be authorized +// (they come from retrieval over KBs the caller may read). +func EnrichSearchResultsImageInfoOnly( + ctx context.Context, + chunkRepo interfaces.ChunkRepository, + results []*types.SearchResult, +) { + enrichSearchResultsImageInfo(results, func(chunkIDs []string) map[string]string { + return CollectImageInfoByChunkIDsOnly(ctx, chunkRepo, chunkIDs) + }) +} + +func enrichSearchResultsImageInfo( + results []*types.SearchResult, + collect func(chunkIDs []string) map[string]string, ) { var chunkIDs []string seen := make(map[string]bool) @@ -205,7 +228,7 @@ func EnrichSearchResultsImageInfo( return } - infoMap := CollectImageInfoByChunkIDs(ctx, chunkRepo, tenantID, chunkIDs) + infoMap := collect(chunkIDs) if len(infoMap) == 0 { return } diff --git a/internal/searchutil/textutil.go b/internal/searchutil/textutil.go index eb927aa0..6d98f0e3 100644 --- a/internal/searchutil/textutil.go +++ b/internal/searchutil/textutil.go @@ -23,8 +23,8 @@ func BuildContentSignature(content string) string { return hex.EncodeToString(hash[:]) } -// containsChinese checks whether text contains any CJK unified ideographs. -func containsChinese(text string) bool { +// ContainsChinese reports whether text contains any CJK unified ideographs. +func ContainsChinese(text string) bool { for _, r := range text { if unicode.Is(unicode.Han, r) { return true @@ -44,7 +44,7 @@ func TokenizeSimple(text string) map[string]struct{} { } var words []string - if containsChinese(text) { + if ContainsChinese(text) { // Use jieba for Chinese text segmentation (search mode for finer granularity) words = types.Jieba.CutForSearch(text, true) } else { @@ -130,8 +130,12 @@ func IsContentContained(normalizedShort, normalizedLong string) bool { // Returns a value in [0, 1] where 1 means the smaller set is fully contained // in the larger set. func ContentOverlapRatio(a, b string) float64 { - tokA := TokenizeSimple(a) - tokB := TokenizeSimple(b) + return TokenOverlapRatio(TokenizeSimple(a), TokenizeSimple(b)) +} + +// TokenOverlapRatio is ContentOverlapRatio over token sets already built with +// TokenizeSimple, for callers comparing one text against many. +func TokenOverlapRatio(tokA, tokB map[string]struct{}) float64 { if len(tokA) == 0 || len(tokB) == 0 { return 0 } diff --git a/internal/types/chat_manage.go b/internal/types/chat_manage.go index 9e6c49d4..54b6ec14 100644 --- a/internal/types/chat_manage.go +++ b/internal/types/chat_manage.go @@ -1,6 +1,9 @@ package types -import "maps" +import ( + "maps" + "strings" +) // PipelineRequest holds immutable configuration set once at the request entry point. type PipelineRequest struct { @@ -118,6 +121,9 @@ type PipelineState struct { RewriteQuery string `json:"rewrite_query,omitempty"` Intent QueryIntent `json:"intent,omitempty"` History []*History `json:"history,omitempty"` + // HistoryLoaded records that History was fetched this turn, so an empty + // History (a first turn) is not fetched again by a later stage. + HistoryLoaded bool `json:"-"` SearchResult []*SearchResult `json:"-"` RerankResult []*SearchResult `json:"-"` @@ -161,7 +167,9 @@ type ChatManage struct { // NeedsRetrieval returns true when the current pipeline execution should // run the retrieval stages (search, rerank, merge, etc.). // For IntentWebSearch, retrieval is only needed if web search is enabled; -// for all other intents it delegates to QueryIntent.NeedsKBRetrieval(). +// otherwise the intent prompt (intent_prompts.yaml "web_search") tells the +// user web search is unavailable. All other intents delegate to +// QueryIntent.NeedsKBRetrieval(). func (c *ChatManage) NeedsRetrieval() bool { if c.Intent == IntentWebSearch { return c.WebSearchEnabled @@ -169,6 +177,23 @@ func (c *ChatManage) NeedsRetrieval() bool { return c.Intent.NeedsKBRetrieval() } +// NormalizeQueryIntent maps a model-produced intent label onto a known +// intent. Case and separators are forgiven ("KB-Search" → kb_search); an +// unknown label becomes the empty intent, which retrieves. Taking the label +// verbatim turned any unexpected value into "no retrieval", so the answer +// was generated without the knowledge base and without an error. +func NormalizeQueryIntent(raw string) QueryIntent { + label := strings.ToLower(strings.TrimSpace(raw)) + label = strings.NewReplacer("-", "_", " ", "_").Replace(label) + switch intent := QueryIntent(label); intent { + case IntentKBSearch, IntentWebSearch, IntentGreeting, IntentChitchat, IntentFollowUp, + IntentImageOnly, IntentDocOnly, IntentSummarize, IntentClarification: + return intent + default: + return "" + } +} + // Clone creates a deep copy of the ChatManage object. // PipelineContext fields (EventBus, MessageID, etc.) are NOT copied because they // are per-execution handles that should not be shared across clones. diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.go index 84fc26bf..32448da3 100644 --- a/internal/types/interfaces/knowledge.go +++ b/internal/types/interfaces/knowledge.go @@ -264,6 +264,9 @@ type KnowledgeRepository interface { DeleteKnowledge(ctx context.Context, tenantID uint64, id string) error DeleteKnowledgeList(ctx context.Context, tenantID uint64, ids []string) error GetKnowledgeBatch(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error) + // GetKnowledgeBatchByIDOnly returns knowledge by IDs without tenant filter + // (for shared-KB resolution; callers check permissions on every row). + GetKnowledgeBatchByIDOnly(ctx context.Context, ids []string) ([]*types.Knowledge, error) // CheckKnowledgeExists checks if knowledge already exists. // For file types, check by fileHash or (fileName+fileSize). // For URL types, check by URL. diff --git a/internal/types/rerank.go b/internal/types/rerank.go index 8f270ba1..72b5f4c8 100644 --- a/internal/types/rerank.go +++ b/internal/types/rerank.go @@ -1,6 +1,9 @@ package types -import "errors" +import ( + "errors" + "fmt" +) // RerankOptions is the per-request rerank control shared by the retrieval // APIs (knowledge-search and hybrid-search). @@ -32,6 +35,9 @@ func (o *RerankOptions) Validate() error { if o != nil && o.TopK < 0 { return errors.New("rerank.top_k must not be negative") } + if o != nil && o.TopK > MaxRequestedResults { + return fmt.Errorf("rerank.top_k must not exceed %d", MaxRequestedResults) + } return nil } diff --git a/internal/types/retrieval_config.go b/internal/types/retrieval_config.go index fe5ab23b..4255bc05 100644 --- a/internal/types/retrieval_config.go +++ b/internal/types/retrieval_config.go @@ -43,6 +43,12 @@ type RetrievalConfig struct { // construction rather than by two independently maintained literals. const DefaultRetrievalTopK = 50 +// MaxRequestedResults caps the result counts a retrieval API caller may ask +// for (knowledge-search match_count, rerank.top_k). knowledge-search runs one +// search per scoped document or tag set and reranks every candidate, so an +// unbounded count multiplied into tens of thousands of billed rerank passages. +const MaxRequestedResults = 200 + // GetEffectiveEmbeddingTopK returns EmbeddingTopK with a fallback default. func (c *RetrievalConfig) GetEffectiveEmbeddingTopK() int { if c == nil || c.EmbeddingTopK <= 0 { diff --git a/internal/types/search.go b/internal/types/search.go index 595cb4f2..84962c7e 100644 --- a/internal/types/search.go +++ b/internal/types/search.go @@ -194,6 +194,9 @@ type SearchResult struct { // ChunkMetadata stores chunk-level metadata (e.g., generated questions) ChunkMetadata JSON `json:"chunk_metadata,omitempty"` + // ContextHeader is the chunk's heading breadcrumb, part of what was + // embedded (Chunk.EmbeddingContent) but not of Content. Internal only. + ContextHeader string `json:"-"` // MatchedContent is the actual content that was matched in vector search // For FAQ: this is the matched question text (standard or similar question) diff --git a/migrations/paradedb/00-init-db.sql b/migrations/paradedb/00-init-db.sql index 116c49e9..1ee30208 100644 --- a/migrations/paradedb/00-init-db.sql +++ b/migrations/paradedb/00-init-db.sql @@ -204,6 +204,8 @@ CREATE TABLE IF NOT EXISTS embeddings ( ); CREATE UNIQUE INDEX IF NOT EXISTS embeddings_unique_source ON embeddings(source_id, source_type); +CREATE INDEX IF NOT EXISTS idx_embeddings_knowledge_id ON embeddings(knowledge_id); +CREATE INDEX IF NOT EXISTS idx_embeddings_chunk_id ON embeddings(chunk_id); CREATE INDEX IF NOT EXISTS embeddings_search_idx ON embeddings USING bm25 (id, knowledge_base_id, content, knowledge_id, chunk_id) WITH ( diff --git a/migrations/versioned/000112_embeddings_knowledge_chunk_index.down.sql b/migrations/versioned/000112_embeddings_knowledge_chunk_index.down.sql new file mode 100644 index 00000000..3c5323a0 --- /dev/null +++ b/migrations/versioned/000112_embeddings_knowledge_chunk_index.down.sql @@ -0,0 +1,2 @@ +DROP INDEX IF EXISTS idx_embeddings_chunk_id; +DROP INDEX IF EXISTS idx_embeddings_knowledge_id; diff --git a/migrations/versioned/000112_embeddings_knowledge_chunk_index.up.sql b/migrations/versioned/000112_embeddings_knowledge_chunk_index.up.sql new file mode 100644 index 00000000..a1cfb913 --- /dev/null +++ b/migrations/versioned/000112_embeddings_knowledge_chunk_index.up.sql @@ -0,0 +1,24 @@ +-- Migration 000112: btree indexes on embeddings(knowledge_id) and (chunk_id) +-- +-- Deleting a document (DeleteByKnowledgeIDList), deleting or re-indexing +-- chunks (DeleteByChunkIDList), toggling chunk enabled state and moving chunk +-- tags (BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID) all filter +-- embeddings by knowledge_id or chunk_id, and so does vector retrieval scoped +-- to documents. Neither column was indexed, so each of these scanned the +-- whole table — every workspace's rows, each carrying its vector. +-- +-- Guarded on the table's existence like 000007 / 000059: deployments whose +-- RETRIEVE_DRIVER excludes postgres never create it. CONCURRENTLY is not used +-- because it cannot run inside the DO block; on a very large table an +-- operator can build the same indexes with CREATE INDEX CONCURRENTLY first, +-- and IF NOT EXISTS makes this migration a no-op afterwards. +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'embeddings') THEN + CREATE INDEX IF NOT EXISTS idx_embeddings_knowledge_id ON embeddings(knowledge_id); + CREATE INDEX IF NOT EXISTS idx_embeddings_chunk_id ON embeddings(chunk_id); + RAISE NOTICE '[Migration 000112] Created knowledge_id and chunk_id indexes on embeddings'; + ELSE + RAISE NOTICE '[Migration 000112] embeddings table does not exist · skipping'; + END IF; +END $$; diff --git a/website-docs/02-architecture/04-rag-pipeline.md b/website-docs/02-architecture/04-rag-pipeline.md index bf1200fc..448c5537 100644 --- a/website-docs/02-architecture/04-rag-pipeline.md +++ b/website-docs/02-architecture/04-rag-pipeline.md @@ -186,20 +186,20 @@ pipeline = types.NewPipelineBuilder(). - 输入组合分三种:纯文本(chat model)、文本+图片、纯图片(优先用支持视觉的 chat model,否则 `VLMModelID`)。 - Prompt 来自 `config/prompt_templates/rewrite.yaml`(system + user 对),可被 Agent 级 `RewritePromptSystem`/`RewritePromptUser` 覆盖;占位符 `{conversation}` / `{query}` / `{language}` 由 `types.RenderPromptPlaceholders` 渲染。 -- 模型要求输出 JSON:`{"rewrite_query":"...","intent":"kb_search","image_description":"..."}`;解析容错(markdown 包裹、字段别名、OCR 字段合并),JSON 完全解析失败时把原文当作改写结果并默认 `kb_search`。 -- 意图枚举(`types.QueryIntent`):`kb_search`、`web_search`、`greeting`、`chitchat`、`follow_up`、`image_only`、`doc_only`、`summarize`、`clarification`。`NeedsKBRetrieval()` 仅对 `kb_search`/`clarification`/`summarize`/空值返回 true;`ChatManage.NeedsRetrieval()` 对 `web_search` 额外看 `WebSearchEnabled`。**后续所有检索类插件都以 `NeedsRetrieval()` 作为跳过条件**。 +- 模型要求输出 JSON:`{"rewrite_query":"...","intent":"kb_search","image_description":"..."}`;解析容错(markdown 包裹、字段别名、OCR 字段合并);回复被输出上限截断时,按字段抢救已写出的 `rewrite_query`、`intent` 与半截 `image_description`;完全无法解析时保留原始查询,意图为空(按需要检索处理)。带图片的轮次输出上限为 2048 token(prompt 要求把 OCR 全文放进 `image_description`)。 +- 意图枚举(`types.QueryIntent`):`kb_search`、`web_search`、`greeting`、`chitchat`、`follow_up`、`image_only`、`doc_only`、`summarize`、`clarification`。模型给出的意图先经 `types.NormalizeQueryIntent` 归一(忽略大小写与 `-`/空格,如 `KB-Search` → `kb_search`),不认识的标签按空值处理。`NeedsKBRetrieval()` 仅对 `kb_search`/`clarification`/`summarize`/空值返回 true;`ChatManage.NeedsRetrieval()` 对 `web_search` 额外看 `WebSearchEnabled`(未开启时走意图提示词,告知用户当前不能联网搜索)。**后续所有检索类插件都以 `NeedsRetrieval()` 作为跳过条件**。 - 非检索意图时 `applyIntentPromptOverride` 用 `config/prompt_templates/intent_prompts.yaml`(模板 id 与意图值一一对应,如 `greeting`)或 Agent 覆盖设置 `SystemPromptOverride`。 - 图片描述异步回写到 user 消息的 `Images[0].Caption`(供下一轮历史使用)。 - 可用 `QueryUnderstandModelID` 为该阶段单独指定小模型,失败回退 `ChatModelID`。 -**PluginExtractEntity**(`extract_entity.go`)在链内层执行:仅当 `NEO4J_ENABLE=true` 且检索范围内存在 `ExtractConfig.Enabled` 的知识库时,用 `config.ExtractManager.ExtractEntity` 模板(`graph_extraction.yaml`)调用 LLM 抽取查询实体,写入 `chatManage.Entity` / `EntityKBIDs` / `EntityKnowledge`,供 `ENTITY_SEARCH` 使用。 +**PluginExtractEntity**(`extract_entity.go`)在链内层执行:仅当 `NEO4J_ENABLE=true`、本轮意图需要知识库检索(寒暄、闲聊等不调用)且检索范围内存在 `ExtractConfig.Enabled` 的知识库时,优先用改写后的查询,用 `config.ExtractManager.ExtractEntity` 模板(`graph_extraction.yaml`)调用 LLM 抽取查询实体,写入 `chatManage.Entity` / `EntityKBIDs` / `EntityKnowledge`,供 `ENTITY_SEARCH` 使用。 ### CHUNK_SEARCH_PARALLEL — 并行检索(chunk + 图谱实体) {#_3-3-chunk-search-parallel-—-并行检索-chunk-图谱实体} `search_parallel.go`。`NeedsRetrieval()` 为假直接跳过。否则将 `chatManage` `Clone()` 两份,用 `RunParallel` 并发执行: - `chunk_search`:内部(未注册的)`PluginSearch.OnEvent(CHUNK_SEARCH, ...)`; -- `entity_search`:有实体时执行 `PluginSearchEntity.OnEvent(ENTITY_SEARCH, ...)`,在 Neo4j 中按 `NameSpace{KnowledgeBase, Knowledge}` 并行 `SearchNode`,将命中的图节点/关系转换为 SearchResult 并组装 `GraphResult`。 +- `entity_search`:有实体时执行 `PluginSearchEntity.OnEvent(ENTITY_SEARCH, ...)`,在 Neo4j 中按 `NameSpace{KnowledgeBase, Knowledge}` 并行 `SearchNode`,将命中的图节点/关系转换为 SearchResult 并组装 `GraphResult`。分块与文档按 ID 查询(不限当前工作空间,组织共享知识库的图谱命中也能解析),只保留属于本轮检索范围内知识库、仍启用且文档存在的分块,最多 30 条;图谱命中没有检索分(`Score=0`),重排时用模型分代替。 两路结果合并后 `removeDuplicateResults` 去重(按 chunk ID + 内容签名 `searchutil.BuildContentSignature`)。两路都空时返回 `ErrSearchNothing`。 @@ -210,20 +210,20 @@ pipeline = types.NewPipelineBuilder(). - 组内无标签/文档约束的整库目标合并为**一次** `HybridSearch` 调用(`params.KnowledgeBaseIDs` 携带多库),带约束的目标逐个 `searchSingleTarget`(携带 `KnowledgeIDs`/`TagIDs`/`ScopeTagIDs`,且显式圈定范围的目标可 `DisableRecallThresholds` 关闭召回阈值); 2. **Web 搜索** `searchWebIfEnabled`:`WebSearchEnabled` 时用租户/Agent 解析出的 `WebSearchProviderID` 调用 `webSearchService.Search`,结果经 `searchutil.ConvertWebSearchResults` 转为 SearchResult(URL 作为 ID,`KnowledgeSource="web_search"`)。 -**查询扩展**(`query_expansion.go`):`EnableQueryExpansion` 且初次召回数少于 `EmbeddingTopK` 时触发。不调用 LLM,本地生成查询变体(去停用词、词序调整、关键短语抽取等)。中文分词走 `types.Jieba.CutForSearch`:连续汉字段落整体交给 jieba 切成词,中英文/数字混排按脚本切换分段处理,不再退化成「一个汉字一个 token」;停用词与长度过滤按 rune 计数,避免多字节字符被误判为单字符,对每个(变体 × SearchTarget)组合并发(信号量上限 16)执行 `HybridSearch`,关键词阈值放宽为原值的 0.8,TopK 放大为 `max(EmbeddingTopK, RerankTopK) * 2`。 +**查询扩展**(`query_expansion.go`):`EnableQueryExpansion` 且初次召回数少于 `EmbeddingTopK` 时触发。不调用 LLM,本地生成查询变体(去停用词、词序调整、关键短语抽取等)。中文分词走 `types.Jieba.CutForSearch`:连续汉字段落整体交给 jieba 切成词,中英文/数字混排按脚本切换分段处理,不再退化成「一个汉字一个 token」;停用词与长度过滤按 rune 计数,避免多字节字符被误判为单字符,对每个(变体 × SearchTarget)组合并发(信号量上限 16)执行**只走关键词**的 `HybridSearch`(变体只在关键词侧增加召回,向量侧与原查询几乎相同,不再为每个变体重新 embedding),关键词阈值放宽为原值的 0.8,TopK 放大为 `max(EmbeddingTopK, RerankTopK) * 2`;关键词检索被关闭时不做扩展。 ### CHUNK_RERANK — 重排、复合打分、MMR、Wiki 加权 {#_3-4-chunk-rerank-—-重排、复合打分、mmr、wiki-加权} **PluginRerank**(`rerank.go`,720 行): 1. **Passage 清洗** `cleanPassageForRerank`:重排模型做的是语义相似度,Markdown 结构语法是噪声。代码块与 `$$...$$` 公式块**只脱掉围栏、保留内部正文**(早期实现整块删除,纯代码或纯公式的候选会被清成空串而丢分);HTML 标签、图片引用、链接标记(保留文字)、裸 URL、表格分隔行(数据行转逗号拼接)、标题/引用/加粗/列表标记按序剥离,最后压缩多余空行。 -2. **Passage 增强** `getEnrichedPassage`:拼入 `ImageInfo` 的 Caption/OCR 文本与 `ChunkMetadata` 中的生成问题(GeneratedQuestions)。 +2. **Passage 增强** `getEnrichedPassage`:拼入 `ImageInfo` 的 Caption/OCR 文本与 `ChunkMetadata` 中的生成问题(GeneratedQuestions);与正文相同的图片文本(OCR / 描述分块自身)不重复拼接。模型配置了单篇或单次请求长度上限时,超长 passage 从尾部截到上限;候选按检索分最多取 200 条送去打分。 3. 调用 `rerankModel.Rerank(ctx, RewriteQuery, passages)`,按 `RerankThreshold` 过滤: - 全部低于阈值且 top1 ≥ `rerankFallbackMinScore`(默认 0.15;用户显式圈定标签/文档范围时为 0,保留权威范围的最佳候选)→ 保留 top1 兜底; - 无结果且阈值 > 0.3 → **阈值降级**重试一次(`threshold * 0.7`,下限 0.3); - - Rerank API 失败 → 回退原始检索结果继续管线。 -4. **复合打分** `compositeScore`:`0.6*模型分 + 0.3*检索基础分 + 0.1*来源权重`(web_search 来源权重 0.95,其余 1.0),clamp 到 [0,1]。基础分/模型分记录在 `Metadata["base_score"]` / `["model_score"]`。早期版本还会乘一个「越靠文档前部越高」的位置先验(±0.05),因为它与分块编辑后的偏移变化耦合且收益不明确,已被移除。 -5. **FAQ 加权**:`FAQPriorityEnabled` 且 `FAQScoreBoost > 1.0` 时,FAQ chunk 分数乘以 boost(上限 1.0),记 `Metadata["faq_boosted"]`。 + - Rerank 模型加载失败(被删除、配置错误)或 API 失败(含默认 60 秒超时)→ 回退原始检索结果继续管线。 +4. **复合打分** `compositeScore`:`0.6*模型分 + 0.3*检索基础分 + 0.1*来源权重`(web_search 来源权重 0.95,其余 1.0),clamp 到 [0,1]。图谱实体检索命中的 chunk 没有检索分,基础分用模型分代替。基础分/模型分/复合分记录在 `Metadata["base_score"]` / `["model_score"]` / `["composite_score"]`。早期版本还会乘一个「越靠文档前部越高」的位置先验(±0.05),因为它与分块编辑后的偏移变化耦合且收益不明确,已被移除。 +5. **FAQ 加权**:`FAQPriorityEnabled` 且 `FAQScoreBoost > 1.0` 时,FAQ chunk 分数乘以 boost,记 `Metadata["faq_boosted"]`。结果不封顶到 1.0——封顶会让高分 FAQ 全部并列 1.0,彼此顺序退化为 tie-breaker。 6. **MMR 多样性选择** `applyMMR`(λ=0.7,k=`RerankTopK`):`mmr = 0.7*relevance - 0.3*max_jaccard_redundancy`,用 `searchutil.TokenizeSimple` + `Jaccard` 并行预计算 token 集合,迭代贪心选出 `RerankResult`。 **PluginMemoryAffinity**(`memory_affinity.go`)注册在链的最内层,同样先 `next()` 再后置处理:对该调用者过往回答中至少引用过 2 次的文档,按使用次数对数增长加权,最高 ×1.15,只用于在相近候选之间打破平局。随后才轮到 WikiBoost 的后置加权。 @@ -238,14 +238,14 @@ pipeline = types.NewPipelineBuilder(). `merge.go` 的 `OnEvent` 注释即流程说明: -1. **选择输入**:优先 `RerankResult`,为空则回退 `SearchResult`(按分排序); +1. **选择输入**:优先 `RerankResult`,为空则回退 `SearchResult`(按分排序并截到 `RerankTopK`,避免对全部召回结果做回表和扩展); 2. **去重**:ID + 内容签名; -3. **注入历史引用**(`merge_history.go`):从最近一轮带引用的历史取 `KnowledgeReferences`,与当前查询做 Jaccard 相似度过滤(阈值 0.15),分数打 0.6 折,最多注入 3 条,标记 `MatchTypeHistory`; +3. **注入历史引用**(`merge_history.go`):从最近一轮带引用的历史取 `KnowledgeReferences`,按引用覆盖了多少查询词过滤(重合系数 `|q∩c|/min(|q|,|c|)` ≥ 0.3;Jaccard 除以并集,约 8 个词的查询对上几百词的分块永远到不了阈值),分数打 0.6 折,最多注入 3 条,标记 `MatchTypeHistory`; 4. **父子块解析** `resolveParentChunks`:text 子块与 image_ocr/image_caption 子块都用**当前** parent_text 内容补齐上下文;图片 Markdown 的收窄靠稳定的图片 URL(`PruneMarkdownImagesByImageInfo`)而不是解析器坐标;ImageInfo 严格限定在命中的 text 子块,避免图片密集的父块把兄弟页面的 OCR 全部灌进上下文。image → text → parent_text 这条链只在确实命中图片结果时才多查一次祖父块; 5. **分组顺序合并** `groupAndMergeCurrentContent`:按 `KnowledgeID + ChunkType` 分组,组内按 `ChunkIndex` 排序后 `mergeSequentialChunks`——序号连续、或一方内容包含另一方时用 `searchutil.JoinChunkContent` 拼接,保留最高分,`SubChunkID` 记录被合并块,`mergeImageInfo` 按 URL 去重合并图片信息; 6. **FAQ 答案填充**(`merge_faq.go`):FAQ 类型 chunk 批量回表读 `FAQMetadata`,重写 Content 为 `Q: 标准问题 + Answer: 答案列表`; -7. **短上下文邻居扩展**(`merge_expand.go`):text 块内容不足 350 字符时,批量取 `PreChunkID`/`NextChunkID` 邻居拼接至最长 850 字符; -8. 扩展引入的新重复**再合并一次**,最终去重 + `removePartialOverlaps`(归一化包含判断 / token 重合率 ≥ 0.85 的跨库近重复删除,低分者被删)。 +7. **短上下文邻居扩展**(`merge_expand.go`):text 块内容不足 350 字符时,批量取 `PreChunkID`/`NextChunkID` 邻居拼接至最长约 850 字符。命中块本身完整保留,剩余长度分给紧挨着它的前文末尾与后文开头;邻居必须属于同一文档,组织共享知识库的分块同样可以扩展; +8. 扩展引入的新重复**再合并一次**,最终去重 + `removePartialOverlaps`(归一化包含判断 / token 重合率 ≥ 0.85 的跨库近重复删除,低分者被删;重合率只在两者 token 数相差不超过 3 倍时比较,避免长网页或父块"覆盖"短分块;每条文本只分词一次)。 结果写入 `chatManage.MergeResult`。 @@ -267,7 +267,7 @@ pipeline = types.NewPipelineBuilder(). - `utils.ValidateInput` 校验查询安全性(注入防护); - 非检索意图路径:仍走 `ContextTemplate` 渲染(`contexts` 为空),以注入 `current_time` 等运行时元数据; -- **FAQ 优先策略**:`FAQPriorityEnabled` 时把 FAQ 与文档结果分为 `source type="faq" priority="high"` 与 `source type="document" priority="supplementary"` 两个分节;最高分 FAQ ≥ `FAQDirectAnswerThreshold` 时其 context 标记 `match="exact"`(提示模型可直接采纳该答案); +- **FAQ 优先策略**:`FAQPriorityEnabled` 时把 FAQ 与文档结果分为 `source type="faq" priority="high"` 与 `source type="document" priority="supplementary"` 两个分节;第一条加权前得分(`composite_score`,未重排时为检索分)≥ `FAQDirectAnswerThreshold` 的 FAQ,其 context 标记 `match="exact"`(提示模型可直接采纳该答案)。比较加权前的分数,是为了不让 FAQ/Wiki/记忆加权把中等匹配抬过阈值; - 普通路径按 `context id="N"` 顺序编号包裹每个增强后的 passage(`getEnrichedPassageForChat` 会把 ImageInfo 以 Markdown 图片+描述内联进内容); - 头部 `buildDocumentHeader` 输出去重后的文档元信息(title/description); - 渲染 `SummaryConfig.ContextTemplate`(来自 `config/prompt_templates/context_template.yaml`),占位符 `{query}` / `{contexts}` / `{language}`;追加图片描述(非视觉模型)、引用上下文 `QuotedContext`、附件 prompt; @@ -487,9 +487,10 @@ sequenceDiagram 5. **fan-out**(`knowledgebase_search_fanout.go`):单组直查零开销;多组用 `errgroup` 并发(上限 4),每组超时 `MULTI_STORE_RETRIEVE_TIMEOUT_SEC`(默认 30s),all-or-nothing 失败策略;结果跨引擎类型时用 `EngineAwareNormalizer` 把向量分归一化到 [0,1](详见检索引擎文档)。 6. **融合**(`knowledgebase_search_fusion.go`): - 仅向量或仅关键词 → `deduplicateByScore`(按 chunk 保留最高分); - - 混合 → **加权 RRF**:`score = vectorWeight/(k+vectorRank) + keywordWeight/(k+keywordRank)`,`k` 与权重来自租户 `RetrievalConfig`(有缺省值),rank 基于各自检索器返回顺序(1-indexed),对分数尺度免疫。 + - 混合 → **加权 RRF**:`score = vectorWeight/(k+vectorRank) + keywordWeight/(k+keywordRank)`,再除以理论最大值 `(vectorWeight+keywordWeight)/(k+1)` 归一化到 [0,1];`k` 与权重来自租户 `RetrievalConfig`(有缺省值),rank 在每个检索结果列表内按分数单独计算(1-indexed),chunk 取最好名次; + - 三条路径输出都在 [0,1](向量为 cosine 相似度),不同检索调用的结果可以一起排序。 7. **FAQ 命中策略**(`knowledgebase_search_faq.go`,仅 FAQ 类型 KB): - - **迭代检索**:去重后不足 `MatchCount` 且首轮已打满 → 从 `TopK*3` 起最多 5 轮翻倍扩大 TopK 重检索,跨 store 组统一生效,chunk 数据缓存避免重复回表;种子与每轮增长均封顶 `maxRetrievalPoolSize`,触顶即停(再迭代只会重发同一个查询); + - **迭代检索**(主 KB 为 FAQ 库时):去重后不足 `MatchCount` 且有某个向量结果列表已打满 → 从首轮深度的 2 倍起最多 5 轮翻倍扩大 TopK 重检索,跨 store 组统一生效,每轮按首轮相同的方式融合(分数尺度一致),chunk 数据缓存避免重复回表;种子与每轮增长均封顶 `maxRetrievalPoolSize`,首轮已到上限则不迭代,触顶即停; - **负例问题过滤**:查询与 FAQ 的 `NegativeQuestions` 精确匹配(小写去空格)即剔除该条——支持"这个问题不要用这条 FAQ 答"的运营配置。 8. 截断到 `MatchCount` 后 `processSearchResults` 补全 chunk 元数据(管线场景 `SkipContextEnrichment=true`,上下文组装留给 merge 阶段)。 diff --git a/website-docs/03-features/05-retrieval-engines.md b/website-docs/03-features/05-retrieval-engines.md index d7f3be5e..da8b5d62 100644 --- a/website-docs/03-features/05-retrieval-engines.md +++ b/website-docs/03-features/05-retrieval-engines.md @@ -152,7 +152,7 @@ flowchart TD `internal/application/repository/retriever/opensearch/`(多文件拆分:`repository.go`、`retrieve.go`、`query.go`、`mapping.go`、`crud.go` 等)。 - **版本门禁** `probeVersion`:拒绝 ES 发行版与 OS 1.x / 2.0-2.3(Lucene HNSW 预览版);2.4-2.10 警告接受;2.11+ / 3.x 干净接受(主测 3.3.2)。`probeKNNPlugin` 要求所有节点装有 `opensearch-knn` 插件。 -- **向量检索**:k-NN 插件 `knn` 查询(`query.go buildKNNQuery`);k-NN 的 `COSINESIMIL` space type 返回 `(1+cosine)/2`,天然 [0,1]。 +- **向量检索**:k-NN 插件 `knn` 查询(`query.go buildKNNQuery`);k-NN 的 `COSINESIMIL` space type 返回 `(1+cosine)/2`。驱动把阈值换算成 `min_score = (1+threshold)/2` 下推,返回时再换回 cosine 相似度(`2*score-1`),与其他引擎同一尺度。 - **关键词检索**:`match` content(BM25)。混合不走 OS 原生 hybrid pipeline,统一交给上层 RRF 融合(`query.go` 注释明示)。 - **建索引**:`mapping.go` 声明式 mapping(`knn_vector` 字段带 method/engine 参数),启动时校验 mapping 指纹,漂移报 `ErrConfigInvalid`;别名管理 + `copy.go` 支持 reindex;索引创建/重建事件经 AuditSink 写审计日志。 - 配置含 `OPENSEARCH_INSECURE_SKIP_VERIFY` 与 SSRF 安全传输层(`transport.go`)。 @@ -173,7 +173,7 @@ flowchart TD `internal/application/repository/retriever/milvus/repository.go`。 - **集合管理**:每维度一个 collection(`{MILVUS_COLLECTION|weknora_embeddings}_{dim}`)。schema 含稠密向量 `embedding`(HNSW 索引,M=16 efConstruction=128,metric 由 `MILVUS_METRIC_TYPE` 决定:IP 默认 / COSINE / L2)与稀疏向量 `content_sparse` —— 通过 **内建 BM25 Function**(`entity.FunctionTypeBM25`)由 content 自动生成,配 `AutoIndex(BM25)`。新建 Collection 的 `content` 使用 Milvus 多语言分析器:英文 `english`、中文 `chinese`(内置 Jieba)、未知语言 `default`(ICU),并以 `language` 字段选择分析器。 -- **向量检索**:`Search` + `WithANNSField(embedding)`,COSINE 模式原始值域 [-1,1],是唯一需要 `(score+1)/2` 归一化的引擎。 +- **向量检索**:`Search` + `WithANNSField(embedding)`。IP / COSINE 直接返回 cosine 相似度;L2 返回平方欧氏距离,驱动换算成 `1 - d/2`,阈值换算成搜索半径 `2(1 - threshold)`。 - **关键词检索**:对 `content_sparse` 做 BM25 稀疏向量检索(Milvus 2.5+ 原生全文检索),查询时根据问题文本的语言传入 `analyzer_name`。返回 Milvus 给出的真实 BM25 分数;跨多个维度 collection 检索时先按分数合并排序,再截取 TopK。 - **过滤**:`filter.go` 构造布尔表达式(kb/knowledge/tag/is_enabled)。 - **启停同步**:`BatchUpdateChunkEnabledStatus` 逐 collection 更新,失败用 `errors.Join` 聚合后**返回错误**而不是只打 warn——主库里已停用的分块绝不能因为索引更新静默失败而继续可被检索到。 @@ -184,7 +184,7 @@ flowchart TD `internal/application/repository/retriever/weaviate/repository.go`。HTTP + gRPC 双通道。 - **类管理**:动态创建 Class(`WEAVIATE_COLLECTION` 解析),支持 ReplicationConfig / ShardingConfig。 -- **向量检索**:GraphQL `nearVector` + `WithCertainty(threshold)`;certainty = `(2-distance)/2`,天然 [0,1],阈值原生下推。 +- **向量检索**:GraphQL `nearVector` + certainty 阈值下推;certainty = `(2-distance)/2 = (1+cos)/2`。驱动下推 `(1+threshold)/2`,返回时换回 cosine 相似度(`2*certainty-1`),与其他引擎同一尺度。 - **关键词检索**:GraphQL **BM25** 查询(`Bm25ArgBuilder`)。 - **过滤**:GraphQL where 过滤 KB/knowledge/tag/is_enabled。 - 配置:`WEAVIATE_HOST` / `WEAVIATE_GRPC_ADDRESS` / `WEAVIATE_SCHEME` / `WEAVIATE_AUTH_ENABLED` + `WEAVIATE_API_KEY`。 @@ -234,18 +234,21 @@ WeKnora 允许不同 KB 使用不同 embedding 模型(维度各异),各引 #### 跨引擎向量分归一化(EngineAwareNormalizer) {#_5-1-跨引擎向量分归一化-engineawarenormalizer} -`internal/application/service/retriever/normalizer.go`。多 store fan-out 且结果跨引擎类型时(`hasMixedEngineTypes`),把各引擎的向量分映射到统一 [0,1]: +所有驱动返回的向量分都是 **cosine 相似度**,向量阈值也按 cosine 相似度解释;引擎原生尺度不同时由驱动自己换算: -| 引擎 | 原始值域 | 归一化 | +| 引擎 | 引擎原生分数 | 驱动换算 | |------|---------|--------| -| Milvus(COSINE) | [-1, 1] 原始 cosine | `(score + 1) / 2` 再 clamp01 | -| Elasticsearch v8 | [0, 1](Lucene script_score 非负不变量) | 直通 clamp01 | -| OpenSearch | [0, 1](k-NN COSINESIMIL 已做 `(1+cos)/2`) | 直通 clamp01 | -| Weaviate | [0, 1](certainty 定义即 `(2-distance)/2`) | 直通 clamp01 | -| Postgres / SQLite / Qdrant / TencentVectorDB / Doris | 理论 [-1,1],IR 归一化 embedding 实际 [0,1] | 直通 clamp01 | -| 未知引擎 | — | clamp01 兜底 + 每请求一次 WARN | +| Postgres / SQLite | cosine 距离 | `1 - distance` | +| Qdrant / TencentVectorDB / Doris | cosine(或归一化向量的内积) | 直通 | +| Milvus(IP / COSINE) | 内积 / cosine | 直通 | +| Milvus(L2) | 平方欧氏距离,单位向量下 = `2 - 2cos` | 分数 `1 - d/2`,阈值换成半径 `2(1 - threshold)` | +| Elasticsearch v8 | `cosineSimilarity` script_score(Lucene 要求非负) | 直通 | +| OpenSearch | k-NN COSINESIMIL:`(1+cos)/2` | 分数 `2*score-1`,阈值 `(1+threshold)/2` | +| Weaviate | certainty:`(1+cos)/2` | 分数 `2*certainty-1`,阈值 `(1+threshold)/2` | -**关键词(BM25)分数不归一化**——其值域无上界,压缩会坍缩长尾;下游 RRF 基于 rank,天然免疫尺度差异。`clamp01` 同时消化 NaN/Inf,保护下游排序的严格弱序不变量。同一引擎内部的结果保持原生尺度(直接可比,不做无谓变换)。 +`internal/application/service/retriever/normalizer.go` 在多 store fan-out 且结果跨引擎类型时(`hasMixedEngineTypes`)再对向量分做一次 clamp01,兜住理论上的负 cosine 与 NaN/Inf;未知引擎同样 clamp01,并每请求打一次 WARN。 + +**关键词(BM25)分数在这一步不归一化**——其值域无上界,压缩会坍缩长尾;融合阶段再按各自列表处理(见下)。`clamp01` 同时消化 NaN/Inf,保护下游排序的严格弱序不变量。 #### RRF 加权融合 {#_5-2-rrf-加权融合} @@ -253,12 +256,16 @@ WeKnora 允许不同 KB 使用不同 embedding 模型(维度各异),各引 ```go // fuseWithRRF -rrfScore = vectorWeight/(rrfK + vectorRank) + keywordWeight/(rrfK + keywordRank) +rrf = vectorWeight/(rrfK + vectorRank) + keywordWeight/(rrfK + keywordRank) +score = rrf / ((vectorWeight + keywordWeight) / (rrfK + 1)) // 归一化到 [0,1] ``` -- rank 为各路结果的 1-indexed 排名(各引擎已按分排序返回); +- 每个 `RetrieveResult`(不同引擎、store 组、文档/FAQ 参数各是一个列表)**单独**按分数排名,chunk 取它在各列表中的最好名次。各列表按 goroutine 完成顺序拼接,拼接后的下标没有意义——否则后到列表的第 1 名会被当成第 N+1 名; +- 分数除以理论最大值,两路都排第一的 chunk 得 1,只在一路排第一的得该路权重占比(缺省 0.7 / 0.3)。未归一化的 RRF 最高约 0.016,与单路检索的 cosine(约 0.5–0.9)混排时会被整体压到后面,复合打分的基础分项和 MMR 的相关性项也失去作用; - `rrfK`、`vectorWeight`、`keywordWeight` 来自租户 `RetrievalConfig`(`GetEffectiveRRFK` / `GetEffectiveRRFWeights` 提供缺省); -- 单路结果时不走 RRF,`deduplicateByScore` 保留每 chunk 最高原始分。只有向量结果时保持原始相似度(对 FAQ 的 embedding 相似度语义很重要,如 `FAQDirectAnswerThreshold` 直接比对该分数);只有关键词结果时,若最高分超过 1,则全部除以最高分折算到 [0,1],保持相对顺序,避免无上界的 BM25 分数让后续复合打分饱和。检索 trace 中仍记录原始 BM25 分数。 +- 单路结果时不走 RRF,`deduplicateByScore` 保留每 chunk 最高分。只有向量结果时保持 cosine 相似度;只有关键词结果时,每个列表按自己的最高分折算到 [0,1](不同引擎的 BM25 不可比),保持相对顺序,避免无上界的 BM25 分数让后续复合打分饱和。检索 trace 中仍记录原始 BM25 分数。 + +三条路径的输出都在 [0,1],所以不同检索调用(按文档/标签的 target、不同 embedding 模型分组、FAQ 与文档调用)的结果可以放在一起排序。 融合之后的复合打分(rerank 模型分 0.6 + 检索基础分 0.3 + 来源权重 0.1、MMR、FAQ/Wiki 加权)发生在 chat pipeline 的 `CHUNK_RERANK` 阶段,见[检索问答流程的重排阶段](../02-architecture/04-rag-pipeline.md#_3-4-chunk-rerank-—-重排、复合打分、mmr、wiki-加权)。 @@ -292,7 +299,7 @@ sequenceDiagram C-->>H: RetrieveResult (带 RetrieverEngineType) H->>H: 跨引擎类型时 EngineAwareNormalizer 归一化向量分 H->>F: classifyRetrievalResults 分路 - F->>F: 双路则 RRF: w_v/(k+rank_v) + w_k/(k+rank_k) + F->>F: 双路则 RRF(各列表单独排名,除以最大值归一化到 [0,1]) F-->>H: 融合去重排序结果 H->>H: FAQ 库: 迭代扩召回 / 负例问题过滤 H-->>P: SearchResult (截断至 matchCount) diff --git a/website-docs/03-features/06-models.md b/website-docs/03-features/06-models.md index 6f664d49..45b3b0f9 100644 --- a/website-docs/03-features/06-models.md +++ b/website-docs/03-features/06-models.md @@ -203,7 +203,7 @@ | `max_documents` / `max_query_chars` / `max_document_chars` / `max_request_chars` | int | 0(不限) | 单次请求的文档数、查询长度、单篇长度与总长度上限,超出自动分批 | | `max_concurrency` | int | 0(使用默认) | 分批后同时发出的请求数 | | `accepts_truncate_prompt_tokens` | bool | false | 服务是否支持 vLLM 的 `truncate_prompt_tokens` | -| `request_timeout_seconds` | int | 0(不单独限制) | 单次请求超时(秒) | +| `request_timeout_seconds` | int | 0(默认 60 秒) | 单次请求超时(秒);超时按调用失败处理,检索回退为召回顺序 | | `extra_body` | object | 空 | 附加到每次请求的字段 | **语音识别模型** diff --git a/website-docs/03-features/07-agent.md b/website-docs/03-features/07-agent.md index 3d144abd..047ac642 100644 --- a/website-docs/03-features/07-agent.md +++ b/website-docs/03-features/07-agent.md @@ -342,7 +342,7 @@ if !state.IsComplete && ctx.Err() == nil { **③ Act(行动)**:`executeToolCalls`(`internal/agent/act.go`)执行本轮所有工具调用: -- `AgentConfig.ParallelToolCalls == true` 且调用数 ≥ 2 时用 `errgroup` **并行执行**(best-effort,单个失败不取消兄弟任务),结果按原顺序回填; +- 调用数 ≥ 2 时用 `errgroup` **并行执行**(`buildAgentConfig` 固定开启 `ParallelToolCalls`;best-effort,单个失败不取消兄弟任务),结果按原顺序回填。只有只读工具(`CanRunConcurrently`:检索、阅读、搜索类)会重叠执行;其他工具是屏障,等前面的调用结束后单独执行,再继续后面的调用; - 每个调用先 `NormalizeToolCallID`,然后解析 JSON 参数——解析失败会先经 `RepairJSON` 修复再试;仍失败则返回带提示的错误结果(`"[Analyze the error above and try a different approach.]"`),让模型换路子而不是让整轮失败; - 单个工具执行超时 `defaultToolExecTimeout = 60s`;`shell_exec` 为 `shellExecToolTimeout = 10m5s`(略长于命令自身 600s 上限,以便返回结构化超时结果),`local_browser` 的人工接管步骤使用单独的等待时长;`ToolExecContext` 中额外携带不带该超时的 `ApprovalCtx`,供 MCP 人工审批/OAuth 等合法长等待使用; - 发射 `EventAgentToolCall`(含中文 display name 的 hint,如 `搜索网页("...")`)、`EventAgentToolResult`、`EventAgentTool` 事件。工具执行失败同样以 `tool_result` 发给客户端(`success: false` 与 `error`),不再作为 `error` 事件,智能体会根据错误继续处理。 @@ -408,10 +408,10 @@ flowchart TD | --- | --- | --- | | `thinking` | `thought`\*、`next_thought_needed`\*、`thought_number`\*、`total_thoughts`\*、`is_revision`、`revises_thought`、`branch_from_thought`、`branch_id`、`needs_more_thoughts` | Sequential Thinking:记录/修订/分支思考步骤;返回思考进度(含 `incomplete_steps`),提示禁止在思考里出现工具名和最终答案 | | `todo_write` | `task`、`steps[]`\*(`id`/`description`/`status`:pending/in_progress/completed) | 创建/更新检索类任务计划,仅限检索任务(总结交给 thinking);返回格式化计划,`display_type: "plan"` | -| `search_knowledge` | `query`\*(一条自然语言问题或短语;keyword 模式下写精确词)、`mode`(`hybrid` 默认 / `semantic` / `keyword`)、`knowledge_base_ids[]`(`bN`,最多 10 个)、`limit`(默认 10,上限 30) | 唯一的知识库检索入口:`hybrid` 走向量 + 关键词的 RRF 融合,`semantic` 只走向量,`keyword` 由关键词索引(BM25 / 引擎关键词检索)提供,不再对 chunks 表做无索引的正则扫描;召回阈值与候选池取全局 `conversation.vector_threshold` / `keyword_threshold` / `embedding_top_k`(随附 `config.yaml` 为 0.2 / 0.3 / 30,未配置时回退 0.6 / 0.5 / 30),不读智能体自身的阈值;有 rerank 模型时重排(打分文本为「文档标题 + 分块正文」,FAQ 除外;阈值默认 0.3,全部未过阈值时保留得分 ≥ 0.15 的最佳候选),结果再做 MMR(λ=0.7)去冗;重排全部拒绝时结果带 `rerank_rejected` 并提示换 `keyword` 查标识符类词;结果带 `cN`/`dN` 短 ID,同一次调用内去重,同一文档的元数据头只输出一次;所选 KB 没有对应索引时按库降级而不是报错:`keyword` 遇到 FAQ 库或纯向量库改走语义检索,`semantic` 遇到纯关键词库改走关键词检索,结果里以 `requested_mode` 和 `mode_fallbacks` 标明哪些库降级及原因;只有作用域内没有任何分块索引(如全是仅 Wiki 的库)时才报错 | -| `read_document` | `id`\*(`dN` 文档句柄或 `cN` 分块句柄)、`offset`(阅读顺序中的位置,从 0 开始,不是 chunk 下标;翻页用返回的 `next_offset`)、`limit`(默认 20,上限 100)、`query`(文档内查找:按空白拆成多个词,分块须包含全部词,顺序不限、大小写不敏感)、`regex`(把整个 `query` 当一条正则,大小写不敏感)、`context`(`cN` 前后各带几个相邻分块,上限 5) | 始终先返回文档元数据头(标题、类型、parse_status、分块数、metadata),再按需返回分块:`dN` 从 `offset` 起分页遍历;`cN` 读取该分块并可带前后 `context`(邻居按 chunk_index 顺序取,不受父分块、摘要、图片分块占用的下标影响);带 `query` 时即使 `id` 是 `cN` 也在其所属文档内查找,返回命中分块及前后各一块上下文(最多 20 处命中),无命中时附提示;单页或单次查找结果不超过工具输出预算的 80%,超出部分用 `next_offset` 续读;FAQ 条目按同样方式读取;校验 KB 在 searchTargets 内及 @mention 范围 | +| `search_knowledge` | `query`\*(一条自然语言问题或短语;keyword 模式下写精确词)、`mode`(`hybrid` 默认 / `semantic` / `keyword`)、`knowledge_base_ids[]`(`bN`,最多 10 个)、`limit`(默认 10,上限 30) | 唯一的知识库检索入口:`hybrid` 走向量 + 关键词的 RRF 融合,`semantic` 只走向量,`keyword` 由关键词索引(BM25 / 引擎关键词检索)提供,不再对 chunks 表做无索引的正则扫描;召回阈值与候选池取全局 `conversation.vector_threshold` / `keyword_threshold` / `embedding_top_k`(随附 `config.yaml` 为 0.2 / 0.3 / 30,未配置时回退 0.6 / 0.5 / 30),不读智能体自身的阈值;有 rerank 模型时重排(打分文本为「文档标题 + 分块正文」,FAQ 除外;阈值默认 0.3,全部未过阈值时保留得分 ≥ 0.15 的最佳候选),结果再做 MMR(λ=0.7)去冗;重排全部拒绝时结果带 `rerank_rejected` 并提示换 `keyword` 查标识符类词;结果带 `cN`/`dN` 短 ID,同一次调用内去重,同一文档的元数据头只输出一次;检索不附带相邻 / 父 / 关联分块(需要上下文时用 `read_document(id=cN, context=k)`),送去重排的候选最多 200 条;输出超过工具输出预算的 4/5 时从排名靠后的结果开始舍弃(至少保留一条),并以 `` 告诉模型;所选 KB 没有对应索引时按库降级而不是报错:`keyword` 遇到 FAQ 库或纯向量库改走语义检索,`semantic` 遇到纯关键词库改走关键词检索,结果里以 `requested_mode` 和 `mode_fallbacks` 标明哪些库降级及原因;只有作用域内没有任何分块索引(如全是仅 Wiki 的库)时才报错 | +| `read_document` | `id`\*(`dN` 文档句柄或 `cN` 分块句柄)、`offset`(阅读顺序中的位置,从 0 开始,不是 chunk 下标;翻页用返回的 `next_offset`)、`limit`(默认 20,上限 100)、`query`(文档内查找:按空白拆成多个词,分块须包含全部词,顺序不限、大小写不敏感)、`regex`(把整个 `query` 当一条正则,大小写不敏感)、`context`(`cN` 前后各带几个相邻分块,上限 5) | 始终先返回文档元数据头(标题、类型、parse_status、分块数、metadata),再按需返回分块:`dN` 从 `offset` 起分页遍历;`cN` 读取该分块并可带前后 `context`(邻居按 chunk_index 顺序取,不受父分块、摘要、图片分块占用的下标影响);带 `query` 时即使 `id` 是 `cN` 也在其所属文档内查找,返回命中分块及前后各一块上下文(最多 20 处命中),被截断时返回 `next_offset`(第一处未返回命中的位置),带上 `offset` 重复同一查询即可继续;无命中时附提示;单页或单次查找结果不超过工具输出预算的 80%,超出部分用 `next_offset` 续读;FAQ 条目按同样方式读取;校验 KB 在 searchTargets 内及 @mention 范围 | | `list_documents` | `knowledge_base_id`\*(`bN`)、`keyword`(按标题或文件名子串过滤)、`page`(默认 1)、`page_size`(默认 20,上限 100) | 分页列出单个知识库的文档,返回可直接交给 `read_document` 的 `dN` 句柄 | -| `query_knowledge_graph` | `knowledge_base_ids[]`\*(1–10 个 `bN`)、`query`\* | 并发查询各 KB 知识图谱的实体与关系;只有当作用域内存在启用图谱的 KB 时才会提供给模型(`agent_service.go` 装配白名单时移除),能力要求 `all_of: [graph]` | +| `query_knowledge_graph` | `knowledge_base_ids[]`\*(1–10 个 `bN`)、`query`\*(实体名或包含实体名的问题) | 并发查询各 KB 知识图谱:用查询本身及其分词后的较长词条在图存储中按名称匹配实体,返回实体间关系(`relations`,模型视图中为 ``)与实体来源分块(排在最前),再附上文本检索命中;各 KB 的失败以 `` 告知模型;只有当作用域内存在启用图谱的 KB 时才会提供给模型(`agent_service.go` 装配白名单时移除),能力要求 `all_of: [graph]` | | `database_query` | `sql`\*(仅 SELECT) | 只读查询白名单表(`knowledge_bases`/`knowledges`/`chunks`),自动注入 tenant_id 过滤与 `deleted_at IS NULL`;SQL 参数在 UI/Langfuse 中脱敏 | | `data_schema` | `knowledge_id`\*(`dN`) | 读取 CSV/Excel 文件的 `table_summary` + `table_column` 类型分块,返回列信息与行数;并告知模型该文档在 `data_analysis` 中固定以表名 `dataset` 访问 | | `data_analysis` | `knowledge_id`\*、`sql`\* | 把 CSV/Excel 载入 DuckDB 后执行 SQL。文档由 `knowledge_id` 选定,SQL 中固定以表名 `dataset` 引用它(每次查询在独立连接上建临时视图映射到物理表,模型永远不需要在 SQL 里写文档 ID);多 Sheet Excel 合并为一张表并暴露 `__sheet_name` 列;自动纠正列名大小写/空格差异;会话结束 Cleanup 时 DROP 所建表 | @@ -424,7 +424,7 @@ flowchart TD | `edit_sandbox_file` | `path`\*、`edits`\*(每项 `old_string`\*、`new_string`\*、`replace_all`) | 基于原版本批量精确替换 | | `search_memory` | `query`\*、`limit`(默认 10,上限 20) | 按当前调用者作用域查长期记忆 | | `search_conversations` | `query`\*、`limit`(默认 5,上限 8) | 检索当前调用者的历史对话;范围由调用者身份决定,不接受范围参数 | -| `wiki_search` | `query`\*(大小写不敏感的 POSIX 正则,如 `stardust\|skyvault`;不是合法正则的文本如 `C++` 按字面匹配)、`regex`(`false` 强制字面匹配,`true` 要求合法正则)、`knowledge_base_ids[]`(`bN`)、`limit`(每个 KB 默认 10,上限 50);旧参数 `queries[]`、`knowledge_base_id` 仍接受 | 在 Wiki 页面(标题/slug/别名/摘要/内容)上搜索,返回带 `bN` 标记的页面 slug 与摘要;之前已返回过的页面仍列出,但省略摘要 | +| `wiki_search` | `query`\*(大小写不敏感的 POSIX 正则,如 `stardust\|skyvault`;不是合法正则的文本如 `C++` 按字面匹配)、`regex`(`false` 强制字面匹配,`true` 要求合法正则)、`knowledge_base_ids[]`(`bN`)、`limit`(每个 KB 默认 10,上限 50);旧参数 `queries[]`、`knowledge_base_id` 仍接受 | 在 Wiki 页面(标题/slug/别名/摘要/内容)上搜索,返回带 `bN` 标记的页面 slug 与摘要;之前已返回过的页面仍列出,但省略摘要;作用域限定到文档或标签时先多取(`limit` 的 5 倍,最多 100)再按来源过滤,保留前 `limit` 条,全部被过滤时以 `filtered_out_of_scope` 说明 | | `wiki_read_page` | `slugs[]`\* | 按 slug 读取 Wiki 页面全文、元数据、出入链(链接附摘要,已见的省略);知识库按 slug 自动路由;`index` slug 返回按类型分组的目录概览(每类 top 20) | | `wiki_write_page` | `slug`\*、`title`\*、`summary`\*、`content`\*、`page_type`\*、`aliases[]`、`source_refs[]` | 新建或整页覆盖 Wiki 页面;写入前规范化并校验 slug;自动处理出链 | | `wiki_replace_text` | `slug`\*、`old_text`\*、`new_text`\*、`source_refs[]` | 精确文本替换,适合小修订 | diff --git a/website-docs/03-features/17-faq.md b/website-docs/03-features/17-faq.md index 8a8f9f24..9f0de384 100644 --- a/website-docs/03-features/17-faq.md +++ b/website-docs/03-features/17-faq.md @@ -85,10 +85,10 @@ type FAQSearchRequest struct { 1. **混合召回**:查询文本归一化后做向量检索 + BM25 关键词检索,融合去重; 2. **两级标签优先**:`FirstPriorityTagIDs` 命中的条目排最前,其次 `SecondPriorityTagIDs`; 3. **负例过滤**(`filterByNegativeQuestions`):查询文本与某条目的任一反例问完全匹配(小写比较)→ 该条目从结果中剔除。典型场景:用户问"不支持 X 吗",避免返回"支持 X"的条目; -4. **迭代召回**(`applyFAQPostProcessing`):当过滤后的唯一条目数不足 `match_count` 且向量结果打满时触发 `iterativeRetrieveWithDeduplication`——最多迭代 5 次、每次 TopK 翻倍(种子 `MatchCount*3` 与每轮增长均封顶 500,触顶即停),带去重与负例过滤缓存,无新结果提前终止; +4. **迭代召回**(`applyFAQPostProcessing`):当过滤后的唯一条目数不足 `match_count` 且某个向量结果列表打满时触发 `iterativeRetrieveWithDeduplication`——最多迭代 5 次、每次 TopK 翻倍(从首轮深度的 2 倍起,封顶 500,触顶即停),每轮与首轮同样融合打分,带负例过滤缓存,所有列表都未打满时提前终止; 5. 结果附带 `score`、`match_type`、`matched_question`(实际命中的是标准问还是哪个相似问),答案按 `answer_strategy`(all / random)返回。 -非 FAQ 类型 KB 直接跳过该后处理(`if kb.Type != types.KnowledgeBaseTypeFAQ { return chunks, nil }`),普通混合检索不受影响;agent 检索链在 FAQ 库上同样经过这条后处理路径。 +检索范围内没有 FAQ 库时直接跳过该后处理,普通混合检索不受影响。只要范围内有 FAQ 库(即使主 KB 是文档库,或 FAQ 库来自组织共享),负例过滤都会生效;迭代召回只在主 KB 为 FAQ 库时触发。agent 检索链在 FAQ 库上同样经过这条后处理路径。 ## 条目与接口参考 diff --git a/website-docs/04-api/01-api-overview.md b/website-docs/04-api/01-api-overview.md index 4bfe4bda..16273cbd 100644 --- a/website-docs/04-api/01-api-overview.md +++ b/website-docs/04-api/01-api-overview.md @@ -254,19 +254,19 @@ X-Accel-Buffering: no | --- | --- | --- | --- | | `enabled` | bool | `true` | 设为 `false` 关闭 rerank,结果保持召回顺序 | | `model_id` | string | 见下文 | rerank 模型 ID(`GET /models` 里 `type` 为 `Rerank` 的模型)。ID 不存在、未激活或不是 rerank 模型时返回 400,不会悄悄换成别的模型 | -| `top_k` | int | 接口的返回条数 | rerank 后最多保留几条;负数返回 400 | +| `top_k` | int | 接口的返回条数 | rerank 后最多保留几条;负数或超过 200 返回 400 | | `threshold` | float | 空间检索配置里的 `rerank_threshold`(未配置时 0.2) | 模型分数下限;`0` 和负数都是合法值 | 不传 `model_id` 时依次使用:空间检索配置里的 `rerank_model_id` → 空间里第一个 rerank 模型。都没有时不做 rerank,按召回顺序返回,`meta.rerank.outcome` 为 `no_model`。 rerank 的过程和问答链路、智能推理的 `search_knowledge` 工具共用同一套实现(`internal/reranking`): -1. 送给模型打分的文本 = 文档标题 + 去掉 Markdown 标记的分块正文 + 图片描述与 OCR 文本 + 生成的问题。FAQ 条目不加标题。 +1. 送给模型打分的文本 = 文档标题 + 去掉 Markdown 标记的分块正文 + 图片描述与 OCR 文本 + 生成的问题。FAQ 条目不加标题。模型配置了单篇或单次请求长度上限(`max_document_chars` / `max_request_chars`)时,超长的文本从尾部截到上限再送出,先截掉的是附加的图片文本和生成问题;不会因为一条超长文本让整批打分失败。 2. 保留分数不低于 `threshold` 的结果。如果一条都没有、而 `threshold` 高于 0.3,就把阈值降到 `max(threshold×0.7, 0.3)` 再筛一次。还是没有的话,最高分不低于 0.15 时只保留这一条,否则返回空列表。 3. 排序分 = `0.6×模型分 + 0.3×召回分 + 0.1×来源权重`;结果的 `metadata` 里带 `model_score` 和 `base_score`。 4. 用 MMR(λ=0.7)从中挑出 `top_k` 条,降低内容重复。 -`hybrid-search` 开启 rerank 时,候选池是融合后排名前 `max(top_k, 50)` 的分块,所以 `match_count` 很小也有足够的候选给模型挑。 +`hybrid-search` 开启 rerank 时,召回深度至少与 `top_k` 相同,候选池是融合后排名前 `max(top_k, 50)` 的分块,所以 `match_count` 很小也有足够的候选给模型挑。 rerank 模型加载失败或调用出错时,请求不会失败,而是按召回顺序返回,并在 `meta.rerank` 里写明原因。 diff --git a/website-docs/04-api/02-api-chat.md b/website-docs/04-api/02-api-chat.md index 73aebbb5..e613b72c 100644 --- a/website-docs/04-api/02-api-chat.md +++ b/website-docs/04-api/02-api-chat.md @@ -428,7 +428,7 @@ curl -N -X POST $BASE/api/v1/agent-chat/s-1 -H "Authorization: Bearer $TOKEN" \ | `tag_ids` | []string | 否 | 标签过滤 | | `mentioned_items` | []object | 否 | 带 KB 范围的标签提及 | | `vector_threshold` / `keyword_threshold` | float | 否 | 召回阈值;省略时用空间检索配置(默认 0.15 / 0.3) | -| `match_count` | int | 否 | 返回条数;省略时用空间配置的 `rerank_top_k`(默认 10)。召回深度会自动加大到不小于它 | +| `match_count` | int | 否 | 返回条数,上限 200;省略时用空间配置的 `rerank_top_k`(默认 10)。召回深度会自动加大到不小于它 | | `disable_keywords_match` / `disable_vector_match` | bool | 否 | 关闭某一路召回;两个都为 `true` 返回 400 | | `rerank` | object | 否 | 覆盖 rerank 设置;`{"enabled":false}` 关闭 rerank。字段见 [rerank 对象](./01-api-overview.md#retrieval-api)。`rerank.top_k` 同时给出时优先于 `match_count` |