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
+113 -62
View File
@@ -13,18 +13,22 @@ import (
const resetPendingStaleWindow = 30 * time.Minute
const restartInterruptedMessage = "Task interrupted due to application restart"
// resetPendingTasks resets the state of any knowledge items or sync logs stuck in processing
// due to an unexpected application restart.
//
// In Lite mode (no REDIS_ADDR) every queued task lived in process memory, so
// any "processing" row at startup is definitively orphaned and must be marked
// failed wholesale. In distributed mode (Asynq on Redis) the active queue
// survives restart, but the *currently executing* task on the dead instance
// is lost — Asynq won't reschedule it until at-least-once retry kicks in,
// which can take minutes or never (e.g. if the deadline has passed). To bound
// the worst case we mark only "long-stale" rows failed: anything that hasn't
// been touched for 30 minutes is well past any reasonable in-flight window.
// Newer rows are left alone so we don't race a peer instance that's mid-process.
// In Lite mode (no REDIS_ADDR) normal queued tasks live in process memory, so
// a "processing" row at startup is orphaned unless it has a durable wiki op
// that can be re-triggered.
//
// Distributed mode is intentionally different: Asynq persists queued/retry
// tasks, and another replica may still be executing the same knowledge. A
// startup hook cannot safely distinguish an orphan from a backlogged task that
// has not opened a span yet. HousekeepingService owns that decision because it
// checks BOTH recent span activity and the real Asynq queue. Consequently this
// hook never resets knowledge/summary rows in distributed mode; it only keeps
// the separate sync-log cleanup below.
func resetPendingTasks(db *gorm.DB) {
distributed := os.Getenv("REDIS_ADDR") != ""
ctx := context.Background()
@@ -35,22 +39,64 @@ func resetPendingTasks(db *gorm.DB) {
staleCutoff = time.Now().Add(-resetPendingStaleWindow)
}
// Cancel orphaned trace spans for knowledge rows we are about to mark
// failed. resetPendingTasks does not touch asynq queues; this only
// prevents the UI from showing duplicate running postprocess.*
// subspans when a later retry also opens fresh spans.
// Resolve Lite-mode orphaned knowledge rows first. A finalizing row whose
// ONLY remaining slot is backed by a durable wiki op is excluded and resumed
// by recoverPendingWikiTasks after handlers are registered. Rows with other
// outstanding in-memory subtasks still fail: the wiki op cannot recover them.
var stuckKnowledge []types.Knowledge
if err := stuckKnowledgeParseQuery(db, distributed, staleCutoff).
Select("id").Find(&stuckKnowledge).Error; err != nil {
logger.Warnf(ctx, "resetPendingTasks: list stuck knowledge failed: %v", err)
} else {
for _, k := range stuckKnowledge {
if !distributed {
if err := stuckKnowledgeParseQuery(db).
Select("id").Find(&stuckKnowledge).Error; err != nil {
logger.Warnf(ctx, "resetPendingTasks: list stuck knowledge failed: %v", err)
}
}
// 1. Reset knowledge parsing tasks (including finalizing rows whose
// enrichment subtasks were lost with the process).
// Update by the resolved ids rather than reusing the GORM chain after
// Find() (which makes PostgreSQL emit an invalid UPDATE ... FROM self).
stuckIDs := knowledgeIDs(stuckKnowledge)
var resetErr error
var resetCount int64
if len(stuckIDs) > 0 {
// Rebuild the query instead of reusing the chain after Find(); reusing it
// makes PostgreSQL emit an invalid UPDATE ... FROM self statement.
result := stuckKnowledgeParseQuery(db).
Where("id IN ?", stuckIDs).
Updates(map[string]interface{}{
"parse_status": types.ParseStatusFailed,
"error_message": restartInterruptedMessage,
"pending_subtasks_count": 0,
})
resetErr = result.Error
resetCount = result.RowsAffected
}
if resetErr != nil {
logger.Warnf(context.Background(), "Failed to reset pending knowledge tasks: %v", resetErr)
} else if resetCount > 0 {
logger.Infof(context.Background(),
"Reset %d stuck knowledge parsing tasks to failed state (distributed=%v)",
resetCount, distributed)
// Cancel orphaned trace spans only after the owning knowledge rows are
// terminal. This prevents the UI from showing duplicate running
// postprocess.* subspans when a later manual retry opens fresh spans.
// Re-read the successfully reset ids so a row whose status changed in
// the small SELECT/UPDATE gap is not accidentally cancelled.
var resetKnowledge []types.Knowledge
if err := db.Select("id").
Where("id IN ? AND parse_status = ? AND error_message = ?",
stuckIDs, types.ParseStatusFailed, restartInterruptedMessage).
Find(&resetKnowledge).Error; err != nil {
logger.Warnf(ctx, "resetPendingTasks: list reset knowledge failed: %v", err)
}
for _, k := range resetKnowledge {
attempt, err := spanRepo.LatestAttempt(ctx, k.ID)
if err != nil || attempt <= 0 {
continue
}
if n, err := spanRepo.CancelAllOpenSpans(ctx, k.ID, attempt,
"SERVER_RESTART", "task interrupted due to application restart"); err != nil {
"SERVER_RESTART", restartInterruptedMessage); err != nil {
logger.Warnf(ctx, "resetPendingTasks: cancel spans for %s failed: %v", k.ID, err)
} else if n > 0 {
logger.Infof(ctx, "resetPendingTasks: cancelled %d open span(s) for knowledge %s attempt %d",
@@ -59,33 +105,19 @@ func resetPendingTasks(db *gorm.DB) {
}
}
// 1. Reset knowledge parsing tasks (including finalizing rows whose
// enrichment subtasks were lost with the process).
// Fresh query — reusing the *gorm.DB chain after Find() makes GORM emit
// UPDATE ... FROM knowledges which PostgreSQL rejects (SQLSTATE 42712).
result := stuckKnowledgeParseQuery(db, distributed, staleCutoff).Updates(map[string]interface{}{
"parse_status": types.ParseStatusFailed,
"error_message": "Task interrupted due to application restart",
"pending_subtasks_count": 0,
})
if result.Error != nil {
logger.Warnf(context.Background(), "Failed to reset pending knowledge tasks: %v", result.Error)
} else if result.RowsAffected > 0 {
logger.Infof(context.Background(),
"Reset %d stuck knowledge parsing tasks to failed state (distributed=%v)",
result.RowsAffected, distributed)
}
// 2. Reset knowledge summary tasks
resultSummary := stuckKnowledgeSummaryQuery(db, distributed, staleCutoff).Updates(map[string]interface{}{
"summary_status": types.SummaryStatusFailed,
})
if resultSummary.Error != nil {
logger.Warnf(context.Background(), "Failed to reset pending summary tasks: %v", resultSummary.Error)
} else if resultSummary.RowsAffected > 0 {
logger.Infof(context.Background(),
"Reset %d stuck summary generation tasks to failed state (distributed=%v)",
resultSummary.RowsAffected, distributed)
// 2. Lite summary tasks are process-local too. Distributed summary tasks
// stay in Asynq and must not be failed merely because this replica started.
if !distributed {
resultSummary := stuckKnowledgeSummaryQuery(db).Updates(map[string]interface{}{
"summary_status": types.SummaryStatusFailed,
})
if resultSummary.Error != nil {
logger.Warnf(context.Background(), "Failed to reset pending summary tasks: %v", resultSummary.Error)
} else if resultSummary.RowsAffected > 0 {
logger.Infof(context.Background(),
"Reset %d stuck summary generation tasks to failed state (distributed=false)",
resultSummary.RowsAffected)
}
}
// 3. Reset data source sync tasks
@@ -104,27 +136,27 @@ func resetPendingTasks(db *gorm.DB) {
}
}
func stuckKnowledgeParseQuery(db *gorm.DB, distributed bool, staleCutoff time.Time) *gorm.DB {
func stuckKnowledgeParseQuery(db *gorm.DB) *gorm.DB {
q := db.Model(&types.Knowledge{}).
Where("parse_status IN ?", []string{
types.ParseStatusPending,
types.ParseStatusProcessing,
types.ParseStatusFinalizing,
types.ParseStatusDeleting,
})
if distributed {
q = q.Where("updated_at < ?", staleCutoff)
}
Where("parse_status IN ?", resettableParseStatuses()).
// Wiki ingest ops are persisted independently from the task trigger.
// When wiki owns the only outstanding slot, keeping this finalizing row
// alive lets startup recreate the trigger and finish cleanly. A count
// above one means at least one non-wiki in-memory subtask was also lost.
Where(`NOT (parse_status = ? AND pending_subtasks_count = 1 AND EXISTS (
SELECT 1 FROM task_pending_ops
WHERE task_pending_ops.task_type = ?
AND task_pending_ops.scope = ?
AND task_pending_ops.dedup_key = knowledges.id
AND task_pending_ops.op = ?
))`, types.ParseStatusFinalizing, types.TypeWikiIngest,
types.TaskScopeKnowledgeBase, "ingest")
return q
}
func stuckKnowledgeSummaryQuery(db *gorm.DB, distributed bool, staleCutoff time.Time) *gorm.DB {
q := db.Model(&types.Knowledge{}).
func stuckKnowledgeSummaryQuery(db *gorm.DB) *gorm.DB {
return db.Model(&types.Knowledge{}).
Where("summary_status IN ?", []string{types.SummaryStatusPending, types.SummaryStatusProcessing})
if distributed {
q = q.Where("updated_at < ?", staleCutoff)
}
return q
}
func stuckSyncLogQuery(db *gorm.DB, distributed bool, staleCutoff time.Time) *gorm.DB {
@@ -135,3 +167,22 @@ func stuckSyncLogQuery(db *gorm.DB, distributed bool, staleCutoff time.Time) *go
}
return q
}
func resettableParseStatuses() []string {
return []string{
types.ParseStatusPending,
types.ParseStatusProcessing,
types.ParseStatusFinalizing,
types.ParseStatusDeleting,
}
}
func knowledgeIDs(rows []types.Knowledge) []string {
ids := make([]string, 0, len(rows))
for _, row := range rows {
if row.ID != "" {
ids = append(ids, row.ID)
}
}
return ids
}