From 95691daab2e292a8c45e0ae200737b1c9e5de222 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AF=89=E8=AF=B4=E6=99=9A=E7=A7=8B?= <81519560+yeliheng-010@users.noreply.github.com> Date: Thu, 8 Oct 2026 01:25:31 +0800 Subject: [PATCH] fix(knowledge): retry document processing after transient indexing failures (#3915) processChunks marked the knowledge failed and returned nil when BatchIndex failed, so ProcessDocument acked the task and the configured document-task retries never ran. A short embedding or vector-store outage left the row permanently failed; unchanged data-source syncs did not reprocess it. While attempts remain, still clean up the partial chunks and vectors but keep the row processing and return the error to the queue. The final attempt (or a caller without a retry loop) records the failure as before. --- .../application/service/knowledge_process.go | 21 ++- .../knowledge_process_index_retry_test.go | 121 ++++++++++++++++++ 2 files changed, 138 insertions(+), 4 deletions(-) create mode 100644 internal/application/service/knowledge_process_index_retry_test.go diff --git a/internal/application/service/knowledge_process.go b/internal/application/service/knowledge_process.go index 5150d015..0329ba91 100644 --- a/internal/application/service/knowledge_process.go +++ b/internal/application/service/knowledge_process.go @@ -724,10 +724,19 @@ func (s *knowledgeService) processChunks(ctx context.Context, err = retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList) if err != nil { - knowledge.ParseStatus = types.ParseStatusFailed - knowledge.ErrorMessage = err.Error() - knowledge.UpdatedAt = time.Now() - s.repo.UpdateKnowledge(ctx, knowledge) + // Embedding and vector-store errors are often transient. While the + // task has attempts left, leave the row processing and hand the + // error to the queue so the idempotent parse runs again; only the + // final attempt (or a caller without a retry loop) records failure. + willRetry := summaryTaskWillRetry(ctx) + if !willRetry { + knowledge.ParseStatus = types.ParseStatusFailed + knowledge.ErrorMessage = err.Error() + knowledge.UpdatedAt = time.Now() + if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil { + logger.Errorf(ctx, "Update knowledge status failed after batch index error: %v", updateErr) + } + } // delete failed chunks if err := s.chunkRepo.DeleteChunksByKnowledgeID(ctx, knowledge.TenantID, knowledge.ID); err != nil { @@ -748,6 +757,9 @@ func (s *knowledgeService) processChunks(ctx context.Context, } s.failStage(ctx, knowledge.ID, types.StageEmbedding, code, "batch index failed", err) + if willRetry { + return fmt.Errorf("batch index: %w", err) + } return nil } logger.GetLogger(ctx).Infof("processChunks batch index successfully, with %d index", len(indexInfoList)) @@ -1094,6 +1106,7 @@ func (s *knowledgeService) saveSummaryState(ctx context.Context, knowledge *type // summaryTaskWillRetry reports whether the current Asynq delivery has another // configured attempt remaining. Calls outside an Asynq worker are terminal. +// Despite the name it is not summary-specific; processChunks uses it too. func summaryTaskWillRetry(ctx context.Context) bool { retried, retryOK := asynq.GetRetryCount(ctx) maxRetry, maxRetryOK := asynq.GetMaxRetry(ctx) diff --git a/internal/application/service/knowledge_process_index_retry_test.go b/internal/application/service/knowledge_process_index_retry_test.go new file mode 100644 index 00000000..89bcf737 --- /dev/null +++ b/internal/application/service/knowledge_process_index_retry_test.go @@ -0,0 +1,121 @@ +package service + +import ( + "context" + "errors" + "testing" + + "github.com/Tencent/WeKnora/internal/models/embedding" + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" +) + +type indexRetryKnowledgeRepo struct { + parentChildKnowledgeRepo + updates []types.Knowledge +} + +func (r *indexRetryKnowledgeRepo) UpdateKnowledge(_ context.Context, k *types.Knowledge) error { + r.updates = append(r.updates, *k) + return nil +} + +type indexRetryChunkRepo struct { + parentChildChunkService + deletes int +} + +func (s *indexRetryChunkRepo) DeleteChunksByKnowledgeID(context.Context, uint64, string) error { + s.deletes++ + return nil +} + +type failingIndexEngine struct { + parentChildRetrieveEngine + err error + indexDeletes int +} + +func (e *failingIndexEngine) BatchIndex( + context.Context, embedding.Embedder, []*types.IndexInfo, []types.RetrieverType, +) error { + return e.err +} + +func (e *failingIndexEngine) DeleteByKnowledgeIDList(context.Context, []string, int, string) error { + e.indexDeletes++ + return nil +} + +func runProcessChunksWithFailingIndex( + ctx context.Context, t *testing.T, +) (*indexRetryKnowledgeRepo, *indexRetryChunkRepo, *failingIndexEngine, error) { + t.Helper() + knowledge := &types.Knowledge{ + ID: "knowledge-1", + TenantID: 1, + KnowledgeBaseID: "kb-1", + ParseStatus: types.ParseStatusProcessing, + } + repo := &indexRetryKnowledgeRepo{parentChildKnowledgeRepo: parentChildKnowledgeRepo{knowledge: knowledge}} + chunks := &indexRetryChunkRepo{} + engine := &failingIndexEngine{err: errors.New("embedding endpoint unavailable")} + tenant := &types.Tenant{ + ID: 1, + RetrieverEngines: types.RetrieverEngines{Engines: []types.RetrieverEngineParams{{ + RetrieverType: types.VectorRetrieverType, + RetrieverEngineType: types.PostgresRetrieverEngineType, + }}}, + } + ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenant) + svc := &knowledgeService{ + repo: repo, + chunkRepo: chunks, + modelService: parentChildModelService{embedder: parentChildEmbedder{}}, + retrieveEngine: parentChildRetrieveRegistry{engine: engine}, + graphEngine: parentChildGraphRepo{}, + tenantRepo: parentChildTenantRepo{}, + task: parentChildTaskEnqueuer{}, + } + kb := &types.KnowledgeBase{ + ID: "kb-1", + TenantID: 1, + EmbeddingModelID: "embedding-1", + IndexingStrategy: types.IndexingStrategy{VectorEnabled: true}, + } + err := svc.processChunks(ctx, kb, knowledge, []types.ParsedChunk{ + {Content: "document body", Seq: 0, Start: 0, End: 13, ParentIndex: -1}, + }) + return repo, chunks, engine, err +} + +// A transient embedding or vector-store outage must reach the task queue while +// retries remain. Acking it here would mark the document failed after the +// first attempt and leave the configured document-task retries unused. +func TestProcessChunksRetriesBatchIndexFailureBeforeLastAttempt(t *testing.T) { + ctx := types.WithTaskRetryMetadata(context.Background(), 0, 3) + + repo, chunks, engine, err := runProcessChunksWithFailingIndex(ctx, t) + + require.ErrorContains(t, err, "embedding endpoint unavailable") + for _, update := range repo.updates { + require.NotEqual(t, types.ParseStatusFailed, update.ParseStatus) + } + // Partial chunks and vectors are still removed; the retry rebuilds them. + require.Equal(t, 2, chunks.deletes) + require.Equal(t, 2, engine.indexDeletes) +} + +func TestProcessChunksFailsKnowledgeOnLastBatchIndexAttempt(t *testing.T) { + ctx := types.WithTaskRetryMetadata(context.Background(), 3, 3) + + repo, chunks, engine, err := runProcessChunksWithFailingIndex(ctx, t) + + require.NoError(t, err) + require.NotEmpty(t, repo.updates) + last := repo.updates[len(repo.updates)-1] + require.Equal(t, types.ParseStatusFailed, last.ParseStatus) + require.Equal(t, "embedding endpoint unavailable", last.ErrorMessage) + require.Equal(t, 2, chunks.deletes) + require.Equal(t, 2, engine.indexDeletes) +}