Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(chunks): keep edited retrieval content consistent

wizardchen6a439a4c3b97
diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue
index e642c59c9..c5db28ed3 100644
--- a/frontend/src/components/doc-content.vue
+++ b/frontend/src/components/doc-content.vue
@@ -980,6 +980,7 @@ const getChunkMeta = (item: any) => {
interface GeneratedQuestion {
id: string;
question: string;
+ content_revision?: number;
}
// 解析生成的问题
@@ -1001,6 +1002,19 @@ const getGeneratedQuestions = (item: any): GeneratedQuestion[] => {
}
};
+const hasStaleGeneratedQuestions = (item: any) => {
+ const questions = getGeneratedQuestions(item);
+ if (!questions.length) return false;
+ try {
+ const metadata = typeof item.metadata === 'string' ? JSON.parse(item.metadata || '{}') : (item.metadata || {});
+ const fallbackRevision = metadata.generated_questions_revision || 0;
+ const currentRevision = item.content_revision || 0;
+ return questions.some((question) => (question.content_revision ?? fallbackRevision) !== currentRevision);
+ } catch {
+ return false;
+ }
+};
+
const editingChunkId = ref('');
const chunkDraft = ref('');
const savingChunkId = ref('');
@@ -1212,7 +1226,6 @@ const addQuestion = async (item: any) => {
questionComposerChunk.value = '';
const metadata = typeof item.metadata === 'string' ? JSON.parse(item.metadata || '{}') : (item.metadata || {});
metadata.generated_questions = [...(metadata.generated_questions || []), result.data];
- metadata.generated_questions_revision = item.content_revision || 0;
item.metadata = metadata;
MessagePlugin.success(t('common.saveSuccess'));
} catch (error: any) {
@@ -1241,8 +1254,9 @@ const saveQuestionEdit = async (item: any, question: GeneratedQuestion) => {
}
savingQuestionKey.value = `${item.id}:${question.id}`;
try {
- await upsertGeneratedQuestion(item.id, value, question.id);
+ const result: any = await upsertGeneratedQuestion(item.id, value, question.id);
question.question = value;
+ question.content_revision = result?.data?.content_revision ?? (item.content_revision || 0);
cancelQuestionEdit();
MessagePlugin.success(t('common.saveSuccess'));
} catch (error: any) {
@@ -1757,6 +1771,9 @@ const handleDetailsScroll = () => {
<t-icon name="help-circle" size="15px" />
<span>{{ $t('knowledgeBase.generatedQuestions') }}</span>
<span class="chunk-popup-count">{{ chunk.questions.length }}</span>
+ <span v-if="hasStaleGeneratedQuestions(chunk.original)" class="chunk-question-stale-hint">
+ {{ $t('knowledgeBase.staleGeneratedQuestions') }}
+ </span>
</div>
<div v-if="canEditContent" class="chunk-popup-actions">
<t-tooltip :content="$t('knowledgeBase.addGeneratedQuestion')" placement="top">
@@ -2850,6 +2867,12 @@ const handleDetailsScroll = () => {
font-weight: 400;
}
+.chunk-question-stale-hint {
+ color: var(--td-warning-color);
+ font-size: 11px;
+ font-weight: 400;
+}
+
.chunk-popup-actions {
gap: 2px;
}
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 5c9e94d4f..0854cb952 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -571,6 +571,7 @@ export default {
editGeneratedQuestion: 'Edit retrieval question',
regenerateQuestions: 'Regenerate questions',
questionsRegenerated: 'Retrieval questions refreshed',
+ staleGeneratedQuestions: 'Content changed; old questions are excluded from retrieval',
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.',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index b71c19763..246ebf5ab 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -581,6 +581,7 @@ export default {
editGeneratedQuestion: "검색 보조 질문 편집",
regenerateQuestions: "질문 다시 생성",
questionsRegenerated: "검색 질문이 업데이트되었습니다",
+ staleGeneratedQuestions: "콘텐츠가 변경되어 이전 질문은 검색에서 제외됩니다",
noGeneratedQuestions: "검색 보조 질문 없음",
docActionUnsupported: "현재 지식베이스 유형은 이 작업을 지원하지 않습니다",
notInitialized:
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index e55b12fd1..14e72079c 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -506,6 +506,7 @@ export default {
editGeneratedQuestion: 'Изменить вопрос для поиска',
regenerateQuestions: 'Пересоздать вопросы',
questionsRegenerated: 'Вопросы для поиска обновлены',
+ staleGeneratedQuestions: 'Содержимое изменено; старые вопросы исключены из поиска',
noGeneratedQuestions: 'Нет вопросов для поиска',
notInitialized: 'База знаний не инициализирована. Пожалуйста, настройте модели в разделе настроек перед загрузкой файлов',
missingStorageEngine: 'Для этой базы знаний не выбрано хранилище. Пожалуйста, настройте хранилище в параметрах перед загрузкой содержимого.',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index bc9183d1f..71a3f3d15 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -570,6 +570,7 @@ export default {
editGeneratedQuestion: "编辑辅助召回问题",
regenerateQuestions: "重新生成问题",
questionsRegenerated: "辅助召回问题已更新",
+ staleGeneratedQuestions: "内容已变更,旧问题暂不参与召回",
noGeneratedQuestions: "暂无辅助召回问题",
docActionUnsupported: "当前知识库类型不支持该操作",
notInitialized:
diff --git a/internal/application/service/chat_pipeline/filter_top_k.go b/internal/application/service/chat_pipeline/filter_top_k.go
index 6f431313a..6af579960 100644
--- a/internal/application/service/chat_pipeline/filter_top_k.go
+++ b/internal/application/service/chat_pipeline/filter_top_k.go
@@ -88,11 +88,8 @@ func sortSearchResultsDeterministically(results []*types.SearchResult) {
if left.ChunkType != right.ChunkType {
return left.ChunkType < right.ChunkType
}
- if left.StartAt != right.StartAt {
- return left.StartAt < right.StartAt
- }
- if left.EndAt != right.EndAt {
- return left.EndAt < right.EndAt
+ if left.ChunkIndex != right.ChunkIndex {
+ return left.ChunkIndex < right.ChunkIndex
}
return left.ID < right.ID
})
diff --git a/internal/application/service/chat_pipeline/merge.go b/internal/application/service/chat_pipeline/merge.go
index f1529deb9..5271b8dee 100644
--- a/internal/application/service/chat_pipeline/merge.go
+++ b/internal/application/service/chat_pipeline/merge.go
@@ -36,10 +36,10 @@ func (p *PluginMerge) ActivationEvents() []types.EventType {
// 2. Deduplicate by ID and content signature
// 3. Inject relevant history references
// 4. Resolve parent chunks (child → parent content)
-// 5. Group by knowledge source + chunk type, merge overlapping ranges
+// 5. Group by knowledge source + chunk type, merge sequential current bodies
// 6. Populate FAQ answers
// 7. Expand short contexts with neighboring chunks
-// 7.5. Re-merge overlapping ranges introduced by expansion
+// 7.5. Re-merge sequential or contained bodies introduced by expansion
// 8. Final deduplication (ID + signature + partial content overlap)
func (p *PluginMerge) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
@@ -77,7 +77,7 @@ func (p *PluginMerge) OnEvent(ctx context.Context,
searchResult = p.resolveParentChunks(ctx, chatManage, searchResult)
// Step 5: Group by knowledge/chunkType and merge overlapping ranges
- mergedChunks := p.groupAndMergeOverlapping(ctx, searchResult)
+ mergedChunks := p.groupAndMergeCurrentContent(ctx, searchResult)
// Step 6: Populate FAQ answers
mergedChunks = p.populateFAQAnswers(ctx, chatManage, mergedChunks)
@@ -86,7 +86,7 @@ func (p *PluginMerge) OnEvent(ctx context.Context,
mergedChunks = p.expandShortContextWithNeighbors(ctx, chatManage, mergedChunks)
// Step 7.5: Re-merge overlapping ranges introduced by expansion
- mergedChunks = p.groupAndMergeOverlapping(ctx, mergedChunks)
+ mergedChunks = p.groupAndMergeCurrentContent(ctx, mergedChunks)
// Step 8: Final dedup — catches exact duplicates plus partial content overlaps
mergedChunks = p.dedup(ctx, "final_dedup", mergedChunks)
@@ -144,9 +144,9 @@ func (p *PluginMerge) injectHistoryResults(
return removeDuplicateResults(combined)
}
-// groupAndMergeOverlapping groups chunks by KnowledgeID + ChunkType, then merges
-// overlapping ranges within each group using mergeOverlappingChunks.
-func (p *PluginMerge) groupAndMergeOverlapping(ctx context.Context, results []*types.SearchResult) []*types.SearchResult {
+// groupAndMergeCurrentContent groups chunks by KnowledgeID + ChunkType, then joins
+// sequential current bodies without consulting source character offsets.
+func (p *PluginMerge) groupAndMergeCurrentContent(ctx context.Context, results []*types.SearchResult) []*types.SearchResult {
// Group by KnowledgeID → ChunkType
knowledgeGroup := make(map[string]map[string][]*types.SearchResult)
for _, chunk := range results {
@@ -181,13 +181,13 @@ func (p *PluginMerge) groupAndMergeOverlapping(ctx context.Context, results []*t
})
sort.Slice(u.chunks, func(i, j int) bool {
- if u.chunks[i].StartAt == u.chunks[j].StartAt {
- return u.chunks[i].EndAt < u.chunks[j].EndAt
+ if u.chunks[i].ChunkIndex == u.chunks[j].ChunkIndex {
+ return u.chunks[i].ID < u.chunks[j].ID
}
- return u.chunks[i].StartAt < u.chunks[j].StartAt
+ return u.chunks[i].ChunkIndex < u.chunks[j].ChunkIndex
})
- grouped := p.mergeOverlappingChunks(ctx, u.knowledgeID, u.chunks)
+ grouped := p.mergeSequentialChunks(ctx, u.knowledgeID, u.chunks)
pipelineInfo(ctx, "Merge", "group_output", map[string]interface{}{
"knowledge_id": u.knowledgeID,
@@ -266,40 +266,6 @@ func (p *PluginMerge) resolveParentChunks(
parentMap[c.ID] = c
}
- // Check if any results are image chunks; only then do we need
- // grandparent resolution and the extra DB round-trip.
- hasImageResults := false
- for _, r := range results {
- if r.ChunkType == string(types.ChunkTypeImageOCR) || r.ChunkType == string(types.ChunkTypeImageCaption) {
- hasImageResults = true
- break
- }
- }
-
- var grandparentIDs []string
- if hasImageResults {
- // Fetch grandparent chunks for the image → text → parent_text chain.
- for _, pc := range parentChunks {
- if pc.ParentChunkID != "" && pc.ChunkType == types.ChunkTypeText {
- if _, already := parentMap[pc.ParentChunkID]; !already {
- grandparentIDs = append(grandparentIDs, pc.ParentChunkID)
- }
- }
- }
- if len(grandparentIDs) > 0 {
- gpChunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, grandparentIDs)
- if err != nil {
- pipelineWarn(ctx, "Merge", "grandparent_fetch_failed", map[string]interface{}{
- "error": err.Error(),
- })
- } else {
- for _, c := range gpChunks {
- parentMap[c.ID] = c
- }
- }
- }
- }
-
// Batch-fetch image_info scoped to matched text children only.
textChildIDs := collectScopedTextChildIDs(results, parentMap)
var scopedImageInfo map[string]string
@@ -321,7 +287,6 @@ func (p *PluginMerge) resolveParentChunks(
if !ok || parent.Content == "" || parent.ChunkType != types.ChunkTypeParentText {
continue
}
- matchStart, matchEnd := r.StartAt, r.EndAt
pipelineInfo(ctx, "Merge", "parent_resolve", map[string]interface{}{
"child_id": r.ID,
"parent_id": r.ParentChunkID,
@@ -329,17 +294,9 @@ func (p *PluginMerge) resolveParentChunks(
"parent_len": runeLen(parent.Content),
"scoped_img": true,
})
- r.Content = searchutil.PruneMarkdownImagesOutsideRange(
- parent.Content, parent.StartAt, matchStart, matchEnd,
- )
- r.StartAt = parent.StartAt
- r.EndAt = parent.EndAt
assignScopedImageInfo(r, scopedImageInfo, r.ID)
- if r.ImageInfo != "" {
- r.ImageInfo = searchutil.FilterImageInfoByMatchRange(
- parent.Content, parent.StartAt, matchStart, matchEnd, r.ImageInfo,
- )
- }
+ parentContent := searchutil.PruneMarkdownImagesByImageInfo(parent.Content, r.ImageInfo)
+ r.Content = searchutil.JoinChunkContent(parentContent, r.Content, "\n\n")
if !containsID(r.SubChunkID, r.ID) {
r.SubChunkID = append(r.SubChunkID, r.ID)
}
@@ -350,39 +307,22 @@ func (p *PluginMerge) resolveParentChunks(
continue
}
hitImageInfo := r.ImageInfo
- contentSource := textParent
- if textParent.ParentChunkID != "" {
- if gp, gpOK := parentMap[textParent.ParentChunkID]; gpOK &&
- gp.ChunkType == types.ChunkTypeParentText && gp.Content != "" {
- contentSource = gp
- }
- }
- matchStart := textParent.StartAt
- matchEnd := textParent.EndAt
- sliced := searchutil.SliceContentByDocumentRange(
- contentSource.Content, contentSource.StartAt, matchStart, matchEnd,
- )
- if sliced == "" {
- sliced = textParent.Content
- matchStart = textParent.StartAt
- matchEnd = textParent.EndAt
- }
pipelineInfo(ctx, "Merge", "image_parent_resolve", map[string]interface{}{
"child_id": r.ID,
"child_type": r.ChunkType,
"text_id": textParent.ID,
- "parent_id": contentSource.ID,
- "match_len": runeLen(sliced),
- "parent_len": runeLen(contentSource.Content),
+ "parent_id": textParent.ID,
+ "match_len": runeLen(textParent.Content),
+ "parent_len": runeLen(textParent.Content),
"scoped": true,
})
- r.Content = sliced
- r.StartAt = matchStart
- r.EndAt = matchEnd
+ r.Content = textParent.Content
+ r.ChunkIndex = textParent.ChunkIndex
assignScopedImageInfo(r, scopedImageInfo, textParent.ID)
if r.ImageInfo == "" && hitImageInfo != "" {
r.ImageInfo = searchutil.FilterImageInfoByContentURLs(r.Content, hitImageInfo)
}
+ r.Content = searchutil.PruneMarkdownImagesByImageInfo(r.Content, r.ImageInfo)
if !containsID(r.SubChunkID, r.ID) {
r.SubChunkID = append(r.SubChunkID, r.ID)
}
diff --git a/internal/application/service/chat_pipeline/merge_expand.go b/internal/application/service/chat_pipeline/merge_expand.go
index 56f37b674..2ee6a6e18 100644
--- a/internal/application/service/chat_pipeline/merge_expand.go
+++ b/internal/application/service/chat_pipeline/merge_expand.go
@@ -3,6 +3,7 @@ package chatpipeline
import (
"context"
+ "github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -176,7 +177,7 @@ func (p *PluginMerge) expandShortContextWithNeighbors(
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, prevCursor)
if prevChunk := chunkMap[prevCursor]; prevChunk != nil &&
prevChunk.KnowledgeID == baseChunk.KnowledgeID {
- prevContent = concatNoOverlap(prevChunk.Content, prevContent)
+ prevContent = searchutil.JoinChunkContent(prevChunk.Content, prevContent, "\n\n")
prevIDs = append([]string{prevChunk.ID}, prevIDs...)
prevCursor = prevChunk.PreChunkID
expanded = true
@@ -194,7 +195,7 @@ func (p *PluginMerge) expandShortContextWithNeighbors(
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, nextCursor)
if nextChunk := chunkMap[nextCursor]; nextChunk != nil &&
nextChunk.KnowledgeID == baseChunk.KnowledgeID {
- nextContent = concatNoOverlap(nextContent, nextChunk.Content)
+ nextContent = searchutil.JoinChunkContent(nextContent, nextChunk.Content, "\n\n")
nextIDs = append(nextIDs, nextChunk.ID)
nextCursor = nextChunk.NextChunkID
expanded = true
@@ -226,14 +227,6 @@ func (p *PluginMerge) expandShortContextWithNeighbors(
}
}
- if prevContent != "" {
- res.StartAt = baseChunk.StartAt - runeLen(prevContent)
- if res.StartAt < 0 {
- res.StartAt = 0
- }
- }
- res.EndAt = res.StartAt + runeLen(res.Content)
-
pipelineInfo(ctx, "Merge", "expand_short_chunk", map[string]interface{}{
"chunk_id": res.ID,
"prev_ids": prevIDs,
@@ -260,10 +253,10 @@ func runeLen(s string) int {
func mergeOrderedContent(prev, base, next string, maxLen int) string {
content := base
if prev != "" {
- content = concatNoOverlap(prev, content)
+ content = searchutil.JoinChunkContent(prev, content, "\n\n")
}
if next != "" {
- content = concatNoOverlap(content, next)
+ content = searchutil.JoinChunkContent(content, next, "\n\n")
}
runes := []rune(content)
if len(runes) > maxLen {
@@ -272,33 +265,6 @@ func mergeOrderedContent(prev, base, next string, maxLen int) string {
return content
}
-// concatNoOverlap concatenates two strings, removing potential overlapping prefix/suffix
-func concatNoOverlap(a, b string) string {
- if a == "" {
- return b
- }
- if b == "" {
- return a
- }
-
- ar := []rune(a)
- br := []rune(b)
- maxOverlap := minInt(len(ar), len(br))
- for k := maxOverlap; k > 0; k-- {
- if string(ar[len(ar)-k:]) == string(br[:k]) {
- return string(ar) + string(br[k:])
- }
- }
- return string(ar) + string(br)
-}
-
-func minInt(a, b int) int {
- if a < b {
- return a
- }
- return b
-}
-
func containsID(ids []string, target string) bool {
for _, id := range ids {
if id == target {
diff --git a/internal/application/service/chat_pipeline/merge_expand_edit_test.go b/internal/application/service/chat_pipeline/merge_expand_edit_test.go
new file mode 100644
index 000000000..62c8b0395
--- /dev/null
+++ b/internal/application/service/chat_pipeline/merge_expand_edit_test.go
@@ -0,0 +1,65 @@
+package chatpipeline
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+type expandChunkRepo struct {
+ interfaces.ChunkRepository
+ chunks map[string]*types.Chunk
+ children map[string][]*types.Chunk
+}
+
+func (r *expandChunkRepo) ListChunksByParentIDs(
+ _ context.Context, _ uint64, parentIDs []string,
+) ([]*types.Chunk, error) {
+ var chunks []*types.Chunk
+ for _, parentID := range parentIDs {
+ chunks = append(chunks, r.children[parentID]...)
+ }
+ return chunks, nil
+}
+
+func (r *expandChunkRepo) ListChunksByID(
+ _ context.Context, _ uint64, ids []string,
+) ([]*types.Chunk, error) {
+ chunks := make([]*types.Chunk, 0, len(ids))
+ for _, id := range ids {
+ if chunk := r.chunks[id]; chunk != nil {
+ chunks = append(chunks, chunk)
+ }
+ }
+ return chunks, nil
+}
+
+func TestExpandShortContextKeepsSourceCoordinates(t *testing.T) {
+ repo := &expandChunkRepo{chunks: map[string]*types.Chunk{
+ "prev": {ID: "prev", KnowledgeID: "doc", ChunkType: types.ChunkTypeText, Content: "edited previous body", NextChunkID: "base"},
+ "base": {ID: "base", KnowledgeID: "doc", ChunkType: types.ChunkTypeText, Content: "edited base body", PreChunkID: "prev", NextChunkID: "next", StartAt: 100, EndAt: 120},
+ "next": {ID: "next", KnowledgeID: "doc", ChunkType: types.ChunkTypeText, Content: "edited 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: "edited base body", StartAt: 100, EndAt: 120,
+ }
+
+ got := plugin.expandShortContextWithNeighbors(ctx, &types.ChatManage{}, []*types.SearchResult{result})
+ if len(got) != 1 {
+ t.Fatalf("result count = %d, want 1", len(got))
+ }
+ if got[0].StartAt != 100 || got[0].EndAt != 120 {
+ t.Fatalf("source coordinates changed to [%d,%d)", got[0].StartAt, got[0].EndAt)
+ }
+ for _, want := range []string{"edited previous body", "edited base body", "edited next body"} {
+ if !strings.Contains(got[0].Content, want) {
+ t.Fatalf("expanded content missing %q: %q", want, got[0].Content)
+ }
+ }
+}
diff --git a/internal/application/service/chat_pipeline/merge_group_deterministic_test.go b/internal/application/service/chat_pipeline/merge_group_deterministic_test.go
index a1538edd9..672cc2d61 100644
--- a/internal/application/service/chat_pipeline/merge_group_deterministic_test.go
+++ b/internal/application/service/chat_pipeline/merge_group_deterministic_test.go
@@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require"
)
-// groupAndMergeOverlapping groups results by KnowledgeID and ChunkType
+// groupAndMergeCurrentContent groups results by KnowledgeID and ChunkType
// using two levels of Go maps. Map iteration order is non-deterministic,
// so the concatenated output can appear in arbitrary order. This test
// verifies that the post-merge sort restores deterministic ordering
@@ -25,7 +25,7 @@ func TestGroupAndMergeOverlapping_DeterministicOrdering(t *testing.T) {
{ID: "high", KnowledgeID: "kb-001", ChunkType: "summary", StartAt: 200, EndAt: 300, Score: 0.9},
{ID: "mid", KnowledgeID: "kb-001", ChunkType: "parent_text", StartAt: 400, EndAt: 500, Score: 0.6},
}
- results := plugin.groupAndMergeOverlapping(context.Background(), chunks)
+ results := plugin.groupAndMergeCurrentContent(context.Background(), chunks)
require.Len(t, results, 3)
assert.Equal(t, "high", results[0].ID, "highest score (0.9) must be first")
@@ -40,7 +40,7 @@ func TestGroupAndMergeOverlapping_DeterministicOrdering(t *testing.T) {
{ID: "ab", KnowledgeID: "kb-ab", ChunkType: "text", StartAt: 0, EndAt: 50, Score: 0.8},
{ID: "aa", KnowledgeID: "kb-aa", ChunkType: "text", StartAt: 0, EndAt: 50, Score: 0.8},
}
- results := plugin.groupAndMergeOverlapping(context.Background(), chunks)
+ results := plugin.groupAndMergeCurrentContent(context.Background(), chunks)
require.Len(t, results, 2)
assert.Equal(t, "aa", results[0].ID, "same score, kb-aa < kb-ab")
})
@@ -50,11 +50,11 @@ func TestGroupAndMergeOverlapping_DeterministicOrdering(t *testing.T) {
// then the merged result competes with a higher-scored summary chunk
// across the inner-map boundary.
chunks := []*types.SearchResult{
- {ID: "low-a", KnowledgeID: "kb-001", ChunkType: "text", StartAt: 0, EndAt: 50, Score: 0.5},
- {ID: "low-b", KnowledgeID: "kb-001", ChunkType: "text", StartAt: 30, EndAt: 80, Score: 0.7},
+ {ID: "low-a", KnowledgeID: "kb-001", ChunkType: "text", ChunkIndex: 1, Content: "first body", StartAt: 0, EndAt: 50, Score: 0.5},
+ {ID: "low-b", KnowledgeID: "kb-001", ChunkType: "text", ChunkIndex: 2, Content: "second body", StartAt: 30, EndAt: 80, Score: 0.7},
{ID: "high", KnowledgeID: "kb-001", ChunkType: "summary", StartAt: 200, EndAt: 300, Score: 0.9},
}
- results := plugin.groupAndMergeOverlapping(context.Background(), chunks)
+ results := plugin.groupAndMergeCurrentContent(context.Background(), chunks)
require.Len(t, results, 2, "two text chunks merged into one, plus one summary")
assert.Equal(t, "high", results[0].ID, "summary (0.9) beats merged text (0.7)")
})
@@ -66,12 +66,43 @@ func TestGroupAndMergeOverlapping_DeterministicOrdering(t *testing.T) {
{ID: "txt", KnowledgeID: "kb-x", ChunkType: "text", StartAt: 0, EndAt: 50, Score: 0.8},
{ID: "sum", KnowledgeID: "kb-x", ChunkType: "summary", StartAt: 100, EndAt: 150, Score: 0.8},
}
- results := plugin.groupAndMergeOverlapping(context.Background(), chunks)
+ results := plugin.groupAndMergeCurrentContent(context.Background(), chunks)
require.Len(t, results, 2)
assert.Equal(t, "sum", results[0].ID, "same kb+score, 'summary' < 'text'")
})
}
+func TestGroupAndMergeOverlapping_IgnoresStaleEditedRanges(t *testing.T) {
+ plugin := &PluginMerge{}
+ chunks := []*types.SearchResult{
+ {
+ ID: "edited-outer", KnowledgeID: "doc", ChunkType: "text", ChunkIndex: 1,
+ StartAt: 0, EndAt: 200, Content: "completely rewritten outer content", Score: 0.4,
+ },
+ {
+ ID: "edited-inner", KnowledgeID: "doc", ChunkType: "text", ChunkIndex: 2,
+ StartAt: 50, EndAt: 100, Content: "independent current inner content", Score: 0.9,
+ },
+ }
+
+ results := plugin.groupAndMergeCurrentContent(context.Background(), chunks)
+ require.Len(t, results, 1)
+ assert.Contains(t, results[0].Content, chunks[0].Content)
+ assert.Contains(t, results[0].Content, chunks[1].Content)
+ assert.Equal(t, 0.9, results[0].Score)
+}
+
+func TestGroupAndMergeOverlapping_DoesNotMergeNonSequentialChunksFromCoordinates(t *testing.T) {
+ plugin := &PluginMerge{}
+ chunks := []*types.SearchResult{
+ {ID: "one", KnowledgeID: "doc", ChunkType: "text", ChunkIndex: 1, StartAt: 0, EndAt: 200, Content: "one"},
+ {ID: "three", KnowledgeID: "doc", ChunkType: "text", ChunkIndex: 3, StartAt: 50, EndAt: 100, Content: "three"},
+ }
+
+ results := plugin.groupAndMergeCurrentContent(context.Background(), chunks)
+ require.Len(t, results, 2)
+}
+
// TestGroupAndMergeOverlapping_CrossKnowledgePreservesMergeLogic verifies
// that chunks from different KnowledgeIDs do NOT accidentally merge across
// knowledge boundaries even when they share StartAt/EndAt ranges.
@@ -81,7 +112,7 @@ func TestGroupAndMergeOverlapping_CrossKnowledgePreservesMergeLogic(t *testing.T
{ID: "a-1", KnowledgeID: "kb-a", ChunkType: "text", StartAt: 0, EndAt: 100, Score: 0.9},
{ID: "b-1", KnowledgeID: "kb-b", ChunkType: "text", StartAt: 0, EndAt: 100, Score: 0.5},
}
- results := plugin.groupAndMergeOverlapping(context.Background(), chunks)
+ results := plugin.groupAndMergeCurrentContent(context.Background(), chunks)
require.Len(t, results, 2, "chunks from different KBs must not merge")
assert.Equal(t, "a-1", results[0].ID, "higher score from kb-a first")
diff --git a/internal/application/service/chat_pipeline/merge_overlap.go b/internal/application/service/chat_pipeline/merge_overlap.go
index 7b786206f..36b6dc721 100644
--- a/internal/application/service/chat_pipeline/merge_overlap.go
+++ b/internal/application/service/chat_pipeline/merge_overlap.go
@@ -9,10 +9,11 @@ import (
"github.com/Tencent/WeKnora/internal/types"
)
-// mergeOverlappingChunks merges chunks with overlapping or adjacent StartAt/EndAt
-// ranges within a single knowledge source group. Chunks MUST be pre-sorted by
-// StartAt ascending, EndAt ascending. The highest score among merged chunks is kept.
-func (p *PluginMerge) mergeOverlappingChunks(
+// mergeSequentialChunks joins sequential current chunk bodies without using
+// parser StartAt/EndAt coordinates. Chunks MUST be pre-sorted by ChunkIndex.
+// Source coordinates remain useful for citations, but arbitrary user edits
+// make them unsafe for deciding whether current content can be discarded.
+func (p *PluginMerge) mergeSequentialChunks(
ctx context.Context,
knowledgeID string,
chunks []*types.SearchResult,
@@ -21,54 +22,48 @@ func (p *PluginMerge) mergeOverlappingChunks(
return nil
}
- merged := []*types.SearchResult{chunks[0]}
+ type mergedGroup struct {
+ result *types.SearchResult
+ lastIndex int
+ }
+ groups := []mergedGroup{{result: chunks[0], lastIndex: chunks[0].ChunkIndex}}
for i := 1; i < len(chunks); i++ {
- lastChunk := merged[len(merged)-1]
-
- // Non-overlapping: add as a new entry
- if chunks[i].StartAt > lastChunk.EndAt {
- merged = append(merged, chunks[i])
+ current := chunks[i]
+ last := &groups[len(groups)-1]
+ lastChunk := last.result
+ textContained := searchutil.ContainsChunkContent(lastChunk.Content, current.Content) ||
+ searchutil.ContainsChunkContent(current.Content, lastChunk.Content)
+ sequential := current.ChunkIndex == last.lastIndex+1
+ if !textContained && !sequential {
+ groups = append(groups, mergedGroup{result: current, lastIndex: current.ChunkIndex})
continue
}
- // Partial overlap: append the non-overlapping suffix.
- //
- // 重叠去重统一交给 searchutil.AppendWithOverlap(按文本匹配),它能
- // 兼容父子分块器补写的零宽表头,以及 HTML 实体导致的 content 长度与
- // EndAt-StartAt 不一致——这两种情况都会让按位置裁剪错位、丢字或重复。
- // StartAt/EndAt 仅用于估算搜索窗口大小。
- if chunks[i].EndAt > lastChunk.EndAt {
- lastChunk.Content = searchutil.AppendWithOverlap(
- lastChunk.Content, chunks[i].Content, lastChunk.EndAt-chunks[i].StartAt,
- )
- lastChunk.EndAt = chunks[i].EndAt
- lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID)
-
- if err := mergeImageInfo(ctx, lastChunk, chunks[i]); err != nil {
- pipelineWarn(ctx, "Merge", "image_merge", map[string]interface{}{
- "knowledge_id": knowledgeID,
- "error": err.Error(),
- })
- }
- } else {
- // Fully contained: track the subsumed chunk and merge its ImageInfo
- if !containsID(lastChunk.SubChunkID, chunks[i].ID) {
- lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID)
- }
- if err := mergeImageInfo(ctx, lastChunk, chunks[i]); err != nil {
- pipelineWarn(ctx, "Merge", "image_merge_contained", map[string]interface{}{
- "knowledge_id": knowledgeID,
- "error": err.Error(),
- })
- }
+ lastChunk.Content = searchutil.JoinChunkContent(lastChunk.Content, current.Content, "\n\n")
+ if !containsID(lastChunk.SubChunkID, current.ID) {
+ lastChunk.SubChunkID = append(lastChunk.SubChunkID, current.ID)
+ }
+ if err := mergeImageInfo(ctx, lastChunk, current); err != nil {
+ pipelineWarn(ctx, "Merge", "image_merge", map[string]interface{}{
+ "knowledge_id": knowledgeID,
+ "error": err.Error(),
+ })
+ }
+ if current.ChunkIndex > last.lastIndex {
+ last.lastIndex = current.ChunkIndex
}
// Keep the higher score
- if chunks[i].Score > lastChunk.Score {
- lastChunk.Score = chunks[i].Score
+ if current.Score > lastChunk.Score {
+ lastChunk.Score = current.Score
}
}
+ merged := make([]*types.SearchResult, 0, len(groups))
+ for _, group := range groups {
+ merged = append(merged, group.result)
+ }
+
// Sort merged chunks by score (highest first)
sort.Slice(merged, func(i, j int) bool {
return merged[i].Score > merged[j].Score
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 30f7ed571..9f5d94279 100644
--- a/internal/application/service/chat_pipeline/merge_parent_resolve_test.go
+++ b/internal/application/service/chat_pipeline/merge_parent_resolve_test.go
@@ -1,13 +1,57 @@
package chatpipeline
import (
+ "context"
"encoding/json"
+ "strings"
"testing"
"github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
)
+func TestResolveParentChunksUsesCurrentContentAndImageURLs(t *testing.T) {
+ parent := &types.Chunk{
+ ID: "parent", ChunkType: types.ChunkTypeParentText, ChunkIndex: 7,
+ Content: "manually inserted prefix\n\n![one](u1)\n\nparent body\n\n![two](u2)",
+ }
+ imageInfo, err := json.Marshal([]types.ImageInfo{{URL: "u2", OCRText: "two"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ repo := &expandChunkRepo{
+ chunks: map[string]*types.Chunk{"parent": parent},
+ children: map[string][]*types.Chunk{
+ "child": {
+ {
+ ID: "image", ParentChunkID: "child", ChunkType: types.ChunkTypeImageOCR,
+ ImageInfo: string(imageInfo),
+ },
+ },
+ },
+ }
+ plugin := &PluginMerge{chunkRepo: repo}
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
+ result := &types.SearchResult{
+ ID: "child", KnowledgeID: "doc", ChunkType: string(types.ChunkTypeText),
+ ParentChunkID: "parent", Content: "current edited child body", StartAt: 999, EndAt: 1001,
+ }
+
+ got := plugin.resolveParentChunks(ctx, &types.ChatManage{}, []*types.SearchResult{result})
+ if len(got) != 1 {
+ t.Fatalf("result count = %d, want 1", len(got))
+ }
+ if !strings.Contains(got[0].Content, "current edited child body") {
+ t.Fatalf("edited child content was lost: %q", got[0].Content)
+ }
+ if strings.Contains(got[0].Content, "u1") || !strings.Contains(got[0].Content, "u2") {
+ t.Fatalf("parent images were not scoped by URL: %q", got[0].Content)
+ }
+ if got[0].StartAt != 999 || got[0].EndAt != 1001 {
+ t.Fatalf("source coordinates changed to [%d,%d)", got[0].StartAt, got[0].EndAt)
+ }
+}
+
func TestCollectScopedTextChildIDs(t *testing.T) {
parentMap := map[string]*types.Chunk{
"parent-1": {ID: "parent-1", ChunkType: types.ChunkTypeParentText},
diff --git a/internal/application/service/chat_pipeline/rerank.go b/internal/application/service/chat_pipeline/rerank.go
index 8887bc53c..d44e24cdd 100644
--- a/internal/application/service/chat_pipeline/rerank.go
+++ b/internal/application/service/chat_pipeline/rerank.go
@@ -444,12 +444,7 @@ func compositeScore(sr *types.SearchResult, modelScore, baseScore float64) float
default:
sourceWeight = 1.0
}
- positionPrior := 1.0
- if sr.StartAt >= 0 {
- positionPrior += searchutil.ClampFloat(1.0-float64(sr.StartAt)/float64(sr.EndAt+1), -0.05, 0.05)
- }
composite := 0.6*modelScore + 0.3*baseScore + 0.1*sourceWeight
- composite *= positionPrior
if composite < 0 {
composite = 0
}
@@ -680,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.GetQuestionStrings(); len(questionStrings) > 0 {
+ } else if questionStrings := docMeta.GetCurrentQuestionStrings(result.ContentRevision); len(questionStrings) > 0 {
enrichments = append(enrichments, strings.Join(questionStrings, "; "))
}
}
diff --git a/internal/application/service/chat_pipeline/search_entity.go b/internal/application/service/chat_pipeline/search_entity.go
index 90415e3ae..05adbdc8c 100644
--- a/internal/application/service/chat_pipeline/search_entity.go
+++ b/internal/application/service/chat_pipeline/search_entity.go
@@ -213,6 +213,7 @@ 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,
diff --git a/internal/application/service/chunk.go b/internal/application/service/chunk.go
index fa23215d1..7e9a16ae7 100644
--- a/internal/application/service/chunk.go
+++ b/internal/application/service/chunk.go
@@ -14,6 +14,7 @@ import (
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
@@ -407,6 +408,12 @@ func (s *chunkService) UpdateDocumentChunk(
}
if newContent == chunk.Content && newEnabled == chunk.IsEnabled {
if chunk.IndexStatus == "failed" {
+ if chunk.ParentChunkID != "" && chunk.ContentRevision > 0 {
+ if err := s.rebuildParentContent(ctx, chunk); err != nil {
+ logger.Warnf(ctx, "Failed to rebuild parent chunk while retrying edit: %v", err)
+ return chunk, nil
+ }
+ }
chunk.IndexStatus = "processing"
_ = s.chunkRepository.UpdateChunk(ctx, chunk)
if err := s.syncChunkIndex(ctx, chunk); err != nil {
@@ -421,6 +428,15 @@ func (s *chunkService) UpdateDocumentChunk(
}
return chunk, nil
}
+ if content != nil {
+ sourceContent := chunk.SourceContent
+ if sourceContent == "" {
+ sourceContent = chunk.Content
+ }
+ if err := validateEditedChunkImages(sourceContent, newContent); err != nil {
+ return nil, err
+ }
+ }
actorID, _ := types.UserIDFromContext(ctx)
now := time.Now()
@@ -442,18 +458,6 @@ func (s *chunkService) UpdateDocumentChunk(
chunk.LastEditorID = actorID
chunk.IndexStatus = "processing"
chunk.UpdatedAt = now
- if bodyChanged {
- meta, metaErr := chunk.DocumentMetadata()
- if metaErr != nil {
- return nil, fmt.Errorf("parse chunk metadata: %w", metaErr)
- }
- if meta != nil {
- meta.GeneratedQuestions = nil
- if err := chunk.SetDocumentMetadata(meta); err != nil {
- return nil, err
- }
- }
- }
if err := s.chunkRepository.SaveChunkRevision(ctx, chunk, revision, oldRevision); err != nil {
return nil, err
}
@@ -461,6 +465,17 @@ func (s *chunkService) UpdateDocumentChunk(
if bodyChanged && chunk.ParentChunkID != "" {
if err := s.rebuildParentContent(ctx, chunk); err != nil {
logger.Warnf(ctx, "Failed to rebuild parent chunk after edit: %v", err)
+ chunk.IndexStatus = "failed"
+ _ = s.chunkRepository.UpdateChunk(ctx, chunk)
+ return chunk, nil
+ }
+ }
+ if bodyChanged || newEnabled != revision.IsEnabled {
+ if err := s.syncEditedChunkImages(ctx, chunk); err != nil {
+ logger.Warnf(ctx, "Failed to synchronize image children after chunk edit: %v", err)
+ chunk.IndexStatus = "failed"
+ _ = s.chunkRepository.UpdateChunk(ctx, chunk)
+ return chunk, nil
}
}
if bodyChanged || newEnabled != revision.IsEnabled {
@@ -486,6 +501,61 @@ func (s *chunkService) UpdateDocumentChunk(
return chunk, nil
}
+func validateEditedChunkImages(sourceContent, editedContent string) error {
+ allowed := searchutil.ImageURLsInContent(sourceContent)
+ for url := range searchutil.ImageURLsInContent(editedContent) {
+ if !allowed[url] {
+ return fmt.Errorf("adding images to an existing chunk is not supported: %s", url)
+ }
+ }
+ return nil
+}
+
+func imageChildMatchesContent(child *types.Chunk, contentURLs map[string]bool) bool {
+ for url := range searchutil.ImageURLsFromInfo(child.ImageInfo) {
+ if contentURLs[url] {
+ return true
+ }
+ }
+ return false
+}
+
+// syncEditedChunkImages removes image OCR/caption children from retrieval
+// when their Markdown image was deleted. Rows are disabled rather than hard
+// deleted so reverting to a historical chunk revision can re-enable them.
+func (s *chunkService) syncEditedChunkImages(ctx context.Context, chunk *types.Chunk) error {
+ children, err := s.chunkRepository.ListChunkByParentID(ctx, chunk.TenantID, chunk.ID)
+ if err != nil {
+ return err
+ }
+ contentURLs := searchutil.ImageURLsInContent(chunk.Content)
+ for _, child := range children {
+ if child.ChunkType != types.ChunkTypeImageOCR && child.ChunkType != types.ChunkTypeImageCaption {
+ continue
+ }
+ desiredEnabled := chunk.IsEnabled && imageChildMatchesContent(child, contentURLs)
+ if child.IsEnabled == desiredEnabled && child.IndexStatus == "ready" {
+ continue
+ }
+ child.IsEnabled = desiredEnabled
+ child.IndexStatus = "processing"
+ child.UpdatedAt = time.Now()
+ if err := s.chunkRepository.UpdateChunk(ctx, child); err != nil {
+ return err
+ }
+ if err := s.syncChunkIndex(ctx, child); err != nil {
+ child.IndexStatus = "failed"
+ _ = s.chunkRepository.UpdateChunk(ctx, child)
+ return err
+ }
+ child.IndexStatus = "ready"
+ if err := s.chunkRepository.UpdateChunk(ctx, child); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
func (s *chunkService) ListChunkRevisions(ctx context.Context, chunkID string) ([]*types.ChunkRevision, error) {
return s.chunkRepository.ListChunkRevisions(ctx, types.MustTenantIDFromContext(ctx), chunkID)
}
@@ -535,11 +605,13 @@ func (s *chunkService) rebuildParentContent(ctx context.Context, edited *types.C
replacements = append(replacements, replacement{start, end, child.Content, child.UpdatedAt})
}
}
- // Overlapping child windows cannot both be projected after arbitrary text
- // replacement. Keep the most recently edited window and ignore older
- // overlaps so the parent remains deterministic.
+ // Overlapping arbitrary replacements cannot both occupy the same source
+ // interval. Keep the latest edit in place, then append every conflicting
+ // current body that is not already represented. Retrieval must prefer a
+ // small amount of duplication over silently losing an accepted edit.
sort.Slice(replacements, func(i, j int) bool { return replacements[i].updatedAt.After(replacements[j].updatedAt) })
selected := make([]replacement, 0, len(replacements))
+ conflicts := make([]replacement, 0)
for _, candidate := range replacements {
overlaps := false
for _, existing := range selected {
@@ -550,6 +622,8 @@ func (s *chunkService) rebuildParentContent(ctx context.Context, edited *types.C
}
if !overlaps {
selected = append(selected, candidate)
+ } else {
+ conflicts = append(conflicts, candidate)
}
}
replacements = selected
@@ -558,6 +632,9 @@ func (s *chunkService) rebuildParentContent(ctx context.Context, edited *types.C
baseRunes = append(append(append([]rune{}, baseRunes[:repl.start]...), []rune(repl.content)...), baseRunes[repl.end:]...)
}
parent.Content = string(baseRunes)
+ for _, conflict := range conflicts {
+ parent.Content = searchutil.JoinChunkContent(parent.Content, conflict.content, "\n\n")
+ }
parent.UpdatedAt = time.Now()
return s.chunkRepository.UpdateChunk(ctx, parent)
}
@@ -600,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) == "" {
+ if strings.TrimSpace(question.Question) == "" || !meta.IsQuestionCurrent(question, chunk.ContentRevision) {
continue
}
items = append(items, &types.IndexInfo{
@@ -632,15 +709,18 @@ func (s *chunkService) UpsertGeneratedQuestion(
if meta == nil {
meta = &types.DocumentChunkMetadata{}
}
- meta.GeneratedQuestionsRevision = chunk.ContentRevision
+ currentRevision := chunk.ContentRevision
if questionID == "" {
questionID = uuid.NewString()
- meta.GeneratedQuestions = append(meta.GeneratedQuestions, types.GeneratedQuestion{ID: questionID, Question: question})
+ meta.GeneratedQuestions = append(meta.GeneratedQuestions, types.GeneratedQuestion{
+ ID: questionID, Question: question, ContentRevision: &currentRevision,
+ })
} else {
found := false
for i := range meta.GeneratedQuestions {
if meta.GeneratedQuestions[i].ID == questionID {
meta.GeneratedQuestions[i].Question = question
+ meta.GeneratedQuestions[i].ContentRevision = &currentRevision
found = true
break
}
diff --git a/internal/application/service/chunk_edit_parent_test.go b/internal/application/service/chunk_edit_parent_test.go
new file mode 100644
index 000000000..058c0aea1
--- /dev/null
+++ b/internal/application/service/chunk_edit_parent_test.go
@@ -0,0 +1,237 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+type editableChunkRepo struct {
+ interfaces.ChunkRepository
+ chunk *types.Chunk
+}
+
+func (r *editableChunkRepo) GetChunkByID(
+ _ context.Context, _ uint64, _ string,
+) (*types.Chunk, error) {
+ copyOfChunk := *r.chunk
+ return &copyOfChunk, nil
+}
+
+func (r *editableChunkRepo) SaveChunkRevision(
+ _ context.Context, chunk *types.Chunk, _ *types.ChunkRevision, _ int,
+) error {
+ copyOfChunk := *chunk
+ r.chunk = &copyOfChunk
+ return nil
+}
+
+func (r *editableChunkRepo) ListChunkByParentID(
+ _ context.Context, _ uint64, _ string,
+) ([]*types.Chunk, error) {
+ return nil, nil
+}
+
+func (r *editableChunkRepo) UpdateChunk(_ context.Context, chunk *types.Chunk) error {
+ copyOfChunk := *chunk
+ r.chunk = &copyOfChunk
+ return nil
+}
+
+type editableChunkKBRepo struct {
+ interfaces.KnowledgeBaseRepository
+}
+
+func (editableChunkKBRepo) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) {
+ return &types.KnowledgeBase{}, nil
+}
+
+type editableChunkKnowledgeRepo struct {
+ interfaces.KnowledgeRepository
+}
+
+func (editableChunkKnowledgeRepo) GetKnowledgeByID(context.Context, uint64, string) (*types.Knowledge, error) {
+ return nil, errors.New("summary refresh not configured in unit test")
+}
+
+type imageSyncChunkRepo struct {
+ interfaces.ChunkRepository
+ children []*types.Chunk
+}
+
+func (r *imageSyncChunkRepo) ListChunkByParentID(
+ _ context.Context, _ uint64, _ string,
+) ([]*types.Chunk, error) {
+ return r.children, nil
+}
+
+func (r *imageSyncChunkRepo) UpdateChunk(_ context.Context, chunk *types.Chunk) error {
+ for i := range r.children {
+ if r.children[i].ID == chunk.ID {
+ copyOfChunk := *chunk
+ r.children[i] = &copyOfChunk
+ return nil
+ }
+ }
+ return nil
+}
+
+type parentRebuildChunkRepo struct {
+ interfaces.ChunkRepository
+ parent *types.Chunk
+ children []*types.Chunk
+ updated *types.Chunk
+}
+
+func TestValidateEditedChunkImages(t *testing.T) {
+ source := "before\n![one](resource://one)\n![two](resource://two)\nafter"
+ if err := validateEditedChunkImages(source, "before\n![two](resource://two)\nafter"); err != nil {
+ t.Fatalf("deleting an original image should be allowed: %v", err)
+ }
+ if err := validateEditedChunkImages(source, source+"\n![new](resource://new)"); err == nil {
+ t.Fatal("adding a new image should be rejected")
+ }
+}
+
+func TestImageChildMatchesEditedContent(t *testing.T) {
+ imageInfo, err := json.Marshal([]types.ImageInfo{{URL: "resource://one", OriginalURL: "original://one"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ child := &types.Chunk{ImageInfo: string(imageInfo)}
+ if !imageChildMatchesContent(child, map[string]bool{"resource://one": true}) {
+ t.Fatal("current image URL should match")
+ }
+ if !imageChildMatchesContent(child, map[string]bool{"original://one": true}) {
+ t.Fatal("original image URL should match")
+ }
+ if imageChildMatchesContent(child, map[string]bool{"resource://other": true}) {
+ t.Fatal("unrelated image URL should not match")
+ }
+}
+
+func TestSyncEditedChunkImagesDisablesAndRestoresImageChildren(t *testing.T) {
+ imageInfo, err := json.Marshal([]types.ImageInfo{{URL: "resource://one"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ repo := &imageSyncChunkRepo{children: []*types.Chunk{{
+ ID: "image", TenantID: 1, KnowledgeBaseID: "kb", ParentChunkID: "text",
+ ChunkType: types.ChunkTypeImageOCR, ImageInfo: string(imageInfo),
+ IsEnabled: true, IndexStatus: "ready",
+ }}}
+ service := &chunkService{chunkRepository: repo, kbRepository: editableChunkKBRepo{}}
+ parent := &types.Chunk{ID: "text", TenantID: 1, IsEnabled: true, Content: "image removed"}
+
+ if err := service.syncEditedChunkImages(context.Background(), parent); err != nil {
+ t.Fatalf("disable removed image child: %v", err)
+ }
+ if repo.children[0].IsEnabled || repo.children[0].IndexStatus != "ready" {
+ t.Fatalf("removed image child was not disabled cleanly: %+v", repo.children[0])
+ }
+
+ parent.Content = "image restored\n![one](resource://one)"
+ if err := service.syncEditedChunkImages(context.Background(), parent); err != nil {
+ t.Fatalf("restore image child: %v", err)
+ }
+ if !repo.children[0].IsEnabled || repo.children[0].IndexStatus != "ready" {
+ t.Fatalf("restored image child was not re-enabled: %+v", repo.children[0])
+ }
+}
+
+func TestUpdateDocumentChunkPreservesGeneratedQuestionsAsStale(t *testing.T) {
+ metadata := &types.DocumentChunkMetadata{
+ GeneratedQuestions: []types.GeneratedQuestion{{ID: "q1", Question: "old question"}},
+ GeneratedQuestionsRevision: 0,
+ }
+ metadataJSON, err := json.Marshal(metadata)
+ if err != nil {
+ t.Fatal(err)
+ }
+ repo := &editableChunkRepo{chunk: &types.Chunk{
+ ID: "chunk", TenantID: 1, KnowledgeID: "knowledge", KnowledgeBaseID: "kb",
+ Content: "old body", SourceContent: "old body", ContentRevision: 0,
+ ChunkType: types.ChunkTypeText, IsEnabled: true, IndexStatus: "ready", Metadata: metadataJSON,
+ }}
+ service := &chunkService{
+ chunkRepository: repo,
+ knowledgeRepo: editableChunkKnowledgeRepo{},
+ kbRepository: editableChunkKBRepo{},
+ }
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
+ newContent := "new body"
+
+ updated, err := service.UpdateDocumentChunk(ctx, "chunk", &newContent, nil, nil)
+ if err != nil {
+ t.Fatalf("update chunk: %v", err)
+ }
+ updatedMetadata, err := updated.DocumentMetadata()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(updatedMetadata.GeneratedQuestions) != 1 || updatedMetadata.GeneratedQuestions[0].Question != "old question" {
+ 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")
+ }
+}
+
+func (r *parentRebuildChunkRepo) GetChunkByID(
+ _ context.Context, _ uint64, _ string,
+) (*types.Chunk, error) {
+ copyOfParent := *r.parent
+ return &copyOfParent, nil
+}
+
+func (r *parentRebuildChunkRepo) ListChunkByParentID(
+ _ context.Context, _ uint64, _ string,
+) ([]*types.Chunk, error) {
+ return r.children, nil
+}
+
+func (r *parentRebuildChunkRepo) UpdateChunk(_ context.Context, chunk *types.Chunk) error {
+ copyOfChunk := *chunk
+ r.updated = &copyOfChunk
+ return nil
+}
+
+func TestRebuildParentContentPreservesConflictingEdits(t *testing.T) {
+ now := time.Now()
+ repo := &parentRebuildChunkRepo{
+ parent: &types.Chunk{
+ ID: "parent", TenantID: 1, ChunkType: types.ChunkTypeParentText,
+ SourceContent: "abcdefghij", Content: "abcdefghij", StartAt: 0, EndAt: 10,
+ },
+ children: []*types.Chunk{
+ {
+ ID: "older", ParentChunkID: "parent", ContentRevision: 1,
+ Content: "OLDER EDIT BODY", StartAt: 0, EndAt: 6, UpdatedAt: now.Add(-time.Minute),
+ },
+ {
+ ID: "newer", ParentChunkID: "parent", ContentRevision: 1,
+ Content: "NEWER EDIT BODY", StartAt: 4, EndAt: 10, UpdatedAt: now,
+ },
+ },
+ }
+ service := &chunkService{chunkRepository: repo}
+ edited := &types.Chunk{TenantID: 1, ParentChunkID: "parent"}
+
+ if err := service.rebuildParentContent(context.Background(), edited); err != nil {
+ t.Fatalf("rebuild parent: %v", err)
+ }
+ if repo.updated == nil {
+ t.Fatal("parent was not updated")
+ }
+ for _, want := range []string{"OLDER EDIT BODY", "NEWER EDIT BODY"} {
+ if !strings.Contains(repo.updated.Content, want) {
+ t.Fatalf("rebuilt parent lost %q: %q", want, repo.updated.Content)
+ }
+ }
+}
diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go
index a73921401..410dea23b 100644
--- a/internal/application/service/custom_agent.go
+++ b/internal/application/service/custom_agent.go
@@ -722,7 +722,11 @@ func (s *customAgentService) getSuggestedQuestions(
if err != nil || meta == nil || len(meta.GeneratedQuestions) == 0 {
continue
}
- q := meta.GeneratedQuestions[0].Question
+ currentQuestions := meta.GetCurrentQuestionStrings(chunk.ContentRevision)
+ if len(currentQuestions) == 0 {
+ continue
+ }
+ q := currentQuestions[0]
if q == "" || seen[q] {
continue
}
diff --git a/internal/application/service/knowledge_process.go b/internal/application/service/knowledge_process.go
index 31624ce4d..e5a96f77c 100644
--- a/internal/application/service/knowledge_process.go
+++ b/internal/application/service/knowledge_process.go
@@ -1583,11 +1583,13 @@ func (s *knowledgeService) processQuestionGenerationForKnowledge(ctx context.Con
// Update chunk metadata with unique IDs for each question
generatedQuestions := make([]types.GeneratedQuestion, len(questions))
+ questionRevision := chunk.ContentRevision
for j, question := range questions {
questionID := fmt.Sprintf("q%d", time.Now().UnixNano()+int64(j))
generatedQuestions[j] = types.GeneratedQuestion{
- ID: questionID,
- Question: question,
+ ID: questionID,
+ Question: question,
+ ContentRevision: &questionRevision,
}
}
meta := &types.DocumentChunkMetadata{
@@ -1918,10 +1920,12 @@ func (s *knowledgeService) processQuestionGenerationForChunks(ctx context.Contex
}
generatedQuestions := make([]types.GeneratedQuestion, len(questions))
+ questionRevision := chunk.ContentRevision
for j, question := range questions {
generatedQuestions[j] = types.GeneratedQuestion{
- ID: fmt.Sprintf("q%d", time.Now().UnixNano()+int64(j)),
- Question: question,
+ ID: fmt.Sprintf("q%d", time.Now().UnixNano()+int64(j)),
+ Question: question,
+ ContentRevision: &questionRevision,
}
}
meta := &types.DocumentChunkMetadata{
@@ -2102,8 +2106,11 @@ func (s *knowledgeService) RegenerateChunkQuestions(
}
chunk = latestChunk
generated := make([]types.GeneratedQuestion, 0, len(questions))
+ questionRevision := chunk.ContentRevision
for _, question := range questions {
- generated = append(generated, types.GeneratedQuestion{ID: uuid.NewString(), Question: question})
+ generated = append(generated, types.GeneratedQuestion{
+ ID: uuid.NewString(), Question: question, ContentRevision: &questionRevision,
+ })
}
meta := &types.DocumentChunkMetadata{
GeneratedQuestions: generated, GeneratedQuestionsRevision: chunk.ContentRevision,
@@ -2689,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) != "" {
+ if strings.TrimSpace(q.Question) != "" && meta.IsQuestionCurrent(q, chunk.ContentRevision) {
indexInfo = append(indexInfo, &types.IndexInfo{
Content: buildKnowledgeIndexContent(knowledge, q.Question), SourceID: types.GeneratedQuestionSourceID(chunk.ID, q.ID),
SourceType: types.ChunkSourceType, ChunkID: chunk.ID,
diff --git a/internal/application/service/knowledgebase_search_results.go b/internal/application/service/knowledgebase_search_results.go
index ec534ce66..865fe2c79 100644
--- a/internal/application/service/knowledgebase_search_results.go
+++ b/internal/application/service/knowledgebase_search_results.go
@@ -311,6 +311,7 @@ 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,
@@ -334,6 +335,12 @@ func (s *knowledgeBaseService) buildSearchResult(chunk *types.Chunk,
// isSearchableChunk checks if a chunk type should be included in search results.
func (s *knowledgeBaseService) isSearchableChunk(chunk *types.Chunk) bool {
+ // An edit is persisted before its retrieval artifacts are synchronized.
+ // Do not hydrate stale vector hits while that synchronization is pending or
+ // failed. Empty is accepted for legacy rows created before index_status.
+ if chunk.IndexStatus == "processing" || chunk.IndexStatus == "failed" {
+ return false
+ }
return slices.Contains([]types.ChunkType{
types.ChunkTypeText, types.ChunkTypeSummary,
types.ChunkTypeTableColumn, types.ChunkTypeTableSummary,
diff --git a/internal/application/service/knowledgebase_search_results_edit_test.go b/internal/application/service/knowledgebase_search_results_edit_test.go
new file mode 100644
index 000000000..407f44f1c
--- /dev/null
+++ b/internal/application/service/knowledgebase_search_results_edit_test.go
@@ -0,0 +1,23 @@
+package service
+
+import (
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+func TestIsSearchableChunkSkipsUnsynchronizedEdits(t *testing.T) {
+ service := &knowledgeBaseService{}
+ for _, status := range []string{"processing", "failed"} {
+ chunk := &types.Chunk{ChunkType: types.ChunkTypeText, IndexStatus: status}
+ if service.isSearchableChunk(chunk) {
+ t.Fatalf("chunk with index status %q should not be searchable", status)
+ }
+ }
+ for _, status := range []string{"", "ready"} {
+ chunk := &types.Chunk{ChunkType: types.ChunkTypeText, IndexStatus: status}
+ if !service.isSearchableChunk(chunk) {
+ t.Fatalf("chunk with index status %q should be searchable", status)
+ }
+ }
+}
diff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.go
index cde73e892..bbe6e50a3 100644
--- a/internal/handler/session/agent_stream_handler.go
+++ b/internal/handler/session/agent_stream_handler.go
@@ -397,6 +397,7 @@ 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"),
}
diff --git a/internal/handler/session/helpers.go b/internal/handler/session/helpers.go
index dbac22269..8192e2166 100644
--- a/internal/handler/session/helpers.go
+++ b/internal/handler/session/helpers.go
@@ -226,6 +226,7 @@ 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")),
diff --git a/internal/searchutil/chunkmerge.go b/internal/searchutil/chunkmerge.go
index c8a4bc2da..fd48c04b4 100644
--- a/internal/searchutil/chunkmerge.go
+++ b/internal/searchutil/chunkmerge.go
@@ -2,13 +2,76 @@ package searchutil
import (
"sort"
+ "strings"
"github.com/Tencent/WeKnora/internal/types"
)
+// JoinChunkContent joins two current chunk bodies without relying on parser
+// offsets. Exact containment is collapsed, a real suffix/prefix overlap is
+// removed, and otherwise both bodies are retained with separator between
+// them. The conservative fallback intentionally prefers small duplication
+// over silently dropping edited content.
+func JoinChunkContent(acc, next, separator string) string {
+ if acc == "" {
+ return next
+ }
+ if next == "" {
+ return acc
+ }
+ if ContainsChunkContent(acc, next) {
+ return acc
+ }
+ if ContainsChunkContent(next, acc) {
+ return next
+ }
+
+ accRunes := []rune(acc)
+ nextRunes := []rune(next)
+ maxOverlap := minInt(len(accRunes), len(nextRunes))
+ // Editable chunks may be much larger than parser-produced chunks. Bound
+ // suffix matching so an adversarial 200 KB edit cannot turn retrieval into
+ // quadratic work. Parser overlap windows are normally far below this cap;
+ // larger unmatched overlap is safely retained as duplication.
+ if maxOverlap > defaultSearchSpan {
+ maxOverlap = defaultSearchSpan
+ }
+ for overlap := maxOverlap; overlap >= minOverlapRunes; overlap-- {
+ if runeSlicesEqual(accRunes[len(accRunes)-overlap:], nextRunes[:overlap]) {
+ return acc + string(nextRunes[overlap:])
+ }
+ }
+ return acc + separator + next
+}
+
+// ContainsChunkContent reports whether the complete current body is safely
+// represented by another body. Very short substrings are not treated as
+// containment because common words and punctuation would create false drops.
+func ContainsChunkContent(container, contained string) bool {
+ if container == "" || contained == "" {
+ return false
+ }
+ if container == contained {
+ return true
+ }
+ return len([]rune(contained)) >= minOverlapRunes && strings.Contains(container, contained)
+}
+
+func runeSlicesEqual(left, right []rune) bool {
+ if len(left) != len(right) {
+ return false
+ }
+ for i := range left {
+ if left[i] != right[i] {
+ return false
+ }
+ }
+ return true
+}
+
// 这里实现 chunk 内容的「重叠拼接」公共逻辑,供文档重建(reconstructContent)、
-// 知识图谱内容合并(graph mergeChunkContents)、检索结果重叠合并
-// (chat_pipeline mergeOverlappingChunks)等多处复用。
+// 知识图谱内容合并(graph mergeChunkContents)等路径复用。聊天检索链路允许
+// 用户编辑 Chunk,使用上面的 JoinChunkContent,避免依赖原文位置坐标。
//
// 历史上各处都用「按位置」的公式裁剪重叠(offset = len(content) - (EndAt -
// lastEndAt) 之类),它默认 len([]rune(Content)) == EndAt-StartAt。但有两类
diff --git a/internal/searchutil/chunkmerge_test.go b/internal/searchutil/chunkmerge_test.go
index 05fe9efaa..5ce2bfff0 100644
--- a/internal/searchutil/chunkmerge_test.go
+++ b/internal/searchutil/chunkmerge_test.go
@@ -58,6 +58,32 @@ func TestAppendWithOverlap_NoOverlap(t *testing.T) {
}
}
+func TestJoinChunkContentUsesCurrentTextInsteadOfSourceOffsets(t *testing.T) {
+ first := "first edited body with no original overlap"
+ second := "second independently edited body"
+ got := JoinChunkContent(first, second, "\n\n")
+ want := first + "\n\n" + second
+ if got != want {
+ t.Fatalf("edited join mismatch:\n got=%q\nwant=%q", got, want)
+ }
+}
+
+func TestJoinChunkContentRemovesRealBoundaryOverlap(t *testing.T) {
+ overlap := "shared boundary text"
+ got := JoinChunkContent("before "+overlap, overlap+" after", "\n\n")
+ want := "before " + overlap + " after"
+ if got != want {
+ t.Fatalf("overlap join mismatch:\n got=%q\nwant=%q", got, want)
+ }
+}
+
+func TestJoinChunkContentCollapsesExactContainment(t *testing.T) {
+ outer := "prefix complete current body suffix"
+ if got := JoinChunkContent(outer, "complete current body", "\n\n"); got != outer {
+ t.Fatalf("contained body should be collapsed: %q", got)
+ }
+}
+
func TestMergeTextChunks_OrdersFiltersAndStitches(t *testing.T) {
header := "| a | b |\n|:--|:--|\n"
chunks := []*types.Chunk{
diff --git a/internal/searchutil/imageinfo_match.go b/internal/searchutil/imageinfo_match.go
index d2c0280c5..0f68ce65c 100644
--- a/internal/searchutil/imageinfo_match.go
+++ b/internal/searchutil/imageinfo_match.go
@@ -67,6 +67,56 @@ func FilterImageInfoByContentURLs(content string, imageInfoJSON string) string {
return marshalImageInfos(filtered)
}
+// ImageURLsFromInfo returns every current and original URL represented by an
+// image_info payload.
+func ImageURLsFromInfo(imageInfoJSON string) map[string]bool {
+ urls := make(map[string]bool)
+ if imageInfoJSON == "" {
+ return urls
+ }
+ var infos []types.ImageInfo
+ if err := json.Unmarshal([]byte(imageInfoJSON), &infos); err != nil {
+ return urls
+ }
+ for _, info := range infos {
+ if info.URL != "" {
+ urls[info.URL] = true
+ }
+ if info.OriginalURL != "" {
+ urls[info.OriginalURL] = true
+ }
+ }
+ return urls
+}
+
+// PruneMarkdownImagesByImageInfo keeps only Markdown images represented by
+// the chunk-scoped image metadata. This is stable after text edits because it
+// matches durable image URLs instead of parser character offsets.
+func PruneMarkdownImagesByImageInfo(content, imageInfoJSON string) string {
+ allowed := make(map[string]bool)
+ if imageInfoJSON != "" {
+ var infos []types.ImageInfo
+ if err := json.Unmarshal([]byte(imageInfoJSON), &infos); err == nil {
+ for _, info := range infos {
+ if info.URL != "" {
+ allowed[info.URL] = true
+ }
+ if info.OriginalURL != "" {
+ allowed[info.OriginalURL] = true
+ }
+ }
+ }
+ }
+ filtered := MarkdownImageRegex.ReplaceAllStringFunc(content, func(image string) string {
+ match := MarkdownImageRegex.FindStringSubmatch(image)
+ if len(match) >= 3 && allowed[match[2]] {
+ return image
+ }
+ return ""
+ })
+ return collapseBlankLines(filtered)
+}
+
// FilterImageInfoByMatchRange keeps image_info entries whose Markdown image
// reference falls within the document rune range [matchStart, matchEnd).
// Used when parent content is expanded for context but multimodal enrichment
diff --git a/internal/searchutil/imageinfo_match_test.go b/internal/searchutil/imageinfo_match_test.go
index 63bcc9738..80060ecf4 100644
--- a/internal/searchutil/imageinfo_match_test.go
+++ b/internal/searchutil/imageinfo_match_test.go
@@ -68,6 +68,22 @@ func TestPruneMarkdownImagesOutsideRange(t *testing.T) {
}
}
+func TestPruneMarkdownImagesByImageInfoIgnoresShiftedOffsets(t *testing.T) {
+ content := "a manually inserted prefix that shifts every parser offset\n\n" +
+ "![p1](u1)\n\nbody\n\n![p2](u2)"
+ raw, err := json.Marshal([]types.ImageInfo{{URL: "u2"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := PruneMarkdownImagesByImageInfo(content, string(raw))
+ if strings.Contains(got, "u1") {
+ t.Fatalf("unscoped image remained: %q", got)
+ }
+ if !strings.Contains(got, "![p2](u2)") {
+ t.Fatalf("scoped image was removed: %q", got)
+ }
+}
+
func TestEnrichContentWithImageInfoForChat_SkipsUnmatched(t *testing.T) {
content := "![p1](u1)\n\n![p2](u2)"
raw, _ := json.Marshal([]types.ImageInfo{{URL: "u2", OCRText: "two"}})
diff --git a/internal/types/faq.go b/internal/types/faq.go
index 57a98a602..994af2246 100644
--- a/internal/types/faq.go
+++ b/internal/types/faq.go
@@ -26,8 +26,9 @@ type FAQChunkMetadata struct {
// GeneratedQuestion 表示AI生成的单个问题
type GeneratedQuestion struct {
- ID string `json:"id"` // 唯一标识,用于构造 source_id
- Question string `json:"question"` // 问题内容
+ ID string `json:"id"` // 唯一标识,用于构造 source_id
+ Question string `json:"question"` // 问题内容
+ ContentRevision *int `json:"content_revision,omitempty"` // 该问题对应的 Chunk 内容版本
}
const maxGeneratedQuestionSourceIDLength = 64
@@ -58,6 +59,17 @@ 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.
+func (m *DocumentChunkMetadata) IsQuestionCurrent(question GeneratedQuestion, chunkRevision int) bool {
+ if question.ContentRevision != nil {
+ return *question.ContentRevision == chunkRevision
+ }
+ return m != nil && m.GeneratedQuestionsRevision == chunkRevision
+}
+
// GetQuestionStrings 返回问题内容字符串列表(兼容旧代码)
func (m *DocumentChunkMetadata) GetQuestionStrings() []string {
if m == nil || len(m.GeneratedQuestions) == 0 {
@@ -70,6 +82,20 @@ 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 {
diff --git a/internal/types/generated_question_revision_test.go b/internal/types/generated_question_revision_test.go
new file mode 100644
index 000000000..aac676bdb
--- /dev/null
+++ b/internal/types/generated_question_revision_test.go
@@ -0,0 +1,23 @@
+package types
+
+import "testing"
+
+func TestDocumentChunkMetadataQuestionRevision(t *testing.T) {
+ oldRevision := 1
+ currentRevision := 2
+ meta := &DocumentChunkMetadata{
+ GeneratedQuestionsRevision: oldRevision,
+ GeneratedQuestions: []GeneratedQuestion{
+ {ID: "old", Question: "old question"},
+ {ID: "current", Question: "current question", ContentRevision: &currentRevision},
+ },
+ }
+
+ questions := meta.GetCurrentQuestionStrings(currentRevision)
+ if len(questions) != 1 || questions[0] != "current question" {
+ t.Fatalf("current questions = %v", questions)
+ }
+ if !meta.IsQuestionCurrent(meta.GeneratedQuestions[0], oldRevision) {
+ t.Fatal("legacy question should use the metadata-level revision")
+ }
+}
diff --git a/internal/types/search.go b/internal/types/search.go
index e9009beac..8b9d94916 100644
--- a/internal/types/search.go
+++ b/internal/types/search.go
@@ -157,6 +157,8 @@ 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