feat(wiki): dedicated worker pool with concurrent claim-based batching

Isolate the wiki generation pipeline from the document parse pipeline so
the two can no longer starve each other during concurrent uploads.

- Dedicated asynq worker pool for QueueWiki (NewWikiAsynqServer) with its
  own concurrency budget (WEKNORA_WIKI_ASYNQ_CONCURRENCY / asynq.wiki_
  concurrency, default 16), split from the parse pool (NewParseAsynqServer).
  Both run the same mux over disjoint queue sets. Replaces the old
  weighted-lottery approach where wiki sat on the low queue (weight 1).
- Task queue: add ClaimBatch (SELECT ... FOR UPDATE SKIP LOCKED + claimed_at)
  and ReleaseByIDs so multiple concurrent consumers pull disjoint rows
  without an external per-KB lock; PeekBatch retained for Lite mode.
- New TypeWikiFinalize debounced KB-global finalize task (index rebuild /
  dead-link cleanup / cross-linking), registered on both Redis and Lite paths.
- Two-level wiki ingest concurrency: IngestMaxInflight caps concurrent
  batches per KB; Map/Reduce fan-out sized within a batch. New config knob
  + system setting + swagger docs.
This commit is contained in:
wizardchen
2026-07-09 13:27:47 +08:00
committed by lyingbug
parent 7642117b70
commit 70e2e85fa6
17 changed files with 1282 additions and 377 deletions
+30 -5
View File
@@ -2,6 +2,7 @@ package interfaces
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -13,11 +14,15 @@ import (
// 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.
// Concurrency model: two consumption primitives coexist.
// - PeekBatch does NOT take row locks; consumers enforce per-(scope_id)
// serialization out-of-band (e.g. an external Redis lock). This is the
// original primitive and is still used by single-process (Lite) mode.
// - ClaimBatch DOES take row locks (SELECT ... FOR UPDATE SKIP LOCKED on
// Postgres) and marks rows with claimed_at, so multiple concurrent
// consumers of the same tuple pull DISJOINT rows without an external
// lock. This is what lets the wiki pipeline drop its exclusive per-KB
// batch lock and spread one KB's backlog across the whole worker pool.
type TaskPendingOpsRepository interface {
// Enqueue inserts a single op. The caller fills in TenantID, TaskType,
// Scope, ScopeID, Op, DedupKey, Payload; ID, FailCount, EnqueuedAt
@@ -30,6 +35,26 @@ type TaskPendingOpsRepository interface {
// IncrFailCount and leave them for the next pass).
PeekBatch(ctx context.Context, taskType, scope, scopeID string, limit int) ([]*types.TaskPendingOp, error)
// ClaimBatch atomically claims up to `limit` rows for the tuple,
// ordered by id ASC (FIFO), and returns them with claimed_at set to
// now. A row is eligible when it is unclaimed (claimed_at IS NULL) or
// its claim is stale (claimed_at < staleBefore) — the latter recovers
// rows abandoned by a crashed worker. On Postgres the selection uses
// FOR UPDATE SKIP LOCKED so concurrent claimers never block on or
// double-claim each other's rows.
//
// Claimed rows are NOT removed: the consumer must DeleteByIDs on
// success, or ReleaseByIDs to hand a still-retryable row back to the
// pool (otherwise it stays claimed until staleBefore elapses).
ClaimBatch(ctx context.Context, taskType, scope, scopeID string, limit int, staleBefore time.Time) ([]*types.TaskPendingOp, error)
// ReleaseByIDs clears claimed_at (back to NULL) for the given rows so
// a claimed-but-not-consumed row becomes immediately eligible for the
// next ClaimBatch. No-op for empty input. Used by the wiki retry path
// to re-queue a transiently-failed op without waiting for its claim to
// go stale. Harmless on rows that were never claimed (Lite mode).
ReleaseByIDs(ctx context.Context, ids []int64) 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.
+14 -3
View File
@@ -1,8 +1,8 @@
package types
// Asynq queue names. MUST stay in sync with the Queues weight map in
// router.NewAsynqServer — a task enqueued to a queue that the server does not
// list will never be consumed.
// Asynq queue names. MUST stay in sync with the Queues weight maps in
// router.NewParseAsynqServer / router.NewWikiAsynqServer — a task enqueued to a
// queue that no server subscribes to will never be consumed.
const (
QueueCritical = "critical"
QueueDefault = "default"
@@ -21,6 +21,16 @@ const (
// question batches from starving the lightweight tasks in the low queue
// (summary, deletes, wiki ingest).
QueueQuestion = "question"
// QueueWiki is the dedicated lane for the Wiki ingest pipeline. Unlike the
// other queues above (which all share a single asynq worker pool), this
// queue is consumed by a SEPARATE asynq server (router.NewWikiAsynqServer)
// with its own concurrency budget. Hard capacity isolation: heavy document
// parsing in the upstream pool can never starve wiki generation, and a
// wiki-generation burst can never starve user-facing parsing. Sizing the
// two pools independently replaces the old weighted-lottery approach where
// wiki sat on the low queue (weight 1) and got ~1/13 of the schedule
// during upload storms.
QueueWiki = "wiki"
)
const (
@@ -41,6 +51,7 @@ const (
TypeManualProcess = "manual:process" // 手工知识更新任务(cleanup + 重新索引)
TypeDataSourceSync = "datasource:sync" // 数据源同步任务
TypeWikiIngest = "wiki:ingest" // Wiki 页面同步任务
TypeWikiFinalize = "wiki:finalize" // Wiki KB 级收尾任务(防抖:索引重建/死链清理/交叉链接)
)
// ExtractChunkPayload represents the extract chunk task payload
+39 -11
View File
@@ -348,24 +348,43 @@ type WikiConfig struct {
// 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.
// Wiki ingest concurrency is two-level:
// 1. batch-level: multiple batches per KB run concurrently in the wiki
// worker pool, capped by IngestMaxInflight (below).
// 2. batch-internal: within one batch, Map and Reduce fan out with
// errgroups sized by IngestMapParallel / IngestReduceParallel.
// Effective peak in-flight LLM calls for one KB ≈
// IngestMaxInflight × max(IngestMapParallel, IngestReduceParallel),
// further bounded by the wiki pool size (WEKNORA_WIKI_ASYNQ_CONCURRENCY).
// IngestBatchSize controls how many pending ops a single batch claims and
// processes before scheduling a follow-up. 0 falls back to the hard-coded
// default (5). Larger batches amortize per-batch setup and let more docs
// share the batch-internal Map/Reduce fan-out; smaller batches spread a
// KB's backlog across more concurrent batches (finer scheduling grain).
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.
// (per-document extraction + summary + chunk citation) WITHIN one batch.
// 0 falls back to 10. Bound by the LLM provider's concurrency limit and
// the worker's outbound HTTP pool. Remember it multiplies with the number
// of concurrent batches (IngestMaxInflight).
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.
// (per-slug page write) WITHIN one batch. 0 falls back to 10. Bound by the
// same LLM concurrency / HTTP pool considerations as the Map phase, plus
// DB connection pool size. Same multiplier caveat as IngestMapParallel.
IngestReduceParallel int `yaml:"ingest_reduce_parallel" json:"ingest_reduce_parallel,omitempty"`
// IngestMaxInflight caps how many ingest batches for THIS KB may run
// concurrently in the shared wiki worker pool (standard/Redis mode
// only). 0 falls back to the hard-coded default (4). Since Phase 3
// removed the exclusive per-KB lock, one KB's backlog could otherwise
// monopolize the whole pool during a bulk import and starve other KBs;
// this knob trades a single KB's peak throughput for cross-KB fairness.
// Set it >= the wiki pool size to effectively disable the cap.
IngestMaxInflight int `yaml:"ingest_max_inflight" json:"ingest_max_inflight,omitempty"`
}
// IngestBatchSizeOrDefault returns IngestBatchSize when set (> 0),
@@ -396,6 +415,15 @@ func (c *WikiConfig) IngestReduceParallelOrDefault(fallback int) int {
return c.IngestReduceParallel
}
// IngestMaxInflightOrDefault returns IngestMaxInflight when set,
// otherwise the hard-coded fallback.
func (c *WikiConfig) IngestMaxInflightOrDefault(fallback int) int {
if c == nil || c.IngestMaxInflight <= 0 {
return fallback
}
return c.IngestMaxInflight
}
// Value implements the driver.Valuer interface
func (c WikiConfig) Value() (driver.Value, error) {
return json.Marshal(c)