fix(chunks): retain questions across content edits

main
wizardchen 2026-07-28 17:38:21 +08:00 committed by lyingbug
parent 6a439a4c3b
commit 48b661134b
17 changed files with 47 additions and 39 deletions

View File

@ -571,7 +571,7 @@ export default {
editGeneratedQuestion: 'Edit retrieval question',
regenerateQuestions: 'Regenerate questions',
questionsRegenerated: 'Retrieval questions refreshed',
staleGeneratedQuestions: 'Content changed; old questions are excluded from retrieval',
staleGeneratedQuestions: 'Generated from an earlier version; regenerate if needed',
noGeneratedQuestions: 'No retrieval questions',
notInitialized: 'Knowledge base is not initialized. Please configure models in settings before uploading files',
missingStorageEngine: 'This knowledge base has no storage engine selected. Please configure a storage engine in settings before uploading content.',

View File

@ -581,7 +581,7 @@ export default {
editGeneratedQuestion: "검색 보조 질문 편집",
regenerateQuestions: "질문 다시 생성",
questionsRegenerated: "검색 질문이 업데이트되었습니다",
staleGeneratedQuestions: "콘텐츠가 변경되어 이전 질문은 검색에서 제외됩니다",
staleGeneratedQuestions: "이전 콘텐츠를 기준으로 생성된 질문입니다. 필요하면 다시 생성하세요",
noGeneratedQuestions: "검색 보조 질문 없음",
docActionUnsupported: "현재 지식베이스 유형은 이 작업을 지원하지 않습니다",
notInitialized:

View File

@ -506,7 +506,7 @@ export default {
editGeneratedQuestion: 'Изменить вопрос для поиска',
regenerateQuestions: 'Пересоздать вопросы',
questionsRegenerated: 'Вопросы для поиска обновлены',
staleGeneratedQuestions: 'Содержимое изменено; старые вопросы исключены из поиска',
staleGeneratedQuestions: 'Вопросы созданы для предыдущей версии; при необходимости создайте их заново',
noGeneratedQuestions: 'Нет вопросов для поиска',
notInitialized: 'База знаний не инициализирована. Пожалуйста, настройте модели в разделе настроек перед загрузкой файлов',
missingStorageEngine: 'Для этой базы знаний не выбрано хранилище. Пожалуйста, настройте хранилище в параметрах перед загрузкой содержимого.',

View File

@ -570,7 +570,7 @@ export default {
editGeneratedQuestion: "编辑辅助召回问题",
regenerateQuestions: "重新生成问题",
questionsRegenerated: "辅助召回问题已更新",
staleGeneratedQuestions: "内容已变更,旧问题暂不参与召回",
staleGeneratedQuestions: "问题基于编辑前内容生成,可按需重新生成",
noGeneratedQuestions: "暂无辅助召回问题",
docActionUnsupported: "当前知识库类型不支持该操作",
notInitialized:

View File

@ -675,7 +675,7 @@ func getEnrichedPassage(ctx context.Context, result *types.SearchResult) string
pipelineWarn(ctx, "Rerank", "chunk_metadata_parse", map[string]interface{}{
"error": err.Error(),
})
} else if questionStrings := docMeta.GetCurrentQuestionStrings(result.ContentRevision); len(questionStrings) > 0 {
} else if questionStrings := docMeta.GetQuestionStrings(); len(questionStrings) > 0 {
enrichments = append(enrichments, strings.Join(questionStrings, "; "))
}
}

View File

@ -1,9 +1,34 @@
package chatpipeline
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestGetEnrichedPassageKeepsQuestionsFromEarlierRevision(t *testing.T) {
metadata, err := json.Marshal(types.DocumentChunkMetadata{
GeneratedQuestionsRevision: 1,
GeneratedQuestions: []types.GeneratedQuestion{{
ID: "old", Question: "question generated before the edit",
}},
})
if err != nil {
t.Fatal(err)
}
passage := getEnrichedPassage(context.Background(), &types.SearchResult{
Content: "edited chunk body",
ChunkMetadata: types.JSON(metadata),
})
if !strings.Contains(passage, "question generated before the edit") {
t.Fatalf("earlier generated question was excluded from rerank passage: %q", passage)
}
}
func TestCleanPassageForRerank(t *testing.T) {
tests := []struct {
name string

View File

@ -213,7 +213,6 @@ func chunk2SearchResult(chunk *types.Chunk, knowledge *types.Knowledge) *types.S
Content: chunk.Content,
KnowledgeID: chunk.KnowledgeID,
ChunkIndex: chunk.ChunkIndex,
ContentRevision: chunk.ContentRevision,
KnowledgeTitle: knowledge.Title,
StartAt: chunk.StartAt,
EndAt: chunk.EndAt,

View File

@ -677,7 +677,7 @@ func (s *chunkService) syncChunkIndex(ctx context.Context, chunk *types.Chunk) e
}
if meta != nil {
for _, question := range meta.GeneratedQuestions {
if strings.TrimSpace(question.Question) == "" || !meta.IsQuestionCurrent(question, chunk.ContentRevision) {
if strings.TrimSpace(question.Question) == "" {
continue
}
items = append(items, &types.IndexInfo{

View File

@ -145,7 +145,7 @@ func TestSyncEditedChunkImagesDisablesAndRestoresImageChildren(t *testing.T) {
}
}
func TestUpdateDocumentChunkPreservesGeneratedQuestionsAsStale(t *testing.T) {
func TestUpdateDocumentChunkPreservesGeneratedQuestionsAcrossRevision(t *testing.T) {
metadata := &types.DocumentChunkMetadata{
GeneratedQuestions: []types.GeneratedQuestion{{ID: "q1", Question: "old question"}},
GeneratedQuestionsRevision: 0,
@ -179,7 +179,7 @@ func TestUpdateDocumentChunkPreservesGeneratedQuestionsAsStale(t *testing.T) {
t.Fatalf("generated questions were cleared: %+v", updatedMetadata.GeneratedQuestions)
}
if updatedMetadata.IsQuestionCurrent(updatedMetadata.GeneratedQuestions[0], updated.ContentRevision) {
t.Fatal("question from the previous content revision should be stale")
t.Fatal("question should remain identifiable as based on the previous content revision")
}
}

View File

@ -722,11 +722,11 @@ func (s *customAgentService) getSuggestedQuestions(
if err != nil || meta == nil || len(meta.GeneratedQuestions) == 0 {
continue
}
currentQuestions := meta.GetCurrentQuestionStrings(chunk.ContentRevision)
if len(currentQuestions) == 0 {
questions := meta.GetQuestionStrings()
if len(questions) == 0 {
continue
}
q := currentQuestions[0]
q := questions[0]
if q == "" || seen[q] {
continue
}

View File

@ -2696,7 +2696,7 @@ func (s *knowledgeService) updateChunkVector(ctx context.Context, kbID string, c
}
if meta != nil {
for _, q := range meta.GeneratedQuestions {
if strings.TrimSpace(q.Question) != "" && meta.IsQuestionCurrent(q, chunk.ContentRevision) {
if strings.TrimSpace(q.Question) != "" {
indexInfo = append(indexInfo, &types.IndexInfo{
Content: buildKnowledgeIndexContent(knowledge, q.Question), SourceID: types.GeneratedQuestionSourceID(chunk.ID, q.ID),
SourceType: types.ChunkSourceType, ChunkID: chunk.ID,

View File

@ -311,7 +311,6 @@ func (s *knowledgeBaseService) buildSearchResult(chunk *types.Chunk,
Content: chunk.Content,
KnowledgeID: chunk.KnowledgeID,
ChunkIndex: chunk.ChunkIndex,
ContentRevision: chunk.ContentRevision,
KnowledgeTitle: knowledge.Title,
StartAt: chunk.StartAt,
EndAt: chunk.EndAt,

View File

@ -397,7 +397,6 @@ func (h *AgentStreamHandler) handleReferences(ctx context.Context, evt event.Eve
KnowledgeID: getString(refMap, "knowledge_id"),
KnowledgeTitle: getString(refMap, "knowledge_title"),
ChunkIndex: int(getFloat64(refMap, "chunk_index")),
ContentRevision: int(getFloat64(refMap, "content_revision")),
KnowledgeDescription: getString(refMap, "knowledge_description"),
KnowledgeBaseID: getString(refMap, "knowledge_base_id"),
}

View File

@ -226,7 +226,6 @@ func buildStreamResponse(evt interfaces.StreamEvent, requestID string) *types.St
Content: getString(refMap, "content"),
KnowledgeID: getString(refMap, "knowledge_id"),
ChunkIndex: int(getFloat64(refMap, "chunk_index")),
ContentRevision: int(getFloat64(refMap, "content_revision")),
KnowledgeTitle: getString(refMap, "knowledge_title"),
StartAt: int(getFloat64(refMap, "start_at")),
EndAt: int(getFloat64(refMap, "end_at")),

View File

@ -59,10 +59,10 @@ type DocumentChunkMetadata struct {
GeneratedQuestionsRevision int `json:"generated_questions_revision,omitempty"`
}
// IsQuestionCurrent reports whether a generated question belongs to the
// current chunk body. Per-question revisions allow stale questions to remain
// visible after an edit without letting them affect retrieval. Legacy rows
// fall back to the metadata-level revision.
// IsQuestionCurrent reports whether a generated question was authored for the
// current chunk body. This is advisory metadata for the UI: questions remain
// valid retrieval aliases across chunk edits. Legacy rows fall back to the
// metadata-level revision.
func (m *DocumentChunkMetadata) IsQuestionCurrent(question GeneratedQuestion, chunkRevision int) bool {
if question.ContentRevision != nil {
return *question.ContentRevision == chunkRevision
@ -82,20 +82,6 @@ func (m *DocumentChunkMetadata) GetQuestionStrings() []string {
return result
}
// GetCurrentQuestionStrings returns only questions tied to chunkRevision.
func (m *DocumentChunkMetadata) GetCurrentQuestionStrings(chunkRevision int) []string {
if m == nil || len(m.GeneratedQuestions) == 0 {
return nil
}
result := make([]string, 0, len(m.GeneratedQuestions))
for _, question := range m.GeneratedQuestions {
if m.IsQuestionCurrent(question, chunkRevision) {
result = append(result, question.Question)
}
}
return result
}
// DocumentMetadata 解析 Chunk 中的文档元数据
func (c *Chunk) DocumentMetadata() (*DocumentChunkMetadata, error) {
if c == nil || len(c.Metadata) == 0 {

View File

@ -13,11 +13,14 @@ func TestDocumentChunkMetadataQuestionRevision(t *testing.T) {
},
}
questions := meta.GetCurrentQuestionStrings(currentRevision)
if len(questions) != 1 || questions[0] != "current question" {
t.Fatalf("current questions = %v", questions)
questions := meta.GetQuestionStrings()
if len(questions) != 2 {
t.Fatalf("all retrieval questions should remain available, got %v", questions)
}
if !meta.IsQuestionCurrent(meta.GeneratedQuestions[0], oldRevision) {
t.Fatal("legacy question should use the metadata-level revision")
}
if meta.IsQuestionCurrent(meta.GeneratedQuestions[0], currentRevision) {
t.Fatal("legacy question should still be identifiable as based on an older revision")
}
}

View File

@ -157,8 +157,6 @@ type SearchResult struct {
KnowledgeID string `gorm:"column:knowledge_id" json:"knowledge_id"`
// Chunk index
ChunkIndex int `gorm:"column:chunk_index" json:"chunk_index"`
// Current editable content revision
ContentRevision int `json:"content_revision"`
// Knowledge title
KnowledgeTitle string `gorm:"column:knowledge_title" json:"knowledge_title"`
// Start at