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
@@ -0,0 +1,252 @@
package repository
import (
"context"
"errors"
"fmt"
"strconv"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// taskPendingOpsRepository implements interfaces.TaskPendingOpsRepository.
type taskPendingOpsRepository struct {
db *gorm.DB
}
// NewTaskPendingOpsRepository constructs a GORM-backed implementation.
func NewTaskPendingOpsRepository(db *gorm.DB) interfaces.TaskPendingOpsRepository {
return &taskPendingOpsRepository{db: db}
}
// Enqueue inserts a single op. Callers must populate TenantID/TaskType/
// Scope/ScopeID/Op (Payload optional). ID, FailCount default to zero;
// EnqueuedAt is filled with the DB-side default if left zero.
func (r *taskPendingOpsRepository) Enqueue(ctx context.Context, op *types.TaskPendingOp) error {
if op == nil {
return errors.New("task pending ops: nil op")
}
if op.TaskType == "" || op.Scope == "" || op.ScopeID == "" {
return errors.New("task pending ops: task_type, scope, scope_id are required")
}
if op.Op == "" {
return errors.New("task pending ops: op is required")
}
if len(op.Payload) == 0 {
// Make sure the JSONB column never sees NULL — the schema sets a
// default but explicit "{}" keeps the row uniform regardless of
// driver-level default handling.
op.Payload = []byte("{}")
}
return r.db.WithContext(ctx).Create(op).Error
}
// PeekBatch returns up to `limit` rows for the (task_type, scope, scope_id)
// tuple ordered by id ASC. Rows are not removed; callers must
// DeleteByIDs once they have been consumed (or IncrFailCount and leave
// them for the next pass). `limit` <= 0 falls back to 1; we clamp the
// upper bound generously so callers can pull large windows when they
// know the consumer can handle them.
func (r *taskPendingOpsRepository) PeekBatch(
ctx context.Context,
taskType, scope, scopeID string,
limit int,
) ([]*types.TaskPendingOp, error) {
if limit <= 0 {
limit = 1
}
if limit > 1000 {
limit = 1000
}
var ops []*types.TaskPendingOp
if err := r.db.WithContext(ctx).
Where("task_type = ? AND scope = ? AND scope_id = ?", taskType, scope, scopeID).
Order("id ASC").
Limit(limit).
Find(&ops).Error; err != nil {
return nil, err
}
return ops, nil
}
// DeleteByIDs removes the given rows in one statement. Empty input is a
// no-op so the caller can invoke unconditionally at the end of a batch.
func (r *taskPendingOpsRepository) DeleteByIDs(ctx context.Context, ids []int64) error {
if len(ids) == 0 {
return nil
}
return r.db.WithContext(ctx).
Where("id IN ?", ids).
Delete(&types.TaskPendingOp{}).Error
}
// IncrFailCount atomically bumps fail_count for one row and returns the
// new value. We use UPDATE ... RETURNING so the read+write happens in
// one round trip and races between concurrent IncrFailCount callers
// resolve to monotonic counts.
//
// A missing row returns (0, nil): the caller's ID may have been removed
// by a concurrent DeleteByIDs (e.g. dead-letter path), which is benign.
func (r *taskPendingOpsRepository) IncrFailCount(ctx context.Context, id int64) (int, error) {
var newCount int
err := r.db.WithContext(ctx).Raw(
`UPDATE task_pending_ops SET fail_count = fail_count + 1 WHERE id = ? RETURNING fail_count`,
id,
).Scan(&newCount).Error
if err != nil {
return 0, err
}
return newCount, nil
}
// PendingCount returns how many rows are currently queued for the
// tuple. Covered by idx_task_pending_ops_scope.
func (r *taskPendingOpsRepository) PendingCount(
ctx context.Context,
taskType, scope, scopeID string,
) (int64, error) {
var n int64
if err := r.db.WithContext(ctx).
Model(&types.TaskPendingOp{}).
Where("task_type = ? AND scope = ? AND scope_id = ?", taskType, scope, scopeID).
Count(&n).Error; err != nil {
return 0, err
}
return n, nil
}
// DeleteByDedupKey drops rows in the tuple whose dedup_key matches.
// If `op` is non-empty, only rows with the matching op are dropped;
// otherwise every matching row is removed. Empty dedup_key is rejected
// to prevent accidentally wiping the entire queue for a KB.
//
// Used by:
// - Wiki delete path: scrub queued WikiOpIngest entries for a
// knowledge that is being deleted, while preserving WikiOpRetract
// so the cleanup can still unlink pages.
// - Wiki reparse path: same scrub of pending ingests so the new
// parse can repopulate cleanly.
func (r *taskPendingOpsRepository) DeleteByDedupKey(
ctx context.Context,
taskType, scope, scopeID, dedupKey, op string,
) error {
if dedupKey == "" {
return fmt.Errorf("task pending ops: empty dedup_key in DeleteByDedupKey")
}
q := r.db.WithContext(ctx).
Where("task_type = ? AND scope = ? AND scope_id = ? AND dedup_key = ?",
taskType, scope, scopeID, dedupKey)
if op != "" {
q = q.Where("op = ?", op)
}
return q.Delete(&types.TaskPendingOp{}).Error
}
// taskDeadLetterRepository implements interfaces.TaskDeadLetterRepository.
type taskDeadLetterRepository struct {
db *gorm.DB
}
// NewTaskDeadLetterRepository constructs a GORM-backed implementation.
func NewTaskDeadLetterRepository(db *gorm.DB) interfaces.TaskDeadLetterRepository {
return &taskDeadLetterRepository{db: db}
}
// Insert records one dead letter. Best-effort caller: the asynq
// middleware swallows the error so a failed insert never masks the
// underlying task error.
func (r *taskDeadLetterRepository) Insert(ctx context.Context, dl *types.TaskDeadLetter) error {
if dl == nil {
return errors.New("task dead letters: nil entry")
}
if dl.TaskType == "" {
return errors.New("task dead letters: task_type is required")
}
if dl.Scope == "" {
dl.Scope = types.TaskScopeUnknown
}
if len(dl.Payload) == 0 {
dl.Payload = []byte("{}")
}
return r.db.WithContext(ctx).Create(dl).Error
}
// ListByScope returns dead letters for (scope, scope_id) newest-first
// with a stringified id cursor. `limit` is clamped to [1, 200]. Empty
// nextCursor signals the tail.
func (r *taskDeadLetterRepository) ListByScope(
ctx context.Context,
scope, scopeID, cursor string,
limit int,
) ([]*types.TaskDeadLetter, string, error) {
if scope == "" || scopeID == "" {
return nil, "", errors.New("task dead letters: scope and scope_id are required")
}
return r.list(ctx, cursor, limit, func(q *gorm.DB) *gorm.DB {
return q.Where("scope = ? AND scope_id = ?", scope, scopeID)
})
}
// ListByTaskType returns dead letters for the given task_type
// newest-first with a stringified id cursor. Same clamping rules.
func (r *taskDeadLetterRepository) ListByTaskType(
ctx context.Context,
taskType, cursor string,
limit int,
) ([]*types.TaskDeadLetter, string, error) {
if taskType == "" {
return nil, "", errors.New("task dead letters: task_type is required")
}
return r.list(ctx, cursor, limit, func(q *gorm.DB) *gorm.DB {
return q.Where("task_type = ?", taskType)
})
}
// list is the shared cursor pagination implementation, parametrized by
// the caller-supplied filter. Mirrors wikiLogEntryRepository.List.
func (r *taskDeadLetterRepository) list(
ctx context.Context,
cursor string,
limit int,
filter func(*gorm.DB) *gorm.DB,
) ([]*types.TaskDeadLetter, string, error) {
if limit <= 0 {
limit = 50
}
if limit > 200 {
limit = 200
}
q := r.db.WithContext(ctx).Order("id DESC").Limit(limit)
q = filter(q)
if cursor != "" {
cursorID, err := strconv.ParseInt(cursor, 10, 64)
if err != nil {
return nil, "", fmt.Errorf("invalid cursor %q: %w", cursor, err)
}
q = q.Where("id < ?", cursorID)
}
var rows []*types.TaskDeadLetter
if err := q.Find(&rows).Error; err != nil {
return nil, "", err
}
nextCursor := ""
if len(rows) == limit {
nextCursor = strconv.FormatInt(rows[len(rows)-1].ID, 10)
}
return rows, nextCursor, nil
}
// DeleteByID drops a single dead letter row. Returns nil even if the
// row is already gone — operators issuing concurrent deletes shouldn't
// see spurious errors.
func (r *taskDeadLetterRepository) DeleteByID(ctx context.Context, id int64) error {
return r.db.WithContext(ctx).
Where("id = ?", id).
Delete(&types.TaskDeadLetter{}).Error
}
@@ -0,0 +1,422 @@
package repository
import (
"context"
"encoding/json"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// taskPendingOpsTestDDL mirrors the production schema in
// migrations/versioned/000041_task_queue_and_wiki_indexes.up.sql but uses
// SQLite-compatible types. INTEGER PRIMARY KEY AUTOINCREMENT preserves
// the monotonically-increasing ID semantics PeekBatch/cursor pagination
// rely on. JSONB → TEXT is fine since GORM round-trips json.RawMessage
// as bytes either way.
const taskPendingOpsTestDDL = `
CREATE TABLE IF NOT EXISTS task_pending_ops (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tenant_id INTEGER NOT NULL,
task_type VARCHAR(64) NOT NULL,
scope VARCHAR(32) NOT NULL,
scope_id VARCHAR(64) NOT NULL,
op VARCHAR(32) NOT NULL,
dedup_key VARCHAR(128) NOT NULL DEFAULT '',
payload TEXT NOT NULL DEFAULT '{}',
fail_count INTEGER NOT NULL DEFAULT 0,
enqueued_at DATETIME DEFAULT CURRENT_TIMESTAMP,
claimed_at DATETIME
);
`
const taskDeadLettersTestDDL = `
CREATE TABLE IF NOT EXISTS task_dead_letters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tenant_id INTEGER NOT NULL,
task_type VARCHAR(64) NOT NULL,
scope VARCHAR(32) NOT NULL,
scope_id VARCHAR(64) NOT NULL,
related_id VARCHAR(64) NOT NULL DEFAULT '',
payload TEXT NOT NULL,
last_error TEXT NOT NULL DEFAULT '',
fail_count INTEGER NOT NULL,
failed_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
`
func setupTaskQueueTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.Exec(taskPendingOpsTestDDL).Error)
require.NoError(t, db.Exec(taskDeadLettersTestDDL).Error)
return db
}
func makePendingOp(taskType, scope, scopeID, op, dedup string, payload []byte) *types.TaskPendingOp {
return &types.TaskPendingOp{
TenantID: 1,
TaskType: taskType,
Scope: scope,
ScopeID: scopeID,
Op: op,
DedupKey: dedup,
Payload: payload,
}
}
// ---------------- TaskPendingOpsRepository ----------------
// TestTaskPendingOps_Enqueue_AssignsIDAndDefaults verifies a freshly
// inserted op gets a positive ID and the empty payload becomes "{}"
// rather than NULL/empty.
func TestTaskPendingOps_Enqueue_AssignsIDAndDefaults(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskPendingOpsRepository(db)
ctx := context.Background()
op := makePendingOp("wiki:ingest", "knowledge_base", "kb-1", "ingest", "k-1", nil)
require.NoError(t, repo.Enqueue(ctx, op))
assert.NotZero(t, op.ID)
assert.Equal(t, json.RawMessage("{}"), op.Payload, "nil payload should default to {}")
}
// TestTaskPendingOps_Enqueue_RejectsMissingFields covers the validation
// layer: every required field must be set, otherwise the call returns an
// error WITHOUT touching the DB.
func TestTaskPendingOps_Enqueue_RejectsMissingFields(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskPendingOpsRepository(db)
ctx := context.Background()
cases := []struct {
name string
op *types.TaskPendingOp
}{
{"nil op", nil},
{"missing task_type", makePendingOp("", "knowledge_base", "kb", "ingest", "", nil)},
{"missing scope", makePendingOp("t", "", "kb", "ingest", "", nil)},
{"missing scope_id", makePendingOp("t", "s", "", "ingest", "", nil)},
{"missing op", makePendingOp("t", "s", "id", "", "", nil)},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
err := repo.Enqueue(ctx, c.op)
assert.Error(t, err)
})
}
var n int64
db.Table("task_pending_ops").Count(&n)
assert.Equal(t, int64(0), n)
}
// TestTaskPendingOps_PeekBatch_ScopedAndOrdered verifies PeekBatch only
// returns rows for the matching tuple, in id ASC order, and respects
// the limit.
func TestTaskPendingOps_PeekBatch_ScopedAndOrdered(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskPendingOpsRepository(db)
ctx := context.Background()
// Three ops in kb-A, two in kb-B, one in different task_type.
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb-A", "ingest", "k1", nil)))
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb-A", "retract", "k2", nil)))
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb-A", "ingest", "k3", nil)))
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb-B", "ingest", "k4", nil)))
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb-B", "ingest", "k5", nil)))
require.NoError(t, repo.Enqueue(ctx, makePendingOp("summary:gen", "knowledge_base", "kb-A", "ingest", "k6", nil)))
// Peek up to 10 from kb-A — should see exactly 3, in insertion order.
got, err := repo.PeekBatch(ctx, "wiki:ingest", "knowledge_base", "kb-A", 10)
require.NoError(t, err)
require.Len(t, got, 3)
assert.Equal(t, "k1", got[0].DedupKey)
assert.Equal(t, "k2", got[1].DedupKey)
assert.Equal(t, "k3", got[2].DedupKey)
assert.True(t, got[0].ID < got[1].ID && got[1].ID < got[2].ID, "ids should be ascending")
// Limit caps result size.
got, err = repo.PeekBatch(ctx, "wiki:ingest", "knowledge_base", "kb-A", 2)
require.NoError(t, err)
assert.Len(t, got, 2)
// Different task_type isolated.
got, err = repo.PeekBatch(ctx, "summary:gen", "knowledge_base", "kb-A", 10)
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, "k6", got[0].DedupKey)
}
// TestTaskPendingOps_DeleteByIDs_RemovesOnlyTargets verifies the
// delete-after-consume path. Empty input must be a no-op so the consumer
// can call it unconditionally.
func TestTaskPendingOps_DeleteByIDs_RemovesOnlyTargets(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskPendingOpsRepository(db)
ctx := context.Background()
a := makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "a", nil)
b := makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "b", nil)
c := makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "c", nil)
require.NoError(t, repo.Enqueue(ctx, a))
require.NoError(t, repo.Enqueue(ctx, b))
require.NoError(t, repo.Enqueue(ctx, c))
// No-op: empty slice.
require.NoError(t, repo.DeleteByIDs(ctx, nil))
require.NoError(t, repo.DeleteByIDs(ctx, []int64{}))
// Delete a + c, keep b.
require.NoError(t, repo.DeleteByIDs(ctx, []int64{a.ID, c.ID}))
got, err := repo.PeekBatch(ctx, "wiki:ingest", "knowledge_base", "kb", 10)
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, "b", got[0].DedupKey)
}
// TestTaskPendingOps_IncrFailCount_ReturnsNewValueAndPersists exercises
// the UPDATE...RETURNING flow. Successive bumps should observe monotonic
// counts.
func TestTaskPendingOps_IncrFailCount_ReturnsNewValueAndPersists(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskPendingOpsRepository(db)
ctx := context.Background()
op := makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "k", nil)
require.NoError(t, repo.Enqueue(ctx, op))
n, err := repo.IncrFailCount(ctx, op.ID)
require.NoError(t, err)
assert.Equal(t, 1, n)
n, err = repo.IncrFailCount(ctx, op.ID)
require.NoError(t, err)
assert.Equal(t, 2, n)
// Persisted value matches what was returned.
rows, err := repo.PeekBatch(ctx, "wiki:ingest", "knowledge_base", "kb", 10)
require.NoError(t, err)
require.Len(t, rows, 1)
assert.Equal(t, 2, rows[0].FailCount)
}
// TestTaskPendingOps_PendingCount_ScopedTuple confirms the count covers
// only the (task_type, scope, scope_id) tuple.
func TestTaskPendingOps_PendingCount_ScopedTuple(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskPendingOpsRepository(db)
ctx := context.Background()
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb-A", "ingest", "k1", nil)))
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb-A", "ingest", "k2", nil)))
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb-B", "ingest", "k3", nil)))
n, err := repo.PendingCount(ctx, "wiki:ingest", "knowledge_base", "kb-A")
require.NoError(t, err)
assert.Equal(t, int64(2), n)
n, err = repo.PendingCount(ctx, "wiki:ingest", "knowledge_base", "missing")
require.NoError(t, err)
assert.Equal(t, int64(0), n)
}
// TestTaskPendingOps_DeleteByDedupKey_Filters tests the wiki delete-race
// helper: matching rows go away, others survive, optional op filter
// narrows the scope, and an empty dedup_key is rejected (so a buggy
// caller can't wipe the entire queue).
func TestTaskPendingOps_DeleteByDedupKey_Filters(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskPendingOpsRepository(db)
ctx := context.Background()
// Two ingests + one retract, all keyed on knowledge "k1"; one ingest
// for unrelated "k2".
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "k1", nil)))
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "k1", nil)))
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb", "retract", "k1", nil)))
require.NoError(t, repo.Enqueue(ctx, makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "k2", nil)))
// Empty key is an error, queue unchanged.
err := repo.DeleteByDedupKey(ctx, "wiki:ingest", "knowledge_base", "kb", "", "")
assert.Error(t, err)
n, _ := repo.PendingCount(ctx, "wiki:ingest", "knowledge_base", "kb")
assert.Equal(t, int64(4), n)
// Drop only "ingest" rows for k1; retract survives.
require.NoError(t, repo.DeleteByDedupKey(ctx, "wiki:ingest", "knowledge_base", "kb", "k1", "ingest"))
rows, err := repo.PeekBatch(ctx, "wiki:ingest", "knowledge_base", "kb", 10)
require.NoError(t, err)
require.Len(t, rows, 2)
// The two survivors must be the retract for k1 and the ingest for k2.
keys := map[string]string{}
for _, r := range rows {
keys[r.Op] = r.DedupKey
}
assert.Equal(t, "k1", keys["retract"])
assert.Equal(t, "k2", keys["ingest"])
// Drop everything keyed on k1 regardless of op (empty op = wildcard).
require.NoError(t, repo.DeleteByDedupKey(ctx, "wiki:ingest", "knowledge_base", "kb", "k1", ""))
rows, err = repo.PeekBatch(ctx, "wiki:ingest", "knowledge_base", "kb", 10)
require.NoError(t, err)
require.Len(t, rows, 1)
assert.Equal(t, "k2", rows[0].DedupKey)
}
// ---------------- TaskDeadLetterRepository ----------------
func makeDeadLetter(taskType, scope, scopeID, relatedID, lastErr string) *types.TaskDeadLetter {
return &types.TaskDeadLetter{
TenantID: 1,
TaskType: taskType,
Scope: scope,
ScopeID: scopeID,
RelatedID: relatedID,
Payload: json.RawMessage(`{"x":1}`),
LastError: lastErr,
FailCount: 5,
}
}
// TestTaskDeadLetter_Insert_DefaultsAndAssignsID covers the empty-payload
// fallback and ID assignment.
func TestTaskDeadLetter_Insert_DefaultsAndAssignsID(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskDeadLetterRepository(db)
ctx := context.Background()
dl := &types.TaskDeadLetter{
TenantID: 1,
TaskType: "wiki:ingest",
ScopeID: "kb",
FailCount: 3,
// Scope intentionally empty — should default to "unknown".
// Payload intentionally nil — should default to "{}".
}
require.NoError(t, repo.Insert(ctx, dl))
assert.NotZero(t, dl.ID)
assert.Equal(t, types.TaskScopeUnknown, dl.Scope)
assert.Equal(t, json.RawMessage("{}"), dl.Payload)
}
// TestTaskDeadLetter_Insert_RejectsMissingFields verifies the guard
// against rows that would leave the table without the columns ops queries
// rely on.
func TestTaskDeadLetter_Insert_RejectsMissingFields(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskDeadLetterRepository(db)
ctx := context.Background()
assert.Error(t, repo.Insert(ctx, nil))
assert.Error(t, repo.Insert(ctx, &types.TaskDeadLetter{ScopeID: "kb"}))
var n int64
db.Table("task_dead_letters").Count(&n)
assert.Equal(t, int64(0), n)
}
// TestTaskDeadLetter_ListByScope_NewestFirstAndCursored exercises the
// cursor pagination path used by the ops console.
func TestTaskDeadLetter_ListByScope_NewestFirstAndCursored(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskDeadLetterRepository(db)
ctx := context.Background()
// Insert 5 rows for kb-A and 2 for kb-B.
for i := 0; i < 5; i++ {
require.NoError(t, repo.Insert(ctx, makeDeadLetter("wiki:ingest", "knowledge_base", "kb-A", "k", "boom")))
}
require.NoError(t, repo.Insert(ctx, makeDeadLetter("wiki:ingest", "knowledge_base", "kb-B", "k", "boom")))
require.NoError(t, repo.Insert(ctx, makeDeadLetter("wiki:ingest", "knowledge_base", "kb-B", "k", "boom")))
// First page of 2 from kb-A, newest first.
page1, cursor, err := repo.ListByScope(ctx, "knowledge_base", "kb-A", "", 2)
require.NoError(t, err)
require.Len(t, page1, 2)
assert.True(t, page1[0].ID > page1[1].ID, "newest first")
require.NotEmpty(t, cursor)
// Second page of 2.
page2, cursor, err := repo.ListByScope(ctx, "knowledge_base", "kb-A", cursor, 2)
require.NoError(t, err)
require.Len(t, page2, 2)
assert.True(t, page1[1].ID > page2[0].ID, "page2 should continue past page1")
require.NotEmpty(t, cursor)
// Last page — only 1 row left, cursor goes empty since len < limit.
page3, cursor, err := repo.ListByScope(ctx, "knowledge_base", "kb-A", cursor, 2)
require.NoError(t, err)
require.Len(t, page3, 1)
assert.Empty(t, cursor)
// kb-B is isolated.
pageB, _, err := repo.ListByScope(ctx, "knowledge_base", "kb-B", "", 10)
require.NoError(t, err)
require.Len(t, pageB, 2)
}
// TestTaskDeadLetter_ListByScope_RejectsMissingScope guards the input
// validation in the public method.
func TestTaskDeadLetter_ListByScope_RejectsMissingScope(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskDeadLetterRepository(db)
ctx := context.Background()
_, _, err := repo.ListByScope(ctx, "", "kb", "", 10)
assert.Error(t, err)
_, _, err = repo.ListByScope(ctx, "knowledge_base", "", "", 10)
assert.Error(t, err)
}
// TestTaskDeadLetter_ListByTaskType_FiltersAndPaginates is the cross-KB
// view: "all summary:generation failures" regardless of which KB they
// belong to.
func TestTaskDeadLetter_ListByTaskType_FiltersAndPaginates(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskDeadLetterRepository(db)
ctx := context.Background()
require.NoError(t, repo.Insert(ctx, makeDeadLetter("wiki:ingest", "knowledge_base", "kb-A", "k1", "")))
require.NoError(t, repo.Insert(ctx, makeDeadLetter("summary:gen", "knowledge_base", "kb-A", "k2", "")))
require.NoError(t, repo.Insert(ctx, makeDeadLetter("summary:gen", "knowledge_base", "kb-B", "k3", "")))
require.NoError(t, repo.Insert(ctx, makeDeadLetter("wiki:ingest", "knowledge_base", "kb-B", "k4", "")))
rows, _, err := repo.ListByTaskType(ctx, "summary:gen", "", 10)
require.NoError(t, err)
require.Len(t, rows, 2)
for _, r := range rows {
assert.Equal(t, "summary:gen", r.TaskType)
}
_, _, err = repo.ListByTaskType(ctx, "", "", 10)
assert.Error(t, err)
}
// TestTaskDeadLetter_DeleteByID_IsIdempotent confirms a missing row does
// not produce an error — operators triggering concurrent deletes should
// see clean success.
func TestTaskDeadLetter_DeleteByID_IsIdempotent(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskDeadLetterRepository(db)
ctx := context.Background()
dl := makeDeadLetter("wiki:ingest", "knowledge_base", "kb", "k", "")
require.NoError(t, repo.Insert(ctx, dl))
require.NoError(t, repo.DeleteByID(ctx, dl.ID))
// Second delete on the same id should silently succeed.
require.NoError(t, repo.DeleteByID(ctx, dl.ID))
// Delete of unknown id should silently succeed.
require.NoError(t, repo.DeleteByID(ctx, 99999))
rows, _, err := repo.ListByScope(ctx, "knowledge_base", "kb", "", 10)
require.NoError(t, err)
assert.Len(t, rows, 0)
}
+349 -1
View File
@@ -298,6 +298,354 @@ func (r *wikiPageRepository) ListBySourceRef(ctx context.Context, kbID string, s
return pages, nil
}
// ListSlugsBySourceRef returns just the slugs of pages that reference the
// given knowledge id. Same predicate as ListBySourceRef (both forms
// "knowledgeID" and "knowledgeID|title"), but projected down to a single
// column so the wiki ingest pipeline doesn't have to load full rows when
// it only needs a "before" set of slugs.
//
// Backed by idx_wiki_pages_source_refs (GIN jsonb_path_ops) for the
// containment branch and idx_wiki_pages_source_refs_text for the legacy
// text-LIKE branch — both added in migration 000041.
func (r *wikiPageRepository) ListSlugsBySourceRef(ctx context.Context, kbID string, sourceKnowledgeID string) ([]string, error) {
needle, err := json.Marshal([]string{sourceKnowledgeID})
if err != nil {
return nil, fmt.Errorf("marshal source ref needle: %w", err)
}
prefix, err := json.Marshal(sourceKnowledgeID + "|")
if err != nil {
return nil, fmt.Errorf("marshal source ref prefix: %w", err)
}
prefixStr := string(prefix)
if len(prefixStr) >= 2 && prefixStr[len(prefixStr)-1] == '"' {
prefixStr = prefixStr[:len(prefixStr)-1]
}
likePattern := "%" + escapeLikePattern(prefixStr) + "%"
var slugs []string
if err := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Where("knowledge_base_id = ? AND (source_refs @> ?::jsonb OR source_refs::text LIKE ?)",
kbID,
string(needle),
likePattern,
).
Pluck("slug", &slugs).Error; err != nil {
return nil, err
}
return slugs, nil
}
// ListBySlugs returns lightweight projections (slug, title, page_type,
// status, aliases, out_links) for the given slugs in one IN query.
// Used by wiki ingest's lazy fetcher path to resolve slug -> title /
// out-links during Map/Reduce without paying for a full ListAll scan.
//
// Empty input returns nil, nil. Slugs not present in the KB are silently
// dropped from the returned map (caller treats absent slugs as "no
// such page" — the same shape ListAll had via missing keys).
func (r *wikiPageRepository) ListBySlugs(
ctx context.Context,
kbID string,
slugs []string,
) (map[string]*types.WikiPageLite, error) {
if len(slugs) == 0 {
return nil, nil
}
var rows []types.WikiPageLite
if err := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Select("slug", "title", "page_type", "status", "aliases", "out_links").
Where("knowledge_base_id = ? AND slug IN ?", kbID, slugs).
Scan(&rows).Error; err != nil {
return nil, err
}
out := make(map[string]*types.WikiPageLite, len(rows))
for i := range rows {
r := rows[i]
out[r.Slug] = &r
}
return out, nil
}
// ListSummariesByKnowledgeIDs returns summary-page content keyed by the
// knowledge id that authored it. The page_type filter is applied first
// (only summary pages have content suitable for retract framing); within
// that subset we look at source_refs for either the bare knowledge id
// or the "knowledgeID|title" legacy form.
//
// Empty kids returns nil, nil. A knowledge id with no surviving summary
// page is silently absent from the result map.
//
// Used by reduceSlugUpdates' retract branch so it can frame "what did
// the now-departed sibling document contribute?" for the WikiPageModify
// LLM call without needing to keep the whole batchCtx.SummaryContent
// map in memory ahead of time.
func (r *wikiPageRepository) ListSummariesByKnowledgeIDs(
ctx context.Context,
kbID string,
kids []string,
) (map[string]string, error) {
if len(kids) == 0 {
return nil, nil
}
// Build a JSONB containment-OR with one needle per knowledge id,
// plus a single text-LIKE OR over the legacy prefix forms. The
// containment branches each get their own GIN index probe; the
// LIKE branch falls back to the text fulltext GIN.
type row struct {
Content string `gorm:"column:content"`
SourceRefs types.StringArray `gorm:"column:source_refs"`
}
q := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Select("content", "source_refs").
Where("knowledge_base_id = ? AND page_type = ? AND status <> ?",
kbID, types.WikiPageTypeSummary, types.WikiPageStatusArchived)
// Build OR clauses without using overly-clever GORM tricks: assemble
// raw SQL fragments + args. Keeping this defensive because source_refs
// patterns include user-controlled knowledge ids.
clauses := make([]string, 0, len(kids)*2)
args := make([]interface{}, 0, len(kids)*2)
for _, kid := range kids {
if kid == "" {
continue
}
needle, err := json.Marshal([]string{kid})
if err != nil {
return nil, fmt.Errorf("marshal kid needle: %w", err)
}
clauses = append(clauses, "source_refs @> ?::jsonb")
args = append(args, string(needle))
prefix, err := json.Marshal(kid + "|")
if err != nil {
return nil, fmt.Errorf("marshal kid prefix: %w", err)
}
prefixStr := string(prefix)
if len(prefixStr) >= 2 && prefixStr[len(prefixStr)-1] == '"' {
prefixStr = prefixStr[:len(prefixStr)-1]
}
clauses = append(clauses, "source_refs::text LIKE ?")
args = append(args, "%"+escapeLikePattern(prefixStr)+"%")
}
if len(clauses) == 0 {
return nil, nil
}
q = q.Where("("+strings.Join(clauses, " OR ")+")", args...)
var rows []row
if err := q.Scan(&rows).Error; err != nil {
return nil, err
}
// Map each row's content to every kid in its source_refs (a single
// summary may carry multiple sources after a previous merge / re-
// ingest). Caller looks up by kid, so duplicates resolve to the
// same content string.
kidSet := make(map[string]struct{}, len(kids))
for _, kid := range kids {
if kid != "" {
kidSet[kid] = struct{}{}
}
}
out := make(map[string]string, len(rows))
for _, r := range rows {
for _, ref := range r.SourceRefs {
refKID := ref
if pipeIdx := strings.Index(ref, "|"); pipeIdx > 0 {
refKID = ref[:pipeIdx]
}
if _, want := kidSet[refKID]; !want {
continue
}
if _, exists := out[refKID]; !exists {
out[refKID] = r.Content
}
}
}
return out, nil
}
// ExistsSlugs reports which of the given slugs are live (non-archived,
// non-deleted) in the KB. Used by cleanDeadLinks to validate out-link
// targets without loading the referenced pages' content. Slugs not
// present in the KB at all map to false; archived slugs also map to
// false so dead-link cleanup treats them as gone.
//
// Empty input returns nil, nil so callers can branch cheaply.
func (r *wikiPageRepository) ExistsSlugs(
ctx context.Context,
kbID string,
slugs []string,
) (map[string]bool, error) {
if len(slugs) == 0 {
return nil, nil
}
var live []string
if err := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Where("knowledge_base_id = ? AND slug IN ? AND status <> ?",
kbID, slugs, types.WikiPageStatusArchived).
Pluck("slug", &live).Error; err != nil {
return nil, err
}
out := make(map[string]bool, len(slugs))
for _, s := range slugs {
out[s] = false
}
for _, s := range live {
out[s] = true
}
return out, nil
}
// ListAllSlugs returns every non-archived page slug in the KB. Used by
// the lint pipeline to compute the "live slug set" for broken-link
// detection without paying for ListAll's full row materialization.
func (r *wikiPageRepository) ListAllSlugs(
ctx context.Context,
kbID string,
) ([]string, error) {
var slugs []string
if err := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Where("knowledge_base_id = ? AND status <> ?", kbID, types.WikiPageStatusArchived).
Pluck("slug", &slugs).Error; err != nil {
return nil, err
}
return slugs, nil
}
// ListPagesCursor returns up to `limit` pages for the KB ordered by
// (knowledge_base_id, id) ascending, paginated by an opaque numeric
// cursor. The cursor is the stringified id of the last row from the
// previous page; "" starts from the beginning. Empty nextCursor =
// end-of-stream.
//
// Used by lint to walk the entire KB without ever holding the full
// page set in memory. `limit` is clamped to [1, 500].
func (r *wikiPageRepository) ListPagesCursor(
ctx context.Context,
kbID string,
cursor string,
limit int,
) ([]*types.WikiPage, string, error) {
if limit <= 0 {
limit = 100
}
if limit > 500 {
limit = 500
}
q := r.db.WithContext(ctx).
Where("knowledge_base_id = ?", kbID).
Order("id ASC").
Limit(limit)
if cursor != "" {
q = q.Where("id > ?", cursor)
}
var pages []*types.WikiPage
if err := q.Find(&pages).Error; err != nil {
return nil, "", err
}
nextCursor := ""
if len(pages) == limit {
nextCursor = pages[len(pages)-1].ID
}
return pages, nextCursor, nil
}
// ListByTypeRecent returns up to `limit` summary-typed pages ordered
// by updated_at DESC, projected to slug/title/summary. Used by the
// rebuildIndexPage first-time generation path — historically that
// loaded EVERY summary page and concatenated them into the prompt,
// which broke the LLM context window once a KB grew past a few
// thousand documents. The recent-N projection caps the prompt size
// at the cost of intro framing for very old documents (which are
// unlikely to be the most-relevant index introductions anyway).
//
// `limit` is clamped to [1, 1000]; 0 falls back to 200.
func (r *wikiPageRepository) ListByTypeRecent(
ctx context.Context,
kbID string,
pageType string,
limit int,
) ([]types.WikiIndexEntry, error) {
if limit <= 0 {
limit = 200
}
if limit > 1000 {
limit = 1000
}
var entries []types.WikiIndexEntry
if err := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Select("slug", "title", "summary").
Where("knowledge_base_id = ? AND page_type = ? AND status <> ?",
kbID, pageType, types.WikiPageStatusArchived).
Order("updated_at DESC").
Limit(limit).
Scan(&entries).Error; err != nil {
return nil, err
}
return entries, nil
}
// FindSimilarPages returns the top-k entity/concept pages whose lowercase
// title is most similar to the given query under PostgreSQL pg_trgm
// trigram similarity. Backed by idx_wiki_pages_title_trgm (GIN
// gin_trgm_ops, migration 000041). Used by the dedup pre-filter to
// surface candidate merge targets without loading every entity/concept
// page into Go.
//
// types is an optional page_type allow-list; empty means entity+concept.
// limit is clamped to [1, 50]. Pages whose title similarity is below
// 0.1 are dropped server-side via the `%` operator (which respects
// pg_trgm.similarity_threshold).
func (r *wikiPageRepository) FindSimilarPages(
ctx context.Context,
kbID string,
query string,
pageTypes []string,
limit int,
) ([]*types.WikiPageLite, error) {
if strings.TrimSpace(query) == "" {
return nil, nil
}
if limit <= 0 {
limit = 20
}
if limit > 50 {
limit = 50
}
if len(pageTypes) == 0 {
pageTypes = []string{types.WikiPageTypeEntity, types.WikiPageTypeConcept}
}
q := strings.ToLower(strings.TrimSpace(query))
var rows []types.WikiPageLite
if err := r.db.Debug().WithContext(ctx).
Model(&types.WikiPage{}).
Select("slug, title, page_type, status, aliases, out_links, similarity(lower(title), ?) AS sim", q).
Where("knowledge_base_id = ? AND page_type IN ? AND status <> ? AND lower(title) % ?",
kbID, pageTypes, types.WikiPageStatusArchived, q).
Order("sim DESC").
Limit(limit).
Scan(&rows).Error; err != nil {
return nil, err
}
out := make([]*types.WikiPageLite, len(rows))
for i := range rows {
r := rows[i]
out[i] = &r
}
return out, nil
}
// ListAll retrieves all wiki pages in a knowledge base
func (r *wikiPageRepository) ListAll(ctx context.Context, kbID string) ([]*types.WikiPage, error) {
var pages []*types.WikiPage
@@ -476,7 +824,7 @@ func (r *wikiPageRepository) ListIssues(ctx context.Context, kbID string, slug s
if status != "" {
query = query.Where("status = ?", status)
}
var issues []*types.WikiPageIssue
if err := query.Order("created_at DESC").Find(&issues).Error; err != nil {
return nil, err