fix(knowledge): recover tasks safely after server restart

Stop failing distributed-mode knowledge rows on startup; let housekeeping
decide using span activity and Asynq queue state. In Lite mode, resume
wiki work from durable task_pending_ops and surface SERVER_RESTART errors
in the processing timeline with i18n support.
This commit is contained in:
wizardchen
2026-07-14 17:20:22 +08:00
committed by lyingbug
parent 28ebcf2525
commit ace84bc757
12 changed files with 462 additions and 74 deletions
@@ -112,7 +112,7 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
threshold := h.staleThreshold()
cutoff := time.Now().Add(-threshold)
// Sweep A: knowledge stuck in "processing".
// Sweep A: knowledge stuck in "pending", "processing", or "finalizing".
//
// Two-stage check is critical here: knowledge.updated_at advances
// only at parse_status transitions, but a long stage (DocReader on
@@ -127,7 +127,9 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
// Knowledge rows with no spans at all (lite mode, in-flight tasks
// from before this code shipped) fall back to the simple
// updated_at check — they have no heartbeat to consult.
// Include 'finalizing' alongside 'processing': finalizing rows still
// Include 'pending' so a task whose enqueue was lost is eventually
// recovered too; filterOutQueued below protects legitimately backlogged
// tasks. Include 'finalizing' alongside 'processing': finalizing rows still
// consume LLM compute via enrichment subtasks (summary/question/graph),
// and the same stall modes (subtask worker dies, retry budget exhausted
// without decrementing the counter) leave the row hanging just as
@@ -136,7 +138,7 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
var candidates []types.Knowledge
if err := h.db.WithContext(ctx).
Where("parse_status IN ? AND updated_at < ?",
[]string{types.ParseStatusProcessing, types.ParseStatusFinalizing}, cutoff).
[]string{types.ParseStatusPending, types.ParseStatusProcessing, types.ParseStatusFinalizing}, cutoff).
Find(&candidates).Error; err != nil {
logger.Warnf(ctx, "[Housekeeping] knowledge candidate query failed: %v", err)
return
@@ -162,7 +164,7 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
}
res := h.db.WithContext(ctx).Model(&types.Knowledge{}).
Where("id IN ? AND parse_status IN ?", stuckIDs,
[]string{types.ParseStatusProcessing, types.ParseStatusFinalizing}).
[]string{types.ParseStatusPending, types.ParseStatusProcessing, types.ParseStatusFinalizing}).
Updates(map[string]interface{}{
"parse_status": types.ParseStatusFailed,
"error_message": "task stuck in processing > " + threshold.String() + ", recovered by housekeeping",
@@ -165,6 +165,40 @@ func TestHousekeeping_RecoversAbandoned(t *testing.T) {
assert.Contains(t, errMsg, "stuck in processing")
}
func TestHousekeeping_RecoversPendingTaskMissingFromQueue(t *testing.T) {
db := setupHousekeepingDB(t)
svc := newHousekeepingSvcForTest(db)
stale := time.Now().Add(-3 * time.Hour)
insertKnowledge(t, db, "kid-pending-orphan", types.ParseStatusPending, stale)
svc.runSweep(context.Background())
var status string
require.NoError(t, db.Raw(
`SELECT parse_status FROM knowledges WHERE id = ?`, "kid-pending-orphan",
).Row().Scan(&status))
assert.Equal(t, types.ParseStatusFailed, status,
"a stale pending row with no queue task must not remain pending forever")
}
func TestHousekeeping_PreservesPendingTaskStillQueued(t *testing.T) {
db := setupHousekeepingDB(t)
svc := newHousekeepingSvcWithInspector(db, fakeTaskInspector{
queued: map[string]bool{"kid-pending-queued": true},
})
stale := time.Now().Add(-3 * time.Hour)
insertKnowledge(t, db, "kid-pending-queued", types.ParseStatusPending, stale)
svc.runSweep(context.Background())
var status string
require.NoError(t, db.Raw(
`SELECT parse_status FROM knowledges WHERE id = ?`, "kid-pending-queued",
).Row().Scan(&status))
assert.Equal(t, types.ParseStatusPending, status,
"backlogged pending work remains owned by the durable queue")
}
// TestHousekeeping_NoFalseKill_ActiveSpan is the regression test for
// the "long DocReader silently runs longer than DocumentProcessTimeout"
// scenario the user flagged. A knowledge whose knowledge.updated_at