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:
@@ -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