Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(wiki): reuse cross-type page for same-title items instead of creating twins (#3547)
LuckVdee3623ab76e1
diff --git a/internal/application/service/wiki_ingest_dedup.go b/internal/application/service/wiki_ingest_dedup.goindex 73063ef5d..0eb678f72 100644--- a/internal/application/service/wiki_ingest_dedup.go+++ b/internal/application/service/wiki_ingest_dedup.go@@ -199,12 +199,13 @@ func dedupMergeRejectReason(srcSlug, dstSlug string, srcCandidates map[string]boreturn ""}-// normalizeWikiIdentityTitle returns the conservative identity key used only-// to prevent same-type, same-title pages from being created under different-// slugs. It intentionally preserves punctuation: "寓言" and "《寓言》" can-// represent a concept and a work/chapter and must remain distinguishable.-// Removing whitespace and folding case is enough to close model formatting-// drift such as "Acme Corp" vs "acme corp".+// normalizeWikiIdentityTitle returns the conservative identity key used to+// prevent same-title pages from being created under different slugs, both+// within a page type and across the entity ↔ concept types (see+// exactIdentityTarget). It intentionally preserves punctuation: "寓言" and+// "《寓言》" can represent a concept and a work/chapter and must remain+// distinguishable. Removing whitespace and folding case is enough to close+// model formatting drift such as "Acme Corp" vs "acme corp".func normalizeWikiIdentityTitle(title string) string {return strings.Map(func(r rune) rune {if unicode.IsSpace(r) {@@ -215,10 +216,15 @@ func normalizeWikiIdentityTitle(title string) string {}// exactIdentityTarget returns the stable existing page for an extracted item-// when a same-type candidate has the exact normalized display title. The LLM-// remains responsible for semantic/alias matches; this deterministic fast path-// only covers the unambiguous identity invariant that one page type should not-// carry two pages with the same visible title.+// when a candidate has the exact normalized display title. Same-type matches+// win; if none exists, a cross-type page with the same title is reused. The+// model's type judgment drifts between ingests, so the same real-world thing+// is often first extracted as "concept" and later as "entity" (issue #3526);+// reusing the existing page keeps one page per title instead of materializing+// a twin whose slug differs only by the type prefix. The LLM remains+// responsible for semantic/alias matches; this deterministic fast path only+// covers the unambiguous identity invariant that one visible title should map+// to a single page.func exactIdentityTarget(item extractedItem,pageType string,@@ -230,25 +236,35 @@ func exactIdentityTarget(return ""}matches := make([]string, 0, 2)+ crossMatches := make([]string, 0, 2)for slug := range candidates {page := pages[slug]- if page == nil || page.PageType != pageType {+ if page == nil || normalizeWikiIdentityTitle(page.Title) != identity {continue}- if normalizeWikiIdentityTitle(page.Title) == identity {+ if page.PageType == pageType {matches = append(matches, page.Slug)+ } else {+ crossMatches = append(crossMatches, page.Slug)}}- if len(matches) == 0 {- return ""- }- for _, slug := range matches {- if slug == item.Slug {- return slug+ if len(matches) > 0 {+ for _, slug := range matches {+ if slug == item.Slug {+ return slug+ }}+ sort.Strings(matches)+ return matches[0]+ }+ // Cross-type fallback: reuse the existing page even though its type+ // prefix differs from this batch's judgment. Downstream writes are keyed+ // by slug and adopt the existing page's type, so the twin never forms.+ if len(crossMatches) > 0 {+ sort.Strings(crossMatches)+ return crossMatches[0]}- sort.Strings(matches)- return matches[0]+ return ""}func identityClaimString(v interface{}) string {@@ -430,6 +446,16 @@ func identityPageCacheKey(pageType, identity string) string {return pageType + "\x00" + identity}+// otherWikiPageType returns the entity/concept counterpart of a page type.+// The cross-type identity fallback (issue #3526) only applies between these+// two; summary/index pages are excluded.+func otherWikiPageType(pageType string) string {+ if pageType == types.WikiPageTypeEntity {+ return types.WikiPageTypeConcept+ }+ return types.WikiPageTypeEntity+}+func loadCachedIdentityPages(batchCtx *WikiBatchContext, pageType, identity string) ([]*types.WikiPageLite, bool) {if batchCtx == nil {return nil, false@@ -547,6 +573,67 @@ func (s *wikiIngestService) attachExactIdentityPages(for identity, slugs := range slugsByIdentity {bindExactIdentityPages(slugs, cached[identity], pageType, identity, candidatePages, itemCandidates)}++ // Cross-type safety net (issue #3526): the trigram probe that feeds+ // itemCandidates usually surfaces a same-title page of the other type,+ // but not always (formatting drift beyond whitespace/case). Fetch those+ // pages explicitly so exactIdentityTarget can reuse them instead of+ // materializing a concept/X + entity/X twin on re-ingest.+ other := otherWikiPageType(pageType)+ crossCached := make(map[string][]*types.WikiPageLite, len(slugsByIdentity))+ crossMiss := make([]string, 0, len(slugsByIdentity))+ for identity := range slugsByIdentity {+ if pages, ok := loadCachedIdentityPages(batchCtx, other, identity); ok {+ crossCached[identity] = pages+ continue+ }+ crossMiss = append(crossMiss, identity)+ }+ if len(crossMiss) > 0 {+ pages, err := s.wikiService.FindPagesByNormalizedTitles(ctx, kbID, other, crossMiss)+ if err != nil {+ logger.Warnf(ctx, "wiki ingest: cross-type identity lookup failed for %s (%d titles): %v",+ other, len(crossMiss), err)+ } else {+ byIdentity := make(map[string][]*types.WikiPageLite, len(crossMiss))+ for _, p := range pages {+ if p == nil {+ continue+ }+ identity := normalizeWikiIdentityTitle(p.Title)+ if identity == "" {+ continue+ }+ byIdentity[identity] = append(byIdentity[identity], p)+ }+ for _, identity := range crossMiss {+ hits := byIdentity[identity]+ if hits == nil {+ hits = []*types.WikiPageLite{}+ }+ crossCached[identity] = hits+ storeCachedIdentityPages(batchCtx, other, identity, hits)+ }+ }+ }+ for identity, slugs := range slugsByIdentity {+ for _, p := range crossCached[identity] {+ if p == nil || p.Slug == "" || p.PageType != other {+ continue+ }+ if _, ok := candidatePages[p.Slug]; !ok {+ candidatePages[p.Slug] = p+ }+ for _, slug := range slugs {+ own := itemCandidates[slug]+ if own == nil {+ own = make(map[string]bool)+ itemCandidates[slug] = own+ }+ own[p.Slug] = true+ }+ }+ }}func collectExactIdentityTargets(diff --git a/internal/application/service/wiki_ingest_dedup_test.go b/internal/application/service/wiki_ingest_dedup_test.goindex fdbe4c54e..d5d328cd0 100644--- a/internal/application/service/wiki_ingest_dedup_test.go+++ b/internal/application/service/wiki_ingest_dedup_test.go@@ -260,7 +260,10 @@ func TestNormalizeWikiIdentityTitlePreservesSemanticPunctuation(t *testing.T) {}}-func TestExactIdentityTargetSameTypeOnly(t *testing.T) {+// TestExactIdentityTargetPrefersSameType covers the same-type-wins rule of+// exactIdentityTarget now that a cross-type exact-title page is reused when+// no same-type page exists (issue #3526).+func TestExactIdentityTargetPrefersSameType(t *testing.T) {item := extractedItem{Name: "孔子", Slug: "entity/kong-zi"}pages := map[string]*types.WikiPageLite{"entity/confucius": {@@ -283,6 +286,40 @@ func TestExactIdentityTargetSameTypeOnly(t *testing.T) {}}+// TestExactIdentityTargetCrossTypeFallback covers issue #3526: a re-ingest+// may judge the same real-world thing as the other page type. Without a+// same-type page, the existing cross-type page must be reused instead of+// materializing a concept/X + entity/X twin.+func TestExactIdentityTargetCrossTypeFallback(t *testing.T) {+ item := extractedItem{Name: "孔子", Slug: "entity/kong-zi"}+ pages := map[string]*types.WikiPageLite{+ "concept/confucius": {+ Slug: "concept/confucius",+ Title: "孔子",+ PageType: types.WikiPageTypeConcept,+ },+ }+ candidates := map[string]bool{"concept/confucius": true}+ if got := exactIdentityTarget(item, types.WikiPageTypeEntity, candidates, pages); got != "concept/confucius" {+ t.Fatalf("exactIdentityTarget = %q, want concept/confucius (cross-type reuse)", got)+ }++ // Same-type match still wins over the cross-type page.+ pages["entity/confucius"] = &types.WikiPageLite{+ Slug: "entity/confucius", Title: "孔 子", PageType: types.WikiPageTypeEntity,+ }+ candidates["entity/confucius"] = true+ if got := exactIdentityTarget(item, types.WikiPageTypeEntity, candidates, pages); got != "entity/confucius" {+ t.Fatalf("exactIdentityTarget = %q, want same-type entity/confucius", got)+ }++ // Differently-titled cross-type pages must not be reused.+ other := extractedItem{Name: "孟子", Slug: "entity/mencius"}+ if got := exactIdentityTarget(other, types.WikiPageTypeEntity, candidates, pages); got != "" {+ t.Fatalf("exactIdentityTarget = %q, want empty for unrelated title", got)+ }+}+func TestWikiIdentityClaimConvergesDifferentSlugs(t *testing.T) {mr, err := miniredis.Run()if err != nil {@@ -569,26 +606,30 @@ func TestWikiIdentityClaimReplacesInvalidRedisValue(t *testing.T) {type stubNormalizedTitleWiki struct {interfaces.WikiPageService- mu sync.Mutex- calls int- last []string- pages []*types.WikiPageLite+ mu sync.Mutex+ callsByType map[string]int+ lastByType map[string][]string+ pages []*types.WikiPageLite}func (s *stubNormalizedTitleWiki) FindPagesByNormalizedTitles(- _ context.Context, _, _ string, identities []string,+ _ context.Context, _, pageType string, identities []string,) ([]*types.WikiPageLite, error) {s.mu.Lock()defer s.mu.Unlock()- s.calls++- s.last = append([]string(nil), identities...)+ if s.callsByType == nil {+ s.callsByType = make(map[string]int)+ s.lastByType = make(map[string][]string)+ }+ s.callsByType[pageType]+++ s.lastByType[pageType] = append([]string(nil), identities...)want := make(map[string]bool, len(identities))for _, id := range identities {want[id] = true}out := make([]*types.WikiPageLite, 0, len(s.pages))for _, p := range s.pages {- if p != nil && want[normalizeWikiIdentityTitle(p.Title)] {+ if p != nil && p.PageType == pageType && want[normalizeWikiIdentityTitle(p.Title)] {out = append(out, p)}}@@ -599,6 +640,8 @@ func TestAttachExactIdentityPagesBatchesAndCaches(t *testing.T) {stub := &stubNormalizedTitleWiki{pages: []*types.WikiPageLite{{Slug: "entity/confucius", Title: "孔 子", PageType: types.WikiPageTypeEntity},+ // Cross-type twin used to assert the issue #3526 safety net.+ {Slug: "concept/mencius", Title: "孟子", PageType: types.WikiPageTypeConcept},},}svc := &wikiIngestService{wikiService: stub}@@ -613,8 +656,10 @@ func TestAttachExactIdentityPagesBatchesAndCaches(t *testing.T) {candidatePages := make(map[string]*types.WikiPageLite)itemCandidates := make(map[string]map[string]bool)svc.attachExactIdentityPages(ctx, "kb-1", types.WikiPageTypeEntity, items, candidatePages, itemCandidates, batch)- if stub.calls != 1 {- t.Fatalf("expected 1 batched lookup, got %d identities=%v", stub.calls, stub.last)+ // Same-type lookup plus the cross-type safety net (issue #3526) each+ // batch per run: entity identities + concept identities.+ if stub.callsByType[types.WikiPageTypeEntity] != 1 || stub.callsByType[types.WikiPageTypeConcept] != 1 {+ t.Fatalf("expected 1 batched lookup per type, got byType=%v", stub.callsByType)}if !itemCandidates["entity/kong-zi"]["entity/confucius"] || !itemCandidates["entity/kongqiu"]["entity/confucius"] {t.Fatalf("exact page not bound to both romanizations: %#v", itemCandidates)@@ -622,19 +667,28 @@ func TestAttachExactIdentityPagesBatchesAndCaches(t *testing.T) {if itemCandidates["entity/mencius"]["entity/confucius"] {t.Fatalf("confucius page leaked onto 孟子: %#v", itemCandidates)}+ // Cross-type safety net: the same-title concept page must be bound to+ // the entity item so exactIdentityTarget can reuse it (issue #3526).+ if !itemCandidates["entity/mencius"]["concept/mencius"] {+ t.Fatalf("cross-type concept page not bound onto 孟子: %#v", itemCandidates["entity/mencius"])+ }+ if candidatePages["concept/mencius"] == nil {+ t.Fatalf("cross-type page missing from candidatePages: %#v", candidatePages)+ }svc.attachExactIdentityPages(ctx, "kb-1", types.WikiPageTypeEntity, items, candidatePages, itemCandidates, batch)- if stub.calls != 1 {- t.Fatalf("batch cache should skip the second lookup, got %d", stub.calls)+ if stub.callsByType[types.WikiPageTypeEntity] != 1 {+ t.Fatalf("batch cache should skip the second lookup, got byType=%v", stub.callsByType)}svc.attachExactIdentityPages(ctx, "kb-1", types.WikiPageTypeEntity, append(items,extractedItem{Name: "荀子", Slug: "entity/xunzi"},), candidatePages, itemCandidates, batch)- if stub.calls != 2 {- t.Fatalf("cache miss should query only the new identity, got %d last=%v", stub.calls, stub.last)+ if stub.callsByType[types.WikiPageTypeEntity] != 2 {+ t.Fatalf("cache miss should query only the new identity, got byType=%v", stub.callsByType)}- if len(stub.last) != 1 || stub.last[0] != normalizeWikiIdentityTitle("荀子") {- t.Fatalf("second lookup should only ask for 荀子: %v", stub.last)+ last := stub.lastByType[types.WikiPageTypeEntity]+ if len(last) != 1 || last[0] != normalizeWikiIdentityTitle("荀子") {+ t.Fatalf("second lookup should only ask for 荀子: %v", last)}}