fix(knowledge): prevent documents from getting stuck in "processing"

Several failure modes left Knowledge.parse_status pinned at "processing"
forever, with no signal to users beyond a permanent spinner. This commit
addresses the root causes and adds a safety net.

- Asynq worker pool: explicit Concurrency (default 16, env-tunable via
  WEKNORA_ASYNQ_CONCURRENCY) so batch uploads don't queue behind a
  CPU-count-sized worker pool. Redis op timeouts raised to 500ms/1000ms
  (WEKNORA_REDIS_OP_TIMEOUT_MS) to absorb bursty multimodal counter ops.

- DocReader RPC: cap each call with WEKNORA_DOCREADER_CALL_TIMEOUT
  (default 30m). Without this, a hung docreader pinned a worker for the
  full DocumentProcessTimeout window.

- ImageMultimodal: finalize-on-last-attempt semantics. A permanently
  failing single image no longer strands the parent — the asynq retry
  is allowed to run, but on the final attempt we count the image
  regardless of outcome. Redis DECR errors fall back to enqueuing the
  post-process task instead of returning silently.

- Dead-letter callback: when DocumentProcess / KnowledgePostProcess /
  ManualProcess exhausts retries, immediately mark the corresponding
  Knowledge as failed with the last error. This surfaces the failure
  in the UI without waiting for the housekeeping sweep.

- HousekeepingService: 5-minute cron that flips knowledge rows stuck
  in "processing" past DocumentProcessTimeout + 10m to failed, plus
  summary rows stuck > 1h. Catches anything the other safety nets
  miss (worker SIGKILL mid-handler, etc.). Disable with
  WEKNORA_HOUSEKEEPING_ENABLED=false.

- Distributed startup recovery: previously the post-restart sweep was
  skipped whenever REDIS_ADDR was set, even though Asynq does not
  reschedule the task that was actively running on the dead instance.
  Now the sweep runs in distributed mode too, but only against rows
  older than 30 minutes to avoid racing peer instances.
