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:
wizardchen
2026-05-09 23:42:53 +08:00
committed by lyingbug
parent 91cf237dd9
commit 04e8105728
24 changed files with 3615 additions and 681 deletions
+86
View File
@@ -0,0 +1,86 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// TaskPendingOpsRepository persists rows for the generic task pending
// queue (`task_pending_ops`). The queue is the durable replacement for
// the Redis-list-backed wiki:pending:<kbID> queue. It is intentionally
// stateless about consumer semantics: the (TaskType, Scope, ScopeID)
// tuple is the only routing primitive the repository understands;
// deduplication, batching, and retry policy live in the consumer.
//
// Concurrency model in this revision: PeekBatch does NOT take row
// locks. Consumers are expected to enforce per-(scope_id) serialization
// out-of-band (wiki ingest does this via Redis SetNX wiki:active:<kbID>).
// The reserved `claimed_at` column lets a future revision adopt
// pessimistic locking without a schema change.
type TaskPendingOpsRepository interface {
// Enqueue inserts a single op. The caller fills in TenantID, TaskType,
// Scope, ScopeID, Op, DedupKey, Payload; ID, FailCount, EnqueuedAt
// are server-side defaults.
Enqueue(ctx context.Context, op *types.TaskPendingOp) error
// PeekBatch returns up to `limit` rows for the given queue tuple,
// ordered by id ASC (FIFO within the queue). Rows are NOT removed —
// callers must DeleteByIDs once the ops have been processed (or
// IncrFailCount and leave them for the next pass).
PeekBatch(ctx context.Context, taskType, scope, scopeID string, limit int) ([]*types.TaskPendingOp, error)
// DeleteByIDs removes the given rows. No-op for empty input. Used
// to consume a successfully-processed batch, and to drop ops that
// have been moved to task_dead_letters.
DeleteByIDs(ctx context.Context, ids []int64) error
// IncrFailCount increments fail_count for one row and returns the
// new value. Returns (0, nil) if the row does not exist (race with
// DeleteByIDs is benign).
IncrFailCount(ctx context.Context, id int64) (int, error)
// PendingCount returns the number of rows currently queued for the
// given tuple. Cheap (covered by idx_task_pending_ops_scope) and
// used by the wiki ingest follow-up scheduler.
PendingCount(ctx context.Context, taskType, scope, scopeID string) (int64, error)
// DeleteByDedupKey removes rows for the tuple whose DedupKey
// matches. If `op` is non-empty, only rows with that exact op are
// removed (this lets wiki ingest scrub queued "ingest" ops while
// preserving "retract" ops for the same knowledge — retract is
// still needed to clean up wiki pages after the source doc is
// deleted). If `op` is empty, every matching row is removed
// regardless of op.
DeleteByDedupKey(ctx context.Context, taskType, scope, scopeID, dedupKey, op string) error
}
// TaskDeadLetterRepository persists rows for the generic task dead-letter
// archive (`task_dead_letters`). Two writers exist: the asynq
// dead-letter middleware (one row per archived asynq task), and the
// service-level retry handlers (one row per in-batch op that exhausted
// its consumer-defined retry budget — wiki ingest is the current case).
//
// Reads are operator-driven: list by scope to triage a single KB,
// list by task_type for cross-KB symptom hunting. No TTL.
type TaskDeadLetterRepository interface {
// Insert records one dead letter. Best-effort caller: the asynq
// middleware ignores the error so a failed insert never masks the
// underlying task error.
Insert(ctx context.Context, dl *types.TaskDeadLetter) error
// ListByScope returns dead letters for the given scope tuple,
// newest-first, paginated by failed-id cursor. `cursor` is the
// stringified id of the oldest entry from the previous page; "" =
// from the newest. Empty nextCursor = end of stream. `limit` is
// clamped to [1, 200].
ListByScope(ctx context.Context, scope, scopeID, cursor string, limit int) ([]*types.TaskDeadLetter, string, error)
// ListByTaskType returns dead letters for the given task_type,
// newest-first, with the same cursor semantics as ListByScope.
ListByTaskType(ctx context.Context, taskType, cursor string, limit int) ([]*types.TaskDeadLetter, string, error)
// DeleteByID drops a single dead letter (e.g. after operators have
// requeued the task manually).
DeleteByID(ctx context.Context, id int64) error
}
+90
View File
@@ -116,6 +116,53 @@ type WikiPageService interface {
// than relying on a caller-provided stale snapshot).
ListPagesBySourceRef(ctx context.Context, kbID string, knowledgeID string) ([]*types.WikiPage, error)
// ListSlugsBySourceRef returns just the slugs of pages that cite the
// given knowledge id. Cheaper than ListPagesBySourceRef when callers
// only need the slug set (e.g. wiki ingest's "before" snapshot).
ListSlugsBySourceRef(ctx context.Context, kbID string, knowledgeID string) ([]string, error)
// ListBySlugs is the lazy fetcher used by the wiki ingest batch
// context: returns lightweight projections (no content / source_refs)
// for the requested slugs in a single IN query. Used in place of
// the pre-batch ListAllPages dump.
ListBySlugs(ctx context.Context, kbID string, slugs []string) (map[string]*types.WikiPageLite, error)
// ListSummariesByKnowledgeIDs returns summary-page content keyed by
// the knowledge id that authored it. Used by the retract / reparse
// branches of reduceSlugUpdates for "what was this doc's
// contribution?" framing.
ListSummariesByKnowledgeIDs(ctx context.Context, kbID string, kids []string) (map[string]string, error)
// ExistsSlugs reports which of the given slugs are live (non-archived).
// Used by cleanDeadLinks to validate out-link targets cheaply.
ExistsSlugs(ctx context.Context, kbID string, slugs []string) (map[string]bool, error)
// ListAllSlugs returns every non-archived slug in the KB. Used by
// lint to compute the live-slug set for broken-link detection.
ListAllSlugs(ctx context.Context, kbID string) ([]string, error)
// ListPagesCursor walks the KB in id-asc order with an opaque
// cursor. Used by lint to stream the page set without holding it
// all in memory at once.
ListPagesCursor(ctx context.Context, kbID string, cursor string, limit int) ([]*types.WikiPage, string, error)
// ListByTypeRecent returns the most-recently-updated pages of the
// given type, projected to slug/title/summary, capped at `limit`.
// Used by rebuildIndexPage's first-time generation path.
ListByTypeRecent(ctx context.Context, kbID string, pageType string, limit int) ([]types.WikiIndexEntry, error)
// FindSimilarPages performs a pg_trgm similarity search over
// page titles. Used by the dedup pre-filter to surface candidate
// merge targets server-side.
FindSimilarPages(ctx context.Context, kbID string, query string, pageTypes []string, limit int) ([]*types.WikiPageLite, error)
// CountByType returns page counts grouped by type for a knowledge
// base. Re-exposed at the service layer so the index intro
// generation path can frame the LLM prompt with "showing N of M"
// metadata when the recent-N projection doesn't cover the full
// summary set.
CountByType(ctx context.Context, kbID string) (map[string]int64, error)
// SearchPages performs full-text search over wiki pages.
SearchPages(ctx context.Context, kbID string, query string, limit int) ([]*types.WikiPage, error)
@@ -174,6 +221,49 @@ type WikiPageRepository interface {
// ListBySourceRef retrieves all wiki pages that reference a given source knowledge ID.
ListBySourceRef(ctx context.Context, kbID string, sourceKnowledgeID string) ([]*types.WikiPage, error)
// ListSlugsBySourceRef returns just the slugs of pages that reference
// the given knowledge id. Same predicate as ListBySourceRef but
// projected to a single column for the wiki ingest pipeline's
// "before" snapshot path.
ListSlugsBySourceRef(ctx context.Context, kbID string, sourceKnowledgeID string) ([]string, error)
// ListBySlugs returns lightweight projections (slug/title/page_type/
// status/aliases/out_links) for the given slugs in one IN query.
// Used by the lazy fetcher path in wiki ingest's Map/Reduce phases.
ListBySlugs(ctx context.Context, kbID string, slugs []string) (map[string]*types.WikiPageLite, error)
// ListSummariesByKnowledgeIDs returns summary-page content keyed by
// the knowledge id that authored it. Used by the retract branch of
// reduceSlugUpdates for "what was this doc's contribution?" framing.
ListSummariesByKnowledgeIDs(ctx context.Context, kbID string, kids []string) (map[string]string, error)
// ExistsSlugs reports which of the given slugs are live (non-
// archived). Used by cleanDeadLinks to validate out-link targets
// without loading the referenced pages' content.
ExistsSlugs(ctx context.Context, kbID string, slugs []string) (map[string]bool, error)
// 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.
ListAllSlugs(ctx context.Context, kbID string) ([]string, error)
// ListPagesCursor returns up to `limit` pages ordered by id ASC,
// paginated by an opaque numeric cursor. Used by lint to stream
// the KB without loading every page at once.
ListPagesCursor(ctx context.Context, kbID string, cursor string, limit int) ([]*types.WikiPage, string, error)
// ListByTypeRecent returns the most-recently-updated pages of the
// given type, projected to slug/title/summary, capped at `limit`.
// Used by rebuildIndexPage's first-time generation path so the
// LLM prompt size is bounded on large KBs.
ListByTypeRecent(ctx context.Context, kbID string, pageType string, limit int) ([]types.WikiIndexEntry, error)
// FindSimilarPages returns the top-k pages whose lowercase title
// is most similar to the query under pg_trgm. `pageTypes` empty
// defaults to entity+concept. Used by the dedup pre-filter to
// surface candidate merge targets server-side.
FindSimilarPages(ctx context.Context, kbID string, query string, pageTypes []string, limit int) ([]*types.WikiPageLite, error)
// ListAll retrieves all wiki pages in a knowledge base (for link rebuilding, graph generation).
ListAll(ctx context.Context, kbID string) ([]*types.WikiPage, error)
+70
View File
@@ -0,0 +1,70 @@
package types
import (
"encoding/json"
"time"
)
// TaskDeadLetter is one row in the `task_dead_letters` archive: a
// permanent record of a task whose retry budget was exhausted. The table
// is populated from two distinct paths:
//
// 1. The asynq dead-letter middleware
// (internal/middleware/asynq_dead_letter.go) inserts a row whenever
// an asynq task's retry count equals its MaxRetry on the way out.
// This is the catch-all that covers every registered task type
// uniformly without per-handler instrumentation.
//
// 2. Service-level retry handlers insert directly when an in-batch
// retry counter exceeds the service-defined cap. Wiki ingest is the
// primary example: per-document ops accumulate fail_count in
// `task_pending_ops`, and once the count exceeds wikiMaxFailRetries
// the op is moved here instead of being requeued.
//
// Operators query by (Scope, ScopeID) — e.g. "all dead letters for KB
// abc" — or by TaskType — e.g. "all summary:generation failures in the
// last 24h". The table has no TTL; rows are kept until manually pruned.
type TaskDeadLetter struct {
// Auto-increment row id.
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
// Tenant scope mirrored from the original task payload (best-effort:
// if the middleware can't decode the payload, this falls back to 0).
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Task identifier (e.g. "wiki:ingest", "summary:generation").
TaskType string `json:"task_type" gorm:"type:varchar(64)"`
// Logical scope, mirrors task_pending_ops.scope. Falls back to
// "unknown" when the middleware doesn't recognize the task type's
// payload.
Scope string `json:"scope" gorm:"type:varchar(32)"`
// Identifier within scope, e.g. kbID for scope="knowledge_base".
ScopeID string `json:"scope_id" gorm:"type:varchar(64)"`
// Optional secondary identifier. Wiki ingest uses this for the
// knowledge_id so per-document failures cluster around the source
// document; other consumers can leave it empty.
RelatedID string `json:"related_id" gorm:"type:varchar(64);default:''"`
// Raw task payload at the time of failure. For asynq tasks this is
// the verbatim asynq.Task.Payload(); for service-level dead letters
// the consumer chooses what to record.
Payload json.RawMessage `json:"payload" gorm:"type:jsonb"`
// String form of the final error. Long stack traces are kept verbatim.
LastError string `json:"last_error" gorm:"type:text;default:''"`
// Total attempt count when the dead-letter record was written.
FailCount int `json:"fail_count"`
// Server-side write time.
FailedAt time.Time `json:"failed_at"`
}
// TableName binds TaskDeadLetter to the `task_dead_letters` table.
func (TaskDeadLetter) TableName() string {
return "task_dead_letters"
}
// Standard scope literals. Repositories accept any string, but consumers
// should prefer these so SQL queries (run from the ops console) don't
// have to guess at variations.
const (
TaskScopeKnowledgeBase = "knowledge_base"
TaskScopeKnowledge = "knowledge"
TaskScopeTenant = "tenant"
TaskScopeUnknown = "unknown"
)
+63
View File
@@ -0,0 +1,63 @@
package types
import (
"encoding/json"
"time"
)
// TaskPendingOp is one entry in the generic task pending queue
// (`task_pending_ops`). The queue is the durable replacement for the
// Redis-list-backed `wiki:pending:<kbID>` queue: rows survive restarts
// and are not subject to TTL eviction.
//
// The (TaskType, Scope, ScopeID) tuple is the queue identity. A consumer
// pulls a batch with PeekBatch on that tuple, deduplicates by DedupKey
// service-side if it cares, processes the ops, then DeleteByIDs the
// consumed rows. FailCount is incremented per-row by IncrFailCount and
// the consumer dead-letters the row once the count exceeds a service-
// defined cap.
type TaskPendingOp struct {
// Auto-increment row id. Used by PeekBatch ordering and by
// DeleteByIDs / IncrFailCount as the row key.
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
// Tenant scope mirrored from the enclosing object so per-tenant
// retention / quota queries don't have to join.
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Free-form task identifier (e.g. "wiki:ingest"). Should match an
// asynq task type when applicable, but the queue itself doesn't
// enforce that — it's just a string.
TaskType string `json:"task_type" gorm:"type:varchar(64)"`
// Logical scope, e.g. "knowledge_base" / "knowledge" / "tenant".
// Read together with ScopeID.
Scope string `json:"scope" gorm:"type:varchar(32)"`
// Identifier within the scope (e.g. kbID for scope="knowledge_base").
ScopeID string `json:"scope_id" gorm:"type:varchar(64)"`
// Operation kind. Service-defined: e.g. "ingest" / "retract" for
// wiki, but other consumers can use whatever vocabulary they like.
Op string `json:"op" gorm:"type:varchar(32)"`
// Optional service-defined deduplication key. The consumer is
// responsible for collapsing equivalent ops within a peeked batch
// (the queue itself does NOT enforce uniqueness — multiple rows with
// the same DedupKey can coexist; the consumer chooses which wins).
DedupKey string `json:"dedup_key" gorm:"type:varchar(128);default:''"`
// JSON-serialized op payload. Schema is consumer-defined; the queue
// stores it verbatim. Use json.RawMessage to avoid double-decode.
Payload json.RawMessage `json:"payload" gorm:"type:jsonb;default:'{}'"`
// In-batch retry counter. Reset to 0 on successful consume.
FailCount int `json:"fail_count" gorm:"default:0"`
// Server-side enqueue time. NOT used for ordering (id is the cursor)
// but useful for ops queries like "rows older than 1h that never
// drained".
EnqueuedAt time.Time `json:"enqueued_at"`
// Optional claim timestamp for future locking workflows. Not used
// in the current revision: consumers rely on external mutual
// exclusion (e.g. wiki:active:<kbID> Redis SetNX). Reserved column
// so future no-lock parallel workers can flip it inside a row-level
// lock without another migration.
ClaimedAt *time.Time `json:"claimed_at,omitempty"`
}
// TableName binds TaskPendingOp to the `task_pending_ops` table.
func (TaskPendingOp) TableName() string {
return "task_pending_ops"
}
+74
View File
@@ -158,6 +158,53 @@ type WikiConfig struct {
// ExtractionGranularity controls how many candidate slugs Pass 0 extracts
// per document. Empty / unknown value is treated as WikiExtractionStandard.
ExtractionGranularity WikiExtractionGranularity `yaml:"extraction_granularity" json:"extraction_granularity,omitempty"`
// IngestBatchSize controls how many pending ops a single batch
// processes before scheduling a follow-up. 0 falls back to the
// hard-coded default (5). Operators on large KBs (4w+ docs) can
// raise this to 10–20 to amortize the lock-acquire / index-rebuild
// overhead across more documents per round.
IngestBatchSize int `yaml:"ingest_batch_size" json:"ingest_batch_size,omitempty"`
// IngestMapParallel sets the errgroup limit for the Map phase
// (per-document extraction + summary + chunk citation). 0 falls
// back to 10. Bound by the LLM provider's concurrency limit and
// the worker's outbound HTTP pool.
IngestMapParallel int `yaml:"ingest_map_parallel" json:"ingest_map_parallel,omitempty"`
// IngestReduceParallel sets the errgroup limit for the Reduce phase
// (per-slug page write). 0 falls back to 10. Bound by the same
// LLM concurrency / HTTP pool considerations as the Map phase,
// plus DB connection pool size.
IngestReduceParallel int `yaml:"ingest_reduce_parallel" json:"ingest_reduce_parallel,omitempty"`
}
// IngestBatchSizeOrDefault returns IngestBatchSize when set (> 0),
// otherwise the hard-coded fallback. Centralized so callers don't have
// to repeat the 0-check.
func (c *WikiConfig) IngestBatchSizeOrDefault(fallback int) int {
if c == nil || c.IngestBatchSize <= 0 {
return fallback
}
return c.IngestBatchSize
}
// IngestMapParallelOrDefault returns IngestMapParallel when set,
// otherwise the hard-coded fallback.
func (c *WikiConfig) IngestMapParallelOrDefault(fallback int) int {
if c == nil || c.IngestMapParallel <= 0 {
return fallback
}
return c.IngestMapParallel
}
// IngestReduceParallelOrDefault returns IngestReduceParallel when set,
// otherwise the hard-coded fallback.
func (c *WikiConfig) IngestReduceParallelOrDefault(fallback int) int {
if c == nil || c.IngestReduceParallel <= 0 {
return fallback
}
return c.IngestReduceParallel
}
// Value implements the driver.Valuer interface
@@ -324,3 +371,30 @@ type WikiIndexResponse struct {
Version int `json:"version"`
Groups []WikiIndexGroup `json:"groups"`
}
// WikiPageLite is a slim projection of WikiPage carrying only the fields
// the wiki ingest pipeline reaches for during Map / Reduce. It exists so
// per-batch fetcher queries don't have to load the full multi-MB content
// column for every page they want a title or out-link from.
//
// Use cases:
//
// - SlugTitleFetcher: resolve slug -> title for log entries and
// cross-link injection.
// - cleanDeadLinks: read out_links + status without pulling content.
// - dedup pre-filter: title + aliases + page_type for the trgm /
// surface-similarity comparisons.
//
// Aliases is included because dedup and cross-link injection both treat
// the alias surface forms as first-class match targets; OutLinks is
// included so dead-link cleanup can determine which pages reference a
// given dead slug without a second query.
type WikiPageLite struct {
Slug string `json:"slug"`
Title string `json:"title"`
PageType string `json:"page_type"`
Status string `json:"status"`
Aliases StringArray `json:"aliases,omitempty"`
OutLinks StringArray `json:"out_links,omitempty"`
}