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.
main
诉说晚秋 2026-10-08 01:25:31 +08:00 committed by GitHub
parent c0c194f625
commit 95691daab2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 138 additions and 4 deletions

View File

@ -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)

View File

@ -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)
}