This commit is contained in:
wizardchen
2026-05-27 13:17:08 +08:00
committed by lyingbug
parent ae4ec0cf06
commit 3ae3ea97c5
8 changed files with 536 additions and 65 deletions
@@ -115,20 +115,36 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
}
// finalize-once semantics: on success we always decrement the parent's
// pending counter. On failure we only decrement when this is the last
// asynq retry, so a permanently-failing single image cannot leave the
// parent knowledge stuck in "processing" forever — which was the #1
// cause of "stuck parsing" reports. Intermediate retries skip finalize
// so we don't double-count and prematurely trigger post-process.
var handleErr error
defer func() {
if handleErr == nil || isFinalAsynqAttempt(ctx) {
s.checkAndFinalizeAllImages(ctx, payload)
} else {
logger.Infof(ctx,
"[ImageMultimodal] Skip finalize on retryable error for %s (will count on last attempt)",
payload.ImageURL)
}
}()
vlmModel, err := s.resolveVLM(ctx, payload.KnowledgeBaseID)
if err != nil {
return fmt.Errorf("resolve VLM: %w", err)
handleErr = fmt.Errorf("resolve VLM: %w", err)
return handleErr
}
// Read image bytes. A provider:// URL must be resolved via FileService —
// it must NEVER be handed to the HTTP downloader (which would fail with
// "unsupported URL scheme"). On unrecoverable read failure for a single
// image, skip it and still trigger finalize so the parent knowledge
// doesn't get stuck in "processing" forever (see issue #1282).
// image, skip it (deferred finalize will count it).
imgBytes, readErr := s.readImageBytes(ctx, payload)
if readErr != nil {
logger.Errorf(ctx, "[ImageMultimodal] Skip unreadable image %s: %v", payload.ImageURL, readErr)
s.checkAndFinalizeAllImages(ctx, payload)
return nil
}
@@ -203,13 +219,14 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
}
if len(newChunks) == 0 {
s.checkAndFinalizeAllImages(ctx, payload)
// Deferred finalize will count this image on success.
return nil
}
// Persist chunks
if err := s.chunkService.CreateChunks(ctx, newChunks); err != nil {
return fmt.Errorf("create multimodal chunks: %w", err)
handleErr = fmt.Errorf("create multimodal chunks: %w", err)
return handleErr
}
for _, c := range newChunks {
logger.Infof(ctx, "[ImageMultimodal] Created %s chunk %s for image %s, len=%d",
@@ -225,11 +242,32 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
// have real textual content (caption/OCR), we can generate questions.
// Note: for documents with multiple images (e.g. PDFs), we also wait until
// all images are processed before triggering summary/question generation.
s.checkAndFinalizeAllImages(ctx, payload)
// Deferred finalize handles the parent knowledge counter.
return nil
}
// isFinalAsynqAttempt reports whether the current task context belongs to the
// last retry attempt before asynq archives the task as a dead-letter. We use
// this to flip multimodal finalize semantics: during normal retries we skip
// counter decrement (the retry might still succeed), but on the final attempt
// we count the image regardless of outcome so a permanently-failing image
// cannot pin the parent knowledge in "processing" forever.
//
// Returns false when the values are unavailable (e.g. when the handler is
// invoked outside an asynq worker, as in unit tests). Treating that case as
// "not final" keeps test ergonomics — tests should drive finalize explicitly.
func isFinalAsynqAttempt(ctx context.Context) bool {
retried, ok := asynq.GetRetryCount(ctx)
if !ok {
return false
}
maxRetry, ok := asynq.GetMaxRetry(ctx)
if !ok {
return false
}
return retried >= maxRetry
}
// indexChunks indexes the newly created multimodal chunks into the retrieval engine
// so they can participate in semantic search.
func (s *ImageMultimodalService) indexChunks(ctx context.Context, payload types.ImageMultimodalPayload, chunks []*types.Chunk) {
@@ -433,7 +471,16 @@ func (s *ImageMultimodalService) checkAndFinalizeAllImages(ctx context.Context,
pendingCount, err := s.redisClient.Decr(ctx, redisKey).Result()
if err != nil && err != redis.Nil {
logger.Warnf(ctx, "[ImageMultimodal] Failed to decrement pending count for %s: %v", payload.KnowledgeID, err)
// Redis hiccup must not strand the parent knowledge. Best-effort:
// enqueue post-process anyway. KnowledgePostProcess is idempotent
// (it transitions parse_status processing → completed under a row
// guard), so a duplicate triggered by a sibling image is harmless.
// The alternative — silently returning — is what produced the
// "permanently stuck" reports we are fixing here.
logger.Warnf(ctx,
"[ImageMultimodal] Decrement failed for %s (%v); fallback-enqueueing post-process",
payload.KnowledgeID, err)
s.enqueueKnowledgePostProcessTask(ctx, payload)
return
}
@@ -0,0 +1,157 @@
// Package service: knowledge housekeeping.
//
// HousekeepingService periodically scans for knowledge rows that have been
// stuck in "processing" longer than any reasonable execution window and
// marks them as failed. This is the safety net that catches anything the
// other defences (asynq retry, dead-letter callback, image_multimodal
// finalize-on-last-attempt) miss — for example:
//
// - Worker process killed mid-handler before any defer could run.
// - DocReader call genuinely exceeding DocReaderCallTimeout AND the
// worker subsequently being lost before retry kicks in.
// - Multimodal Redis counter set to N but ALL N image tasks failing in
// ways that bypass finalize (extremely rare; defence-in-depth here).
//
// Without this sweep, a single unlucky failure mode can leave a knowledge
// row in "processing" forever — invisible to users except as a permanent
// spinner. With this sweep the worst-case latency from stall to user-
// visible failure is bounded to ~1 stale-threshold + 1 sweep interval.
package service
import (
"context"
"os"
"strings"
"sync"
"time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/robfig/cron/v3"
"gorm.io/gorm"
)
// HousekeepingService runs background sweeps to recover stuck rows.
type HousekeepingService struct {
db *gorm.DB
cfg *config.Config
cron *cron.Cron
mu sync.Mutex
started bool
}
// NewHousekeepingService constructs a HousekeepingService. It does NOT start
// the cron — call Start in the application bootstrap so a misconfigured
// cron schedule cannot prevent the rest of the service from coming up.
func NewHousekeepingService(db *gorm.DB, cfg *config.Config) *HousekeepingService {
return &HousekeepingService{
db: db,
cfg: cfg,
cron: cron.New(cron.WithSeconds(), cron.WithChain(
cron.Recover(cron.DefaultLogger),
)),
}
}
// Start registers the sweep schedule and begins the background runner.
// Idempotent — repeated calls are a no-op so wiring code can call Start
// without coordinating ordering.
func (h *HousekeepingService) Start(ctx context.Context) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.started {
return nil
}
if !housekeepingEnabled() {
logger.Infof(ctx, "[Housekeeping] disabled via WEKNORA_HOUSEKEEPING_ENABLED=false")
return nil
}
// Every 5 minutes — frequent enough that user-visible recovery latency
// is acceptable, infrequent enough that the SQL sweep is invisible to
// query load even on large knowledge tables.
if _, err := h.cron.AddFunc("0 */5 * * * *", func() {
// Use Background so a cancelled bootstrap ctx doesn't stop sweeps.
h.runSweep(context.Background())
}); err != nil {
return err
}
h.cron.Start()
h.started = true
logger.Infof(ctx, "[Housekeeping] started with 5-minute sweep")
return nil
}
// Stop halts the cron and waits for in-flight sweeps to finish.
func (h *HousekeepingService) Stop() {
h.mu.Lock()
defer h.mu.Unlock()
if !h.started {
return
}
c := h.cron.Stop()
<-c.Done()
h.started = false
}
// runSweep is exported on the type for testability — tests can drive a
// single sweep without waiting for the cron tick.
func (h *HousekeepingService) runSweep(ctx context.Context) {
threshold := h.staleThreshold()
cutoff := time.Now().Add(-threshold)
// Sweep A: knowledge stuck in "processing".
resKnowledge := h.db.WithContext(ctx).Model(&types.Knowledge{}).
Where("parse_status = ? AND updated_at < ?", types.ParseStatusProcessing, cutoff).
Updates(map[string]interface{}{
"parse_status": types.ParseStatusFailed,
"error_message": "task stuck in processing > " + threshold.String() + ", recovered by housekeeping",
})
if resKnowledge.Error != nil {
logger.Warnf(ctx, "[Housekeeping] knowledge sweep failed: %v", resKnowledge.Error)
} else if resKnowledge.RowsAffected > 0 {
logger.Infof(ctx, "[Housekeeping] recovered %d stuck knowledge rows (threshold=%s)",
resKnowledge.RowsAffected, threshold)
}
// Sweep B: knowledge summary stuck. Summary is post-parse; threshold
// is shorter because summary tasks are bounded by a single LLM call.
summaryCutoff := time.Now().Add(-1 * time.Hour)
resSummary := h.db.WithContext(ctx).Model(&types.Knowledge{}).
Where("summary_status = ? AND updated_at < ?", types.SummaryStatusProcessing, summaryCutoff).
Update("summary_status", types.SummaryStatusFailed)
if resSummary.Error != nil {
logger.Warnf(ctx, "[Housekeeping] summary sweep failed: %v", resSummary.Error)
} else if resSummary.RowsAffected > 0 {
logger.Infof(ctx, "[Housekeeping] recovered %d stuck summary rows", resSummary.RowsAffected)
}
}
// staleThreshold returns how long a "processing" row may sit untouched
// before housekeeping treats it as orphaned. The floor is 1 hour so that a
// genuinely slow large-PDF parse cannot be killed mid-flight; the ceiling
// scales with the operator-configured DocumentProcessTimeout plus 10 minute
// buffer to absorb scheduling jitter.
func (h *HousekeepingService) staleThreshold() time.Duration {
base := 1 * time.Hour
if h.cfg != nil && h.cfg.KnowledgeBase != nil && h.cfg.KnowledgeBase.DocumentProcessTimeout > base {
base = h.cfg.KnowledgeBase.DocumentProcessTimeout
}
return base + 10*time.Minute
}
func housekeepingEnabled() bool {
// Default-on: missing/empty env enables the sweep. Operators must
// explicitly set "false" to opt out, matching the plan's commitment
// that no env change is required for the safety net to engage.
v := strings.TrimSpace(os.Getenv("WEKNORA_HOUSEKEEPING_ENABLED"))
if v == "" {
return true
}
switch strings.ToLower(v) {
case "0", "false", "off", "no":
return false
}
return true
}
@@ -2340,7 +2340,7 @@ func (s *knowledgeService) convert(
req.FileType = fileType
}
result, err := reader.Read(ctx, req)
result, err := s.callDocReaderWithTimeout(ctx, reader, req)
if err != nil {
return s.failKnowledge(ctx, knowledge, isLastRetry, "document read failed: %v", err)
}
@@ -2356,7 +2356,42 @@ func (s *knowledgeService) convert(
return result, nil
}
// resolveDocReader returns the appropriate DocReader for the given engine.
// callDocReaderWithTimeout wraps the DocReader RPC in a child context whose
// deadline is min(parent_deadline, DocReaderCallTimeout). Without this cap,
// a hung docreader (network partition, GC pause, OCR runaway) silently
// burns the whole DocumentProcessTimeout budget and pins a worker for hours
// — the #1 cause of "knowledge stuck in processing" reports.
//
// On timeout we annotate the error so retries / dead-letter consumers can
// distinguish "docreader was slow" from "docreader returned an error".
func (s *knowledgeService) callDocReaderWithTimeout(
ctx context.Context, reader interfaces.DocReader, req *types.ReadRequest,
) (*types.ReadResult, error) {
timeout := 30 * time.Minute
if s.config != nil && s.config.KnowledgeBase != nil && s.config.KnowledgeBase.DocReaderCallTimeout > 0 {
timeout = s.config.KnowledgeBase.DocReaderCallTimeout
}
callCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
start := time.Now()
result, err := reader.Read(callCtx, req)
elapsed := time.Since(start)
if err != nil {
// Promote DeadlineExceeded into a clearer message; retain underlying
// error via %w so errors.Is(callCtx.Err(), context.DeadlineExceeded)
// still works for upstream classification.
if errors.Is(callCtx.Err(), context.DeadlineExceeded) && !errors.Is(ctx.Err(), context.DeadlineExceeded) {
logger.Errorf(ctx, "[convert] docreader call timed out after %s (limit %s) for %q",
elapsed, timeout, req.FileName)
return nil, fmt.Errorf("docreader call timeout after %s: %w", timeout, err)
}
return nil, err
}
logger.Infof(ctx, "[convert] docreader call ok in %s for %q", elapsed, req.FileName)
return result, nil
}
// Returns nil when the required service is unavailable.
func (s *knowledgeService) resolveDocReader(ctx context.Context, engine, fileType string, isURL bool, overrides map[string]string) interfaces.DocReader {
switch engine {