perf(wiki-ingest): scale to 4w-doc KBs + generic task queue / dead-letter
The wiki ingest post-process pipeline OOM'd and ran for hours on KBs
with ~40k documents. The dominant tail was a per-batch ListAllPages
that pulled every page (multi-MB content blobs) into Go memory, plus a
24h-TTL Redis pending list whose data could be evicted before a long
serialized backlog drained. dedup did O(P × N) Jaccard scoring in Go
on every batch. Lint loaded the full graph. The index page kept the
entire wiki directory in its content column and rewrote the TOAST
chunk on every ingest. None of these survive at 4w docs.
This change reworks the write path end to end and pulls the durable-
queue + dead-letter primitives out of wiki and into shared
infrastructure that every asynq task type now benefits from.
- migration 000041: task_pending_ops + task_dead_letters tables, plus
three GIN indexes on wiki_pages (source_refs jsonb_path_ops,
source_refs text fallback, lower(title) trgm).
- TaskPendingOpsRepository + TaskDeadLetterRepository in
internal/application/repository/task_queue.go: cursor-paginated
list, atomic IncrFailCount via UPDATE…RETURNING, dedup-key scoped
delete that refuses empty keys so a buggy caller can't wipe a KB's
queue.
- internal/middleware/asynqdl: writes a task_dead_letters row when an
asynq task exhausts its retry budget. Payload-agnostic — a small
probe struct extracts TenantID + scope hints across every existing
payload type, so summary:generation / image:multimodal /
faq_import / kb:clone / etc. all dead-letter without per-handler
code. Best-effort: an insert failure never masks the underlying
task error. Installed in router/task.go before the langfuse mw so
it sees raw errors.
- Pending queue moved Redis → PG (no TTL, restart-durable). Redis
keeps just the active-batch lock and the delete tombstone.
- In-batch retry budget (wikiMaxFailRetries=5) tracked via
pendingRepo.IncrFailCount; over the cap the row is moved to
task_dead_letters with task_type=wiki:ingest, related_id=knowledge
id. Asynq retries (10) are handled by the new middleware.
- Removed the per-batch ListAllPages. WikiBatchContext now carries
lazy fetcher closures (SlugTitleMany, SummaryByKnowledgeID) with
mutex-protected caches; reduce reaches for titles / summaries on
demand instead of pre-loading the whole KB.
- getExistingPageSlugsForKnowledge now uses ListSlugsBySourceRef,
which the new GIN index on source_refs serves as a Bitmap Index
Scan instead of a sequential text LIKE.
- Dedup pre-filter uses pg_trgm via FindSimilarPages
(idx_wiki_pages_title_trgm). For each new entity/concept (and each
of its aliases) we ask the DB for the top-K trigram-similar
existing pages and union the results — bounded prompt size, no Go-
side O(P × M) loop. Small KBs (≤25 entities) bypass the pre-filter.
- cleanDeadLinks / injectCrossLinks are scoped to the batch's
affected slugs (a few dozen) instead of every page in the KB. Both
use the new lite ListBySlugs / ExistsSlugs repo methods so they
pull only slug + title + outlinks, not full content.
- Slug fuzzy resolve (slug_fuzzy.go): when the LLM emits
[[bad-slug|display]] the cleanup path now tries display-text
reverse lookup → hyphen/case normalized equality → char-bigram
Jaccard ≥ 0.8 before stripping. Recovers the common pinyin-word-
break drift case ("shang-hai-tower" vs "shanghai-tower") in place
instead of replacing the link with plain text.
- rebuildIndexPage uses ListByTypeRecent(200) for the first-time
intro and drops the full DocumentSummaries blob from the
incremental update prompt, so its context stays bounded regardless
of KB size.
- Concurrency tunables surfaced in WikiConfig: IngestBatchSize /
IngestMapParallel / IngestReduceParallel, with sensible defaults
via OrDefault helpers. scheduleFollowUp drops to ProcessIn(0) so
follow-ups don't waste asynq retry slots bouncing on the active
lock.
- RunLint walks pages via the new ListPagesCursor in 200-page
windows and computes the live-slug set with a one-column
ListAllSlugs Pluck instead of a Limit:0 GetGraph that materialized
every node + edge. Memory is now bounded; 40k pages walks in
constant ~4MB.
- 14 GORM tests for both repos against an in-memory SQLite mirror of
the production DDL (task_queue_test.go).
- 6 tests for the dead-letter middleware covering retry budget
detection, payload-agnostic scope inference, error truncation, and
repo-failure isolation.
- 7 tests for the slug fuzzy resolve helper covering the three
resolution stages, display-text priority over normalized equality,
bigram fallback acceptance, and rejection of unrelated slugs.
- Existing wiki_ingest / wiki_lint / wiki_page tests updated to the
new fetcher / cursor APIs.
This commit is contained in:
@@ -36,24 +36,25 @@ var (
|
||||
// knowledgeService implements the knowledge service interface
|
||||
// service 实现知识服务接口
|
||||
type knowledgeService struct {
|
||||
config *config.Config
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
repo interfaces.KnowledgeRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
tenantRepo interfaces.TenantRepository
|
||||
tenantService interfaces.TenantService
|
||||
documentReader interfaces.DocumentReader
|
||||
chunkService interfaces.ChunkService
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
tagService interfaces.KnowledgeTagService
|
||||
fileSvc interfaces.FileService
|
||||
modelService interfaces.ModelService
|
||||
task interfaces.TaskEnqueuer
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
redisClient *redis.Client
|
||||
kbShareService interfaces.KBShareService
|
||||
imageResolver *docparser.ImageResolver
|
||||
config *config.Config
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
repo interfaces.KnowledgeRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
tenantRepo interfaces.TenantRepository
|
||||
tenantService interfaces.TenantService
|
||||
documentReader interfaces.DocumentReader
|
||||
chunkService interfaces.ChunkService
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
tagService interfaces.KnowledgeTagService
|
||||
fileSvc interfaces.FileService
|
||||
modelService interfaces.ModelService
|
||||
task interfaces.TaskEnqueuer
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
redisClient *redis.Client
|
||||
kbShareService interfaces.KBShareService
|
||||
imageResolver *docparser.ImageResolver
|
||||
taskPendingRepo interfaces.TaskPendingOpsRepository
|
||||
|
||||
// In-memory fallbacks for Lite mode (no Redis)
|
||||
memFAQProgress sync.Map // taskID -> *types.FAQImportProgress
|
||||
@@ -90,28 +91,30 @@ func NewKnowledgeService(
|
||||
imageResolver *docparser.ImageResolver,
|
||||
wikiRepo interfaces.WikiPageRepository,
|
||||
wikiService interfaces.WikiPageService,
|
||||
taskPendingRepo interfaces.TaskPendingOpsRepository,
|
||||
) (interfaces.KnowledgeService, error) {
|
||||
return &knowledgeService{
|
||||
config: config,
|
||||
repo: repo,
|
||||
kbService: kbService,
|
||||
tenantRepo: tenantRepo,
|
||||
tenantService: tenantService,
|
||||
documentReader: documentReader,
|
||||
chunkService: chunkService,
|
||||
chunkRepo: chunkRepo,
|
||||
tagRepo: tagRepo,
|
||||
tagService: tagService,
|
||||
fileSvc: fileSvc,
|
||||
modelService: modelService,
|
||||
task: task,
|
||||
graphEngine: graphEngine,
|
||||
retrieveEngine: retrieveEngine,
|
||||
redisClient: redisClient,
|
||||
kbShareService: kbShareService,
|
||||
imageResolver: imageResolver,
|
||||
wikiRepo: wikiRepo,
|
||||
wikiService: wikiService,
|
||||
config: config,
|
||||
repo: repo,
|
||||
kbService: kbService,
|
||||
tenantRepo: tenantRepo,
|
||||
tenantService: tenantService,
|
||||
documentReader: documentReader,
|
||||
chunkService: chunkService,
|
||||
chunkRepo: chunkRepo,
|
||||
tagRepo: tagRepo,
|
||||
tagService: tagService,
|
||||
fileSvc: fileSvc,
|
||||
modelService: modelService,
|
||||
task: task,
|
||||
graphEngine: graphEngine,
|
||||
retrieveEngine: retrieveEngine,
|
||||
redisClient: redisClient,
|
||||
kbShareService: kbShareService,
|
||||
imageResolver: imageResolver,
|
||||
wikiRepo: wikiRepo,
|
||||
wikiService: wikiService,
|
||||
taskPendingRepo: taskPendingRepo,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -282,7 +282,7 @@ func (s *knowledgeService) cleanupWikiOnKnowledgeDelete(ctx context.Context, kno
|
||||
// so the knowledge's disappearance is reflected in the UI.
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||
EnqueueWikiRetract(ctx, s.task, s.redisClient, WikiRetractPayload{
|
||||
EnqueueWikiRetract(ctx, s.task, s.taskPendingRepo, WikiRetractPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
KnowledgeID: knowledgeID,
|
||||
@@ -309,59 +309,25 @@ func (s *knowledgeService) markKnowledgeDeletedForWiki(ctx context.Context, kbID
|
||||
}
|
||||
|
||||
// scrubWikiPendingIngest removes queued WikiOpIngest entries for a knowledge
|
||||
// from the debounced pending list. Used by both the delete path (we're about
|
||||
// to soft-delete the doc, no point ingesting it) and the reparse path (the
|
||||
// from task_pending_ops. Used by both the delete path (we're about to
|
||||
// soft-delete the doc, no point ingesting it) and the reparse path (the
|
||||
// old chunks are about to vanish, so any pending ingest would either race
|
||||
// with the cleanup or no-op on an empty chunk set — and the post-process
|
||||
// task will enqueue a fresh ingest once new chunks land anyway).
|
||||
//
|
||||
// Retract entries stay put — delete still needs them to unlink referencing
|
||||
// pages, and reparse never enqueues retracts for the doc being reparsed.
|
||||
//
|
||||
// We use LREM against JSON-encoded entries plus a best-effort raw-UUID
|
||||
// fallback for backward compatibility with the legacy format documented in
|
||||
// peekPendingList.
|
||||
// We pass op=WikiOpIngest so DeleteByDedupKey filters to the ingest rows
|
||||
// only.
|
||||
func (s *knowledgeService) scrubWikiPendingIngest(ctx context.Context, kbID, knowledgeID, reason string) {
|
||||
if s.redisClient == nil || kbID == "" || knowledgeID == "" {
|
||||
if s.taskPendingRepo == nil || kbID == "" || knowledgeID == "" {
|
||||
return
|
||||
}
|
||||
pendingKey := wikiPendingKeyPrefix + kbID
|
||||
|
||||
// Best-effort: inspect the list, remove matching ingest entries one by one.
|
||||
// The list is bounded (wikiMaxDocsPerBatch at a time on the consumer
|
||||
// side, practical uploads rarely exceed a few dozen), so a single LRange
|
||||
// is safe.
|
||||
items, err := s.redisClient.LRange(ctx, pendingKey, 0, -1).Result()
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "wiki %s: failed to read pending list %s: %v", reason, pendingKey, err)
|
||||
if err := s.taskPendingRepo.DeleteByDedupKey(ctx, wikiTaskType, wikiTaskScope, kbID, knowledgeID, WikiOpIngest); err != nil {
|
||||
logger.Warnf(ctx, "wiki %s: failed to scrub pending ingest ops for knowledge %s: %v", reason, knowledgeID, err)
|
||||
return
|
||||
}
|
||||
removed := 0
|
||||
for _, item := range items {
|
||||
// Legacy raw-UUID form
|
||||
if item == knowledgeID {
|
||||
if n, err := s.redisClient.LRem(ctx, pendingKey, 0, item).Result(); err == nil {
|
||||
removed += int(n)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(item, "{") {
|
||||
continue
|
||||
}
|
||||
var op WikiPendingOp
|
||||
if err := json.Unmarshal([]byte(item), &op); err != nil {
|
||||
continue
|
||||
}
|
||||
if op.KnowledgeID != knowledgeID || op.Op != WikiOpIngest {
|
||||
continue
|
||||
}
|
||||
if n, err := s.redisClient.LRem(ctx, pendingKey, 0, item).Result(); err == nil {
|
||||
removed += int(n)
|
||||
}
|
||||
}
|
||||
if removed > 0 {
|
||||
logger.Infof(ctx, "wiki %s: scrubbed %d pending ingest ops for knowledge %s", reason, removed, knowledgeID)
|
||||
}
|
||||
logger.Infof(ctx, "wiki %s: scrubbed pending ingest ops for knowledge %s", reason, knowledgeID)
|
||||
}
|
||||
|
||||
// prepareWikiForReparse is the reparse counterpart to
|
||||
|
||||
@@ -17,11 +17,12 @@ import (
|
||||
// KnowledgePostProcessService acts as an orchestrator for all post-processing tasks
|
||||
// after a document has been parsed and split into chunks (including multimodal OCR/Caption).
|
||||
type KnowledgePostProcessService struct {
|
||||
knowledgeRepo interfaces.KnowledgeRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
chunkService interfaces.ChunkService
|
||||
taskEnqueuer interfaces.TaskEnqueuer
|
||||
redisClient *redis.Client
|
||||
knowledgeRepo interfaces.KnowledgeRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
chunkService interfaces.ChunkService
|
||||
taskEnqueuer interfaces.TaskEnqueuer
|
||||
pendingRepo interfaces.TaskPendingOpsRepository
|
||||
redisClient *redis.Client
|
||||
}
|
||||
|
||||
func NewKnowledgePostProcessService(
|
||||
@@ -29,6 +30,7 @@ func NewKnowledgePostProcessService(
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
chunkService interfaces.ChunkService,
|
||||
taskEnqueuer interfaces.TaskEnqueuer,
|
||||
pendingRepo interfaces.TaskPendingOpsRepository,
|
||||
redisClient *redis.Client,
|
||||
) interfaces.TaskHandler {
|
||||
return &KnowledgePostProcessService{
|
||||
@@ -36,6 +38,7 @@ func NewKnowledgePostProcessService(
|
||||
kbService: kbService,
|
||||
chunkService: chunkService,
|
||||
taskEnqueuer: taskEnqueuer,
|
||||
pendingRepo: pendingRepo,
|
||||
redisClient: redisClient,
|
||||
}
|
||||
}
|
||||
@@ -126,7 +129,7 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
||||
|
||||
// 6. Spawn Wiki Ingest Task if wiki indexing is enabled in IndexingStrategy
|
||||
if kb.IndexingStrategy.WikiEnabled && len(textChunks) > 0 {
|
||||
EnqueueWikiIngest(ctx, s.taskEnqueuer, s.redisClient, payload.TenantID, payload.KnowledgeBaseID, payload.KnowledgeID)
|
||||
EnqueueWikiIngest(ctx, s.taskEnqueuer, s.pendingRepo, payload.TenantID, payload.KnowledgeBaseID, payload.KnowledgeID)
|
||||
logger.Infof(ctx, "[KnowledgePostProcess] Enqueued wiki ingest task for %s", payload.KnowledgeID)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/searchutil"
|
||||
)
|
||||
|
||||
// Fuzzy slug resolution: rescue LLM-generated `[[slug|display]]` links
|
||||
// where the slug is *almost* right but not exactly the one in the KB.
|
||||
//
|
||||
// Background: the wiki ingest LLM is given an `<available_wiki_pages>`
|
||||
// block listing exact `[[slug]] = title` entries. Empirically — even
|
||||
// when the prompt explicitly says "copy-paste the slug verbatim" —
|
||||
// open-source models such as deepseek-v3 routinely munge slugs in
|
||||
// predictable ways:
|
||||
//
|
||||
// - inserting hyphens that happen to look like pinyin word breaks
|
||||
// ("shanghaitower" → "shang-hai-tower"),
|
||||
// - dropping or duplicating hyphens,
|
||||
// - normalizing the case of an ASCII slug,
|
||||
// - latinizing names that should have stayed CJK.
|
||||
//
|
||||
// The display text is almost always still correct (the model just
|
||||
// copy-pastes the title), so we have two levers to find the *real*
|
||||
// slug: a tolerant string compare on the slug itself, and a reverse
|
||||
// lookup from display text. Combined, these recover the vast majority
|
||||
// of broken links without any LLM cost — the alternative being
|
||||
// stripDeadWikiLinks, which gives up and emits plain text.
|
||||
//
|
||||
// Cleanup callers (stripDeadWikiLinks, cleanDeadLinks) consult
|
||||
// resolveDeadSlug FIRST and only fall back to "strip to plain text"
|
||||
// when no live candidate is close enough to be safe.
|
||||
|
||||
// slugResolveBigramThreshold is the minimum char-bigram Jaccard
|
||||
// similarity required for the bigram fallback to accept a candidate.
|
||||
// 0.8 is intentionally conservative: at this level "shang-hai-tower"
|
||||
// and "shanghai-tower" still match (most bigrams overlap), but
|
||||
// "user-profile" and "user-permissions" do NOT (different stems even
|
||||
// though the prefix matches). Anything weaker risks linking to the
|
||||
// wrong page, which is worse than emitting plain text.
|
||||
const slugResolveBigramThreshold = 0.8
|
||||
|
||||
// normalizeSlugForCompare collapses cosmetic slug variations so two
|
||||
// slugs that differ only in hyphenation or case compare equal.
|
||||
//
|
||||
// Specifically:
|
||||
// - lowercases ASCII letters (slugify already does this, so most
|
||||
// real slugs are already lowercase, but the LLM occasionally
|
||||
// produces capitalized forms),
|
||||
// - removes every hyphen and underscore.
|
||||
//
|
||||
// Hyphens in wiki slugs are purely visual separators — slugify uses
|
||||
// them between word fragments. Removing them lets us treat
|
||||
// "shang-hai-tower" and "shanghai-tower" as the same logical token bag.
|
||||
//
|
||||
// CJK runes are preserved verbatim: they ARE the meaningful identity
|
||||
// of CJK slugs, so collapsing them would over-merge.
|
||||
func normalizeSlugForCompare(slug string) string {
|
||||
slug = strings.ToLower(slug)
|
||||
slug = strings.ReplaceAll(slug, "-", "")
|
||||
slug = strings.ReplaceAll(slug, "_", "")
|
||||
return slug
|
||||
}
|
||||
|
||||
// resolveDeadSlug attempts to map a dead `[[slug]]` reference back to
|
||||
// a live KB slug, using progressively more permissive heuristics:
|
||||
//
|
||||
// 1. Display-text reverse lookup. If the LLM emitted "[[bad-slug|上海
|
||||
// 中心大厦]]" and there's a live page whose Title or alias is
|
||||
// "上海中心大厦", return its slug. This is the most common case
|
||||
// by far (the model copies the title correctly even when it
|
||||
// mangles the slug).
|
||||
//
|
||||
// 2. Hyphen/case-normalized slug equality. Two slugs that compare
|
||||
// equal under normalizeSlugForCompare are treated as the same
|
||||
// logical page. Catches the LLM's "insert pinyin breaks" pattern.
|
||||
//
|
||||
// 3. Bigram Jaccard similarity ≥ slugResolveBigramThreshold (0.8).
|
||||
// Catches typos and minor character substitutions that the
|
||||
// normalize step doesn't fix. Computed via searchutil.Jaccard
|
||||
// against character bigrams of each candidate slug.
|
||||
//
|
||||
// Returns the resolved live slug and true on success; "" and false
|
||||
// when no candidate is close enough to be safe.
|
||||
//
|
||||
// The candidate pool is supplied by the caller as `liveSlugs`. The
|
||||
// caller is also responsible for passing a `titleToSlug` map keyed
|
||||
// by exact (case-sensitive) page title and alias surface forms. Both
|
||||
// maps are consulted only — never mutated.
|
||||
func resolveDeadSlug(
|
||||
deadSlug string,
|
||||
displayText string,
|
||||
liveSlugs map[string]struct{},
|
||||
titleToSlug map[string]string,
|
||||
) (string, bool) {
|
||||
if deadSlug == "" {
|
||||
return "", false
|
||||
}
|
||||
// Already live? No-op success.
|
||||
if _, ok := liveSlugs[deadSlug]; ok {
|
||||
return deadSlug, true
|
||||
}
|
||||
|
||||
// (1) Display-text reverse lookup. Trim whitespace because LLM
|
||||
// occasionally emits `[[slug| display ]]` with stray spaces, and
|
||||
// the user-side title would have been written without them.
|
||||
if dt := strings.TrimSpace(displayText); dt != "" {
|
||||
if slug, ok := titleToSlug[dt]; ok && slug != "" {
|
||||
if _, live := liveSlugs[slug]; live {
|
||||
return slug, true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// (2) Normalized-equality check. Compute the dead slug's normal
|
||||
// form once and compare against every live candidate's normal
|
||||
// form. O(N) but N is bounded — this only fires on the dead-link
|
||||
// path, and `liveSlugs` is the per-batch affected set, not the
|
||||
// full KB.
|
||||
deadNorm := normalizeSlugForCompare(deadSlug)
|
||||
if deadNorm == "" {
|
||||
// Slug was nothing but hyphens / underscores after normalize
|
||||
// — nothing meaningful to compare against.
|
||||
return "", false
|
||||
}
|
||||
for cand := range liveSlugs {
|
||||
if normalizeSlugForCompare(cand) == deadNorm {
|
||||
return cand, true
|
||||
}
|
||||
}
|
||||
|
||||
// (3) Bigram Jaccard fallback. Use searchutil.Jaccard against
|
||||
// the character bigrams of each slug. We restrict the bigram
|
||||
// alphabet to the slug's normalized form (lowercase, no hyphens)
|
||||
// so a hyphenation difference doesn't dominate the bigram set
|
||||
// the way it would for raw slug strings.
|
||||
deadGrams := slugCharBigrams(deadNorm)
|
||||
if len(deadGrams) == 0 {
|
||||
return "", false
|
||||
}
|
||||
var (
|
||||
bestSlug string
|
||||
bestScore float64
|
||||
)
|
||||
for cand := range liveSlugs {
|
||||
candNorm := normalizeSlugForCompare(cand)
|
||||
if candNorm == "" {
|
||||
continue
|
||||
}
|
||||
candGrams := slugCharBigrams(candNorm)
|
||||
if len(candGrams) == 0 {
|
||||
continue
|
||||
}
|
||||
score := searchutil.Jaccard(deadGrams, candGrams)
|
||||
if score > bestScore {
|
||||
bestScore = score
|
||||
bestSlug = cand
|
||||
}
|
||||
}
|
||||
if bestScore >= slugResolveBigramThreshold {
|
||||
return bestSlug, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// slugCharBigrams returns a character-bigram set for the given (already
|
||||
// normalized) slug. Single-rune slugs degrade to a 1-gram so they still
|
||||
// contribute a comparable signal.
|
||||
//
|
||||
// Mirrors surfaceGrams in wiki_ingest_dedup.go but operates on a slug
|
||||
// (which is already lowercased / hyphen-stripped) rather than a raw
|
||||
// surface form, so we don't redo the lowercasing or punctuation
|
||||
// stripping work.
|
||||
func slugCharBigrams(s string) map[string]struct{} {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
runes := []rune(s)
|
||||
if len(runes) == 1 {
|
||||
return map[string]struct{}{string(runes): {}}
|
||||
}
|
||||
out := make(map[string]struct{}, len(runes))
|
||||
for i := 0; i < len(runes)-1; i++ {
|
||||
out[string(runes[i:i+2])] = struct{}{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package service
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizeSlugForCompare(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"shang-hai-tower": "shanghaitower",
|
||||
"shanghai-tower": "shanghaitower",
|
||||
"SHANG-HAI-TOWER": "shanghaitower",
|
||||
"under_score_slug": "underscoreslug",
|
||||
"entity/shanghai-tower": "entity/shanghaitower",
|
||||
"": "",
|
||||
"---": "",
|
||||
"中文-slug": "中文slug",
|
||||
}
|
||||
for input, want := range cases {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
if got := normalizeSlugForCompare(input); got != want {
|
||||
t.Errorf("normalizeSlugForCompare(%q) = %q, want %q", input, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDeadSlug_HyphenVariation(t *testing.T) {
|
||||
// The exact bug pattern reported in production: the LLM inserted a
|
||||
// pinyin word break in a CJK-derived slug ("shang-hai" instead of
|
||||
// "shanghai") even though the display text was copied verbatim from
|
||||
// the canonical title. Resolver should heal the hyphenation drift
|
||||
// using the display-text reverse lookup.
|
||||
live := map[string]struct{}{
|
||||
"entity/shanghai-tower": {},
|
||||
}
|
||||
titleToSlug := map[string]string{
|
||||
"上海中心大厦": "entity/shanghai-tower",
|
||||
}
|
||||
got, ok := resolveDeadSlug(
|
||||
"entity/shang-hai-tower",
|
||||
"上海中心大厦",
|
||||
live, titleToSlug,
|
||||
)
|
||||
if !ok {
|
||||
t.Fatal("expected resolution success on pinyin-break drift case")
|
||||
}
|
||||
if got != "entity/shanghai-tower" {
|
||||
t.Errorf("expected canonical slug, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDeadSlug_ExactMatchPasses(t *testing.T) {
|
||||
live := map[string]struct{}{
|
||||
"entity/foo": {},
|
||||
}
|
||||
got, ok := resolveDeadSlug("entity/foo", "", live, nil)
|
||||
if !ok || got != "entity/foo" {
|
||||
t.Errorf("expected pass-through for live slug, got (%q, %v)", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDeadSlug_DisplayTextLookupPriority(t *testing.T) {
|
||||
// Even when normalized-equality would also find a candidate,
|
||||
// display-text lookup should win because it's the highest-
|
||||
// confidence signal.
|
||||
live := map[string]struct{}{
|
||||
"entity/exact-match": {},
|
||||
"entity/exactmatch": {},
|
||||
}
|
||||
titleToSlug := map[string]string{
|
||||
"Exact Match": "entity/exactmatch",
|
||||
}
|
||||
got, ok := resolveDeadSlug(
|
||||
"entity/exact-match-typo",
|
||||
"Exact Match",
|
||||
live, titleToSlug,
|
||||
)
|
||||
if !ok {
|
||||
t.Fatal("expected resolution")
|
||||
}
|
||||
if got != "entity/exactmatch" {
|
||||
t.Errorf("display-text lookup should have won; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDeadSlug_DisplayTextStillRequiresLive(t *testing.T) {
|
||||
// titleToSlug points at a slug that's NOT in liveSlugs; we
|
||||
// shouldn't return it.
|
||||
live := map[string]struct{}{
|
||||
"entity/something-else": {},
|
||||
}
|
||||
titleToSlug := map[string]string{
|
||||
"Title": "entity/dead-target",
|
||||
}
|
||||
if _, ok := resolveDeadSlug("entity/x", "Title", live, titleToSlug); ok {
|
||||
t.Fatal("must not return a slug that isn't in liveSlugs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDeadSlug_BigramFallback(t *testing.T) {
|
||||
// Slug differs from canonical by a single character (typo).
|
||||
// Normalized-equality won't catch this; bigram Jaccard should.
|
||||
live := map[string]struct{}{
|
||||
"entity/zhongguo-yinhang": {},
|
||||
}
|
||||
got, ok := resolveDeadSlug(
|
||||
"entity/zhongguo-yinghang", // h↔gh transposition typo
|
||||
"",
|
||||
live, nil,
|
||||
)
|
||||
if !ok {
|
||||
t.Fatal("expected bigram fallback to recover the typo")
|
||||
}
|
||||
if got != "entity/zhongguo-yinhang" {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDeadSlug_RejectsUnrelated(t *testing.T) {
|
||||
// Completely unrelated candidates must not match — better to
|
||||
// strip the link than to silently link to the wrong page.
|
||||
live := map[string]struct{}{
|
||||
"entity/foo": {},
|
||||
"entity/bar": {},
|
||||
"entity/baz": {},
|
||||
}
|
||||
if got, ok := resolveDeadSlug("entity/quuxasdf", "", live, nil); ok {
|
||||
t.Errorf("expected no match for unrelated slug; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDeadSlug_EmptyInputs(t *testing.T) {
|
||||
if _, ok := resolveDeadSlug("", "any", nil, nil); ok {
|
||||
t.Error("empty deadSlug must return false")
|
||||
}
|
||||
if _, ok := resolveDeadSlug("entity/foo", "", nil, nil); ok {
|
||||
t.Error("empty liveSlugs / titleToSlug must return false")
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,12 +18,18 @@ import (
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
// scheduleFollowUp enqueues another asynq trigger task if there are
|
||||
// still pending ops in task_pending_ops for this KB. Returns true when
|
||||
// a follow-up was scheduled.
|
||||
//
|
||||
// We use a short ProcessIn (5s) so the active-batch lock has time to
|
||||
// release before the next worker tries to acquire it; otherwise we'd
|
||||
// just bounce on ErrWikiIngestConcurrent and burn an asynq retry slot.
|
||||
func (s *wikiIngestService) scheduleFollowUp(ctx context.Context, payload WikiIngestPayload) bool {
|
||||
if s.redisClient == nil {
|
||||
if s.pendingRepo == nil {
|
||||
return false
|
||||
}
|
||||
pendingKey := wikiPendingKeyPrefix + payload.KnowledgeBaseID
|
||||
count, err := s.redisClient.LLen(ctx, pendingKey).Result()
|
||||
count, err := s.pendingRepo.PendingCount(ctx, wikiTaskType, wikiTaskScope, payload.KnowledgeBaseID)
|
||||
if err != nil || count == 0 {
|
||||
return false
|
||||
}
|
||||
@@ -65,11 +71,17 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
followUpScheduled := false
|
||||
totalPagesAffected := 0
|
||||
docPreview := make([]string, 0, 6)
|
||||
// Tunables resolved from KB.WikiConfig once we've loaded the KB.
|
||||
// Captured up here so the deferred stats log can observe them
|
||||
// regardless of which exit path we took.
|
||||
loggedBatchSize := 0
|
||||
loggedMapPar := 0
|
||||
loggedReducePar := 0
|
||||
|
||||
defer func() {
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"wiki ingest stats: kb=%s tenant=%d retry=%d/%d status=%s elapsed=%s mode=%s lock_acquired=%v pending_ops=%d ops(ingest=%d,retract=%d) ingest(success=%d,failed=%d) retract_handled=%d pages(total=%d) index(rebuild_attempted=%v,rebuild_succeeded=%v) followup=%v preview=%s",
|
||||
"wiki ingest stats: kb=%s tenant=%d retry=%d/%d status=%s elapsed=%s mode=%s lock_acquired=%v pending_ops=%d ops(ingest=%d,retract=%d) ingest(success=%d,failed=%d) retract_handled=%d pages(total=%d) index(rebuild_attempted=%v,rebuild_succeeded=%v) followup=%v tunables(batch=%d,map_par=%d,reduce_par=%d) preview=%s",
|
||||
payload.KnowledgeBaseID,
|
||||
payload.TenantID,
|
||||
retryCount,
|
||||
@@ -88,6 +100,9 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
indexRebuildAttempted,
|
||||
indexRebuildSucceeded,
|
||||
followUpScheduled,
|
||||
loggedBatchSize,
|
||||
loggedMapPar,
|
||||
loggedReducePar,
|
||||
previewStringSlice(docPreview, 6),
|
||||
)
|
||||
}()
|
||||
@@ -117,21 +132,21 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
logger.Warnf(ctx, "wiki ingest: redis SetNX failed: %v", err)
|
||||
} else if !acquired {
|
||||
exitStatus = "active_lock_conflict"
|
||||
// If the pending list is already empty, the active batch will process
|
||||
// everything — no need to retry. Returning nil avoids burning through the
|
||||
// retry budget on tasks that would be no-ops when they eventually acquire
|
||||
// the lock. If there are still pending ops, retry so we don't miss them
|
||||
// in case the active batch drained the list before we RPush'd.
|
||||
pendingKey := wikiPendingKeyPrefix + payload.KnowledgeBaseID
|
||||
n, nErr := s.redisClient.LLen(ctx, pendingKey).Result()
|
||||
// If task_pending_ops is already empty for this KB, the active
|
||||
// batch will drain whatever was queued. Returning nil avoids
|
||||
// burning through the retry budget on tasks that would be
|
||||
// no-ops when they eventually acquire the lock. If rows still
|
||||
// remain, retry so we don't miss them in case the active
|
||||
// batch drained its peek before our op landed.
|
||||
n, nErr := s.pendingRepo.PendingCount(ctx, wikiTaskType, wikiTaskScope, payload.KnowledgeBaseID)
|
||||
if nErr != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: failed to read pending length during lock conflict for KB %s: %v", payload.KnowledgeBaseID, nErr)
|
||||
logger.Warnf(ctx, "wiki ingest: failed to read pending count during lock conflict for KB %s: %v", payload.KnowledgeBaseID, nErr)
|
||||
logger.Infof(ctx, "wiki ingest: another batch active for KB %s, deferring to asynq retry", payload.KnowledgeBaseID)
|
||||
return ErrWikiIngestConcurrent
|
||||
}
|
||||
if n == 0 {
|
||||
exitStatus = "active_lock_conflict_empty"
|
||||
logger.Infof(ctx, "wiki ingest: concurrent batch active for KB %s, pending list empty — skipping", payload.KnowledgeBaseID)
|
||||
logger.Infof(ctx, "wiki ingest: concurrent batch active for KB %s, pending queue empty — skipping", payload.KnowledgeBaseID)
|
||||
return nil
|
||||
}
|
||||
logger.Infof(ctx, "wiki ingest: another batch active for KB %s, deferring to asynq retry", payload.KnowledgeBaseID)
|
||||
@@ -196,31 +211,34 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
return fmt.Errorf("wiki ingest: get chat model: %w", err)
|
||||
}
|
||||
|
||||
// Resolve per-KB tunables once. WikiConfig.IngestBatchSize /
|
||||
// IngestMapParallel / IngestReduceParallel let operators on
|
||||
// 4w-document KBs raise the throughput knob (more docs per batch +
|
||||
// more concurrent LLM calls) without a code deploy. Zero falls back
|
||||
// to the historical defaults so existing KBs see no behaviour
|
||||
// change until they opt in.
|
||||
batchSize := kb.WikiConfig.IngestBatchSizeOrDefault(wikiMaxDocsPerBatch)
|
||||
mapParallel := kb.WikiConfig.IngestMapParallelOrDefault(10)
|
||||
reduceParallel := kb.WikiConfig.IngestReduceParallelOrDefault(10)
|
||||
loggedBatchSize = batchSize
|
||||
loggedMapPar = mapParallel
|
||||
loggedReducePar = reduceParallel
|
||||
loggedBatchSize = batchSize
|
||||
loggedMapPar = mapParallel
|
||||
loggedReducePar = reduceParallel
|
||||
|
||||
lang := types.LanguageNameFromContext(ctx)
|
||||
|
||||
pendingOps, peekedCount := s.peekPendingList(ctx, payload.KnowledgeBaseID)
|
||||
pendingOps, peekedIDs := s.peekPendingList(ctx, payload.KnowledgeBaseID, batchSize)
|
||||
pendingOpsCount = len(pendingOps)
|
||||
if len(pendingOps) == 0 {
|
||||
if s.redisClient != nil {
|
||||
exitStatus = "no_pending_ops"
|
||||
logger.Infof(ctx, "wiki ingest: no pending operations for KB %s", payload.KnowledgeBaseID)
|
||||
return nil
|
||||
}
|
||||
if len(payload.LiteOps) > 0 {
|
||||
pendingOps = payload.LiteOps
|
||||
peekedCount = len(pendingOps)
|
||||
pendingOpsCount = len(pendingOps)
|
||||
} else {
|
||||
exitStatus = "no_lite_ops"
|
||||
return nil
|
||||
}
|
||||
exitStatus = "no_pending_ops"
|
||||
logger.Infof(ctx, "wiki ingest: no pending operations for KB %s", payload.KnowledgeBaseID)
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "wiki ingest: batch processing %d ops for KB %s", len(pendingOps), payload.KnowledgeBaseID)
|
||||
|
||||
// Fetch all existing pages once, shared across Map and Reduce phases
|
||||
allPages, _ := s.wikiService.ListAllPages(ctx, payload.KnowledgeBaseID)
|
||||
|
||||
// Resolve extraction granularity once per batch. Historical rows with
|
||||
// empty/unknown values fall back to Standard via Normalize(). Failures
|
||||
// to load the KB (unlikely since we're already acting on it) also
|
||||
@@ -230,25 +248,115 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
granularity = kb.WikiConfig.ExtractionGranularity.Normalize()
|
||||
}
|
||||
|
||||
batchCtx := &WikiBatchContext{
|
||||
AllPages: allPages,
|
||||
SlugTitleMap: make(map[string]string),
|
||||
SummaryContentByKnowledgeID: make(map[string]string),
|
||||
ExtractionGranularity: granularity,
|
||||
}
|
||||
for _, p := range allPages {
|
||||
if p.PageType != types.WikiPageTypeIndex && p.PageType != types.WikiPageTypeLog && p.Status != types.WikiPageStatusArchived {
|
||||
batchCtx.SlugTitleMap[p.Slug] = p.Title
|
||||
// Build the per-batch lazy fetchers. These replace the legacy
|
||||
// pre-batch ListAllPages dump: instead of pulling ~100MB of rows
|
||||
// up front (and walking them several more times during the batch),
|
||||
// callers pay only for the slugs / knowledge ids they actually
|
||||
// reach for. Cache hits keep repeat lookups within the batch free.
|
||||
var (
|
||||
fetchMu sync.Mutex
|
||||
slugTitleCache = make(map[string]string) // slug -> title; "" = known-missing
|
||||
summaryKIDCache = make(map[string]string) // kid -> content; "" = known-missing
|
||||
)
|
||||
|
||||
resolveSlugs := func(ctx context.Context, slugs []string) map[string]string {
|
||||
// Filter to the slugs we don't already have cached.
|
||||
fetchMu.Lock()
|
||||
need := slugs[:0:0]
|
||||
for _, slug := range slugs {
|
||||
if _, ok := slugTitleCache[slug]; ok {
|
||||
continue
|
||||
}
|
||||
need = append(need, slug)
|
||||
}
|
||||
if p.PageType == types.WikiPageTypeSummary && p.Content != "" {
|
||||
for _, ref := range p.SourceRefs {
|
||||
kid := ref
|
||||
if pipeIdx := strings.Index(ref, "|"); pipeIdx > 0 {
|
||||
kid = ref[:pipeIdx]
|
||||
fetchMu.Unlock()
|
||||
|
||||
if len(need) > 0 {
|
||||
pages, err := s.wikiService.ListBySlugs(ctx, payload.KnowledgeBaseID, need)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: ListBySlugs(%d slugs) failed: %v", len(need), err)
|
||||
}
|
||||
fetchMu.Lock()
|
||||
for _, slug := range need {
|
||||
if p, ok := pages[slug]; ok && p != nil {
|
||||
if p.Status == types.WikiPageStatusArchived ||
|
||||
p.PageType == types.WikiPageTypeIndex ||
|
||||
p.PageType == types.WikiPageTypeLog {
|
||||
// Treat archived / system pages as missing from the
|
||||
// title-resolution map: cleanDeadLinks shouldn't link
|
||||
// to them, and the log-feed slug-title fallback
|
||||
// should degrade to slug-only display.
|
||||
slugTitleCache[slug] = ""
|
||||
continue
|
||||
}
|
||||
slugTitleCache[slug] = p.Title
|
||||
} else {
|
||||
slugTitleCache[slug] = ""
|
||||
}
|
||||
batchCtx.SummaryContentByKnowledgeID[kid] = p.Content
|
||||
}
|
||||
fetchMu.Unlock()
|
||||
}
|
||||
|
||||
out := make(map[string]string, len(slugs))
|
||||
fetchMu.Lock()
|
||||
for _, slug := range slugs {
|
||||
if title := slugTitleCache[slug]; title != "" {
|
||||
out[slug] = title
|
||||
}
|
||||
}
|
||||
fetchMu.Unlock()
|
||||
return out
|
||||
}
|
||||
|
||||
resolveSummaries := func(ctx context.Context, kids []string) map[string]string {
|
||||
fetchMu.Lock()
|
||||
need := kids[:0:0]
|
||||
for _, kid := range kids {
|
||||
if _, ok := summaryKIDCache[kid]; ok {
|
||||
continue
|
||||
}
|
||||
need = append(need, kid)
|
||||
}
|
||||
fetchMu.Unlock()
|
||||
|
||||
if len(need) > 0 {
|
||||
contents, err := s.wikiService.ListSummariesByKnowledgeIDs(ctx, payload.KnowledgeBaseID, need)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: ListSummariesByKnowledgeIDs(%d kids) failed: %v", len(need), err)
|
||||
}
|
||||
fetchMu.Lock()
|
||||
for _, kid := range need {
|
||||
if c, ok := contents[kid]; ok && c != "" {
|
||||
summaryKIDCache[kid] = c
|
||||
} else {
|
||||
summaryKIDCache[kid] = ""
|
||||
}
|
||||
}
|
||||
fetchMu.Unlock()
|
||||
}
|
||||
|
||||
out := make(map[string]string, len(kids))
|
||||
fetchMu.Lock()
|
||||
for _, kid := range kids {
|
||||
if content := summaryKIDCache[kid]; content != "" {
|
||||
out[kid] = content
|
||||
}
|
||||
}
|
||||
fetchMu.Unlock()
|
||||
return out
|
||||
}
|
||||
|
||||
batchCtx := &WikiBatchContext{
|
||||
SlugTitle: func(ctx context.Context, slug string) string {
|
||||
m := resolveSlugs(ctx, []string{slug})
|
||||
return m[slug]
|
||||
},
|
||||
SlugTitleMany: resolveSlugs,
|
||||
SummaryContentByKnowledgeID: func(ctx context.Context, kid string) string {
|
||||
m := resolveSummaries(ctx, []string{kid})
|
||||
return m[kid]
|
||||
},
|
||||
ExtractionGranularity: granularity,
|
||||
}
|
||||
|
||||
// 1. MAP PHASE (Parallel extraction and generation of updates)
|
||||
@@ -259,7 +367,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
var retractChangeDesc strings.Builder
|
||||
|
||||
eg, mapCtx := errgroup.WithContext(ctx)
|
||||
eg.SetLimit(10) // Map phase limit
|
||||
eg.SetLimit(mapParallel) // Map phase limit (configurable via WikiConfig)
|
||||
|
||||
for _, op := range pendingOps {
|
||||
op := op
|
||||
@@ -352,12 +460,12 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
}
|
||||
mapMu.Unlock()
|
||||
|
||||
// Reset the per-document failure counter on success so transient
|
||||
// errors don't permanently exhaust the retry budget.
|
||||
if s.redisClient != nil {
|
||||
failKey := wikiFailCountKeyPrefix + payload.KnowledgeBaseID + ":" + op.KnowledgeID
|
||||
s.redisClient.Del(mapCtx, failKey)
|
||||
}
|
||||
// No fail-count reset needed: a successful op is added
|
||||
// to peekedIDs and gets DELETEd from task_pending_ops at
|
||||
// trim time, so there is no stale fail_count column to
|
||||
// scrub. Compare with the legacy Redis path, which kept
|
||||
// a separate wiki:failcount:<...> key alive for 24h
|
||||
// regardless of whether the original op had drained.
|
||||
}
|
||||
return nil
|
||||
})
|
||||
@@ -366,7 +474,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
|
||||
// 2. REDUCE PHASE (Parallel upserting grouped by Slug)
|
||||
egReduce, reduceCtx := errgroup.WithContext(ctx)
|
||||
egReduce.SetLimit(10) // Reduce phase limit (LLM + DB concurrent connections)
|
||||
egReduce.SetLimit(reduceParallel) // Reduce phase limit (LLM + DB concurrent connections, configurable)
|
||||
|
||||
var reduceMu sync.Mutex
|
||||
var allPagesAffected []string
|
||||
@@ -415,7 +523,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
// those slugs into actual pages. Rewrite those dead links to plain
|
||||
// text so the summary doesn't contain unresolvable references.
|
||||
if len(failedAdditionSlugs) > 0 && len(docResults) > 0 {
|
||||
s.sanitizeDeadSummaryLinks(ctx, payload.KnowledgeBaseID, docResults, failedAdditionSlugs)
|
||||
s.sanitizeDeadSummaryLinks(ctx, payload.KnowledgeBaseID, docResults, failedAdditionSlugs, batchCtx)
|
||||
}
|
||||
|
||||
totalPagesAffected = len(allPagesAffected)
|
||||
@@ -436,10 +544,10 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
if len(slugs) == 0 {
|
||||
return nil
|
||||
}
|
||||
titles := batchCtx.SlugTitleMany(ctx, slugs)
|
||||
out := make([]types.WikiLogPageRef, 0, len(slugs))
|
||||
for _, slug := range slugs {
|
||||
title := batchCtx.SlugTitleMap[slug]
|
||||
out = append(out, types.WikiLogPageRef{Slug: slug, Title: title})
|
||||
out = append(out, types.WikiLogPageRef{Slug: slug, Title: titles[slug]})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -502,24 +610,68 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
// failed entity slugs); sanitizeDeadSummaryLinks above handles the
|
||||
// well-known summary case, and this pass is the safety net for the
|
||||
// long tail (cross-doc citations, prior batches' lingering refs).
|
||||
if len(retractPagesAffected) > 0 || len(failedAdditionSlugs) > 0 || len(allPagesAffected) > 0 {
|
||||
// Dead-link cleanup: scoped to this batch's affected pages so the
|
||||
// pass scales with batch size, not with KB size. The lint
|
||||
// AutoFix path takes care of long-tail cleanup across the whole
|
||||
// KB out-of-band.
|
||||
if len(allPagesAffected) > 0 {
|
||||
logger.Infof(ctx, "wiki ingest: cleaning dead links")
|
||||
s.cleanDeadLinks(ctx, payload.KnowledgeBaseID)
|
||||
s.cleanDeadLinks(ctx, payload.KnowledgeBaseID, allPagesAffected, batchCtx)
|
||||
}
|
||||
|
||||
if len(allPagesAffected) > 0 {
|
||||
// Build the freshRefs set: every (slug, title) pair this batch
|
||||
// successfully wrote, minus any that landed in failedAdditionSlugs.
|
||||
// These are the "newly-mentionable" pages — links to them will
|
||||
// not have appeared in older content yet, so injectCrossLinks
|
||||
// targets exactly the affected pages with this fresh ref set.
|
||||
freshRefs := make([]linkRef, 0, len(docResults)*4)
|
||||
for _, dr := range docResults {
|
||||
if dr == nil {
|
||||
continue
|
||||
}
|
||||
for _, p := range dr.Pages {
|
||||
if p.Slug == "" || p.Title == "" {
|
||||
continue
|
||||
}
|
||||
if _, bad := failedAdditionSlugs[p.Slug]; bad {
|
||||
continue
|
||||
}
|
||||
freshRefs = append(freshRefs, linkRef{slug: p.Slug, matchText: p.Title})
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "wiki ingest: injecting cross links")
|
||||
s.injectCrossLinks(ctx, payload.KnowledgeBaseID, allPagesAffected)
|
||||
s.injectCrossLinks(ctx, payload.KnowledgeBaseID, allPagesAffected, freshRefs, batchCtx)
|
||||
|
||||
logger.Infof(ctx, "wiki ingest: publishing draft pages")
|
||||
s.publishDraftPages(ctx, payload.KnowledgeBaseID, allPagesAffected)
|
||||
}
|
||||
|
||||
s.trimPendingList(ctx, payload.KnowledgeBaseID, peekedCount)
|
||||
// Build the trim set: rows that should be removed from
|
||||
// task_pending_ops. We start from the full peekedIDs (every row we
|
||||
// pulled, even ones de-duplicated by knowledge_id) and subtract
|
||||
// any failed op's dbID — those need to stay in place so the
|
||||
// requeueFailedOps path can decide between retry and dead-letter.
|
||||
failedIDSet := make(map[int64]struct{}, len(failedOps))
|
||||
for _, op := range failedOps {
|
||||
if op.dbID != 0 {
|
||||
failedIDSet[op.dbID] = struct{}{}
|
||||
}
|
||||
}
|
||||
trimIDs := make([]int64, 0, len(peekedIDs))
|
||||
for _, id := range peekedIDs {
|
||||
if _, fail := failedIDSet[id]; fail {
|
||||
continue
|
||||
}
|
||||
trimIDs = append(trimIDs, id)
|
||||
}
|
||||
s.trimPendingList(ctx, trimIDs)
|
||||
|
||||
// Re-enqueue failed ops so they get retried in the next follow-up batch.
|
||||
// This must happen after trim: trim removes the consumed batch head, then
|
||||
// requeue appends the failed items to the tail for a future attempt.
|
||||
// Process failed ops: increment fail_count and dead-letter once
|
||||
// the cap is hit. Must come AFTER trim so successful siblings are
|
||||
// already gone from the queue — otherwise a follow-up batch could
|
||||
// re-pick them up.
|
||||
if len(failedOps) > 0 {
|
||||
s.requeueFailedOps(ctx, payload, failedOps)
|
||||
}
|
||||
@@ -611,11 +763,11 @@ func (s *wikiIngestService) mapOneDocument(
|
||||
pass0Failed bool
|
||||
)
|
||||
logger.Infof(ctx, "wiki ingest: pass 0 — extracting candidate slugs for %s", knowledgeID)
|
||||
extractedEntities, extractedConcepts, slugItems, err = s.extractCandidateSlugs(ctx, chatModel, content, lang, oldPageSlugs, batchCtx)
|
||||
extractedEntities, extractedConcepts, slugItems, err = s.extractCandidateSlugs(ctx, chatModel, payload.KnowledgeBaseID, content, lang, oldPageSlugs, batchCtx)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: pass 0 failed for %s (%v) — falling back to legacy extractor", knowledgeID, err)
|
||||
pass0Failed = true
|
||||
extractedEntities, extractedConcepts, slugItems, err = s.extractEntitiesAndConceptsNoUpsert(ctx, chatModel, content, lang, oldPageSlugs, batchCtx)
|
||||
extractedEntities, extractedConcepts, slugItems, err = s.extractEntitiesAndConceptsNoUpsert(ctx, chatModel, payload.KnowledgeBaseID, content, lang, oldPageSlugs, batchCtx)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: legacy fallback also failed for %s: %v", knowledgeID, err)
|
||||
return nil, nil, err
|
||||
@@ -830,10 +982,11 @@ func (s *wikiIngestService) mapOneDocument(
|
||||
// SummaryBody, so emitting an extra retract would just be
|
||||
// dead weight that the summary branch discards anyway.
|
||||
//
|
||||
// priorContribution is the doc's LAST summary body snapshotted at the
|
||||
// start of this batch (from allPages scan). Empty on first-ever ingest
|
||||
// — in that case oldPageSlugs is also empty, so we never consult it.
|
||||
priorContribution := batchCtx.SummaryContentByKnowledgeID[knowledgeID]
|
||||
// priorContribution is the doc's LAST summary body, fetched lazily
|
||||
// at this point (rather than pre-loaded into the batch context).
|
||||
// Empty on first-ever ingest — in that case oldPageSlugs is also
|
||||
// empty, so we never consult it.
|
||||
priorContribution := batchCtx.SummaryContentByKnowledgeID(ctx, knowledgeID)
|
||||
|
||||
newSlugSet := make(map[string]bool, len(extractedPages))
|
||||
for _, ns := range extractedPages {
|
||||
@@ -889,6 +1042,7 @@ func (s *wikiIngestService) mapOneDocument(
|
||||
func (s *wikiIngestService) extractEntitiesAndConceptsNoUpsert(
|
||||
ctx context.Context,
|
||||
chatModel chat.Chat,
|
||||
kbID string,
|
||||
content, lang string,
|
||||
oldPageSlugs map[string]bool,
|
||||
batchCtx *WikiBatchContext,
|
||||
@@ -929,8 +1083,13 @@ func (s *wikiIngestService) extractEntitiesAndConceptsNoUpsert(
|
||||
return nil, nil, nil, fmt.Errorf("parse combined extraction JSON: %w", err)
|
||||
}
|
||||
|
||||
// Dedup pre-filter is dispatched against the wiki page repo via
|
||||
// pg_trgm (see deduplicateExtractedBatch). Until the trgm path
|
||||
// lands the dedup pre-filter degrades to "no dedup" which is the
|
||||
// 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, result.Entities, result.Concepts, batchCtx.AllPages,
|
||||
ctx, chatModel, kbID, result.Entities, result.Concepts,
|
||||
)
|
||||
|
||||
slugItems := make(map[string]extractedItem)
|
||||
@@ -1082,7 +1241,7 @@ func (s *wikiIngestService) reduceSlugUpdates(
|
||||
continue
|
||||
}
|
||||
|
||||
if content, ok := batchCtx.SummaryContentByKnowledgeID[refKnowledgeID]; ok {
|
||||
if content := batchCtx.SummaryContentByKnowledgeID(ctx, refKnowledgeID); content != "" {
|
||||
fmt.Fprintf(&remainingSourcesContent, "<document>\n<title>%s</title>\n<content>\n%s\n</content>\n</document>\n\n", refTitle, content)
|
||||
} else {
|
||||
fmt.Fprintf(&remainingSourcesContent, "<document>\n<title>%s</title>\n<content>\n(summary not available)\n</content>\n</document>\n\n", refTitle)
|
||||
@@ -1157,8 +1316,9 @@ func (s *wikiIngestService) reduceSlugUpdates(
|
||||
}
|
||||
|
||||
if len(additions) > 0 || len(retracts) > 0 {
|
||||
titles := batchCtx.SlugTitleMany(ctx, []string(page.OutLinks))
|
||||
for _, outSlug := range page.OutLinks {
|
||||
if title, ok := batchCtx.SlugTitleMap[outSlug]; ok {
|
||||
if title := titles[outSlug]; title != "" {
|
||||
fmt.Fprintf(&relatedSlugs, "- %s (%s)\n", outSlug, title)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ type citationPipelineOutcome struct {
|
||||
func (s *wikiIngestService) extractCandidateSlugs(
|
||||
ctx context.Context,
|
||||
chatModel chat.Chat,
|
||||
kbID string,
|
||||
content, lang string,
|
||||
oldPageSlugs map[string]bool,
|
||||
batchCtx *WikiBatchContext,
|
||||
@@ -111,7 +112,7 @@ func (s *wikiIngestService) extractCandidateSlugs(
|
||||
}
|
||||
|
||||
result.Entities, result.Concepts = s.deduplicateExtractedBatch(
|
||||
ctx, chatModel, result.Entities, result.Concepts, batchCtx.AllPages,
|
||||
ctx, chatModel, kbID, result.Entities, result.Concepts,
|
||||
)
|
||||
|
||||
slugItems := make(map[string]extractedItem, len(result.Entities)+len(result.Concepts))
|
||||
|
||||
@@ -73,7 +73,24 @@ func NewWikiLintService(
|
||||
}
|
||||
}
|
||||
|
||||
// RunLint performs a comprehensive health check on a wiki knowledge base
|
||||
// lintCursorBatch is the per-batch limit for the streaming page walk.
|
||||
// Picked at 200 because wiki pages can carry multi-KB content blobs
|
||||
// and 200 rows × ~20KB ≈ 4MB resident at a time, which is well within
|
||||
// what we want to hold while running per-page checks.
|
||||
const lintCursorBatch = 200
|
||||
|
||||
// RunLint performs a comprehensive health check on a wiki knowledge base.
|
||||
//
|
||||
// At 4w-document scale the legacy "load every page in one shot"
|
||||
// approach was the dominant tail in this method (and intermittently
|
||||
// caused OOM in production). We now walk the page set via
|
||||
// ListPagesCursor in lintCursorBatch-sized windows, accumulating
|
||||
// issues incrementally — memory stays bounded regardless of KB size.
|
||||
//
|
||||
// We also drop the GetGraph(Limit:0) call that the legacy path used
|
||||
// to compute the live-slug set. ListAllSlugs is a one-column projection
|
||||
// over the same predicate (kbID + status<>archived), so it gives the
|
||||
// same answer at a fraction of the cost.
|
||||
func (s *WikiLintService) RunLint(ctx context.Context, kbID string) (*WikiLintReport, error) {
|
||||
// Validate KB
|
||||
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID)
|
||||
@@ -90,159 +107,170 @@ func (s *WikiLintService) RunLint(ctx context.Context, kbID string) (*WikiLintRe
|
||||
return nil, fmt.Errorf("get stats: %w", err)
|
||||
}
|
||||
|
||||
// Get graph for link analysis. Lint needs the FULL graph to detect
|
||||
// orphans and broken links across every page, so we pass Limit=0
|
||||
// which the service treats as "no cap".
|
||||
graph, err := s.wikiService.GetGraph(ctx, &types.WikiGraphRequest{
|
||||
KnowledgeBaseID: kbID,
|
||||
Mode: types.WikiGraphModeOverview,
|
||||
Limit: 0,
|
||||
})
|
||||
// Compute the live-slug set from the cheap one-column projection.
|
||||
// This replaces a full GetGraph call (which materialized every node
|
||||
// + edge) with a single Pluck("slug") query.
|
||||
liveSlugs, err := s.wikiService.ListAllSlugs(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get graph: %w", err)
|
||||
return nil, fmt.Errorf("list all slugs: %w", err)
|
||||
}
|
||||
|
||||
// Get all pages for detailed analysis
|
||||
resp, err := s.wikiService.ListPages(ctx, &types.WikiPageListRequest{
|
||||
KnowledgeBaseID: kbID,
|
||||
PageSize: 500,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list pages: %w", err)
|
||||
slugSet := make(map[string]bool, len(liveSlugs))
|
||||
for _, slug := range liveSlugs {
|
||||
slugSet[slug] = true
|
||||
}
|
||||
|
||||
var issues []WikiLintIssue
|
||||
healthScore := 100
|
||||
knowledgeLive := make(map[string]bool) // kid -> exists; cached across pages
|
||||
|
||||
// Build slug set for link validation
|
||||
slugSet := make(map[string]bool)
|
||||
for _, node := range graph.Nodes {
|
||||
slugSet[node.Slug] = true
|
||||
}
|
||||
|
||||
// Check 1: Orphan pages (no inbound links, excluding index/log)
|
||||
for _, page := range resp.Pages {
|
||||
if page.PageType == types.WikiPageTypeIndex || page.PageType == types.WikiPageTypeLog {
|
||||
continue
|
||||
}
|
||||
if len(page.InLinks) == 0 {
|
||||
issues = append(issues, WikiLintIssue{
|
||||
Type: LintIssueOrphanPage,
|
||||
Severity: SeverityWarning,
|
||||
PageSlug: page.Slug,
|
||||
Description: fmt.Sprintf("Page '%s' has no inbound links — it's disconnected from the wiki", page.Title),
|
||||
AutoFixable: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Check 2: Broken links
|
||||
for _, page := range resp.Pages {
|
||||
for _, outLink := range page.OutLinks {
|
||||
if !slugSet[outLink] {
|
||||
issues = append(issues, WikiLintIssue{
|
||||
Type: LintIssueBrokenLink,
|
||||
Severity: SeverityError,
|
||||
PageSlug: page.Slug,
|
||||
TargetSlug: outLink,
|
||||
Description: fmt.Sprintf("Page '%s' links to [[%s]] which does not exist", page.Title, outLink),
|
||||
AutoFixable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check 3: Empty content
|
||||
for _, page := range resp.Pages {
|
||||
content := strings.TrimSpace(page.Content)
|
||||
if len(content) < 50 {
|
||||
issues = append(issues, WikiLintIssue{
|
||||
Type: LintIssueEmptyContent,
|
||||
Severity: SeverityWarning,
|
||||
PageSlug: page.Slug,
|
||||
Description: fmt.Sprintf("Page '%s' has very little content (%d chars)", page.Title, len(content)),
|
||||
AutoFixable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Check 4: Stale source refs — source_refs pointing at soft-deleted
|
||||
// knowledge. This is the primary self-heal for the ingest/delete race
|
||||
// condition: if a wiki_ingest task managed to slip past the in-flight
|
||||
// guards and wrote a page for a knowledge that has since been deleted,
|
||||
// the page becomes a dead-end (wiki_read_source_doc returns "knowledge
|
||||
// not found"). Flag it so AutoFix can strip the ref, and delete the
|
||||
// page if no live refs remain.
|
||||
if s.knowledgeService != nil {
|
||||
knowledgeLive := make(map[string]bool) // kid -> exists
|
||||
for _, page := range resp.Pages {
|
||||
// Skip wiki-intrinsic pages: index/log never carry SourceRefs
|
||||
// anyway, and accidentally flagging them would risk AutoFix
|
||||
// deleting system pages.
|
||||
if page.PageType == types.WikiPageTypeIndex || page.PageType == types.WikiPageTypeLog {
|
||||
continue
|
||||
}
|
||||
for _, ref := range page.SourceRefs {
|
||||
kid := ref
|
||||
if i := strings.Index(ref, "|"); i > 0 {
|
||||
kid = ref[:i]
|
||||
}
|
||||
if kid == "" {
|
||||
continue
|
||||
}
|
||||
live, seen := knowledgeLive[kid]
|
||||
if !seen {
|
||||
kn, err := s.knowledgeService.GetKnowledgeByIDOnly(ctx, kid)
|
||||
live = err == nil && kn != nil
|
||||
knowledgeLive[kid] = live
|
||||
}
|
||||
if !live {
|
||||
issues = append(issues, WikiLintIssue{
|
||||
Type: LintIssueStaleRef,
|
||||
Severity: SeverityError,
|
||||
PageSlug: page.Slug,
|
||||
TargetSlug: kid,
|
||||
Description: fmt.Sprintf("Page '%s' references deleted knowledge %s", page.Title, kid),
|
||||
AutoFixable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check 5: Missing cross-references (entities mentioned in content but not linked)
|
||||
// First-pass walk: orphan / broken-link / empty / stale-ref
|
||||
// detection. Each check is independent of order; we accumulate
|
||||
// issues per-batch and the cursor walk keeps memory bounded.
|
||||
//
|
||||
// We collect entity / concept titles in this pass too so the
|
||||
// missing-cross-ref check (which is intrinsically O(N×M) in
|
||||
// distinct entities × pages) doesn't need a second walk to find
|
||||
// candidates. The check itself runs in a second walk because it
|
||||
// needs the full entity-title set to compare against any page.
|
||||
entitySlugs := make(map[string]string) // slug -> title
|
||||
for _, page := range resp.Pages {
|
||||
if page.PageType == types.WikiPageTypeEntity || page.PageType == types.WikiPageTypeConcept {
|
||||
entitySlugs[page.Slug] = page.Title
|
||||
|
||||
cursor := ""
|
||||
for {
|
||||
pages, next, err := s.wikiService.ListPagesCursor(ctx, kbID, cursor, lintCursorBatch)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list pages cursor: %w", err)
|
||||
}
|
||||
}
|
||||
for _, page := range resp.Pages {
|
||||
for slug, title := range entitySlugs {
|
||||
if slug == page.Slug {
|
||||
continue
|
||||
if len(pages) == 0 {
|
||||
break
|
||||
}
|
||||
for _, page := range pages {
|
||||
// Track entity/concept titles for the second pass.
|
||||
if page.PageType == types.WikiPageTypeEntity || page.PageType == types.WikiPageTypeConcept {
|
||||
entitySlugs[page.Slug] = page.Title
|
||||
}
|
||||
// Check if title is mentioned in content but not linked
|
||||
if strings.Contains(strings.ToLower(page.Content), strings.ToLower(title)) {
|
||||
linked := false
|
||||
for _, l := range page.OutLinks {
|
||||
if l == slug {
|
||||
linked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !linked {
|
||||
|
||||
// Check 1: Orphan pages (no inbound links, excluding system pages).
|
||||
if page.PageType != types.WikiPageTypeIndex && page.PageType != types.WikiPageTypeLog {
|
||||
if len(page.InLinks) == 0 {
|
||||
issues = append(issues, WikiLintIssue{
|
||||
Type: LintIssueMissingCrossRef,
|
||||
Severity: SeverityInfo,
|
||||
Type: LintIssueOrphanPage,
|
||||
Severity: SeverityWarning,
|
||||
PageSlug: page.Slug,
|
||||
TargetSlug: slug,
|
||||
Description: fmt.Sprintf("Page '%s' mentions '%s' but doesn't link to [[%s]]", page.Title, title, slug),
|
||||
Description: fmt.Sprintf("Page '%s' has no inbound links — it's disconnected from the wiki", page.Title),
|
||||
AutoFixable: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Check 2: Broken links — outlinks pointing at slugs that
|
||||
// don't exist in the live set.
|
||||
for _, outLink := range page.OutLinks {
|
||||
if !slugSet[outLink] {
|
||||
issues = append(issues, WikiLintIssue{
|
||||
Type: LintIssueBrokenLink,
|
||||
Severity: SeverityError,
|
||||
PageSlug: page.Slug,
|
||||
TargetSlug: outLink,
|
||||
Description: fmt.Sprintf("Page '%s' links to [[%s]] which does not exist", page.Title, outLink),
|
||||
AutoFixable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Check 3: Empty content.
|
||||
content := strings.TrimSpace(page.Content)
|
||||
if len(content) < 50 {
|
||||
issues = append(issues, WikiLintIssue{
|
||||
Type: LintIssueEmptyContent,
|
||||
Severity: SeverityWarning,
|
||||
PageSlug: page.Slug,
|
||||
Description: fmt.Sprintf("Page '%s' has very little content (%d chars)", page.Title, len(content)),
|
||||
AutoFixable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Check 4: Stale source refs — source_refs pointing at
|
||||
// soft-deleted knowledge. Cached knowledgeLive lookup keeps
|
||||
// per-kid checks O(1) after the first batch encounters
|
||||
// each id.
|
||||
if s.knowledgeService != nil &&
|
||||
page.PageType != types.WikiPageTypeIndex &&
|
||||
page.PageType != types.WikiPageTypeLog {
|
||||
for _, ref := range page.SourceRefs {
|
||||
kid := ref
|
||||
if i := strings.Index(ref, "|"); i > 0 {
|
||||
kid = ref[:i]
|
||||
}
|
||||
if kid == "" {
|
||||
continue
|
||||
}
|
||||
live, seen := knowledgeLive[kid]
|
||||
if !seen {
|
||||
kn, err := s.knowledgeService.GetKnowledgeByIDOnly(ctx, kid)
|
||||
live = err == nil && kn != nil
|
||||
knowledgeLive[kid] = live
|
||||
}
|
||||
if !live {
|
||||
issues = append(issues, WikiLintIssue{
|
||||
Type: LintIssueStaleRef,
|
||||
Severity: SeverityError,
|
||||
PageSlug: page.Slug,
|
||||
TargetSlug: kid,
|
||||
Description: fmt.Sprintf("Page '%s' references deleted knowledge %s", page.Title, kid),
|
||||
AutoFixable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
|
||||
// Second-pass walk: missing-cross-ref check. This needs the full
|
||||
// entitySlugs map (built in pass 1), so it has to be a separate
|
||||
// pass — but it's still streaming.
|
||||
cursor = ""
|
||||
for {
|
||||
pages, next, err := s.wikiService.ListPagesCursor(ctx, kbID, cursor, lintCursorBatch)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list pages cursor (pass 2): %w", err)
|
||||
}
|
||||
if len(pages) == 0 {
|
||||
break
|
||||
}
|
||||
for _, page := range pages {
|
||||
lowerContent := strings.ToLower(page.Content)
|
||||
outLinkSet := make(map[string]struct{}, len(page.OutLinks))
|
||||
for _, l := range page.OutLinks {
|
||||
outLinkSet[l] = struct{}{}
|
||||
}
|
||||
for slug, title := range entitySlugs {
|
||||
if slug == page.Slug || title == "" {
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(lowerContent, strings.ToLower(title)) {
|
||||
continue
|
||||
}
|
||||
if _, linked := outLinkSet[slug]; linked {
|
||||
continue
|
||||
}
|
||||
issues = append(issues, WikiLintIssue{
|
||||
Type: LintIssueMissingCrossRef,
|
||||
Severity: SeverityInfo,
|
||||
PageSlug: page.Slug,
|
||||
TargetSlug: slug,
|
||||
Description: fmt.Sprintf("Page '%s' mentions '%s' but doesn't link to [[%s]]", page.Title, title, slug),
|
||||
AutoFixable: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
|
||||
// Calculate health score
|
||||
|
||||
@@ -23,10 +23,11 @@ var wikiLinkRegex = regexp.MustCompile(`\[\[([^\]]+)\]\]`)
|
||||
|
||||
// wikiPageService implements the WikiPageService interface
|
||||
type wikiPageService struct {
|
||||
repo interfaces.WikiPageRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
redisClient *redis.Client
|
||||
repo interfaces.WikiPageRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
taskPendingRepo interfaces.TaskPendingOpsRepository
|
||||
redisClient *redis.Client
|
||||
}
|
||||
|
||||
// NewWikiPageService creates a new wiki page service
|
||||
@@ -34,13 +35,15 @@ func NewWikiPageService(
|
||||
repo interfaces.WikiPageRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
taskPendingRepo interfaces.TaskPendingOpsRepository,
|
||||
redisClient *redis.Client,
|
||||
) interfaces.WikiPageService {
|
||||
return &wikiPageService{
|
||||
repo: repo,
|
||||
chunkRepo: chunkRepo,
|
||||
kbService: kbService,
|
||||
redisClient: redisClient,
|
||||
repo: repo,
|
||||
chunkRepo: chunkRepo,
|
||||
kbService: kbService,
|
||||
taskPendingRepo: taskPendingRepo,
|
||||
redisClient: redisClient,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -667,8 +670,15 @@ func (s *wikiPageService) GetStats(ctx context.Context, kbID string) (*types.Wik
|
||||
var pendingTasks int64
|
||||
var pendingIssues int64
|
||||
var isActive bool
|
||||
if s.taskPendingRepo != nil {
|
||||
// Pending wiki ingest ops live in task_pending_ops keyed by
|
||||
// (task_type="wiki:ingest", scope="knowledge_base", scope_id=kbID).
|
||||
pendingTasks, _ = s.taskPendingRepo.PendingCount(ctx, wikiTaskType, wikiTaskScope, kbID)
|
||||
}
|
||||
if s.redisClient != nil {
|
||||
pendingTasks, _ = s.redisClient.LLen(ctx, "wiki:pending:"+kbID).Result()
|
||||
// The "active batch in progress" flag is still a Redis-only
|
||||
// short-lived signal (per-process lock with TTL renew); not
|
||||
// worth migrating since it carries no durable state.
|
||||
activeFlag, _ := s.redisClient.Exists(ctx, "wiki:active:"+kbID).Result()
|
||||
isActive = activeFlag > 0
|
||||
}
|
||||
@@ -746,6 +756,67 @@ func (s *wikiPageService) ListPagesBySourceRef(ctx context.Context, kbID string,
|
||||
return s.repo.ListBySourceRef(ctx, kbID, knowledgeID)
|
||||
}
|
||||
|
||||
// ListSlugsBySourceRef returns just the slugs of pages that cite the given
|
||||
// knowledge id. Backed by the source_refs GIN index added in migration
|
||||
// 000041 — the wiki ingest pipeline uses it as a cheap "before" snapshot
|
||||
// when reconciling old vs new extraction sets.
|
||||
func (s *wikiPageService) ListSlugsBySourceRef(ctx context.Context, kbID string, knowledgeID string) ([]string, error) {
|
||||
return s.repo.ListSlugsBySourceRef(ctx, kbID, knowledgeID)
|
||||
}
|
||||
|
||||
// ListBySlugs is the lazy fetcher used by wiki ingest's batch context.
|
||||
// Returns lightweight projections (no content / source_refs / chunk_refs)
|
||||
// for the requested slugs, in a single IN query. Used in place of the
|
||||
// pre-batch ListAllPages dump that historically pulled hundreds of MB
|
||||
// for KBs in the tens of thousands of pages.
|
||||
func (s *wikiPageService) ListBySlugs(ctx context.Context, kbID string, slugs []string) (map[string]*types.WikiPageLite, error) {
|
||||
return s.repo.ListBySlugs(ctx, kbID, slugs)
|
||||
}
|
||||
|
||||
// ListSummariesByKnowledgeIDs is the lazy fetcher for the retract /
|
||||
// reparse branches of reduceSlugUpdates. Returns the content of each
|
||||
// surviving summary page keyed by its source knowledge id.
|
||||
func (s *wikiPageService) ListSummariesByKnowledgeIDs(ctx context.Context, kbID string, kids []string) (map[string]string, error) {
|
||||
return s.repo.ListSummariesByKnowledgeIDs(ctx, kbID, kids)
|
||||
}
|
||||
|
||||
// ExistsSlugs reports which of the given slugs are live (non-archived,
|
||||
// non-deleted) in the KB. Used by cleanDeadLinks to validate out-link
|
||||
// targets before stripping them.
|
||||
func (s *wikiPageService) ExistsSlugs(ctx context.Context, kbID string, slugs []string) (map[string]bool, error) {
|
||||
return s.repo.ExistsSlugs(ctx, kbID, slugs)
|
||||
}
|
||||
|
||||
// ListAllSlugs returns every non-archived slug in the KB. Used by lint
|
||||
// to compute the live-slug set without paying for ListAll's full row
|
||||
// materialization.
|
||||
func (s *wikiPageService) ListAllSlugs(ctx context.Context, kbID string) ([]string, error) {
|
||||
return s.repo.ListAllSlugs(ctx, kbID)
|
||||
}
|
||||
|
||||
// ListPagesCursor is the lint-side cursor pagination over wiki_pages.
|
||||
func (s *wikiPageService) ListPagesCursor(ctx context.Context, kbID string, cursor string, limit int) ([]*types.WikiPage, string, error) {
|
||||
return s.repo.ListPagesCursor(ctx, kbID, cursor, limit)
|
||||
}
|
||||
|
||||
// ListByTypeRecent caps the page count for first-time index intro
|
||||
// generation so the LLM prompt stays bounded on large KBs.
|
||||
func (s *wikiPageService) ListByTypeRecent(ctx context.Context, kbID string, pageType string, limit int) ([]types.WikiIndexEntry, error) {
|
||||
return s.repo.ListByTypeRecent(ctx, kbID, pageType, limit)
|
||||
}
|
||||
|
||||
// FindSimilarPages performs a pg_trgm similarity search; used by the
|
||||
// dedup pre-filter to surface candidate merge targets.
|
||||
func (s *wikiPageService) FindSimilarPages(ctx context.Context, kbID string, query string, pageTypes []string, limit int) ([]*types.WikiPageLite, error) {
|
||||
return s.repo.FindSimilarPages(ctx, kbID, query, pageTypes, limit)
|
||||
}
|
||||
|
||||
// CountByType is a service-layer pass-through over the repo. Used by
|
||||
// the index intro path to frame the LLM prompt's "showing N of M" hint.
|
||||
func (s *wikiPageService) CountByType(ctx context.Context, kbID string) (map[string]int64, error) {
|
||||
return s.repo.CountByType(ctx, kbID)
|
||||
}
|
||||
|
||||
// SearchPages performs full-text search over wiki pages
|
||||
func (s *wikiPageService) SearchPages(ctx context.Context, kbID string, query string, limit int) ([]*types.WikiPage, error) {
|
||||
return s.repo.Search(ctx, kbID, query, limit)
|
||||
|
||||
Reference in New Issue
Block a user