Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(housekeeping): scan the queues once per sweep, not once per row (#4360)

Chris Chen186c9d571cfa
diff --git a/internal/application/service/knowledge_housekeeping.go b/internal/application/service/knowledge_housekeeping.go
index 89d712c79..ef3e0f25d 100644
--- a/internal/application/service/knowledge_housekeeping.go
+++ b/internal/application/service/knowledge_housekeeping.go
@@ -67,8 +67,8 @@ type HousekeepingService struct {
queuedAt time.Time
}
-// queuedProbeTTL bounds how often QueuedWork rescans the queue; clients poll
-// far more often than a backlog changes.
+// queuedProbeTTL bounds how often QueuedWork and the sweep rescan the queue;
+// clients poll far more often than a backlog changes.
const queuedProbeTTL = time.Minute
// openSpanStatuses are the span states meaning "this span never finished".
@@ -375,17 +375,19 @@ func (h *HousekeepingService) recoverStrandedPendingSummaries(ctx context.Contex
logger.Warnf(ctx, "[Housekeeping] pending summary query failed: %v", err)
return
}
+ if len(rows) == 0 {
+ return
+ }
+ // One shared queue scan answers every row (see filterOutQueued).
+ queued, err := h.queuedSnapshot(ctx)
+ if err != nil {
+ logger.Warnf(ctx, "[Housekeeping] summary queue probe failed: %v (deferring %d row(s))", err, len(rows))
+ return
+ }
var recovered int64
for _, k := range rows {
- if h.inspector != nil {
- queued, err := h.inspector.HasQueuedTasksForKnowledge(ctx, k.ID)
- if err != nil {
- logger.Warnf(ctx, "[Housekeeping] summary queue probe failed for %s: %v (deferring)", k.ID, err)
- continue
- }
- if queued {
- continue
- }
+ if _, ok := queued[k.ID]; ok {
+ continue
}
res := h.db.WithContext(ctx).Model(&types.Knowledge{}).
Where("id = ? AND summary_status = ?", k.ID, types.SummaryStatusPending).
@@ -680,14 +682,14 @@ func (h *HousekeepingService) closeStalledSpans(
// durable per document in task_pending_ops (dedup_key = knowledge ID), while
// asynq only carries a per-KB wake-up trigger whose payload has no knowledge
// ID — and TypeWikiIngest is deliberately absent from the inspector's
-// taskTypesForKnowledgeCancel set anyway. So HasQueuedTasksForKnowledge
+// taskTypesForKnowledgeCancel set anyway. So the queue snapshot
// structurally reports "nothing queued" for a document whose only outstanding
// work is a queued Wiki ingest, and the sweep force-fails a perfectly healthy
// row. Probe the durable table directly before consulting the inspector.
//
// When no inspector is wired (nil) the durable gate still applies; only the
// transient queue check is skipped. On probe error we fail safe, but in
-// opposite directions by design: an inspector error KEEPS the candidate as
+// opposite directions by design: a queue scan error KEEPS the candidates as
// stuck (matching the span heartbeat query), whereas a durable-table error
// DEFERS every candidate to the next sweep — we cannot tell backlog from
// orphan without it, and wrongly failing a live document is not recoverable
@@ -720,6 +722,19 @@ func (h *HousekeepingService) filterOutQueued(
durable[id] = struct{}{}
}
+ // One shared queue scan answers every candidate. Under a large backlog
+ // every waiting document is a candidate, and probing per candidate walks
+ // the queues once per document, saturating Redis for hours. A nil
+ // snapshot (no inspector, or a failed scan) leaves every candidate stuck.
+ var queued map[string]struct{}
+ if len(durable) < len(candidates) {
+ var err error
+ if queued, err = h.queuedSnapshot(ctx); err != nil {
+ logger.Warnf(ctx, "[Housekeeping] %v (will fail safe and treat %d candidate(s) as stuck)",
+ err, len(candidates)-len(durable))
+ }
+ }
+
out := candidates[:0]
for _, k := range candidates {
if _, ok := durable[k.ID]; ok {
@@ -727,18 +742,7 @@ func (h *HousekeepingService) filterOutQueued(
wikiHeld = append(wikiHeld, k)
continue
}
- if h.inspector == nil {
- out = append(out, k)
- continue
- }
- queued, err := h.inspector.HasQueuedTasksForKnowledge(ctx, k.ID)
- if err != nil {
- logger.Warnf(ctx,
- "[Housekeeping] queue probe failed for %s: %v (will fail safe and treat as stuck)", k.ID, err)
- out = append(out, k)
- continue
- }
- if queued {
+ if _, ok := queued[k.ID]; ok {
skipped++
continue
}
diff --git a/internal/application/service/knowledge_housekeeping_queue_scan_test.go b/internal/application/service/knowledge_housekeeping_queue_scan_test.go
new file mode 100644
index 000000000..71bb5bbb1
--- /dev/null
+++ b/internal/application/service/knowledge_housekeeping_queue_scan_test.go
@@ -0,0 +1,107 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// queuePassCountingInspector counts every walk over the queues. Against asynq
+// a per-document probe pages through the queues until it finds the document,
+// so with a large backlog each probe costs about as much as a full scan.
+type queuePassCountingInspector struct {
+ countingTaskInspector
+ probes int
+}
+
+func (f *queuePassCountingInspector) HasQueuedTasksForKnowledge(
+ _ context.Context, knowledgeID string,
+) (bool, error) {
+ f.probes++
+ if f.err != nil {
+ return false, f.err
+ }
+ return f.queued[knowledgeID], nil
+}
+
+func (f *queuePassCountingInspector) passes() int { return f.scans + f.probes }
+
+// Under a large import every document waiting for enrichment goes stale at
+// once. Probing the queues per document made one sweep cost candidates ×
+// queue length and kept Redis saturated for hours; a sweep must walk the
+// queues at most once however many rows it checks.
+func TestHousekeeping_SweepScansQueuesOnce(t *testing.T) {
+ db := setupHousekeepingDB(t)
+ inspector := &queuePassCountingInspector{}
+ inspector.queued = map[string]bool{}
+ svc := newHousekeepingSvcWithInspector(db, inspector)
+ stale := time.Now().Add(-3 * time.Hour)
+
+ const rows = 20
+ for i := 0; i < rows; i++ {
+ backlogged := fmt.Sprintf("k-backlogged-%d", i)
+ insertKnowledge(t, db, backlogged, types.ParseStatusFinalizing, stale)
+ inspector.queued[backlogged] = true
+ insertKnowledge(t, db, fmt.Sprintf("k-orphan-%d", i), types.ParseStatusProcessing, stale)
+
+ queuedSummary := fmt.Sprintf("k-summary-queued-%d", i)
+ insertKnowledgeWithSummary(t, db, queuedSummary,
+ types.ParseStatusCompleted, types.SummaryStatusPending, stale)
+ inspector.queued[queuedSummary] = true
+ insertKnowledgeWithSummary(t, db, fmt.Sprintf("k-summary-lost-%d", i),
+ types.ParseStatusCompleted, types.SummaryStatusPending, stale)
+ }
+
+ svc.runSweep(context.Background())
+
+ assert.LessOrEqual(t, inspector.passes(), 1,
+ "one sweep walks the queues at most once (scans=%d, per-row probes=%d)",
+ inspector.scans, inspector.probes)
+ for i := 0; i < rows; i++ {
+ status, _ := readKnowledgeStatus(t, db, fmt.Sprintf("k-backlogged-%d", i))
+ assert.Equal(t, types.ParseStatusFinalizing, status, "backlogged row %d", i)
+ status, _ = readKnowledgeStatus(t, db, fmt.Sprintf("k-orphan-%d", i))
+ assert.Equal(t, types.ParseStatusFailed, status, "orphaned row %d", i)
+ assert.Equal(t, types.SummaryStatusPending,
+ readSummaryStatus(t, db, fmt.Sprintf("k-summary-queued-%d", i)), "queued summary %d", i)
+ assert.Equal(t, types.SummaryStatusFailed,
+ readSummaryStatus(t, db, fmt.Sprintf("k-summary-lost-%d", i)), "lost summary %d", i)
+ }
+}
+
+// When the queue scan fails, Sweep A keeps treating its candidates as stuck
+// (TestHousekeeping_QueueProbeError_FailsSafe), but a pending summary is only
+// a spinner and waits for the next sweep instead of being failed blind.
+func TestHousekeeping_QueueScanErrorDefersStrandedSummaries(t *testing.T) {
+ db := setupHousekeepingDB(t)
+ svc := newHousekeepingSvcWithInspector(db, fakeTaskInspector{err: errors.New("redis unavailable")})
+ stale := time.Now().Add(-2 * time.Hour)
+ insertKnowledgeWithSummary(t, db, "k-summary", types.ParseStatusCompleted, types.SummaryStatusPending, stale)
+
+ svc.recoverStrandedPendingSummaries(context.Background(), time.Now().Add(-time.Hour))
+
+ assert.Equal(t, types.SummaryStatusPending, readSummaryStatus(t, db, "k-summary"))
+}
+
+// The sweep must not walk the queues when it has nothing to check: no stale
+// row, or only rows the durable Wiki table already holds.
+func TestHousekeeping_NoQueueScanWithoutCandidates(t *testing.T) {
+ db := setupHousekeepingDB(t)
+ inspector := &queuePassCountingInspector{}
+ svc := newHousekeepingSvcWithInspector(db, inspector)
+ insertKnowledge(t, db, "k-fresh", types.ParseStatusProcessing, time.Now())
+ insertKnowledge(t, db, "k-wiki", types.ParseStatusFinalizing, time.Now().Add(-3*time.Hour))
+ insertWikiPendingOp(t, db, "kb-1", "k-wiki")
+
+ svc.runSweep(context.Background())
+
+ require.Zero(t, inspector.passes())
+ status, _ := readKnowledgeStatus(t, db, "k-wiki")
+ assert.Equal(t, types.ParseStatusFinalizing, status)
+}
diff --git a/internal/router/task_inspector.go b/internal/router/task_inspector.go
index 633747cde..deef569c4 100644
--- a/internal/router/task_inspector.go
+++ b/internal/router/task_inspector.go
@@ -183,9 +183,10 @@ func matchesKnowledgeListDelete(taskType string, payload []byte, knowledgeID str
// HasQueuedTasksForKnowledge reports whether any pending / scheduled /
// retry / active task referencing knowledgeID still lives in the queue.
-// Read-only counterpart of CancelTasksForKnowledge — the housekeeping
-// sweep uses it to avoid flagging a backlogged-but-not-orphaned row as
-// failed. Short-circuits on the first match and never deletes anything.
+// Read-only counterpart of CancelTasksForKnowledge. Short-circuits on the
+// first match and never deletes anything, but each call pages through the
+// queues from the start: to check many documents (e.g. the housekeeping
+// sweep), use QueuedKnowledgeIDs instead.
func (a *asynqTaskInspector) HasQueuedTasksForKnowledge(
ctx context.Context, knowledgeID string,
) (bool, error) {
diff --git a/internal/types/interfaces/task_inspector.go b/internal/types/interfaces/task_inspector.go
index 20f5fdf1d..820589126 100644
--- a/internal/types/interfaces/task_inspector.go
+++ b/internal/types/interfaces/task_inspector.go
@@ -31,11 +31,10 @@ type TaskInspector interface {
// HasQueuedTasksForKnowledge reports whether any pending / scheduled
// / retry / active task referencing the given knowledge ID still
// lives in the queue backend. It is the read-only counterpart of
- // CancelTasksForKnowledge: the housekeeping sweep calls it before
- // flipping a long-idle "processing"/"finalizing" row to "failed" so
- // it can tell a genuinely orphaned row (no task anywhere) from one
- // whose enrichment subtasks are merely backlogged behind a busy
- // queue (no span heartbeat yet because no worker has picked them up).
+ // CancelTasksForKnowledge: it tells a genuinely orphaned row (no task
+ // anywhere) from one whose enrichment subtasks are merely backlogged
+ // behind a busy queue (no span heartbeat yet because no worker has
+ // picked them up).
//
// Best-effort and short-circuiting: it returns true as soon as the
// first match is seen. On backend error it returns (false, err);