Files
Enterprise-Knowledge-Base/internal/middleware/asynqdl/asynqdl_test.go
T
wizardchen 04e8105728 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.
2026-05-10 00:01:06 +08:00

229 lines
6.7 KiB
Go

package asynqdl
import (
"context"
"encoding/json"
"errors"
"sync"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/hibiken/asynq"
)
// fakeRepo records calls to Insert in memory so tests can assert how
// many dead-letter rows would have been written. It implements only
// the subset of TaskDeadLetterRepository the middleware uses; the
// Lister methods are unused in the middleware path.
type fakeRepo struct {
mu sync.Mutex
rows []*types.TaskDeadLetter
fail error
}
func (f *fakeRepo) Insert(ctx context.Context, dl *types.TaskDeadLetter) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.fail != nil {
return f.fail
}
cp := *dl // defensive copy: callers may reuse the struct
f.rows = append(f.rows, &cp)
return nil
}
func (f *fakeRepo) ListByScope(context.Context, string, string, string, int) ([]*types.TaskDeadLetter, string, error) {
return nil, "", nil
}
func (f *fakeRepo) ListByTaskType(context.Context, string, string, int) ([]*types.TaskDeadLetter, string, error) {
return nil, "", nil
}
func (f *fakeRepo) DeleteByID(context.Context, int64) error { return nil }
// captureRow returns the i'th row safely under the lock.
func (f *fakeRepo) captureRow(i int) *types.TaskDeadLetter {
f.mu.Lock()
defer f.mu.Unlock()
if i >= len(f.rows) {
return nil
}
return f.rows[i]
}
func (f *fakeRepo) rowCount() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.rows)
}
// runMiddleware wires up the middleware around a handler that always
// returns handlerErr. We invoke it directly (no asynq server) so retry
// counters come from the helper-injected ctx values; isFinalAttempt
// treats a missing pair as "final" for testability.
func runMiddleware(repo *fakeRepo, taskType string, payload []byte, handlerErr error) error {
mw := Middleware(repo)
wrapped := mw(asynq.HandlerFunc(func(_ context.Context, _ *asynq.Task) error {
return handlerErr
}))
t := asynq.NewTask(taskType, payload)
return wrapped.ProcessTask(context.Background(), t)
}
func TestMiddleware_NilHandlerErr_NoInsert(t *testing.T) {
repo := &fakeRepo{}
if err := runMiddleware(repo, "any:task", []byte(`{"tenant_id":1}`), nil); err != nil {
t.Fatalf("expected nil error, got %v", err)
}
if got := repo.rowCount(); got != 0 {
t.Fatalf("expected zero inserts on success, got %d", got)
}
}
func TestMiddleware_FailureWithoutAsynqCtx_RecordsRow(t *testing.T) {
repo := &fakeRepo{}
payload, _ := json.Marshal(map[string]any{
"tenant_id": 42,
"knowledge_base_id": "kb-abc",
"knowledge_id": "k-1",
})
wantErr := errors.New("boom")
gotErr := runMiddleware(repo, "wiki:ingest", payload, wantErr)
if !errors.Is(gotErr, wantErr) {
t.Fatalf("expected the original task error to propagate, got %v", gotErr)
}
if got := repo.rowCount(); got != 1 {
t.Fatalf("expected exactly one insert, got %d", got)
}
row := repo.captureRow(0)
if row.TaskType != "wiki:ingest" {
t.Errorf("task_type: got %q", row.TaskType)
}
if row.TenantID != 42 {
t.Errorf("tenant_id: got %d", row.TenantID)
}
if row.Scope != types.TaskScopeKnowledgeBase || row.ScopeID != "kb-abc" {
t.Errorf("scope tuple: got (%q, %q)", row.Scope, row.ScopeID)
}
if row.RelatedID != "k-1" {
t.Errorf("related_id: got %q", row.RelatedID)
}
if row.LastError != "boom" {
t.Errorf("last_error: got %q", row.LastError)
}
}
func TestMiddleware_UnknownPayload_StillRecords(t *testing.T) {
repo := &fakeRepo{}
// Payload that doesn't carry any of the well-known identifier keys.
payload := []byte(`{"some_unrelated":"value"}`)
_ = runMiddleware(repo, "future:weird", payload, errors.New("nope"))
if got := repo.rowCount(); got != 1 {
t.Fatalf("expected one insert for unknown payload, got %d", got)
}
row := repo.captureRow(0)
if row.Scope != types.TaskScopeUnknown {
t.Errorf("expected scope=unknown for unparseable payload, got %q", row.Scope)
}
if row.ScopeID != "" {
t.Errorf("expected empty scope_id for unknown scope, got %q", row.ScopeID)
}
if string(row.Payload) != string(payload) {
t.Errorf("expected payload preserved verbatim, got %s", string(row.Payload))
}
}
func TestMiddleware_NilPayload_DefaultsToEmptyObject(t *testing.T) {
repo := &fakeRepo{}
_ = runMiddleware(repo, "any:task", nil, errors.New("err"))
row := repo.captureRow(0)
if row == nil {
t.Fatal("expected a row")
}
if string(row.Payload) != "{}" {
t.Errorf("expected payload normalized to {}, got %s", string(row.Payload))
}
}
func TestMiddleware_LongErrorTruncated(t *testing.T) {
repo := &fakeRepo{}
long := make([]byte, 16384)
for i := range long {
long[i] = 'x'
}
_ = runMiddleware(repo, "any", []byte("{}"), errors.New(string(long)))
row := repo.captureRow(0)
if got := len(row.LastError); got > 8192 {
t.Errorf("expected last_error truncated to <=8192 bytes, got %d", got)
}
const suffix = "...(truncated)"
if got := row.LastError[len(row.LastError)-len(suffix):]; got != suffix {
t.Errorf("expected truncation suffix %q, got %q", suffix, got)
}
}
func TestMiddleware_RepoFailure_DoesNotMaskTaskError(t *testing.T) {
repo := &fakeRepo{fail: errors.New("db down")}
wantErr := errors.New("task boom")
gotErr := runMiddleware(repo, "any", []byte(`{"tenant_id":1}`), wantErr)
if !errors.Is(gotErr, wantErr) {
t.Fatalf("repo failure must not mask task error; got %v", gotErr)
}
}
func TestInferScope_Priority(t *testing.T) {
tests := []struct {
name string
probe payloadProbe
wantScope string
wantID string
}{
{
name: "knowledge_base_id wins over knowledge_id",
probe: payloadProbe{KnowledgeBaseID: "kb1", KnowledgeID: "k1"},
wantScope: types.TaskScopeKnowledgeBase,
wantID: "kb1",
},
{
name: "kb_id alias resolves to knowledge_base scope",
probe: payloadProbe{KBID: "kb-faq"},
wantScope: types.TaskScopeKnowledgeBase,
wantID: "kb-faq",
},
{
name: "source_kb_id from KnowledgeMovePayload",
probe: payloadProbe{SourceKBID: "src-kb", TargetKBID: "tgt-kb"},
wantScope: types.TaskScopeKnowledgeBase,
wantID: "src-kb",
},
{
name: "knowledge_id only",
probe: payloadProbe{KnowledgeID: "k-only"},
wantScope: types.TaskScopeKnowledge,
wantID: "k-only",
},
{
name: "tenant_id fallback",
probe: payloadProbe{TenantID: 7},
wantScope: types.TaskScopeTenant,
wantID: "7",
},
{
name: "no identifiers — unknown scope",
probe: payloadProbe{},
wantScope: types.TaskScopeUnknown,
wantID: "",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
gotScope, gotID := inferScope(tc.probe)
if gotScope != tc.wantScope || gotID != tc.wantID {
t.Errorf("inferScope: got (%q, %q), want (%q, %q)",
gotScope, gotID, tc.wantScope, tc.wantID)
}
})
}
}