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(queue): order ClaimBatch by fail_count so retries cannot starve new work (#3444)

Fuzzycorrect13d0b9f94a7e
diff --git a/internal/application/repository/task_queue.go b/internal/application/repository/task_queue.go
index 63df64113..21a47f04c 100644
--- a/internal/application/repository/task_queue.go
+++ b/internal/application/repository/task_queue.go
@@ -158,11 +158,17 @@ func (r *taskPendingOpsRepository) SeedKnowledgeFinalizingWithPendingOp(
}
// 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.
+// tuple ordered least-failed first, oldest first within the same
+// fail_count. 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.
+//
+// The fail_count-then-id order matches ClaimBatch: a retried row keeps
+// its original id, so a pure id sort lets it starve never-attempted
+// work. When every row still has fail_count = 0 this is exactly the
+// previous FIFO.
func (r *taskPendingOpsRepository) PeekBatch(
ctx context.Context,
taskType, scope, scopeID string,
@@ -177,7 +183,7 @@ func (r *taskPendingOpsRepository) PeekBatch(
var ops []*types.TaskPendingOp
if err := r.db.WithContext(ctx).
Where("task_type = ? AND scope = ? AND scope_id = ?", taskType, scope, scopeID).
- Order("id ASC").
+ Order("fail_count ASC, id ASC").
Limit(limit).
Find(&ops).Error; err != nil {
return nil, err
@@ -206,12 +212,13 @@ func (r *taskPendingOpsRepository) PeekBatch(
// (claimed_at < staleBefore), AND the key has no fresh claim. The whole thing
// runs in one transaction:
//
-// - Postgres: we lock the ANCHOR row (earliest eligible id) of each
-// candidate dedup_key with FOR UPDATE SKIP LOCKED. Because the anchor
-// uniquely represents its key, SKIP LOCKED hands concurrent claimers
-// DISJOINT key sets — a key whose anchor is already locked by another
-// in-flight claim is skipped entirely rather than half-claimed. We then
-// stamp every eligible row of the chosen keys and read them back.
+// - Postgres: we lock the ANCHOR row (least-failed, then earliest
+// eligible id) of each candidate dedup_key with FOR UPDATE SKIP
+// LOCKED. Because the anchor uniquely represents its key, SKIP LOCKED
+// hands concurrent claimers DISJOINT key sets — a key whose anchor is
+// already locked by another in-flight claim is skipped entirely rather
+// than half-claimed. We then stamp every eligible row of the chosen
+// keys and read them back.
// - Other dialects (SQLite, used by unit tests / Lite mode): writes are
// serialized by the single-writer engine, so a plain grouped SELECT +
// UPDATE is already race-free.
@@ -234,20 +241,26 @@ func (r *taskPendingOpsRepository) ClaimBatch(
now := time.Now()
var claimed []*types.TaskPendingOp
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- // 1. Pick up to `limit` distinct dedup_keys to claim, oldest first.
+ // 1. Pick up to `limit` distinct dedup_keys to claim: least-failed
+ // first, oldest first within the same fail_count. A failed op keeps
+ // its original id AND its original position, so ordering purely by
+ // id lets a repeatedly-retried head block every never-attempted
+ // sibling behind it until its own retry budget runs out — the queue
+ // drains a handful of stuck documents while the backlog starves.
// Keys with a fresh claim are excluded WHOLESALE so a late sibling
// of an in-flight document never gets claimed on its own.
var keys []string
if tx.Dialector.Name() == "postgres" {
- // Lock the anchor (earliest eligible) row of each key with SKIP
- // LOCKED so concurrent claimers get disjoint KEY sets, then map
- // the locked anchors back to their dedup_keys. The NOT IN subquery
- // drops any key that still has a fresh (non-stale) claim.
+ // Lock the anchor (least-failed, earliest eligible) row of each
+ // key with SKIP LOCKED so concurrent claimers get disjoint KEY
+ // sets, then map the locked anchors back to their dedup_keys. The
+ // NOT IN subquery drops any key that still has a fresh (non-stale)
+ // claim.
const anchorSQL = `
SELECT dedup_key FROM task_pending_ops
WHERE id IN (
SELECT id FROM (
- SELECT id, ROW_NUMBER() OVER (PARTITION BY dedup_key ORDER BY id) AS rn
+ SELECT id, ROW_NUMBER() OVER (PARTITION BY dedup_key ORDER BY fail_count ASC, id ASC) AS rn
FROM task_pending_ops
WHERE task_type = ? AND scope = ? AND scope_id = ?
AND (claimed_at IS NULL OR claimed_at < ?)
@@ -258,7 +271,7 @@ WHERE id IN (
)
) anchors WHERE anchors.rn = 1
)
-ORDER BY id ASC
+ORDER BY fail_count ASC, id ASC
LIMIT ?
FOR UPDATE SKIP LOCKED`
if err := tx.Raw(anchorSQL,
@@ -278,7 +291,7 @@ FOR UPDATE SKIP LOCKED`
Where("(claimed_at IS NULL OR claimed_at < ?)", staleBefore).
Where("dedup_key NOT IN (?)", freshKeys).
Group("dedup_key").
- Order("MIN(id) ASC").
+ Order("MIN(fail_count) ASC, MIN(id) ASC").
Limit(limit).
Pluck("dedup_key", &keys).Error; err != nil {
return err
diff --git a/internal/application/repository/task_queue_test.go b/internal/application/repository/task_queue_test.go
index 7d78ce7bb..539bfd818 100644
--- a/internal/application/repository/task_queue_test.go
+++ b/internal/application/repository/task_queue_test.go
@@ -236,8 +236,9 @@ func TestTaskPendingOps_Enqueue_RejectsMissingFields(t *testing.T) {
}
// TestTaskPendingOps_PeekBatch_ScopedAndOrdered verifies PeekBatch only
-// returns rows for the matching tuple, in id ASC order, and respects
-// the limit.
+// returns rows for the matching tuple, least-failed then id ASC (which
+// is insertion order when every row is still fail_count = 0), and
+// respects the limit.
func TestTaskPendingOps_PeekBatch_ScopedAndOrdered(t *testing.T) {
db := setupTaskQueueTestDB(t)
repo := NewTaskPendingOpsRepository(db)
@@ -272,6 +273,37 @@ func TestTaskPendingOps_PeekBatch_ScopedAndOrdered(t *testing.T) {
assert.Equal(t, "k6", got[0].DedupKey)
}
+// TestTaskPendingOps_PeekBatch_PrefersLeastFailed is the Lite-mode twin
+// of TestTaskPendingOps_ClaimBatch_PrefersLeastFailed: peekPendingList
+// still uses PeekBatch, and a retried row keeps its original (lowest)
+// id, so a pure id sort would starve never-attempted work the same way.
+func TestTaskPendingOps_PeekBatch_PrefersLeastFailed(t *testing.T) {
+ db := setupTaskQueueTestDB(t)
+ repo := NewTaskPendingOpsRepository(db)
+ ctx := context.Background()
+
+ hot := makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "hot", nil)
+ require.NoError(t, repo.Enqueue(ctx, hot))
+ require.NoError(t, repo.Enqueue(ctx,
+ makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "fresh", nil)))
+
+ _, err := repo.IncrFailCount(ctx, hot.ID)
+ require.NoError(t, err)
+
+ next, err := repo.PeekBatch(ctx, "wiki:ingest", "knowledge_base", "kb", 1)
+ require.NoError(t, err)
+ require.Len(t, next, 1)
+ assert.Equal(t, "fresh", next[0].DedupKey,
+ "a retried document must not starve a never-attempted one")
+
+ both, err := repo.PeekBatch(ctx, "wiki:ingest", "knowledge_base", "kb", 2)
+ require.NoError(t, err)
+ require.Len(t, both, 2)
+ assert.Equal(t, "fresh", both[0].DedupKey)
+ assert.Equal(t, "hot", both[1].DedupKey,
+ "a retried document must still be returned after untried work")
+}
+
// TestTaskPendingOps_DeleteByIDs_RemovesOnlyTargets verifies the
// delete-after-consume path. Empty input must be a no-op so the consumer
// can call it unconditionally.
@@ -531,6 +563,53 @@ func TestTaskPendingOps_ClaimBatch_MarksAndReturnsDisjoint(t *testing.T) {
assert.Len(t, third, 0)
}
+// TestTaskPendingOps_ClaimBatch_PrefersLeastFailed guards the starvation fix.
+// A retried document keeps its ORIGINAL id — requeueFailedOps releases the
+// claim rather than moving the row, so the fail_count budget keeps counting
+// down — which under a pure `id ASC` ordering let it park at the head of the
+// queue while never-attempted documents sat behind it. Observed on a real
+// 87-document KB: four re-run documents held the head and all forty
+// never-started ones waited. Selection must drain untried work first, without
+// stranding a document that keeps failing.
+func TestTaskPendingOps_ClaimBatch_PrefersLeastFailed(t *testing.T) {
+ db := setupTaskQueueTestDB(t)
+ repo := NewTaskPendingOpsRepository(db)
+ ctx := context.Background()
+
+ // "hot" is enqueued FIRST, so it owns the lowest id.
+ require.NoError(t, repo.Enqueue(ctx,
+ makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "hot", nil)))
+ require.NoError(t, repo.Enqueue(ctx,
+ makePendingOp("wiki:ingest", "knowledge_base", "kb", "ingest", "fresh", nil)))
+
+ stale := time.Now().Add(-time.Hour)
+
+ // Replay the retry path on "hot": claim it, bump fail_count, release it
+ // back to the pool exactly as requeueFailedOps does.
+ first, err := repo.ClaimBatch(ctx, "wiki:ingest", "knowledge_base", "kb", 1, stale)
+ require.NoError(t, err)
+ require.Len(t, first, 1)
+ require.Equal(t, "hot", first[0].DedupKey)
+ _, err = repo.IncrFailCount(ctx, first[0].ID)
+ require.NoError(t, err)
+ require.NoError(t, repo.ReleaseByIDs(ctx, []int64{first[0].ID}))
+
+ // "hot" holds the lower id but has a failure on record; the
+ // never-attempted document must be selected ahead of it.
+ next, err := repo.ClaimBatch(ctx, "wiki:ingest", "knowledge_base", "kb", 1, stale)
+ require.NoError(t, err)
+ require.Len(t, next, 1)
+ assert.Equal(t, "fresh", next[0].DedupKey,
+ "a retried document must not starve a never-attempted one")
+
+ // The retried document still gets its turn once nothing fresher remains.
+ last, err := repo.ClaimBatch(ctx, "wiki:ingest", "knowledge_base", "kb", 1, stale)
+ require.NoError(t, err)
+ require.Len(t, last, 1)
+ assert.Equal(t, "hot", last[0].DedupKey,
+ "a retried document must eventually be picked up, not stranded")
+}
+
// TestTaskPendingOps_ClaimBatch_KeepsSameKeyTogether verifies the
// dedup_key affinity invariant: all rows sharing a knowledge_id are claimed
// in the SAME batch (never split), and `limit` counts distinct keys, not
diff --git a/internal/application/service/wiki_ingest.go b/internal/application/service/wiki_ingest.go
index 685221fd7..1e2ea5f83 100644
--- a/internal/application/service/wiki_ingest.go
+++ b/internal/application/service/wiki_ingest.go
@@ -839,9 +839,9 @@ func (s *wikiIngestService) scheduleFinalizeRetry(ctx context.Context, payload W
}
// peekPendingList loads up to `limit` ops from task_pending_ops for
-// this KB, ordered FIFO. Rows are NOT removed; callers must
-// DeleteByIDs once they have been consumed (or IncrFailCount + leave
-// them in place for the next pass).
+// this KB, least-failed first (then FIFO). Rows are NOT removed;
+// callers must DeleteByIDs once they have been consumed (or
+// IncrFailCount + leave them in place for the next pass).
//
// peekedIDs returns the DB ids of every row included in the peek
// (NOT just the ones that survived dedup) so trimPendingList can
@@ -1181,8 +1181,10 @@ func (s *wikiIngestService) finalizeWikiSubtask(ctx context.Context, knowledgeID
// so a single round trip handles both bookkeeping and retry-budget
// check.
// - If the count is <= wikiMaxFailRetries: leave the row in place.
-// The next follow-up batch's PeekBatch will pick it up naturally
-// (rows are ordered by id ASC and we never moved/touched it).
+// The next follow-up batch's ClaimBatch / PeekBatch will pick it
+// up after never-attempted work (both order by fail_count ASC,
+// then id ASC). The row is not moved, so the fail_count budget
+// keeps counting down.
// - If the count exceeds the retry cap: archive the op into
// task_dead_letters and DeleteByIDs to remove it from the queue.
// Settlement failures are returned so the caller does not mark claims
@@ -1203,8 +1205,8 @@ func (s *wikiIngestService) requeueFailedOps(ctx context.Context, payload WikiIn
logger.Warnf(ctx, "wiki ingest: failed to increment fail count for %s (id=%d): %v", op.KnowledgeID, op.dbID, err)
settleErrs = append(settleErrs, fmt.Errorf("increment fail count id=%d: %w", op.dbID, err))
// Without a fresh count we can't tell whether to drop. Be
- // conservative: leave the row in place; the next PeekBatch
- // will see it again and we'll try once more.
+ // conservative: leave the row in place; the next ClaimBatch
+ // / PeekBatch will see it again and we'll try once more.
continue
}
if count <= wikiMaxFailRetries {
diff --git a/internal/types/interfaces/task_queue.go b/internal/types/interfaces/task_queue.go
index 7eb2005cb..6c05aae9a 100644
--- a/internal/types/interfaces/task_queue.go
+++ b/internal/types/interfaces/task_queue.go
@@ -30,9 +30,10 @@ type TaskPendingOpsRepository interface {
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).
+ // ordered by fail_count ASC, id ASC (least-failed first; FIFO among
+ // rows with the same fail_count). 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)
// ClaimBatch atomically claims eligible rows for the tuple, grouped by
@@ -42,9 +43,11 @@ type TaskPendingOpsRepository interface {
// several queued ops is never split across two concurrent batches.
// 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 per-key anchor row is
- // locked with FOR UPDATE SKIP LOCKED so concurrent claimers take
- // disjoint key sets without blocking or double-claiming.
+ // abandoned by a crashed worker. Keys are selected least-failed first
+ // (then oldest id) so a retried row cannot starve never-attempted
+ // work. On Postgres the per-key anchor row is locked with FOR UPDATE
+ // SKIP LOCKED so concurrent claimers take disjoint key sets without
+ // blocking or double-claiming.
//
// Claimed rows are NOT removed: the consumer must DeleteByIDs on
// success, or ReleaseByIDs to hand a still-retryable row back to the
diff --git a/internal/types/task_pending_op.go b/internal/types/task_pending_op.go
index 8e892353b..6d654e500 100644
--- a/internal/types/task_pending_op.go
+++ b/internal/types/task_pending_op.go
@@ -17,8 +17,8 @@ import (
// 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.
+ // Auto-increment row id. Tie-break for PeekBatch / ClaimBatch
+ // after fail_count, and the row key for DeleteByIDs / IncrFailCount.
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.