From 28dd15ec30d89b880d1182ff3b7ad77939eca2eb Mon Sep 17 00:00:00 2001 From: lawrence Date: Mon, 17 Aug 2026 18:53:22 +0800 Subject: [PATCH] =?UTF-8?q?fix(retrieval):=20=E5=88=86=E6=AE=B5=E4=B8=AD?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E7=9A=84=E5=9B=BE=E7=89=87=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E8=A2=AB=E6=A3=80=E7=B4=A2=E5=88=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 从分段里删掉一张图片后,这张图仍会回到检索结果和模型上下文里。 三个问题串在一起: 1. 删图时 syncEditedChunkImages 会把 image_ocr / image_caption 子块置为 禁用,但 CollectImageInfoByChunkIDs 查子块时不看 is_enabled,又把它们的 image_info 挂回了父块。knowledge_search 工具随后把每条 image_info 无条件 渲染成 markdown 图片写进 LLM 上下文,图片就这样回来了。这里按 is_enabled 过滤,两级遍历都跳过禁用子块。过滤放在 collector 而不是工具输出层:纯图片 分块的正文本身就是 OCR 文本、没有 markdown 图片语法,按正文过滤会误杀。 chat_pipeline 里既有的 fake 仓储 fixture 同步补上 IsEnabled: true:它们不 走 DB 默认值,零值 false 会被新的过滤当成已禁用子块。 2. UpdateImageInfo 补建 image_ocr / image_caption 子块时没有设置 IsEnabled。 CreateChunks 用 Select("*") 插入,gorm 的 default:true 不生效,零值 false 直接落库,这些子块一出生就是禁用的。补上 IsEnabled: true —— 否则第 1 点 的过滤会把它们永久丢弃。其余 CreateChunks 调用方均已显式设置该字段。 3. 摘要刷新每次都新建一条 summary 分块,旧的留着且仍然启用。原因是它复用了 ListChunksByKnowledgeID 的结果,而那个查询硬编码 chunk_type = 'text', "查找已有 summary 分块"的分支永远匹配不上。残留的旧摘要描述的是编辑前的 文档,会让用户已经删掉的内容继续被检索到。新增按 chunk_type 过滤的仓储 方法,刷新时原地更新已有 summary 分块。 --- internal/application/repository/chunk.go | 20 +++++ .../merge_parent_resolve_test.go | 2 + .../application/service/knowledge_process.go | 42 ++++++---- internal/searchutil/imageinfo.go | 11 +++ .../searchutil/imageinfo_disabled_test.go | 84 +++++++++++++++++++ internal/types/interfaces/chunk.go | 9 +- 6 files changed, 153 insertions(+), 15 deletions(-) create mode 100644 internal/searchutil/imageinfo_disabled_test.go diff --git a/internal/application/repository/chunk.go b/internal/application/repository/chunk.go index 17be8e55..ccb9fe87 100644 --- a/internal/application/repository/chunk.go +++ b/internal/application/repository/chunk.go @@ -160,6 +160,26 @@ func (r *chunkRepository) ListChunksByKnowledgeID( return chunks, nil } +// ListChunksByKnowledgeIDAndTypes lists a knowledge's chunks restricted to the +// given chunk types. ListChunksByKnowledgeID is text-only by design, so callers +// that also need summary / parent_text / image chunks come through here rather +// than widening that query underneath its existing callers. +func (r *chunkRepository) ListChunksByKnowledgeIDAndTypes( + ctx context.Context, tenantID uint64, knowledgeID string, chunkTypes []types.ChunkType, +) ([]*types.Chunk, error) { + if len(chunkTypes) == 0 { + return nil, nil + } + var chunks []*types.Chunk + if err := r.db.WithContext(ctx). + Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN ?", tenantID, knowledgeID, chunkTypes). + Order("chunk_index ASC"). + Find(&chunks).Error; err != nil { + return nil, err + } + return chunks, nil +} + // ListPagedChunksByKnowledgeID lists chunks for a knowledge ID with pagination func (r *chunkRepository) ListPagedChunksByKnowledgeID( ctx context.Context, diff --git a/internal/application/service/chat_pipeline/merge_parent_resolve_test.go b/internal/application/service/chat_pipeline/merge_parent_resolve_test.go index 67516a3f..5ae6688d 100644 --- a/internal/application/service/chat_pipeline/merge_parent_resolve_test.go +++ b/internal/application/service/chat_pipeline/merge_parent_resolve_test.go @@ -26,6 +26,7 @@ func TestResolveParentChunksUsesCurrentContentAndImageURLs(t *testing.T) { { ID: "image", ParentChunkID: "child", ChunkType: types.ChunkTypeImageOCR, ImageInfo: string(imageInfo), + IsEnabled: true, }, }, }, @@ -73,6 +74,7 @@ func TestResolveImageChunkKeepsGrandparentContextWithoutCoordinateSlicing(t *tes "text": {{ ID: "image", ParentChunkID: "text", ChunkType: types.ChunkTypeImageOCR, ImageInfo: string(imageInfo), + IsEnabled: true, }}, }, } diff --git a/internal/application/service/knowledge_process.go b/internal/application/service/knowledge_process.go index 3ac25784..6c2f7350 100644 --- a/internal/application/service/knowledge_process.go +++ b/internal/application/service/knowledge_process.go @@ -2340,26 +2340,35 @@ func (s *knowledgeService) RegenerateKnowledgeSummary( return nil, err } if kb.NeedsEmbeddingModel() { - found := false maxIndex := 0 - summaryChunks := make([]*types.Chunk, 0, 1) for _, chunk := range allChunks { if chunk.ChunkIndex > maxIndex { maxIndex = chunk.ChunkIndex } - if chunk.ChunkType == types.ChunkTypeSummary { - chunk.Content = "# Summary\n" + summary - chunk.SourceContent = chunk.Content - chunk.IsEnabled = true - chunk.UpdatedAt = time.Now() - if err := s.chunkRepo.UpdateChunk(ctx, chunk); err != nil { - return nil, err - } - summaryChunks = append(summaryChunks, chunk) - found = true - } } - if !found { + // allChunks holds text chunks only, so it can never carry the existing + // summary chunk. Scanning it for one always came up empty, which left + // every refresh appending a new summary chunk beside the stale one -- + // and a stale summary stays enabled and indexed, so content the user + // edited out of the document kept being retrievable through it. + existingSummaries, err := s.chunkRepo.ListChunksByKnowledgeIDAndTypes( + ctx, tenantID, knowledgeID, []types.ChunkType{types.ChunkTypeSummary}, + ) + if err != nil { + return nil, err + } + summaryChunks := make([]*types.Chunk, 0, len(existingSummaries)) + for _, chunk := range existingSummaries { + chunk.Content = "# Summary\n" + summary + chunk.SourceContent = chunk.Content + chunk.IsEnabled = true + chunk.UpdatedAt = time.Now() + if err := s.chunkRepo.UpdateChunk(ctx, chunk); err != nil { + return nil, err + } + summaryChunks = append(summaryChunks, chunk) + } + if len(summaryChunks) == 0 { summaryChunk := &types.Chunk{ ID: uuid.NewString(), TenantID: tenantID, KnowledgeID: knowledge.ID, KnowledgeBaseID: knowledge.KnowledgeBaseID, Content: "# Summary\n" + summary, @@ -2973,6 +2982,10 @@ func (s *knowledgeService) UpdateImageInfo( ChunkType: types.ChunkTypeImageCaption, ParentChunkID: chunk.ID, ImageInfo: imageInfo, + // CreateChunks inserts with Select("*"), so the gorm default:true never + // applies -- an unset IsEnabled lands in the database as false and the + // chunk is silently excluded from retrieval and model context. + IsEnabled: true, } addChunk = append(addChunk, captionChunk) logger.Infof(ctx, "Created new caption chunk ID: %s for image URL: %s", captionChunk.ID, image.OriginalURL) @@ -2989,6 +3002,7 @@ func (s *knowledgeService) UpdateImageInfo( ChunkType: types.ChunkTypeImageOCR, ParentChunkID: chunk.ID, ImageInfo: imageInfo, + IsEnabled: true, } addChunk = append(addChunk, ocrChunk) logger.Infof(ctx, "Created new OCR chunk ID: %s for image URL: %s", ocrChunk.ID, image.OriginalURL) diff --git a/internal/searchutil/imageinfo.go b/internal/searchutil/imageinfo.go index 7cba563f..487563ae 100644 --- a/internal/searchutil/imageinfo.go +++ b/internal/searchutil/imageinfo.go @@ -46,6 +46,11 @@ const HTMLImageSrcURLGroup = 2 // - If chunkIDs are parent_text chunks, their children are text chunks // whose children are image chunks → two queries. // +// Disabled children are skipped at both levels. Removing an image from a chunk +// disables its image_ocr / image_caption children (syncEditedChunkImages), and +// disabling a text chunk disables them too; honoring that flag here is what +// keeps a deleted image out of retrieval, summaries and model context. +// // Returns a map of input chunkID → merged image_info JSON string. func CollectImageInfoByChunkIDs( ctx context.Context, @@ -107,6 +112,9 @@ func CollectImageInfoByChunkIDs( textToParent := make(map[string]string) for _, child := range children { + if !child.IsEnabled { + continue + } switch child.ChunkType { case types.ChunkTypeImageOCR, types.ChunkTypeImageCaption: addInfo(child.ParentChunkID, child) @@ -120,6 +128,9 @@ func CollectImageInfoByChunkIDs( grandChildren, err := chunkRepo.ListChunksByParentIDs(ctx, tenantID, textChildIDs) if err == nil { for _, gc := range grandChildren { + if !gc.IsEnabled { + continue + } if gc.ChunkType != types.ChunkTypeImageOCR && gc.ChunkType != types.ChunkTypeImageCaption { continue } diff --git a/internal/searchutil/imageinfo_disabled_test.go b/internal/searchutil/imageinfo_disabled_test.go new file mode 100644 index 00000000..6d4e4149 --- /dev/null +++ b/internal/searchutil/imageinfo_disabled_test.go @@ -0,0 +1,84 @@ +package searchutil + +import ( + "context" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// childrenByParentRepo serves chunk children from a static parent → children map. +type childrenByParentRepo struct { + interfaces.ChunkRepository + byParent map[string][]*types.Chunk +} + +func (r childrenByParentRepo) ListChunksByParentIDs( + _ context.Context, _ uint64, parentIDs []string, +) ([]*types.Chunk, error) { + var out []*types.Chunk + for _, id := range parentIDs { + out = append(out, r.byParent[id]...) + } + return out, nil +} + +func imageChild(id, parentID string, chunkType types.ChunkType, url string, enabled bool) *types.Chunk { + return &types.Chunk{ + ID: id, + ParentChunkID: parentID, + ChunkType: chunkType, + IsEnabled: enabled, + ImageInfo: `[{"url":"` + url + `","caption":"a screenshot"}]`, + } +} + +// Deleting an image from a chunk disables its image children. Their image_info +// must not come back through enrichment, or the removed image reappears in +// summaries, tool output and model context. +func TestCollectImageInfoByChunkIDsSkipsDisabledImageChildren(t *testing.T) { + repo := childrenByParentRepo{byParent: map[string][]*types.Chunk{ + "text-1": { + imageChild("ocr-1", "text-1", types.ChunkTypeImageOCR, "resource://removed", false), + imageChild("cap-1", "text-1", types.ChunkTypeImageCaption, "resource://removed", false), + }, + "text-2": { + imageChild("ocr-2", "text-2", types.ChunkTypeImageOCR, "resource://kept", true), + }, + }} + + got := CollectImageInfoByChunkIDs(context.Background(), repo, 1, []string{"text-1", "text-2"}) + + if _, ok := got["text-1"]; ok { + t.Fatalf("disabled image children leaked image_info: %q", got["text-1"]) + } + if got["text-2"] == "" { + t.Fatal("enabled image child lost its image_info") + } +} + +// The parent_text → text → image path must apply the same rule at both levels. +func TestCollectImageInfoByChunkIDsSkipsDisabledGrandchildrenAndTextChildren(t *testing.T) { + repo := childrenByParentRepo{byParent: map[string][]*types.Chunk{ + "parent-1": { + {ID: "text-1", ParentChunkID: "parent-1", ChunkType: types.ChunkTypeText, IsEnabled: true}, + }, + "parent-2": { + // Disabling a text chunk hides everything under it. + {ID: "text-2", ParentChunkID: "parent-2", ChunkType: types.ChunkTypeText, IsEnabled: false}, + }, + "text-1": { + imageChild("ocr-1", "text-1", types.ChunkTypeImageOCR, "resource://removed", false), + }, + "text-2": { + imageChild("ocr-2", "text-2", types.ChunkTypeImageOCR, "resource://hidden", true), + }, + }} + + got := CollectImageInfoByChunkIDs(context.Background(), repo, 1, []string{"parent-1", "parent-2"}) + + if len(got) != 0 { + t.Fatalf("expected no image_info, got %v", got) + } +} diff --git a/internal/types/interfaces/chunk.go b/internal/types/interfaces/chunk.go index 9f6434d6..28cf8a4c 100644 --- a/internal/types/interfaces/chunk.go +++ b/internal/types/interfaces/chunk.go @@ -28,8 +28,15 @@ type ChunkRepository interface { ListChunksByIDOnly(ctx context.Context, ids []string) ([]*types.Chunk, error) // ListChunksBySeqID lists chunks by seq_ids ListChunksBySeqID(ctx context.Context, tenantID uint64, seqIDs []int64) ([]*types.Chunk, error) - // ListChunksByKnowledgeID lists chunks by knowledge id + // ListChunksByKnowledgeID lists the knowledge's text chunks. Despite the name + // it filters to chunk_type = 'text'; reach for ListChunksByKnowledgeIDAndTypes + // when summary, parent_text or image chunks are needed too. ListChunksByKnowledgeID(ctx context.Context, tenantID uint64, knowledgeID string) ([]*types.Chunk, error) + // ListChunksByKnowledgeIDAndTypes lists the knowledge's chunks restricted to + // the given chunk types, ordered by chunk_index. + ListChunksByKnowledgeIDAndTypes( + ctx context.Context, tenantID uint64, knowledgeID string, chunkTypes []types.ChunkType, + ) ([]*types.Chunk, error) // ListPagedChunksByKnowledgeID lists paged chunks by knowledge id. // When tagIDs is non-empty, results are filtered by tag_id (OR semantics). // knowledgeType: "faq" or "manual" - determines sort order and search behavior