From 1320c50bde50b3522191c5e051f401a63d71f39b Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 28 Jul 2026 15:50:39 +0800 Subject: [PATCH] refactor(knowledge): keep metadata document scoped --- internal/agent/tools/knowledge_search.go | 37 +++++++- .../tools/knowledge_search_metadata_test.go | 62 ++++++++++++ internal/application/service/chunk.go | 11 +-- internal/application/service/knowledge.go | 7 -- .../service/knowledge_index_content.go | 21 ++++ .../service/knowledge_index_content_test.go | 95 +++++++++++++++++++ .../application/service/knowledge_process.go | 27 ++---- internal/modelcontext/model_output.go | 13 ++- internal/modelcontext/sources_test.go | 26 +++++ internal/types/knowledge.go | 5 +- 10 files changed, 262 insertions(+), 42 deletions(-) create mode 100644 internal/agent/tools/knowledge_search_metadata_test.go create mode 100644 internal/application/service/knowledge_index_content.go create mode 100644 internal/application/service/knowledge_index_content_test.go diff --git a/internal/agent/tools/knowledge_search.go b/internal/agent/tools/knowledge_search.go index 78b3620a..9870c72b 100644 --- a/internal/agent/tools/knowledge_search.go +++ b/internal/agent/tools/knowledge_search.go @@ -1103,6 +1103,39 @@ func (t *KnowledgeSearchTool) buildContentSignature(content string) string { return searchutil.BuildContentSignature(content) } +// writeKnowledgeMetadataHeader emits document-scoped metadata once per +// knowledge item. Chunk entries keep only chunk-specific content so repeated +// results from the same document do not waste model context. +func writeKnowledgeMetadataHeader(ob *strings.Builder, results []*searchResultWithMeta) { + seen := make(map[string]struct{}, len(results)) + hasMetadata := false + var documents strings.Builder + for _, result := range results { + if result == nil || result.SearchResult == nil || result.KnowledgeID == "" || result.KnowledgeCustomMetadata == "" { + continue + } + if _, ok := seen[result.KnowledgeID]; ok { + continue + } + seen[result.KnowledgeID] = struct{}{} + hasMetadata = true + documents.WriteString(fmt.Sprintf( + "\n", + xmlEscape(result.KnowledgeID), + xmlEscape(result.KnowledgeBaseID), + xmlEscape(result.KnowledgeTitle), + )) + documents.WriteString(fmt.Sprintf("%s\n", xmlEscape(result.KnowledgeCustomMetadata))) + documents.WriteString("\n") + } + if !hasMetadata { + return + } + ob.WriteString("\n") + ob.WriteString(documents.String()) + ob.WriteString("\n") +} + // formatOutput formats the search results for display func (t *KnowledgeSearchTool) formatOutput( ctx context.Context, @@ -1148,6 +1181,7 @@ func (t *KnowledgeSearchTool) formatOutput( for _, q := range queries { ob.WriteString(fmt.Sprintf("%s\n", xmlEscape(q))) } + writeKnowledgeMetadataHeader(&ob, results) formattedResults := make([]map[string]interface{}, 0, len(results)) @@ -1274,9 +1308,6 @@ func (t *KnowledgeSearchTool) formatOutput( if snippet != "" { ob.WriteString(fmt.Sprintf("%s\n", xmlEscape(snippet))) } - if result.KnowledgeCustomMetadata != "" { - ob.WriteString(fmt.Sprintf("%s\n", xmlEscape(result.KnowledgeCustomMetadata))) - } ob.WriteString(fmt.Sprintf("%s\n", result.Content)) if result.ImageInfo != "" { diff --git a/internal/agent/tools/knowledge_search_metadata_test.go b/internal/agent/tools/knowledge_search_metadata_test.go new file mode 100644 index 00000000..5b5ccc1d --- /dev/null +++ b/internal/agent/tools/knowledge_search_metadata_test.go @@ -0,0 +1,62 @@ +package tools + +import ( + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" +) + +func TestWriteKnowledgeMetadataHeaderDeduplicatesByKnowledge(t *testing.T) { + t.Parallel() + results := []*searchResultWithMeta{ + { + SearchResult: &types.SearchResult{ + KnowledgeID: "knowledge-1", KnowledgeTitle: "Document ", + KnowledgeCustomMetadata: "region: Shanghai & Suzhou", + }, + KnowledgeBaseID: "kb-1", + }, + { + SearchResult: &types.SearchResult{ + KnowledgeID: "knowledge-1", KnowledgeTitle: "Document ", + KnowledgeCustomMetadata: "region: Shanghai & Suzhou", + }, + KnowledgeBaseID: "kb-1", + }, + { + SearchResult: &types.SearchResult{ + KnowledgeID: "knowledge-2", KnowledgeTitle: "Document Two", + }, + KnowledgeBaseID: "kb-1", + }, + { + SearchResult: &types.SearchResult{ + KnowledgeID: "knowledge-3", KnowledgeTitle: "Document Three", + KnowledgeCustomMetadata: "owner: Alice", + }, + KnowledgeBaseID: "kb-2", + }, + } + + var output strings.Builder + writeKnowledgeMetadataHeader(&output, results) + text := output.String() + + require.Equal(t, 1, strings.Count(text, `knowledge_id="knowledge-1"`)) + require.Equal(t, 1, strings.Count(text, `knowledge_id="knowledge-3"`)) + require.NotContains(t, text, `knowledge_id="knowledge-2"`) + require.Equal(t, 2, strings.Count(text, "")) + require.Contains(t, text, "Document <One>") + require.Contains(t, text, "Shanghai & Suzhou") +} + +func TestWriteKnowledgeMetadataHeaderOmitsEmptySection(t *testing.T) { + t.Parallel() + var output strings.Builder + writeKnowledgeMetadataHeader(&output, []*searchResultWithMeta{{ + SearchResult: &types.SearchResult{KnowledgeID: "knowledge-1"}, + }}) + require.Empty(t, output.String()) +} diff --git a/internal/application/service/chunk.go b/internal/application/service/chunk.go index eb8a2f9f..bea69671 100644 --- a/internal/application/service/chunk.go +++ b/internal/application/service/chunk.go @@ -578,15 +578,8 @@ func (s *chunkService) syncChunkIndex(ctx context.Context, chunk *types.Chunk) e if err != nil { return err } - prefix := "" - if knowledge.Title != "" { - prefix = strings.TrimSpace(knowledge.Title) + "\n" - } - if metadata := knowledge.CustomMetadataText(); metadata != "" { - prefix += "Metadata:\n" + metadata + "\n" - } items := []*types.IndexInfo{{ - Content: prefix + chunk.EmbeddingContent(), SourceID: chunk.ID, + Content: buildKnowledgeIndexContent(knowledge, chunk.EmbeddingContent()), SourceID: chunk.ID, SourceType: types.ChunkSourceType, ChunkID: chunk.ID, KnowledgeID: chunk.KnowledgeID, KnowledgeBaseID: chunk.KnowledgeBaseID, KnowledgeType: kb.Type, IsEnabled: true, @@ -601,7 +594,7 @@ func (s *chunkService) syncChunkIndex(ctx context.Context, chunk *types.Chunk) e continue } items = append(items, &types.IndexInfo{ - Content: prefix + question.Question, SourceID: types.GeneratedQuestionSourceID(chunk.ID, question.ID), + Content: buildKnowledgeIndexContent(knowledge, question.Question), SourceID: types.GeneratedQuestionSourceID(chunk.ID, question.ID), SourceType: types.ChunkSourceType, ChunkID: chunk.ID, KnowledgeID: chunk.KnowledgeID, KnowledgeBaseID: chunk.KnowledgeBaseID, KnowledgeType: kb.Type, IsEnabled: true, diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.go index 4567b081..fe671d39 100644 --- a/internal/application/service/knowledge.go +++ b/internal/application/service/knowledge.go @@ -638,13 +638,6 @@ func (s *knowledgeService) UpdateKnowledge(ctx context.Context, knowledge *types return err } if metadataChanged { - chunks, err := s.chunkRepo.ListChunksByKnowledgeID(ctx, record.TenantID, record.ID) - if err != nil { - return fmt.Errorf("list chunks for metadata reindex: %w", err) - } - if err := s.updateChunkVector(ctx, record.KnowledgeBaseID, chunks); err != nil { - return fmt.Errorf("metadata saved but reindex failed: %w", err) - } if record.SummaryStatus == types.SummaryStatusCompleted { _ = s.repo.UpdateKnowledgeColumn(ctx, record.ID, "summary_status", types.SummaryStatusPending) } diff --git a/internal/application/service/knowledge_index_content.go b/internal/application/service/knowledge_index_content.go new file mode 100644 index 00000000..1b079645 --- /dev/null +++ b/internal/application/service/knowledge_index_content.go @@ -0,0 +1,21 @@ +package service + +import ( + "strings" + + "github.com/Tencent/WeKnora/internal/types" +) + +// buildKnowledgeIndexContent adds only the document title to searchable text. +// Custom metadata stays document-scoped: it is supplied once to the answer +// model and summary model, rather than repeated in every chunk embedding. +func buildKnowledgeIndexContent(knowledge *types.Knowledge, content string) string { + if knowledge == nil { + return content + } + title := strings.TrimSpace(knowledge.Title) + if title == "" { + return content + } + return title + "\n" + content +} diff --git a/internal/application/service/knowledge_index_content_test.go b/internal/application/service/knowledge_index_content_test.go new file mode 100644 index 00000000..e9d46272 --- /dev/null +++ b/internal/application/service/knowledge_index_content_test.go @@ -0,0 +1,95 @@ +package service + +import ( + "context" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/stretchr/testify/require" +) + +func TestBuildKnowledgeIndexContentExcludesCustomMetadata(t *testing.T) { + t.Parallel() + knowledge := &types.Knowledge{ + Title: " WeKnora Handbook ", + CustomMetadata: types.JSON(`{"region":"Shanghai","department":"R&D"}`), + } + + content := buildKnowledgeIndexContent(knowledge, "Chunk body") + + require.Equal(t, "WeKnora Handbook\nChunk body", content) + require.NotContains(t, content, "Shanghai") + require.NotContains(t, content, "department") +} + +func TestBuildKnowledgeIndexContentWithoutTitleReturnsContent(t *testing.T) { + t.Parallel() + require.Equal(t, "Chunk body", buildKnowledgeIndexContent(&types.Knowledge{ + CustomMetadata: types.JSON(`{"region":"Shanghai"}`), + }, "Chunk body")) + require.Equal(t, "Chunk body", buildKnowledgeIndexContent(nil, "Chunk body")) +} + +type metadataUpdateKnowledgeRepo struct { + interfaces.KnowledgeRepository + knowledge *types.Knowledge + summaryStatusUpdate interface{} +} + +func (r *metadataUpdateKnowledgeRepo) GetKnowledgeByID( + _ context.Context, _ uint64, _ string, +) (*types.Knowledge, error) { + clone := *r.knowledge + return &clone, nil +} + +func (r *metadataUpdateKnowledgeRepo) UpdateKnowledge(_ context.Context, knowledge *types.Knowledge) error { + clone := *knowledge + r.knowledge = &clone + return nil +} + +func (r *metadataUpdateKnowledgeRepo) UpdateKnowledgeColumn( + _ context.Context, _ string, column string, value interface{}, +) error { + if column == "summary_status" { + r.summaryStatusUpdate = value + } + return nil +} + +type metadataUpdateChunkRepo struct { + interfaces.ChunkRepository + listCalls int +} + +func (r *metadataUpdateChunkRepo) ListChunksByKnowledgeID( + _ context.Context, _ uint64, _ string, +) ([]*types.Chunk, error) { + r.listCalls++ + return nil, nil +} + +func TestUpdateKnowledgeMetadataDoesNotReindexChunks(t *testing.T) { + t.Parallel() + repo := &metadataUpdateKnowledgeRepo{knowledge: &types.Knowledge{ + ID: "knowledge-1", + TenantID: 7, + SummaryStatus: types.SummaryStatusCompleted, + CustomMetadata: types.JSON(`{"region":"Beijing"}`), + }} + chunkRepo := &metadataUpdateChunkRepo{} + service := &knowledgeService{repo: repo, chunkRepo: chunkRepo} + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7)) + + err := service.UpdateKnowledge(ctx, &types.Knowledge{ + ID: "knowledge-1", + CustomMetadata: types.JSON(`{"region":"Shanghai"}`), + }) + + require.NoError(t, err) + require.JSONEq(t, `{"region":"Shanghai"}`, string(repo.knowledge.CustomMetadata)) + require.Zero(t, chunkRepo.listCalls) + require.Equal(t, types.SummaryStatusPending, repo.summaryStatusUpdate) +} diff --git a/internal/application/service/knowledge_process.go b/internal/application/service/knowledge_process.go index d41a1015..c59a6c94 100644 --- a/internal/application/service/knowledge_process.go +++ b/internal/application/service/knowledge_process.go @@ -529,18 +529,12 @@ func (s *knowledgeService) processChunks(ctx context.Context, // Prepend the document title to improve semantic alignment between // question-style queries and statement-style chunk content. indexInfoList := make([]*types.IndexInfo, 0, len(textChunks)) - titlePrefix := "" - if t := strings.TrimSpace(knowledge.Title); t != "" { - titlePrefix = t + "\n" - } - if metadata := knowledge.CustomMetadataText(); metadata != "" { - titlePrefix += "Metadata:\n" + metadata + "\n" - } for _, chunk := range textChunks { // chunk.EmbeddingContent prepends ContextHeader (heading breadcrumb) // when the chunker populated it during Tier-1 splitting; falls back - // to plain Content otherwise. Title prefix sits outermost. - indexContent := titlePrefix + chunk.EmbeddingContent() + // to plain Content otherwise. The document title sits outermost; + // custom metadata remains document-scoped model context. + indexContent := buildKnowledgeIndexContent(knowledge, chunk.EmbeddingContent()) indexInfoList = append(indexInfoList, &types.IndexInfo{ Content: indexContent, SourceID: chunk.ID, @@ -1602,7 +1596,7 @@ func (s *knowledgeService) processQuestionGenerationForKnowledge(ctx context.Con for _, gq := range generatedQuestions { sourceID := types.GeneratedQuestionSourceID(chunk.ID, gq.ID) indexInfoList = append(indexInfoList, &types.IndexInfo{ - Content: gq.Question, + Content: buildKnowledgeIndexContent(knowledge, gq.Question), SourceID: sourceID, SourceType: types.ChunkSourceType, ChunkID: chunk.ID, @@ -1929,7 +1923,7 @@ func (s *knowledgeService) processQuestionGenerationForChunks(ctx context.Contex } for _, gq := range generatedQuestions { indexInfoList = append(indexInfoList, &types.IndexInfo{ - Content: gq.Question, + Content: buildKnowledgeIndexContent(knowledge, gq.Question), SourceID: types.GeneratedQuestionSourceID(chunk.ID, gq.ID), SourceType: types.ChunkSourceType, ChunkID: chunk.ID, @@ -2663,15 +2657,8 @@ func (s *knowledgeService) updateChunkVector(ctx context.Context, kbID string, c } knowledgeCache[chunk.KnowledgeID] = knowledge } - prefix := "" - if title := strings.TrimSpace(knowledge.Title); title != "" { - prefix = title + "\n" - } - if metadata := knowledge.CustomMetadataText(); metadata != "" { - prefix += "Metadata:\n" + metadata + "\n" - } indexInfo = append(indexInfo, &types.IndexInfo{ - Content: prefix + chunk.EmbeddingContent(), + Content: buildKnowledgeIndexContent(knowledge, chunk.EmbeddingContent()), SourceID: chunk.ID, SourceType: types.ChunkSourceType, ChunkID: chunk.ID, @@ -2688,7 +2675,7 @@ func (s *knowledgeService) updateChunkVector(ctx context.Context, kbID string, c for _, q := range meta.GeneratedQuestions { if strings.TrimSpace(q.Question) != "" { indexInfo = append(indexInfo, &types.IndexInfo{ - Content: prefix + q.Question, SourceID: types.GeneratedQuestionSourceID(chunk.ID, q.ID), + Content: buildKnowledgeIndexContent(knowledge, q.Question), SourceID: types.GeneratedQuestionSourceID(chunk.ID, q.ID), SourceType: types.ChunkSourceType, ChunkID: chunk.ID, KnowledgeID: chunk.KnowledgeID, KnowledgeBaseID: chunk.KnowledgeBaseID, KnowledgeType: sourceKB.Type, IsEnabled: true, diff --git a/internal/modelcontext/model_output.go b/internal/modelcontext/model_output.go index d0651097..ca01792f 100644 --- a/internal/modelcontext/model_output.go +++ b/internal/modelcontext/model_output.go @@ -150,6 +150,7 @@ type modelChunk struct { docHandle string kbHandle string title string + metadata string chunkType string index int view string @@ -195,6 +196,7 @@ func (r *sourceRegistry) modelKnowledgeOutput(mode string, rows []map[string]int docHandle: r.RegisterDocument(knowledgeID), kbHandle: r.RegisterKnowledgeBase(kbID), title: title, + metadata: stringValue(row, "knowledge_metadata"), chunkType: chunkType, index: chunkIndex, view: viewForRow(row, mode), @@ -255,6 +257,7 @@ func renderKnowledgeChunks(mode string, chunks []modelChunk) string { handle string kbHandle string title string + metadata string chunks []modelChunk order int } @@ -267,9 +270,14 @@ func renderKnowledgeChunks(mode string, chunks []modelChunk) string { } group := groupsByKey[key] if group == nil { - group = &docGroup{handle: chunk.docHandle, kbHandle: chunk.kbHandle, title: chunk.title, order: chunk.inputOrder} + group = &docGroup{ + handle: chunk.docHandle, kbHandle: chunk.kbHandle, title: chunk.title, + metadata: chunk.metadata, order: chunk.inputOrder, + } groupsByKey[key] = group groups = append(groups, group) + } else if group.metadata == "" { + group.metadata = chunk.metadata } group.chunks = append(group.chunks, chunk) } @@ -289,6 +297,9 @@ func renderKnowledgeChunks(mode string, chunks []modelChunk) string { fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(group.title)) } b.WriteString(">\n") + if group.metadata != "" { + fmt.Fprintf(&b, " %s\n", escapeText(group.metadata)) + } for _, chunk := range group.chunks { fmt.Fprintf(&b, " ")) + require.Contains(t, output, "region: Shanghai & Suzhou") + require.Equal(t, 2, strings.Count(output, "