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(wiki): prevent concurrent duplicate page identities (#2850)

JYao-Chen2523dc7276c3
diff --git a/internal/application/repository/wiki_page.go b/internal/application/repository/wiki_page.go
index 519dde17f..b5df908e2 100644
--- a/internal/application/repository/wiki_page.go
+++ b/internal/application/repository/wiki_page.go
@@ -1055,6 +1055,103 @@ func (r *wikiPageRepository) FindSimilarPages(
return out, nil
}
+func wikiNormalizedTitleSQL(db *gorm.DB) string {
+ if db != nil && db.Dialector != nil && db.Dialector.Name() == "sqlite" {
+ // SQLite has no POSIX [[:space:]]. Strip the common separators that
+ // model formatting drift actually produces; callers still re-check
+ // with the Go identity fold so extras cannot leak through.
+ return "lower(replace(replace(replace(replace(replace(replace(title, ' ', ''), char(9), ''), char(10), ''), char(13), ''), char(160), ''), char(12288), ''))"
+ }
+ return "regexp_replace(lower(title), '[[:space:]]+', '', 'g')"
+}
+
+const (
+ wikiNormalizedTitleQueryChunk = 100
+ wikiNormalizedTitleRowCap = 500
+)
+
+func wikiNormalizedTitleLookupLimit(n int) int {
+ if n <= 0 {
+ return 0
+ }
+ limit := n * 8
+ if limit < 50 {
+ limit = 50
+ }
+ if limit > wikiNormalizedTitleRowCap {
+ limit = wikiNormalizedTitleRowCap
+ }
+ return limit
+}
+
+func uniqNormalizedTitleIdentities(identities []string) []string {
+ if len(identities) == 0 {
+ return nil
+ }
+ seen := make(map[string]struct{}, len(identities))
+ out := make([]string, 0, len(identities))
+ for _, identity := range identities {
+ identity = strings.TrimSpace(identity)
+ if identity == "" {
+ continue
+ }
+ if _, ok := seen[identity]; ok {
+ continue
+ }
+ seen[identity] = struct{}{}
+ out = append(out, identity)
+ }
+ return out
+}
+
+// FindPagesByNormalizedTitle returns non-archived pages of pageType whose
+// whitespace-stripped, lowercased title equals identity.
+func (r *wikiPageRepository) FindPagesByNormalizedTitle(
+ ctx context.Context,
+ kbID, pageType, identity string,
+) ([]*types.WikiPageLite, error) {
+ return r.FindPagesByNormalizedTitles(ctx, kbID, pageType, []string{identity})
+}
+
+// FindPagesByNormalizedTitles returns non-archived pages of pageType whose
+// whitespace-stripped, lowercased title is in identities.
+func (r *wikiPageRepository) FindPagesByNormalizedTitles(
+ ctx context.Context,
+ kbID, pageType string,
+ identities []string,
+) ([]*types.WikiPageLite, error) {
+ identities = uniqNormalizedTitleIdentities(identities)
+ if kbID == "" || pageType == "" || len(identities) == 0 {
+ return nil, nil
+ }
+
+ normSQL := wikiNormalizedTitleSQL(r.db)
+ out := make([]*types.WikiPageLite, 0, len(identities))
+ for start := 0; start < len(identities); start += wikiNormalizedTitleQueryChunk {
+ end := start + wikiNormalizedTitleQueryChunk
+ if end > len(identities) {
+ end = len(identities)
+ }
+ chunk := identities[start:end]
+ var rows []types.WikiPageLite
+ if err := r.db.WithContext(ctx).
+ Model(&types.WikiPage{}).
+ Select("slug, title, page_type, status, aliases, out_links").
+ Where("knowledge_base_id = ? AND page_type = ? AND status <> ? AND "+normSQL+" IN ?",
+ kbID, pageType, types.WikiPageStatusArchived, chunk).
+ Order("slug ASC").
+ Limit(wikiNormalizedTitleLookupLimit(len(chunk))).
+ Scan(&rows).Error; err != nil {
+ return nil, err
+ }
+ for i := range rows {
+ row := rows[i]
+ out = append(out, &row)
+ }
+ }
+ return out, nil
+}
+
// ListAll retrieves all non-archived wiki pages in a knowledge base.
func (r *wikiPageRepository) ListAll(ctx context.Context, kbID string) ([]*types.WikiPage, error) {
var pages []*types.WikiPage
diff --git a/internal/application/service/wiki_ingest.go b/internal/application/service/wiki_ingest.go
index 40f6e0c19..a35428e6c 100644
--- a/internal/application/service/wiki_ingest.go
+++ b/internal/application/service/wiki_ingest.go
@@ -59,6 +59,36 @@ const (
// page (entity/concept/summary/index) so two concurrent batches for the
// same KB can't lost-update the same slug. Key: wiki:slug:{kbID}:{slug}.
wikiSlugLockPrefix = "wiki:slug:"
+
+ // wikiIdentityClaimPrefix reserves the slug chosen for one normalized
+ // (page type, display title) identity while concurrent map phases are
+ // still running. The existing per-slug lock cannot help when two models
+ // emit different slugs for the same title, because those reducers lock
+ // different keys. A short-lived identity claim makes both batches use
+ // the same slug before summaries and page updates are materialized.
+ wikiIdentityClaimPrefix = "wiki:identity:"
+ wikiIdentityClaimTTL = 2 * time.Hour
+ // wikiIdentityClaimScript atomically GET-or-SET (or overwrite when
+ // ARGV[3] is "1"). A valid existing slug wins and has its TTL refreshed.
+ // Missing or corrupt values are replaced so callers cannot diverge on a
+ // dirty key. KEYS[1]=claim key; ARGV = proposed slug, TTL seconds,
+ // authoritative ("0"/"1"), required slug prefix.
+ wikiIdentityClaimScript = `
+local proposed = ARGV[1]
+local ttl = tonumber(ARGV[2])
+local prefix = ARGV[4]
+if ARGV[3] == '1' then
+ redis.call('SET', KEYS[1], proposed, 'EX', ttl)
+ return proposed
+end
+local existing = redis.call('GET', KEYS[1])
+if type(existing) == 'string' and string.sub(existing, 1, #prefix) == prefix then
+ redis.call('EXPIRE', KEYS[1], ttl)
+ return existing
+end
+redis.call('SET', KEYS[1], proposed, 'EX', ttl)
+return proposed
+`
// wikiSlugLockTTL bounds the per-slug lock so a crashed reducer can't
// wedge a hot page forever. Comfortably longer than a single reduce
// (one LLM modify call).
@@ -1298,6 +1328,18 @@ type WikiBatchContext struct {
// pre-resolved ids and never races on folder creation. Read-only during
// reduce.
PlannedFolderID map[string]string
+
+ // identityClaims is the Lite-mode and Redis-error fallback for identity
+ // reservations. Map workers in one batch run concurrently even though Lite
+ // serializes batches, so they still need to converge before Reduce groups
+ // updates by slug. The map is batch-scoped and disappears with the batch.
+ identityClaims sync.Map
+
+ // identityPages memoizes exact title lookups for this batch so concurrent
+ // map workers probing the same (page type, normalized title) share one DB
+ // round-trip. Values are []*types.WikiPageLite, including empty slices
+ // for confirmed misses.
+ identityPages sync.Map
}
// SlugUpdate represents a single update operation for a specific slug
@@ -2243,10 +2285,6 @@ func xmlEscape(s string) string {
return s
}
-// deduplicateExtractedBatch deduplicates both entities and concepts against
-// existing wiki pages in a single LLM call. Uses pre-loaded allPages to avoid
-// redundant DB queries. This replaces the two separate deduplicateItems calls
-// that each queried ListAllPages + made a separate LLM call.
// deduplicateExtractedBatch deduplicates both entities and concepts against
// existing wiki pages in a single LLM call. Pre-filters candidates via the
// pg_trgm trigram index on lower(title) — every new item issues a
@@ -2262,12 +2300,14 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
chatModel chat.Chat,
kbID string,
entities, concepts []extractedItem,
+ batchCtx *WikiBatchContext,
) ([]extractedItem, []extractedItem) {
if len(entities) == 0 && len(concepts) == 0 {
return entities, concepts
}
if s.wikiService == nil {
- return entities, concepts
+ return s.stabilizeExtractedIdentities(ctx, kbID, types.WikiPageTypeEntity, entities, nil, nil, batchCtx),
+ s.stabilizeExtractedIdentities(ctx, kbID, types.WikiPageTypeConcept, concepts, nil, nil, batchCtx)
}
// Build the candidate set: for each new item, ask the repo for
@@ -2323,11 +2363,31 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
for _, c := range concepts {
probe(c)
}
+ s.attachExactIdentityPages(ctx, kbID, types.WikiPageTypeEntity, entities, candidatePages, itemCandidates, batchCtx)
+ s.attachExactIdentityPages(ctx, kbID, types.WikiPageTypeConcept, concepts, candidatePages, itemCandidates, batchCtx)
+
+ // Resolve exact same-type, same-title candidates deterministically before
+ // asking the model about semantic/alias variants. Besides avoiding an LLM
+ // call for the obvious case, this makes an already-materialized page
+ // authoritative for the identity reservation below.
+ exactTargets := make(map[string]string)
+ mergeTargets := make(map[string]string)
+ collectExactIdentityTargets(entities, types.WikiPageTypeEntity, itemCandidates, candidatePages, exactTargets)
+ collectExactIdentityTargets(concepts, types.WikiPageTypeConcept, itemCandidates, candidatePages, exactTargets)
+
+ stabilize := func() ([]extractedItem, []extractedItem) {
+ return s.stabilizeExtractedIdentities(
+ ctx, kbID, types.WikiPageTypeEntity, entities, mergeTargets, exactTargets, batchCtx,
+ ), s.stabilizeExtractedIdentities(
+ ctx, kbID, types.WikiPageTypeConcept, concepts, mergeTargets, exactTargets, batchCtx,
+ )
+ }
+
if len(candidatePages) == 0 {
- // No similar existing pages — nothing to merge against. The
- // items pass through unchanged.
+ // No similar existing pages — identity reservations still make
+ // concurrent batches converge before they materialize new pages.
logger.Infof(ctx, "wiki ingest: no similar existing pages found for %d new items", len(entities)+len(concepts))
- return entities, concepts
+ return stabilize()
}
logger.Infof(ctx, "wiki ingest: %d similar existing pages selected for %d new items",
len(candidatePages), len(entities)+len(concepts))
@@ -2345,6 +2405,9 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
var candBuf strings.Builder
groups := 0
renderGroup := func(item extractedItem, itemType string) {
+ if exactTargets[item.Slug] != "" {
+ return
+ }
cset := itemCandidates[item.Slug]
if len(cset) == 0 {
return
@@ -2378,9 +2441,8 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
renderGroup(item, "concept")
}
if groups == 0 {
- // Every new item's candidate list is empty after scoping —
- // nothing the model could safely merge.
- return entities, concepts
+ // Every item was resolved exactly or has no safe semantic candidate.
+ return stabilize()
}
dedupeJSON, err := s.generateWithTemplate(ctx, chatModel, agent.WikiDeduplicationPrompt, map[string]string{
@@ -2388,7 +2450,7 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
})
if err != nil {
logger.Warnf(ctx, "wiki ingest: deduplication LLM call failed: %v", err)
- return entities, concepts
+ return stabilize()
}
dedupeJSON = cleanLLMJSON(dedupeJSON)
@@ -2398,11 +2460,7 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
}
if err := json.Unmarshal([]byte(dedupeJSON), &dedupeResult); err != nil {
logger.Warnf(ctx, "wiki ingest: failed to parse dedup JSON: %v\nRaw: %s", err, dedupeJSON)
- return entities, concepts
- }
-
- if len(dedupeResult.Merges) == 0 {
- return entities, concepts
+ return stabilize()
}
validMerge := func(srcSlug, dstSlug string) bool {
@@ -2413,20 +2471,26 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
return true
}
- for i, item := range entities {
+ for _, item := range entities {
+ if exactTargets[item.Slug] != "" {
+ continue
+ }
if existingSlug, ok := dedupeResult.Merges[item.Slug]; ok && validMerge(item.Slug, existingSlug) {
logger.Infof(ctx, "wiki ingest: dedup merge %s → %s", item.Slug, existingSlug)
- entities[i].Slug = existingSlug
+ mergeTargets[item.Slug] = existingSlug
}
}
- for i, item := range concepts {
+ for _, item := range concepts {
+ if exactTargets[item.Slug] != "" {
+ continue
+ }
if existingSlug, ok := dedupeResult.Merges[item.Slug]; ok && validMerge(item.Slug, existingSlug) {
logger.Infof(ctx, "wiki ingest: dedup merge %s → %s", item.Slug, existingSlug)
- concepts[i].Slug = existingSlug
+ mergeTargets[item.Slug] = existingSlug
}
}
- return entities, concepts
+ return stabilize()
}
// generateWithTemplate executes a prompt template and calls the LLM with
diff --git a/internal/application/service/wiki_ingest_batch.go b/internal/application/service/wiki_ingest_batch.go
index 4fb7e7a9d..cd94fee7a 100644
--- a/internal/application/service/wiki_ingest_batch.go
+++ b/internal/application/service/wiki_ingest_batch.go
@@ -562,6 +562,11 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
}
_ = eg.Wait()
+ // Re-read identity claims after every map worker has chosen a slug so
+ // concurrent romanizations of the same title collapse before taxonomy
+ // planning and Reduce lock by slug.
+ slugUpdates = s.remapSlugUpdatesByIdentity(ctx, payload.KnowledgeBaseID, slugUpdates, batchCtx)
+
// Plan the directory once for the whole batch BEFORE reduce. Reduce writes
// pages in parallel, so it can't converge on shared folders on its own; this
// single pass assigns every new entity/concept slug a coherent category_path
@@ -1364,6 +1369,9 @@ func (s *wikiIngestService) mapOneDocument(
// citations simply keep their Description+Details fallback).
var uncited int
extractedEntities, extractedConcepts, uncited = mergeCitationsIntoItems(extractedEntities, extractedConcepts, citations, newSlugs)
+ extractedEntities, extractedConcepts = s.reclaimExtractedIdentities(
+ ctx, payload.KnowledgeBaseID, extractedEntities, extractedConcepts, batchCtx,
+ )
// Rebuild slugItems so stale entries (for slugs that did not survive the
// merge) and brand-new slugs discovered by the citation pass are both
@@ -1644,7 +1652,7 @@ func (s *wikiIngestService) extractEntitiesAndConceptsNoUpsert(
// safe default — the LLM merge call simply doesn't get a candidate
// list and the items pass through unchanged.
result.Entities, result.Concepts = s.deduplicateExtractedBatch(
- ctx, chatModel, kbID, result.Entities, result.Concepts,
+ ctx, chatModel, kbID, result.Entities, result.Concepts, batchCtx,
)
slugItems := make(map[string]extractedItem)
diff --git a/internal/application/service/wiki_ingest_cite.go b/internal/application/service/wiki_ingest_cite.go
index cf2f5fee5..40282494a 100644
--- a/internal/application/service/wiki_ingest_cite.go
+++ b/internal/application/service/wiki_ingest_cite.go
@@ -115,7 +115,7 @@ func (s *wikiIngestService) extractCandidateSlugs(
}
result.Entities, result.Concepts = s.deduplicateExtractedBatch(
- ctx, chatModel, kbID, result.Entities, result.Concepts,
+ ctx, chatModel, kbID, result.Entities, result.Concepts, batchCtx,
)
slugItems := make(map[string]extractedItem, len(result.Entities)+len(result.Concepts))
diff --git a/internal/application/service/wiki_ingest_dedup.go b/internal/application/service/wiki_ingest_dedup.go
index 75cbf903c..899f2570c 100644
--- a/internal/application/service/wiki_ingest_dedup.go
+++ b/internal/application/service/wiki_ingest_dedup.go
@@ -1,10 +1,13 @@
package service
import (
+ "context"
"sort"
"strings"
+ "time"
"unicode"
+ "github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -212,6 +215,436 @@ func dedupMergeRejectReason(srcSlug, dstSlug string, srcCandidates map[string]bo
return ""
}
+// 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".
+func normalizeWikiIdentityTitle(title string) string {
+ return strings.Map(func(r rune) rune {
+ if unicode.IsSpace(r) {
+ return -1
+ }
+ return unicode.ToLower(r)
+ }, strings.TrimSpace(title))
+}
+
+// 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.
+func exactIdentityTarget(
+ item extractedItem,
+ pageType string,
+ candidates map[string]bool,
+ pages map[string]*types.WikiPageLite,
+) string {
+ identity := normalizeWikiIdentityTitle(item.Name)
+ if identity == "" {
+ return ""
+ }
+ matches := make([]string, 0, 2)
+ for slug := range candidates {
+ page := pages[slug]
+ if page == nil || page.PageType != pageType {
+ continue
+ }
+ if normalizeWikiIdentityTitle(page.Title) == identity {
+ matches = append(matches, page.Slug)
+ }
+ }
+ if len(matches) == 0 {
+ return ""
+ }
+ for _, slug := range matches {
+ if slug == item.Slug {
+ return slug
+ }
+ }
+ sort.Strings(matches)
+ return matches[0]
+}
+
+func identityClaimString(v interface{}) string {
+ switch x := v.(type) {
+ case string:
+ return x
+ case []byte:
+ return string(x)
+ default:
+ return ""
+ }
+}
+
+// claimWikiIdentitySlug reserves one slug for a normalized (KB, page type,
+// title) identity before Reduce starts. Standard mode uses Redis so concurrent
+// batches/processes converge; the batch-local map covers Lite mode and a Redis
+// error. Only exact existing-page resolutions are authoritative and may
+// overwrite a provisional claim. Semantic LLM merges must SetNX so they cannot
+// split a title that another worker already reserved.
+func (s *wikiIngestService) claimWikiIdentitySlug(
+ ctx context.Context,
+ kbID, pageType, title, proposedSlug string,
+ authoritative bool,
+ batchCtx *WikiBatchContext,
+) string {
+ identity := normalizeWikiIdentityTitle(title)
+ expectedPrefix := pageType + "/"
+ if identity == "" || proposedSlug == "" || !strings.HasPrefix(proposedSlug, expectedPrefix) {
+ return proposedSlug
+ }
+
+ claim := proposedSlug
+ usedRedis := false
+ claimKey := wikiIdentityClaimPrefix + kbID + ":" + pageType + ":" + identity
+ if s.redisClient != nil {
+ authArg := "0"
+ if authoritative {
+ authArg = "1"
+ }
+ ttlSec := int64(wikiIdentityClaimTTL / time.Second)
+ if ttlSec < 1 {
+ ttlSec = 1
+ }
+ res, err := s.redisClient.Eval(ctx, wikiIdentityClaimScript, []string{claimKey},
+ proposedSlug, ttlSec, authArg, expectedPrefix).Result()
+ if err != nil {
+ logger.Warnf(ctx, "wiki ingest: identity claim failed for %s: %v (using batch-local claim)", proposedSlug, err)
+ } else if existing := identityClaimString(res); strings.HasPrefix(existing, expectedPrefix) {
+ claim = existing
+ usedRedis = true
+ }
+ }
+
+ if batchCtx != nil {
+ localKey := pageType + "\x00" + identity
+ if authoritative || usedRedis {
+ // Redis is the cross-batch source of truth when it answered.
+ // Exact existing-page hits also overwrite a stale local value.
+ batchCtx.identityClaims.Store(localKey, claim)
+ } else {
+ actual, _ := batchCtx.identityClaims.LoadOrStore(localKey, claim)
+ if existing, ok := actual.(string); ok && strings.HasPrefix(existing, expectedPrefix) {
+ claim = existing
+ }
+ }
+ }
+ return claim
+}
+
+// preferWikiIdentityDisplayName keeps the tighter display form when two names
+// fold to the same identity ("孔子" over "孔 子") and returns the discarded
+// form so it can be recorded as an alias.
+func preferWikiIdentityDisplayName(dst, src string) (name, extraAlias string) {
+ if dst == "" {
+ return src, ""
+ }
+ if src == "" || src == dst {
+ return dst, ""
+ }
+ if normalizeWikiIdentityTitle(dst) == normalizeWikiIdentityTitle(src) {
+ if len([]rune(src)) < len([]rune(dst)) {
+ return src, dst
+ }
+ return dst, src
+ }
+ return dst, src
+}
+
+// mergeExtractedIdentity folds duplicate candidates that converged to the same
+// slug. It preserves every alias/chunk reference and keeps the richer fallback
+// text, so convergence never discards evidence before the citation/reduce pass.
+func mergeExtractedIdentity(dst, src extractedItem) extractedItem {
+ name, extraAlias := preferWikiIdentityDisplayName(dst.Name, src.Name)
+ dst.Name = name
+ dst.Aliases = appendUniqueString(dst.Aliases, extraAlias)
+ for _, alias := range src.Aliases {
+ dst.Aliases = appendUniqueString(dst.Aliases, alias)
+ }
+ if len([]rune(src.Description)) > len([]rune(dst.Description)) {
+ dst.Description = src.Description
+ }
+ if len([]rune(src.Details)) > len([]rune(dst.Details)) {
+ dst.Details = src.Details
+ }
+ for _, chunkID := range src.SourceChunks {
+ dst.SourceChunks = appendUniqueString(dst.SourceChunks, chunkID)
+ }
+ return dst
+}
+
+func appendUniqueString(values []string, value string) []string {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ return values
+ }
+ for _, existing := range values {
+ if existing == value {
+ return values
+ }
+ }
+ return append(values, value)
+}
+
+// stabilizeExtractedIdentities applies deterministic existing-page resolutions,
+// cross-batch identity claims, and same-result coalescing. mergeTargets maps
+// an extracted slug to a semantic/LLM merge destination and is not
+// authoritative. exactTargets maps an extracted slug to an existing same-title
+// page and may overwrite a provisional Redis claim.
+func (s *wikiIngestService) stabilizeExtractedIdentities(
+ ctx context.Context,
+ kbID, pageType string,
+ items []extractedItem,
+ mergeTargets, exactTargets map[string]string,
+ batchCtx *WikiBatchContext,
+) []extractedItem {
+ out := make([]extractedItem, 0, len(items))
+ bySlug := make(map[string]int, len(items))
+ claimedByIdentity := make(map[string]string, len(items))
+ for _, item := range items {
+ originalSlug := item.Slug
+ authoritative := false
+ if target := exactTargets[originalSlug]; target != "" {
+ item.Slug = target
+ authoritative = true
+ } else if target := mergeTargets[originalSlug]; target != "" {
+ item.Slug = target
+ }
+ identity := normalizeWikiIdentityTitle(item.Name)
+ if !authoritative {
+ if slug, ok := claimedByIdentity[identity]; ok && slug != "" {
+ item.Slug = slug
+ } else {
+ item.Slug = s.claimWikiIdentitySlug(
+ ctx, kbID, pageType, item.Name, item.Slug, false, batchCtx,
+ )
+ if identity != "" {
+ claimedByIdentity[identity] = item.Slug
+ }
+ }
+ } else {
+ item.Slug = s.claimWikiIdentitySlug(
+ ctx, kbID, pageType, item.Name, item.Slug, true, batchCtx,
+ )
+ if identity != "" {
+ claimedByIdentity[identity] = item.Slug
+ }
+ }
+ if idx, ok := bySlug[item.Slug]; ok {
+ out[idx] = mergeExtractedIdentity(out[idx], item)
+ continue
+ }
+ bySlug[item.Slug] = len(out)
+ out = append(out, item)
+ }
+ return out
+}
+
+func identityPageCacheKey(pageType, identity string) string {
+ return pageType + "\x00" + identity
+}
+
+func loadCachedIdentityPages(batchCtx *WikiBatchContext, pageType, identity string) ([]*types.WikiPageLite, bool) {
+ if batchCtx == nil {
+ return nil, false
+ }
+ v, ok := batchCtx.identityPages.Load(identityPageCacheKey(pageType, identity))
+ if !ok {
+ return nil, false
+ }
+ pages, _ := v.([]*types.WikiPageLite)
+ return pages, true
+}
+
+func storeCachedIdentityPages(batchCtx *WikiBatchContext, pageType, identity string, pages []*types.WikiPageLite) {
+ if batchCtx == nil {
+ return
+ }
+ if pages == nil {
+ pages = []*types.WikiPageLite{}
+ }
+ batchCtx.identityPages.Store(identityPageCacheKey(pageType, identity), pages)
+}
+
+func bindExactIdentityPages(
+ itemSlugs []string,
+ pages []*types.WikiPageLite,
+ pageType, identity string,
+ candidatePages map[string]*types.WikiPageLite,
+ itemCandidates map[string]map[string]bool,
+) {
+ if len(itemSlugs) == 0 || len(pages) == 0 {
+ return
+ }
+ for _, p := range pages {
+ if p == nil || p.Slug == "" || p.PageType != pageType {
+ continue
+ }
+ if normalizeWikiIdentityTitle(p.Title) != identity {
+ continue
+ }
+ if _, ok := candidatePages[p.Slug]; !ok {
+ candidatePages[p.Slug] = p
+ }
+ for _, slug := range itemSlugs {
+ own := itemCandidates[slug]
+ if own == nil {
+ own = make(map[string]bool)
+ itemCandidates[slug] = own
+ }
+ own[p.Slug] = true
+ }
+ }
+}
+
+func (s *wikiIngestService) attachExactIdentityPages(
+ ctx context.Context,
+ kbID, pageType string,
+ items []extractedItem,
+ candidatePages map[string]*types.WikiPageLite,
+ itemCandidates map[string]map[string]bool,
+ batchCtx *WikiBatchContext,
+) {
+ if s.wikiService == nil || len(items) == 0 {
+ return
+ }
+
+ slugsByIdentity := make(map[string][]string, len(items))
+ for _, item := range items {
+ identity := normalizeWikiIdentityTitle(item.Name)
+ if identity == "" || item.Slug == "" {
+ continue
+ }
+ slugsByIdentity[identity] = append(slugsByIdentity[identity], item.Slug)
+ }
+ if len(slugsByIdentity) == 0 {
+ return
+ }
+
+ cached := make(map[string][]*types.WikiPageLite, len(slugsByIdentity))
+ miss := make([]string, 0, len(slugsByIdentity))
+ for identity := range slugsByIdentity {
+ if pages, ok := loadCachedIdentityPages(batchCtx, pageType, identity); ok {
+ cached[identity] = pages
+ continue
+ }
+ miss = append(miss, identity)
+ }
+
+ if len(miss) > 0 {
+ pages, err := s.wikiService.FindPagesByNormalizedTitles(ctx, kbID, pageType, miss)
+ if err != nil {
+ logger.Warnf(ctx, "wiki ingest: exact identity lookup failed for %s (%d titles): %v", pageType, len(miss), err)
+ } else {
+ byIdentity := make(map[string][]*types.WikiPageLite, len(miss))
+ for _, p := range pages {
+ if p == nil {
+ continue
+ }
+ identity := normalizeWikiIdentityTitle(p.Title)
+ if identity == "" {
+ continue
+ }
+ byIdentity[identity] = append(byIdentity[identity], p)
+ }
+ for _, identity := range miss {
+ hits := byIdentity[identity]
+ if hits == nil {
+ hits = []*types.WikiPageLite{}
+ }
+ cached[identity] = hits
+ storeCachedIdentityPages(batchCtx, pageType, identity, hits)
+ }
+ }
+ }
+
+ for identity, slugs := range slugsByIdentity {
+ bindExactIdentityPages(slugs, cached[identity], pageType, identity, candidatePages, itemCandidates)
+ }
+}
+
+func collectExactIdentityTargets(
+ items []extractedItem,
+ pageType string,
+ itemCandidates map[string]map[string]bool,
+ candidatePages map[string]*types.WikiPageLite,
+ exactTargets map[string]string,
+) {
+ for _, item := range items {
+ if target := exactIdentityTarget(item, pageType, itemCandidates[item.Slug], candidatePages); target != "" {
+ exactTargets[item.Slug] = target
+ }
+ }
+}
+
+// reclaimExtractedIdentities re-runs exact title lookup plus identity claims
+// after citation discovery. Citation new_slugs skip the extract-time dedup
+// pass, so without this they can materialize a second same-title page.
+func (s *wikiIngestService) reclaimExtractedIdentities(
+ ctx context.Context,
+ kbID string,
+ entities, concepts []extractedItem,
+ batchCtx *WikiBatchContext,
+) ([]extractedItem, []extractedItem) {
+ if len(entities) == 0 && len(concepts) == 0 {
+ return entities, concepts
+ }
+ candidatePages := make(map[string]*types.WikiPageLite)
+ itemCandidates := make(map[string]map[string]bool)
+ s.attachExactIdentityPages(ctx, kbID, types.WikiPageTypeEntity, entities, candidatePages, itemCandidates, batchCtx)
+ s.attachExactIdentityPages(ctx, kbID, types.WikiPageTypeConcept, concepts, candidatePages, itemCandidates, batchCtx)
+ exactTargets := make(map[string]string)
+ collectExactIdentityTargets(entities, types.WikiPageTypeEntity, itemCandidates, candidatePages, exactTargets)
+ collectExactIdentityTargets(concepts, types.WikiPageTypeConcept, itemCandidates, candidatePages, exactTargets)
+ return s.stabilizeExtractedIdentities(ctx, kbID, types.WikiPageTypeEntity, entities, nil, exactTargets, batchCtx),
+ s.stabilizeExtractedIdentities(ctx, kbID, types.WikiPageTypeConcept, concepts, nil, exactTargets, batchCtx)
+}
+
+// remapSlugUpdatesByIdentity re-reads identity claims after every map worker
+// has finished so in-flight slug choices converge before Reduce groups and
+// locks by slug. Summary/retract updates keep their original slugs.
+func (s *wikiIngestService) remapSlugUpdatesByIdentity(
+ ctx context.Context,
+ kbID string,
+ slugUpdates map[string][]SlugUpdate,
+ batchCtx *WikiBatchContext,
+) map[string][]SlugUpdate {
+ if len(slugUpdates) == 0 {
+ return slugUpdates
+ }
+ out := make(map[string][]SlugUpdate, len(slugUpdates))
+ claimedByIdentity := make(map[string]string, len(slugUpdates))
+ for _, updates := range slugUpdates {
+ for _, u := range updates {
+ if u.Type == types.WikiPageTypeEntity || u.Type == types.WikiPageTypeConcept {
+ title := u.Item.Name
+ if title == "" {
+ title = u.Slug
+ }
+ identity := normalizeWikiIdentityTitle(title)
+ var claimed string
+ if identity != "" {
+ claimed = claimedByIdentity[u.Type+"\x00"+identity]
+ }
+ if claimed == "" {
+ claimed = s.claimWikiIdentitySlug(ctx, kbID, u.Type, title, u.Slug, false, batchCtx)
+ if identity != "" && claimed != "" {
+ claimedByIdentity[u.Type+"\x00"+identity] = claimed
+ }
+ }
+ if claimed != "" {
+ u.Slug = claimed
+ u.Item.Slug = claimed
+ }
+ }
+ out[u.Slug] = append(out[u.Slug], u)
+ }
+ }
+ return out
+}
+
// dedupPairScore is the max similarity between any surface form of a and
// b (plus the slug-token similarity). Slug and name signals live in
// different symbol spaces (ASCII pinyin vs raw surface form) so we take
diff --git a/internal/application/service/wiki_ingest_dedup_test.go b/internal/application/service/wiki_ingest_dedup_test.go
index 6261044d4..fdbe4c54e 100644
--- a/internal/application/service/wiki_ingest_dedup_test.go
+++ b/internal/application/service/wiki_ingest_dedup_test.go
@@ -1,10 +1,16 @@
package service
import (
+ "context"
"strings"
+ "sync"
"testing"
+ "github.com/alicebob/miniredis/v2"
+ "github.com/redis/go-redis/v9"
+
"github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
)
func TestDedupMergeRejectReason(t *testing.T) {
@@ -244,3 +250,391 @@ func TestDedupPairScore_UnrelatedCJKPair(t *testing.T) {
dedupCandidateScoreFloor, s)
}
}
+
+func TestNormalizeWikiIdentityTitlePreservesSemanticPunctuation(t *testing.T) {
+ if got := normalizeWikiIdentityTitle(" Acme Corp "); got != "acmecorp" {
+ t.Fatalf("normalizeWikiIdentityTitle whitespace/case = %q, want acmecorp", got)
+ }
+ if normalizeWikiIdentityTitle("寓言") == normalizeWikiIdentityTitle("《寓言》") {
+ t.Fatal("concept title and work/chapter title must keep distinct identities")
+ }
+}
+
+func TestExactIdentityTargetSameTypeOnly(t *testing.T) {
+ item := extractedItem{Name: "孔子", Slug: "entity/kong-zi"}
+ pages := map[string]*types.WikiPageLite{
+ "entity/confucius": {
+ Slug: "entity/confucius",
+ Title: "孔 子",
+ PageType: types.WikiPageTypeEntity,
+ },
+ "concept/confucius": {
+ Slug: "concept/confucius",
+ Title: "孔子",
+ PageType: types.WikiPageTypeConcept,
+ },
+ }
+ candidates := map[string]bool{
+ "entity/confucius": true,
+ "concept/confucius": true,
+ }
+ if got := exactIdentityTarget(item, types.WikiPageTypeEntity, candidates, pages); got != "entity/confucius" {
+ t.Fatalf("exactIdentityTarget = %q, want entity/confucius", got)
+ }
+}
+
+func TestWikiIdentityClaimConvergesDifferentSlugs(t *testing.T) {
+ mr, err := miniredis.Run()
+ if err != nil {
+ t.Fatalf("start miniredis: %v", err)
+ }
+ defer mr.Close()
+
+ rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
+ defer rdb.Close()
+ svc := &wikiIngestService{redisClient: rdb}
+ ctx := context.Background()
+
+ proposals := []string{
+ "entity/kong-zi",
+ "entity/confucius",
+ "entity/kongzi",
+ "entity/kong-qiu",
+ }
+ results := make([]string, len(proposals))
+ var wg sync.WaitGroup
+ for i, proposal := range proposals {
+ i, proposal := i, proposal
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ results[i] = svc.claimWikiIdentitySlug(
+ ctx, "kb-1", types.WikiPageTypeEntity, "孔 子", proposal, false, &WikiBatchContext{},
+ )
+ }()
+ }
+ wg.Wait()
+ for i := 1; i < len(results); i++ {
+ if results[i] != results[0] {
+ t.Fatalf("concurrent identity claims did not converge: %#v", results)
+ }
+ }
+
+ // A verified existing page is authoritative and replaces a provisional
+ // reservation left by an earlier map worker.
+ authoritative := svc.claimWikiIdentitySlug(
+ ctx, "kb-1", types.WikiPageTypeEntity, "孔子", "entity/confucius", true, &WikiBatchContext{},
+ )
+ third := svc.claimWikiIdentitySlug(
+ ctx, "kb-1", types.WikiPageTypeEntity, "孔子", "entity/kongzi", false, &WikiBatchContext{},
+ )
+ if authoritative != "entity/confucius" || third != authoritative {
+ t.Fatalf("authoritative identity did not replace claim: authoritative=%q third=%q", authoritative, third)
+ }
+}
+
+func TestWikiIdentityClaimKeepsDistinctTypesAndPunctuation(t *testing.T) {
+ batch := &WikiBatchContext{}
+ svc := &wikiIngestService{}
+ ctx := context.Background()
+
+ concept := svc.claimWikiIdentitySlug(
+ ctx, "kb-1", types.WikiPageTypeConcept, "寓言", "concept/fable-zhuangzi", false, batch,
+ )
+ chapter := svc.claimWikiIdentitySlug(
+ ctx, "kb-1", types.WikiPageTypeConcept, "《寓言》", "concept/yuyan-chapter", false, batch,
+ )
+ entity := svc.claimWikiIdentitySlug(
+ ctx, "kb-1", types.WikiPageTypeEntity, "寓言", "entity/yuyan-zhuangzi", false, batch,
+ )
+ if concept != "concept/fable-zhuangzi" || chapter != "concept/yuyan-chapter" || entity != "entity/yuyan-zhuangzi" {
+ t.Fatalf("distinct identities were collapsed: concept=%q chapter=%q entity=%q", concept, chapter, entity)
+ }
+}
+
+func TestStabilizeExtractedIdentitiesCoalescesEvidence(t *testing.T) {
+ svc := &wikiIngestService{}
+ batch := &WikiBatchContext{}
+ items := []extractedItem{
+ {
+ Name: "孔 子", Slug: "entity/kong-zi", Aliases: []string{"孔丘"},
+ Description: "思想家", Details: "短", SourceChunks: []string{"chunk-1"},
+ },
+ {
+ Name: "孔子", Slug: "entity/confucius", Aliases: []string{"Confucius"},
+ Description: "中国古代思想家、教育家", Details: "更完整的说明", SourceChunks: []string{"chunk-2"},
+ },
+ }
+ got := svc.stabilizeExtractedIdentities(
+ context.Background(), "kb-1", types.WikiPageTypeEntity, items, nil, nil, batch,
+ )
+ if len(got) != 1 {
+ t.Fatalf("stabilized item count = %d, want 1", len(got))
+ }
+ if got[0].Slug != "entity/kong-zi" {
+ t.Fatalf("stabilized slug = %q, want first claimed slug", got[0].Slug)
+ }
+ if got[0].Name != "孔子" {
+ t.Fatalf("compact display name not preferred: %#v", got[0])
+ }
+ if got[0].Description != "中国古代思想家、教育家" || got[0].Details != "更完整的说明" {
+ t.Fatalf("richer fallback text not preserved: %#v", got[0])
+ }
+ if len(got[0].SourceChunks) != 2 {
+ t.Fatalf("source chunks were not unioned: %#v", got[0].SourceChunks)
+ }
+}
+
+func TestWikiIdentityClaimRedisOverridesStaleLocal(t *testing.T) {
+ mr, err := miniredis.Run()
+ if err != nil {
+ t.Fatalf("start miniredis: %v", err)
+ }
+ defer mr.Close()
+
+ rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
+ defer rdb.Close()
+ svc := &wikiIngestService{redisClient: rdb}
+ ctx := context.Background()
+ batch := &WikiBatchContext{}
+ identity := normalizeWikiIdentityTitle("孔子")
+ batch.identityClaims.Store(types.WikiPageTypeEntity+"\x00"+identity, "entity/kong-zi")
+ if err := rdb.Set(ctx, wikiIdentityClaimPrefix+"kb-1:"+types.WikiPageTypeEntity+":"+identity, "entity/confucius", wikiIdentityClaimTTL).Err(); err != nil {
+ t.Fatalf("seed redis claim: %v", err)
+ }
+
+ got := svc.claimWikiIdentitySlug(ctx, "kb-1", types.WikiPageTypeEntity, "孔子", "entity/kongqiu", false, batch)
+ if got != "entity/confucius" {
+ t.Fatalf("redis claim should beat stale local map: got %q", got)
+ }
+ if stored, _ := batch.identityClaims.Load(types.WikiPageTypeEntity + "\x00" + identity); stored != "entity/confucius" {
+ t.Fatalf("local cache not refreshed from redis: %#v", stored)
+ }
+}
+
+func TestStabilizeLLMMergeDoesNotOverrideRedisClaim(t *testing.T) {
+ mr, err := miniredis.Run()
+ if err != nil {
+ t.Fatalf("start miniredis: %v", err)
+ }
+ defer mr.Close()
+
+ rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
+ defer rdb.Close()
+ svc := &wikiIngestService{redisClient: rdb}
+ ctx := context.Background()
+ batch := &WikiBatchContext{}
+
+ first := svc.claimWikiIdentitySlug(ctx, "kb-1", types.WikiPageTypeEntity, "孔子", "entity/kong-zi", false, batch)
+ if first != "entity/kong-zi" {
+ t.Fatalf("provisional claim = %q, want entity/kong-zi", first)
+ }
+
+ got := svc.stabilizeExtractedIdentities(ctx, "kb-1", types.WikiPageTypeEntity, []extractedItem{
+ {Name: "孔子", Slug: "entity/confucius"},
+ }, map[string]string{"entity/confucius": "entity/kong-zi-institute"}, nil, batch)
+ if len(got) != 1 || got[0].Slug != "entity/kong-zi" {
+ t.Fatalf("LLM merge overwrote identity claim: %#v", got)
+ }
+}
+
+func TestStabilizeExactTargetIsAuthoritative(t *testing.T) {
+ mr, err := miniredis.Run()
+ if err != nil {
+ t.Fatalf("start miniredis: %v", err)
+ }
+ defer mr.Close()
+
+ rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
+ defer rdb.Close()
+ svc := &wikiIngestService{redisClient: rdb}
+ ctx := context.Background()
+ batch := &WikiBatchContext{}
+
+ svc.claimWikiIdentitySlug(ctx, "kb-1", types.WikiPageTypeEntity, "孔子", "entity/kong-zi", false, batch)
+ got := svc.stabilizeExtractedIdentities(ctx, "kb-1", types.WikiPageTypeEntity, []extractedItem{
+ {Name: "孔子", Slug: "entity/kong-zi"},
+ }, nil, map[string]string{"entity/kong-zi": "entity/confucius"}, batch)
+ if len(got) != 1 || got[0].Slug != "entity/confucius" {
+ t.Fatalf("exact existing page should replace provisional claim: %#v", got)
+ }
+
+ follow := svc.claimWikiIdentitySlug(ctx, "kb-1", types.WikiPageTypeEntity, "孔子", "entity/kongqiu", false, &WikiBatchContext{})
+ if follow != "entity/confucius" {
+ t.Fatalf("authoritative exact hit did not stick in redis: %q", follow)
+ }
+}
+
+func TestWikiIdentityClaimLiteConcurrentSameBatch(t *testing.T) {
+ svc := &wikiIngestService{}
+ batch := &WikiBatchContext{}
+ ctx := context.Background()
+ proposals := []string{"entity/kong-zi", "entity/confucius", "entity/kongzi"}
+ results := make([]string, len(proposals))
+ var wg sync.WaitGroup
+ for i, proposal := range proposals {
+ i, proposal := i, proposal
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ results[i] = svc.claimWikiIdentitySlug(ctx, "kb-1", types.WikiPageTypeEntity, "孔子", proposal, false, batch)
+ }()
+ }
+ wg.Wait()
+ for i := 1; i < len(results); i++ {
+ if results[i] != results[0] {
+ t.Fatalf("lite same-batch claims did not converge: %#v", results)
+ }
+ }
+}
+
+func TestRemapSlugUpdatesByIdentityConverges(t *testing.T) {
+ svc := &wikiIngestService{}
+ batch := &WikiBatchContext{}
+ ctx := context.Background()
+ svc.claimWikiIdentitySlug(ctx, "kb-1", types.WikiPageTypeEntity, "孔子", "entity/kong-zi", false, batch)
+
+ got := svc.remapSlugUpdatesByIdentity(ctx, "kb-1", map[string][]SlugUpdate{
+ "entity/kong-zi": {{
+ Slug: "entity/kong-zi", Type: types.WikiPageTypeEntity,
+ Item: extractedItem{Name: "孔子", Slug: "entity/kong-zi"},
+ }},
+ "entity/confucius": {{
+ Slug: "entity/confucius", Type: types.WikiPageTypeEntity,
+ Item: extractedItem{Name: "孔 子", Slug: "entity/confucius"},
+ }},
+ "summary/doc": {{Slug: "summary/doc", Type: types.WikiPageTypeSummary}},
+ }, batch)
+ if len(got["entity/kong-zi"]) != 2 {
+ t.Fatalf("entity updates should coalesce onto claimed slug: %#v", got)
+ }
+ for _, u := range got["entity/kong-zi"] {
+ if u.Item.Slug != "entity/kong-zi" {
+ t.Fatalf("remap left Item.Slug stale: %#v", u)
+ }
+ }
+ if len(got["summary/doc"]) != 1 {
+ t.Fatalf("summary slug should stay untouched: %#v", got)
+ }
+ if _, ok := got["entity/confucius"]; ok {
+ t.Fatalf("unclaimed romanization should have been remapped away: %#v", got)
+ }
+}
+
+func TestReclaimExtractedIdentitiesCoalescesCitationSlugs(t *testing.T) {
+ svc := &wikiIngestService{}
+ batch := &WikiBatchContext{}
+ svc.claimWikiIdentitySlug(context.Background(), "kb-1", types.WikiPageTypeEntity, "孔子", "entity/kong-zi", false, batch)
+
+ entities, concepts := svc.reclaimExtractedIdentities(context.Background(), "kb-1", []extractedItem{
+ {Name: "孔子", Slug: "entity/kong-zi", SourceChunks: []string{"c1"}},
+ {Name: "孔 子", Slug: "entity/confucius", SourceChunks: []string{"c2"}},
+ }, nil, batch)
+ if len(entities) != 1 || entities[0].Slug != "entity/kong-zi" {
+ t.Fatalf("citation slugs did not reclaim onto identity: entities=%#v", entities)
+ }
+ if len(entities[0].SourceChunks) != 2 {
+ t.Fatalf("reclaim dropped citation evidence: %#v", entities[0])
+ }
+ if len(concepts) != 0 {
+ t.Fatalf("unexpected concepts: %#v", concepts)
+ }
+}
+
+func TestWikiIdentityClaimReplacesInvalidRedisValue(t *testing.T) {
+ mr, err := miniredis.Run()
+ if err != nil {
+ t.Fatalf("start miniredis: %v", err)
+ }
+ defer mr.Close()
+
+ rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
+ defer rdb.Close()
+ svc := &wikiIngestService{redisClient: rdb}
+ ctx := context.Background()
+ identity := normalizeWikiIdentityTitle("孔子")
+ if err := rdb.Set(ctx, wikiIdentityClaimPrefix+"kb-1:"+types.WikiPageTypeEntity+":"+identity, "garbage", wikiIdentityClaimTTL).Err(); err != nil {
+ t.Fatalf("seed invalid redis claim: %v", err)
+ }
+
+ first := svc.claimWikiIdentitySlug(ctx, "kb-1", types.WikiPageTypeEntity, "孔子", "entity/kong-zi", false, &WikiBatchContext{})
+ if first != "entity/kong-zi" {
+ t.Fatalf("invalid redis value should be replaced: got %q", first)
+ }
+ second := svc.claimWikiIdentitySlug(ctx, "kb-1", types.WikiPageTypeEntity, "孔子", "entity/confucius", false, &WikiBatchContext{})
+ if second != "entity/kong-zi" {
+ t.Fatalf("callers did not converge after replacing invalid value: %q", second)
+ }
+}
+
+type stubNormalizedTitleWiki struct {
+ interfaces.WikiPageService
+ mu sync.Mutex
+ calls int
+ last []string
+ pages []*types.WikiPageLite
+}
+
+func (s *stubNormalizedTitleWiki) FindPagesByNormalizedTitles(
+ _ context.Context, _, _ string, identities []string,
+) ([]*types.WikiPageLite, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.calls++
+ s.last = 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)] {
+ out = append(out, p)
+ }
+ }
+ return out, nil
+}
+
+func TestAttachExactIdentityPagesBatchesAndCaches(t *testing.T) {
+ stub := &stubNormalizedTitleWiki{
+ pages: []*types.WikiPageLite{
+ {Slug: "entity/confucius", Title: "孔 子", PageType: types.WikiPageTypeEntity},
+ },
+ }
+ svc := &wikiIngestService{wikiService: stub}
+ batch := &WikiBatchContext{}
+ ctx := context.Background()
+ items := []extractedItem{
+ {Name: "孔子", Slug: "entity/kong-zi"},
+ {Name: "孔 子", Slug: "entity/kongqiu"},
+ {Name: "孟子", Slug: "entity/mencius"},
+ }
+
+ 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)
+ }
+ if !itemCandidates["entity/kong-zi"]["entity/confucius"] || !itemCandidates["entity/kongqiu"]["entity/confucius"] {
+ t.Fatalf("exact page not bound to both romanizations: %#v", itemCandidates)
+ }
+ if itemCandidates["entity/mencius"]["entity/confucius"] {
+ t.Fatalf("confucius page leaked onto 孟子: %#v", itemCandidates)
+ }
+
+ 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)
+ }
+
+ 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 len(stub.last) != 1 || stub.last[0] != normalizeWikiIdentityTitle("荀子") {
+ t.Fatalf("second lookup should only ask for 荀子: %v", stub.last)
+ }
+}
diff --git a/internal/application/service/wiki_page.go b/internal/application/service/wiki_page.go
index 3ed3f108d..8dfc502ac 100644
--- a/internal/application/service/wiki_page.go
+++ b/internal/application/service/wiki_page.go
@@ -993,6 +993,18 @@ func (s *wikiPageService) FindSimilarPages(ctx context.Context, kbID string, que
return s.repo.FindSimilarPages(ctx, kbID, query, pageTypes, limit)
}
+// FindPagesByNormalizedTitle looks up exact same-type title identities for
+// wiki ingest, independent of the trigram top-K used for semantic dedup.
+func (s *wikiPageService) FindPagesByNormalizedTitle(ctx context.Context, kbID, pageType, identity string) ([]*types.WikiPageLite, error) {
+ return s.repo.FindPagesByNormalizedTitle(ctx, kbID, pageType, identity)
+}
+
+// FindPagesByNormalizedTitles looks up several normalized title identities
+// in one query so wiki ingest does not seq-scan once per extracted item.
+func (s *wikiPageService) FindPagesByNormalizedTitles(ctx context.Context, kbID, pageType string, identities []string) ([]*types.WikiPageLite, error) {
+ return s.repo.FindPagesByNormalizedTitles(ctx, kbID, pageType, identities)
+}
+
// ListDistinctCategoryPaths returns the existing wiki folder paths. Used by
// wiki ingest's taxonomy planner to ground folder reuse.
func (s *wikiPageService) ListDistinctCategoryPaths(ctx context.Context, kbID string, maxPaths int) ([][]string, error) {
diff --git a/internal/application/service/wiki_page_test.go b/internal/application/service/wiki_page_test.go
index 9d1c6cdee..af353c017 100644
--- a/internal/application/service/wiki_page_test.go
+++ b/internal/application/service/wiki_page_test.go
@@ -605,3 +605,44 @@ func TestComputeGraphSubset_EgoRejectsMissingCenter(t *testing.T) {
t.Fatalf("expected error for missing center slug")
}
}
+
+func TestFindPagesByNormalizedTitleMatchesWhitespace(t *testing.T) {
+ db, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}, &types.WikiPageRevision{}))
+
+ ctx := context.Background()
+ repo := repository.NewWikiPageRepository(db)
+ svc := NewWikiPageService(repo, nil, nil, nil, nil)
+ now := time.Now()
+ require.NoError(t, repo.Create(ctx, &types.WikiPage{
+ ID: "page-kong", TenantID: 1, KnowledgeBaseID: "kb-id", Slug: "entity/confucius",
+ Title: "孔 子", PageType: types.WikiPageTypeEntity, Status: types.WikiPageStatusPublished,
+ Version: 1, CreatedAt: now, UpdatedAt: now,
+ }))
+ require.NoError(t, repo.Create(ctx, &types.WikiPage{
+ ID: "page-fable", TenantID: 1, KnowledgeBaseID: "kb-id", Slug: "concept/yuyan",
+ Title: "《寓言》", PageType: types.WikiPageTypeConcept, Status: types.WikiPageStatusPublished,
+ Version: 1, CreatedAt: now, UpdatedAt: now,
+ }))
+
+ pages, err := svc.FindPagesByNormalizedTitle(ctx, "kb-id", types.WikiPageTypeEntity, "孔子")
+ require.NoError(t, err)
+ require.Len(t, pages, 1)
+ require.Equal(t, "entity/confucius", pages[0].Slug)
+
+ none, err := svc.FindPagesByNormalizedTitle(ctx, "kb-id", types.WikiPageTypeConcept, "寓言")
+ require.NoError(t, err)
+ require.Empty(t, none, "punctuation-significant titles must stay distinct")
+
+ require.NoError(t, repo.Create(ctx, &types.WikiPage{
+ ID: "page-mencius", TenantID: 1, KnowledgeBaseID: "kb-id", Slug: "entity/mencius",
+ Title: "孟子", PageType: types.WikiPageTypeEntity, Status: types.WikiPageStatusPublished,
+ Version: 1, CreatedAt: now, UpdatedAt: now,
+ }))
+ batched, err := svc.FindPagesByNormalizedTitles(ctx, "kb-id", types.WikiPageTypeEntity, []string{"孔子", "孟子", "孔子"})
+ require.NoError(t, err)
+ require.Len(t, batched, 2)
+ slugs := []string{batched[0].Slug, batched[1].Slug}
+ require.ElementsMatch(t, []string{"entity/confucius", "entity/mencius"}, slugs)
+}
diff --git a/internal/types/interfaces/wiki_page.go b/internal/types/interfaces/wiki_page.go
index 985062d73..13517c1f3 100644
--- a/internal/types/interfaces/wiki_page.go
+++ b/internal/types/interfaces/wiki_page.go
@@ -153,6 +153,17 @@ type WikiPageService interface {
// merge targets server-side.
FindSimilarPages(ctx context.Context, kbID string, query string, pageTypes []string, limit int) ([]*types.WikiPageLite, error)
+ // FindPagesByNormalizedTitle returns non-archived pages of pageType whose
+ // display title matches identity after the same whitespace/case fold used
+ // by wiki ingest identity claims. Used so exact same-title pages are found
+ // even when they miss the trigram top-K.
+ FindPagesByNormalizedTitle(ctx context.Context, kbID, pageType, identity string) ([]*types.WikiPageLite, error)
+
+ // FindPagesByNormalizedTitles is the batched form of
+ // FindPagesByNormalizedTitle. identities are already whitespace-stripped
+ // and lowercased; empty entries are ignored.
+ FindPagesByNormalizedTitles(ctx context.Context, kbID, pageType string, identities []string) ([]*types.WikiPageLite, error)
+
// ListDistinctCategoryPaths returns the existing wiki folder paths (split
// into segments), capped at maxPaths. Used by wiki ingest's taxonomy
// planner as the pool of folders to reuse.
@@ -318,6 +329,14 @@ type WikiPageRepository interface {
// surface candidate merge targets server-side.
FindSimilarPages(ctx context.Context, kbID string, query string, pageTypes []string, limit int) ([]*types.WikiPageLite, error)
+ // FindPagesByNormalizedTitle returns non-archived pages of pageType whose
+ // whitespace-stripped, lowercased title equals identity.
+ FindPagesByNormalizedTitle(ctx context.Context, kbID, pageType, identity string) ([]*types.WikiPageLite, error)
+
+ // FindPagesByNormalizedTitles is the batched form of
+ // FindPagesByNormalizedTitle.
+ FindPagesByNormalizedTitles(ctx context.Context, kbID, pageType string, identities []string) ([]*types.WikiPageLite, error)
+
// ListDistinctCategoryPaths returns the materialized paths of existing
// wiki folders (split into segments), capped at maxPaths. Used by the
// wiki ingest taxonomy planner as the pool of folders to reuse.