fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.main
parent
1bf717a54d
commit
ab115c0944
|
|
@ -1452,6 +1452,16 @@ const updateStatus = (analyzeList: KnowledgeCard[], delay = 1500) => {
|
|||
delete traceAvailableById[item.id];
|
||||
}
|
||||
});
|
||||
// A requested row the batch no longer returns is gone (deleted
|
||||
// elsewhere, replaced by a data-source sync). Left in the list it
|
||||
// kept its in-flight status, so its spinner and this poll never ended.
|
||||
const returnedIds = new Set((result.data as KnowledgeCard[]).map(item => item.id));
|
||||
const goneIds = new Set(analyzeList.map(item => item.id).filter(id => !returnedIds.has(id)));
|
||||
if (goneIds.size > 0) {
|
||||
const before = cardList.value.length;
|
||||
cardList.value = cardList.value.filter(card => !goneIds.has(card.id));
|
||||
total.value = Math.max(0, total.value - (before - cardList.value.length));
|
||||
}
|
||||
}
|
||||
if (shouldRefreshWikiStatus) {
|
||||
void fetchWikiStatusOnce();
|
||||
|
|
|
|||
|
|
@ -667,10 +667,17 @@ func (r *knowledgeRepository) UpdateActiveDeletingKnowledgeColumns(
|
|||
// across PostgreSQL and SQLite. The promote UPDATE's WHERE clause
|
||||
// (parse_status='finalizing' AND pending_subtasks_count=0) makes it
|
||||
// safe to run from any number of concurrent callers — at most one wins.
|
||||
// Both run in one transaction: a promote that failed after its decrement
|
||||
// committed left the counter at zero with nobody left to promote the row.
|
||||
func (r *knowledgeRepository) FinalizeSubtask(
|
||||
ctx context.Context, id string,
|
||||
) (int, bool, error) {
|
||||
promoted, err := finalizeSubtask(r.db.WithContext(ctx), id)
|
||||
var promoted bool
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var err error
|
||||
promoted, err = finalizeSubtask(tx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -234,6 +234,62 @@ func TestFinalizeSubtask_DecrementClampedAtZero(t *testing.T) {
|
|||
assert.Equal(t, 0, count, "pending_subtasks_count must be clamped at zero")
|
||||
}
|
||||
|
||||
// A row no longer in finalizing (cancelled, failed by housekeeping) only has
|
||||
// its counter decremented: reaching zero must not promote it to completed.
|
||||
func TestFinalizeSubtask_NonFinalizingRowOnlyDecrements(t *testing.T) {
|
||||
for _, status := range []string{types.ParseStatusCancelled, types.ParseStatusFailed, types.ParseStatusProcessing} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
id := insertKnowledgeWithStatus(t, db, status, false)
|
||||
require.NoError(t, db.Exec(`UPDATE knowledges SET pending_subtasks_count = 1 WHERE id = ?`, id).Error)
|
||||
|
||||
count, promoted, err := repo.FinalizeSubtask(context.Background(), id)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.False(t, promoted)
|
||||
assert.Zero(t, count)
|
||||
got, n := reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, status, got)
|
||||
assert.Zero(t, n)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Decrement and promote commit together: a promote that failed after its
|
||||
// decrement had committed left the counter at zero with nobody left to
|
||||
// promote the row. A failed promote must roll the decrement back so the
|
||||
// retried release drains the same slot again.
|
||||
func TestFinalizeSubtask_FailedPromoteRollsBackDecrement(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
id := insertProcessingKnowledge(t, db)
|
||||
_, err := repo.SetFinalizing(ctx, id, 1)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(`
|
||||
CREATE TRIGGER refuse_promote BEFORE UPDATE OF parse_status ON knowledges
|
||||
WHEN NEW.parse_status = 'completed'
|
||||
BEGIN SELECT RAISE(ABORT, 'promote refused'); END
|
||||
`).Error)
|
||||
|
||||
_, promoted, err := repo.FinalizeSubtask(ctx, id)
|
||||
|
||||
require.ErrorContains(t, err, "promote refused")
|
||||
assert.False(t, promoted)
|
||||
status, count := reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, types.ParseStatusFinalizing, status)
|
||||
assert.Equal(t, 1, count, "the decrement must roll back with the failed promote")
|
||||
|
||||
require.NoError(t, db.Exec(`DROP TRIGGER refuse_promote`).Error)
|
||||
_, promoted, err = repo.FinalizeSubtask(ctx, id)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, promoted, "the retried release drains and promotes")
|
||||
status, count = reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, types.ParseStatusCompleted, status)
|
||||
assert.Zero(t, count)
|
||||
}
|
||||
|
||||
// TestSetFinalizingAndFinalizeSubtask_ClearStaleErrorMessage is the
|
||||
// regression test for stale error_message: a row that failed once keeps
|
||||
// error_message set, and both entering finalizing (a new attempt) and
|
||||
|
|
|
|||
|
|
@ -1396,7 +1396,13 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource
|
|||
return isUpdate, fmt.Errorf("marshal datasource metadata: %w", mErr)
|
||||
}
|
||||
created.Metadata = types.JSON(metadataBytes)
|
||||
if uErr := s.knowledgeService.GetRepository().UpdateKnowledge(ctx, created); uErr != nil {
|
||||
// Only the metadata column: the processing task is already
|
||||
// queued, and a full-row save of this snapshot could put
|
||||
// parse_status back to "pending" under a worker that has moved
|
||||
// it on, which then skips post-process and strands the row.
|
||||
if uErr := s.knowledgeService.GetRepository().UpdateKnowledgeColumn(
|
||||
ctx, created.ID, "metadata", created.Metadata,
|
||||
); uErr != nil {
|
||||
return isUpdate, fmt.Errorf("attach datasource metadata: %w", uErr)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
|
@ -277,7 +278,7 @@ type deletionLookupKnowledgeRepo struct {
|
|||
interfaces.KnowledgeRepository
|
||||
knowledge *types.Knowledge
|
||||
lookupErr error
|
||||
metadataUpdates []map[string]string // metadata persisted via UpdateKnowledge
|
||||
metadataUpdates []map[string]string // metadata persisted via UpdateKnowledge / UpdateKnowledgeColumn
|
||||
metadataUpdateErr error
|
||||
hardDeleted []string
|
||||
hardDeleteErr error
|
||||
|
|
@ -301,6 +302,19 @@ func (r *deletionLookupKnowledgeRepo) UpdateKnowledge(_ context.Context, knowled
|
|||
return nil
|
||||
}
|
||||
|
||||
func (r *deletionLookupKnowledgeRepo) UpdateKnowledgeColumn(
|
||||
ctx context.Context, id string, column string, value interface{},
|
||||
) error {
|
||||
if column != "metadata" {
|
||||
return fmt.Errorf("unexpected column update %q", column)
|
||||
}
|
||||
raw, ok := value.(types.JSON)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected metadata value %T", value)
|
||||
}
|
||||
return r.UpdateKnowledge(ctx, &types.Knowledge{ID: id, Metadata: raw})
|
||||
}
|
||||
|
||||
func (r *deletionLookupKnowledgeRepo) FindByDataSourceExternalID(
|
||||
_ context.Context, tenantID uint64, knowledgeBaseID, dataSourceID, externalID string,
|
||||
) (*types.Knowledge, error) {
|
||||
|
|
|
|||
|
|
@ -148,7 +148,7 @@ func (s *ImageMultimodalService) tracker() SpanTracker {
|
|||
}
|
||||
|
||||
// Handle implements asynq handler for TypeImageMultimodal.
|
||||
func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) error {
|
||||
func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) (retErr error) {
|
||||
var payload types.ImageMultimodalPayload
|
||||
if err := json.Unmarshal(task.Payload(), &payload); err != nil {
|
||||
return fmt.Errorf("unmarshal image multimodal payload: %w", err)
|
||||
|
|
@ -163,11 +163,27 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
|
|||
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
|
||||
}
|
||||
|
||||
// A reparse re-seeded the fan-in counter for its own images. Counting
|
||||
// this stale image would drain a slot of the new run and finalize it
|
||||
// before its images are done.
|
||||
if attemptSuperseded(ctx, s.tracker(), payload.KnowledgeID, payload.Attempt) {
|
||||
logger.Infof(ctx, "[ImageMultimodal] Attempt %d of %s superseded, dropping image %s",
|
||||
payload.Attempt, payload.KnowledgeID, payload.ImageURL)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Drop orphaned or user-aborted work before touching VLM. Missing
|
||||
// knowledge/KB rows are permanent failures — retrying only burns queue
|
||||
// capacity (asynq default MaxRetry=25 on legacy tasks).
|
||||
drop, dropErr := s.shouldDropOrphanedMultimodal(ctx, &payload)
|
||||
if dropErr != nil {
|
||||
if isFinalAsynqAttempt(ctx) {
|
||||
// No retry follows, so this image must still be counted or
|
||||
// the parent never reaches post-process.
|
||||
if err := s.checkAndFinalizeAllImages(ctx, payload); err != nil {
|
||||
return errors.Join(dropErr, err)
|
||||
}
|
||||
}
|
||||
return dropErr
|
||||
}
|
||||
if drop {
|
||||
|
|
@ -176,8 +192,7 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
|
|||
payload.ChunkID, payload.KnowledgeID, payload.KnowledgeBaseID, payload.ImageURL)
|
||||
// Still count this image toward the parent finalize gate so a task
|
||||
// of dropped orphans cannot strand multimodal:pending forever.
|
||||
s.checkAndFinalizeAllImages(ctx, payload)
|
||||
return nil
|
||||
return s.checkAndFinalizeAllImages(ctx, payload)
|
||||
}
|
||||
|
||||
tracker := s.tracker()
|
||||
|
|
@ -195,7 +210,9 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
|
|||
var handleErr error
|
||||
defer func() {
|
||||
if handleErr == nil || isFinalAsynqAttempt(ctx) {
|
||||
s.checkAndFinalizeAllImages(ctx, payload)
|
||||
if err := s.checkAndFinalizeAllImages(ctx, payload); err != nil && retErr == nil {
|
||||
retErr = err
|
||||
}
|
||||
} else {
|
||||
logger.Infof(ctx,
|
||||
"[ImageMultimodal] Skip finalize on retryable error for %s (will count on last attempt)",
|
||||
|
|
@ -806,42 +823,57 @@ func multimodalPendingKey(knowledgeID string) string {
|
|||
return fmt.Sprintf("multimodal:pending:%s", knowledgeID)
|
||||
}
|
||||
|
||||
// checkAndFinalizeAllImages decrements the parent's pending-image counter and
|
||||
// enqueues post-process once the counter reaches zero.
|
||||
func (s *ImageMultimodalService) checkAndFinalizeAllImages(ctx context.Context, payload types.ImageMultimodalPayload) {
|
||||
if s.redisClient == nil {
|
||||
s.enqueueKnowledgePostProcessTask(ctx, payload)
|
||||
return
|
||||
}
|
||||
|
||||
// checkAndFinalizeAllImages counts one image of the parent knowledge and,
|
||||
// once every image is counted, hands the knowledge to post-process. An error
|
||||
// means post-process could not be enqueued; the caller must fail the task so
|
||||
// the row is not left in "processing" with nobody to move it on.
|
||||
func (s *ImageMultimodalService) checkAndFinalizeAllImages(
|
||||
ctx context.Context, payload types.ImageMultimodalPayload,
|
||||
) error {
|
||||
redisKey := multimodalPendingKey(payload.KnowledgeID)
|
||||
|
||||
pendingCount, err := s.redisClient.Decr(ctx, redisKey).Result()
|
||||
if err != nil && err != redis.Nil {
|
||||
// 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
|
||||
var pendingCount int64
|
||||
if s.redisClient == nil {
|
||||
pendingCount = liteMultimodalDecrBy(redisKey, 1)
|
||||
} else {
|
||||
var err error
|
||||
pendingCount, err = s.redisClient.Decr(ctx, redisKey).Result()
|
||||
if err != nil && err != redis.Nil {
|
||||
// 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)
|
||||
return s.enqueueKnowledgePostProcessTask(ctx, payload)
|
||||
}
|
||||
}
|
||||
|
||||
if pendingCount <= 0 {
|
||||
logger.Infof(ctx, "[ImageMultimodal] All images processed for knowledge %s. Finalizing...", payload.KnowledgeID)
|
||||
if pendingCount > 0 {
|
||||
return nil
|
||||
}
|
||||
logger.Infof(ctx, "[ImageMultimodal] All images processed for knowledge %s. Finalizing...", payload.KnowledgeID)
|
||||
// Enqueue before dropping the counter: a retry of this task then finds
|
||||
// the key at or below zero and enqueues again.
|
||||
if err := s.enqueueKnowledgePostProcessTask(ctx, payload); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.redisClient == nil {
|
||||
liteMultimodalDel(redisKey)
|
||||
} else {
|
||||
s.redisClient.Del(ctx, redisKey)
|
||||
|
||||
s.enqueueKnowledgePostProcessTask(ctx, payload)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ImageMultimodalService) enqueueKnowledgePostProcessTask(ctx context.Context, payload types.ImageMultimodalPayload) {
|
||||
func (s *ImageMultimodalService) enqueueKnowledgePostProcessTask(
|
||||
ctx context.Context, payload types.ImageMultimodalPayload,
|
||||
) error {
|
||||
if s.taskEnqueuer == nil {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
taskPayload := types.KnowledgePostProcessPayload{
|
||||
|
|
@ -849,19 +881,22 @@ func (s *ImageMultimodalService) enqueueKnowledgePostProcessTask(ctx context.Con
|
|||
KnowledgeID: payload.KnowledgeID,
|
||||
KnowledgeBaseID: payload.KnowledgeBaseID,
|
||||
Language: payload.Language,
|
||||
// Lets post-process skip itself when a reparse superseded the run.
|
||||
Attempt: payload.Attempt,
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &taskPayload)
|
||||
payloadBytes, err := json.Marshal(taskPayload)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to marshal post process payload: %v", err)
|
||||
return
|
||||
return fmt.Errorf("marshal post process payload: %w", err)
|
||||
}
|
||||
|
||||
task := asynq.NewTask(types.TypeKnowledgePostProcess, payloadBytes,
|
||||
knowledgePostProcessTaskOptions()...)
|
||||
if _, err := s.taskEnqueuer.Enqueue(task); err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to enqueue post process task for %s: %v", payload.KnowledgeID, err)
|
||||
} else {
|
||||
logger.Infof(ctx, "[ImageMultimodal] Enqueued post process task for %s", payload.KnowledgeID)
|
||||
if err := enqueueWithRetry(ctx, s.taskEnqueuer, task); err != nil {
|
||||
logger.Errorf(ctx, "[ImageMultimodal] Failed to enqueue post process task for %s: %v", payload.KnowledgeID, err)
|
||||
return err
|
||||
}
|
||||
logger.Infof(ctx, "[ImageMultimodal] Enqueued post process task for %s", payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ import (
|
|||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// Error definitions for knowledge service operations
|
||||
|
|
@ -200,6 +202,30 @@ func attemptSuperseded(ctx context.Context, tracker SpanTracker, knowledgeID str
|
|||
return tracker.LatestAttempt(ctx, knowledgeID) > attempt
|
||||
}
|
||||
|
||||
// currentAttemptSuperseded reports whether a newer attempt has started than the
|
||||
// one this pipeline step runs under (see withAttempt).
|
||||
func (s *knowledgeService) currentAttemptSuperseded(ctx context.Context, knowledgeID string) bool {
|
||||
return attemptSuperseded(ctx, s.tracker(), knowledgeID, attemptFromCtx(ctx))
|
||||
}
|
||||
|
||||
// summaryStatusClosedExpr moves a summary that is still pending or processing
|
||||
// to closed, and leaves a finished one alone. For writes that end a parse run:
|
||||
// the run's summary task no longer exists to settle the status itself.
|
||||
func summaryStatusClosedExpr(closed string) clause.Expr {
|
||||
return gorm.Expr("CASE WHEN summary_status IN (?, ?) THEN ? ELSE summary_status END",
|
||||
types.SummaryStatusPending, types.SummaryStatusProcessing, closed)
|
||||
}
|
||||
|
||||
// isInFlightParseStatus reports whether a parse run may still own queued or
|
||||
// running tasks for a knowledge in this status.
|
||||
func isInFlightParseStatus(status string) bool {
|
||||
switch status {
|
||||
case types.ParseStatusPending, types.ParseStatusProcessing, types.ParseStatusFinalizing:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// finalizeSubtaskDetachedTimeout bounds the detached decrement so a wedged DB
|
||||
// connection can't hang a worker goroutine forever in its terminal defer.
|
||||
const finalizeSubtaskDetachedTimeout = 10 * time.Second
|
||||
|
|
@ -237,12 +263,45 @@ func finalizeSubtaskDetached(
|
|||
if !willDrain {
|
||||
return
|
||||
}
|
||||
if err := releaseSubtaskSlot(ctx, repo, knowledgeID); err != nil {
|
||||
logger.Errorf(ctx, "finalize subtask decrement failed source=%s knowledge=%s err=%v; "+
|
||||
"row will be left to the housekeeping sweep", source, knowledgeID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// subtaskSlotReleaseAttempts bounds the retry of one slot release. The
|
||||
// release is the only thing that drains the slot — the task has already
|
||||
// finished — so one transient DB error must not strand the row in
|
||||
// "finalizing". The decrement and promote commit together, so a failed
|
||||
// attempt rolled back and retrying it cannot drain twice.
|
||||
const (
|
||||
subtaskSlotReleaseAttempts = 3
|
||||
subtaskSlotReleaseBackoff = 200 * time.Millisecond
|
||||
)
|
||||
|
||||
// releaseSubtaskSlot releases one finalizing slot on a context detached from
|
||||
// the caller's cancellation (see finalizeSubtaskDetached), retrying transient
|
||||
// failures within finalizeSubtaskDetachedTimeout.
|
||||
func releaseSubtaskSlot(ctx context.Context, repo interfaces.KnowledgeRepository, knowledgeID string) error {
|
||||
dctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), finalizeSubtaskDetachedTimeout)
|
||||
defer cancel()
|
||||
if _, _, err := repo.FinalizeSubtask(dctx, knowledgeID); err != nil {
|
||||
logger.Warnf(ctx, "finalize subtask decrement failed source=%s knowledge=%s err=%v",
|
||||
source, knowledgeID, err)
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= subtaskSlotReleaseAttempts; attempt++ {
|
||||
_, _, err := repo.FinalizeSubtask(dctx, knowledgeID)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
lastErr = err
|
||||
if attempt == subtaskSlotReleaseAttempts {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-time.After(time.Duration(attempt) * subtaskSlotReleaseBackoff):
|
||||
case <-dctx.Done():
|
||||
return fmt.Errorf("%w (last error: %v)", dctx.Err(), lastErr)
|
||||
}
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// beginStage / endStage / failStage / skipStage are the by-name shims
|
||||
|
|
|
|||
|
|
@ -0,0 +1,334 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// attemptTracker is a SpanTracker whose LatestAttempt a test controls, so a
|
||||
// stale task can be made to see a newer (reparse) attempt. latest[i] is
|
||||
// returned for the i-th call and the last entry for every later one, which
|
||||
// lets a test flip to "superseded" partway through a pipeline.
|
||||
type attemptTracker struct {
|
||||
noopSpanTracker
|
||||
mu sync.Mutex
|
||||
latest []int
|
||||
calls int
|
||||
opened int
|
||||
nextOpen int
|
||||
events *[]string
|
||||
}
|
||||
|
||||
func newAttemptTracker(latest ...int) *attemptTracker {
|
||||
return &attemptTracker{latest: latest}
|
||||
}
|
||||
|
||||
func (t *attemptTracker) LatestAttempt(context.Context, string) int {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if len(t.latest) == 0 {
|
||||
return 0
|
||||
}
|
||||
i := t.calls
|
||||
t.calls++
|
||||
if i >= len(t.latest) {
|
||||
i = len(t.latest) - 1
|
||||
}
|
||||
return t.latest[i]
|
||||
}
|
||||
|
||||
func (t *attemptTracker) OpenAttempt(context.Context, string, string) (*Span, int, error) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.opened++
|
||||
if t.events != nil {
|
||||
*t.events = append(*t.events, "open-attempt")
|
||||
}
|
||||
t.nextOpen++
|
||||
return &Span{}, t.nextOpen, nil
|
||||
}
|
||||
|
||||
func newDocumentProcessTask(t *testing.T, attempt int) *asynq.Task {
|
||||
t.Helper()
|
||||
payload, err := json.Marshal(types.DocumentProcessPayload{
|
||||
TenantID: 1,
|
||||
KnowledgeID: "k-1",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
FilePath: "file.md",
|
||||
FileName: "file.md",
|
||||
Attempt: attempt,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return asynq.NewTask(types.TypeDocumentProcess, payload)
|
||||
}
|
||||
|
||||
func processingKnowledge() *types.Knowledge {
|
||||
return &types.Knowledge{
|
||||
ID: "k-1",
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
ParseStatus: types.ParseStatusProcessing,
|
||||
FilePath: "file.md",
|
||||
}
|
||||
}
|
||||
|
||||
// A ProcessDocument task queued before a reparse must not touch the row the
|
||||
// reparse now owns: writing "processing" back and wiping the new chunks is
|
||||
// what stranded rows mid-reparse.
|
||||
func TestProcessDocumentSkipsSupersededAttemptWithoutWritingRow(t *testing.T) {
|
||||
repo := &embedFailureKnowledgeRepo{knowledge: processingKnowledge()}
|
||||
svc := &knowledgeService{
|
||||
repo: repo,
|
||||
tenantRepo: &summaryRefreshTenantRepo{tenant: &types.Tenant{ID: 1}},
|
||||
spanTracker: newAttemptTracker(3),
|
||||
}
|
||||
|
||||
err := svc.ProcessDocument(context.Background(), newDocumentProcessTask(t, 2))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, repo.updates, "a superseded task must not write the row")
|
||||
}
|
||||
|
||||
// Acking a task whose tenant or row could not be read left the row pending
|
||||
// with no task behind it; those failures must be retried.
|
||||
func TestProcessDocumentRetriesUnreadableTenantOrKnowledge(t *testing.T) {
|
||||
readErr := errors.New("connection reset")
|
||||
tests := []struct {
|
||||
name string
|
||||
tenant *summaryRefreshTenantRepo
|
||||
repo *abortCheckRepo
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "tenant lookup fails",
|
||||
tenant: &summaryRefreshTenantRepo{err: readErr},
|
||||
repo: &abortCheckRepo{knowledge: processingKnowledge()},
|
||||
wantErr: readErr,
|
||||
},
|
||||
{
|
||||
name: "knowledge read fails",
|
||||
tenant: &summaryRefreshTenantRepo{tenant: &types.Tenant{ID: 1}},
|
||||
repo: &abortCheckRepo{err: readErr},
|
||||
wantErr: readErr,
|
||||
},
|
||||
{
|
||||
name: "knowledge is gone",
|
||||
tenant: &summaryRefreshTenantRepo{tenant: &types.Tenant{ID: 1}},
|
||||
repo: &abortCheckRepo{err: apprepo.ErrKnowledgeNotFound},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
svc := &knowledgeService{repo: test.repo, tenantRepo: test.tenant}
|
||||
|
||||
err := svc.ProcessDocument(context.Background(), newDocumentProcessTask(t, 1))
|
||||
|
||||
if test.wantErr == nil {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.ErrorIs(t, err, test.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessManualUpdateRetriesUnreadableTenantOrKnowledge(t *testing.T) {
|
||||
readErr := errors.New("connection reset")
|
||||
payload, err := json.Marshal(types.ManualProcessPayload{
|
||||
TenantID: 1, KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", Content: "body",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
task := asynq.NewTask(types.TypeManualProcess, payload)
|
||||
tests := []struct {
|
||||
name string
|
||||
tenant *summaryRefreshTenantRepo
|
||||
repo *abortCheckRepo
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "tenant lookup fails",
|
||||
tenant: &summaryRefreshTenantRepo{err: readErr},
|
||||
repo: &abortCheckRepo{knowledge: processingKnowledge()},
|
||||
wantErr: readErr,
|
||||
},
|
||||
{
|
||||
name: "knowledge read fails",
|
||||
tenant: &summaryRefreshTenantRepo{tenant: &types.Tenant{ID: 1}},
|
||||
repo: &abortCheckRepo{err: readErr},
|
||||
wantErr: readErr,
|
||||
},
|
||||
{
|
||||
name: "knowledge is gone",
|
||||
tenant: &summaryRefreshTenantRepo{tenant: &types.Tenant{ID: 1}},
|
||||
repo: &abortCheckRepo{err: apprepo.ErrKnowledgeNotFound},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
svc := &knowledgeService{repo: test.repo, tenantRepo: test.tenant}
|
||||
|
||||
err := svc.ProcessManualUpdate(context.Background(), task)
|
||||
|
||||
if test.wantErr == nil {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.ErrorIs(t, err, test.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// processChunks under an attempt a reparse has superseded must leave the new
|
||||
// attempt's chunks alone. modelService is nil on purpose: going past the
|
||||
// guard would panic resolving the embedder.
|
||||
func TestProcessChunksSkipsSupersededAttemptBeforeTouchingChunks(t *testing.T) {
|
||||
knowledge := processingKnowledge()
|
||||
repo := &embedFailureKnowledgeRepo{knowledge: knowledge}
|
||||
chunks := &deleteCountingChunkRepo{}
|
||||
svc := &knowledgeService{repo: repo, chunkRepo: chunks, spanTracker: newAttemptTracker(2)}
|
||||
kb := &types.KnowledgeBase{
|
||||
ID: "kb-1", TenantID: 1, EmbeddingModelID: "embedding-1",
|
||||
IndexingStrategy: types.IndexingStrategy{VectorEnabled: true},
|
||||
}
|
||||
|
||||
err := svc.processChunks(withAttempt(context.Background(), 1), kb, knowledge,
|
||||
[]types.ParsedChunk{{Content: "body"}})
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, chunks.deletes)
|
||||
assert.Empty(t, repo.updates)
|
||||
}
|
||||
|
||||
type chunkWriteCountingRepo struct {
|
||||
parentChildChunkService
|
||||
deletes int
|
||||
}
|
||||
|
||||
func (r *chunkWriteCountingRepo) DeleteChunksByKnowledgeID(context.Context, uint64, string) error {
|
||||
r.deletes++
|
||||
return nil
|
||||
}
|
||||
|
||||
func newIndexingHarness(
|
||||
knowledge *types.Knowledge, task interfaces.TaskEnqueuer, tracker SpanTracker,
|
||||
) (*knowledgeService, *embedFailureKnowledgeRepo, *types.KnowledgeBase, context.Context) {
|
||||
repo := &embedFailureKnowledgeRepo{knowledge: knowledge}
|
||||
tenant := &types.Tenant{
|
||||
ID: 1,
|
||||
RetrieverEngines: types.RetrieverEngines{Engines: []types.RetrieverEngineParams{{
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
RetrieverEngineType: types.PostgresRetrieverEngineType,
|
||||
}}},
|
||||
}
|
||||
svc := &knowledgeService{
|
||||
repo: repo,
|
||||
chunkRepo: &chunkWriteCountingRepo{},
|
||||
modelService: parentChildModelService{embedder: parentChildEmbedder{}},
|
||||
retrieveEngine: parentChildRetrieveRegistry{engine: &parentChildRetrieveEngine{}},
|
||||
graphEngine: parentChildGraphRepo{},
|
||||
tenantRepo: parentChildTenantRepo{},
|
||||
task: task,
|
||||
spanTracker: tracker,
|
||||
}
|
||||
kb := &types.KnowledgeBase{
|
||||
ID: "kb-1", TenantID: 1, EmbeddingModelID: "embedding-1",
|
||||
IndexingStrategy: types.IndexingStrategy{VectorEnabled: true},
|
||||
}
|
||||
ctx := context.WithValue(context.Background(), types.TenantInfoContextKey, tenant)
|
||||
return svc, repo, kb, ctx
|
||||
}
|
||||
|
||||
// A reparse that lands while this run is embedding must not see its row put
|
||||
// back to this run's final status, nor get a post-process for the old run.
|
||||
func TestProcessChunksSkipsCompletionWhenSupersededWhileIndexing(t *testing.T) {
|
||||
enqueuer := &slotReleaseEnqueuer{}
|
||||
// Current at the entry guard, superseded by the completion guard.
|
||||
svc, repo, kb, ctx := newIndexingHarness(processingKnowledge(), enqueuer, newAttemptTracker(1, 2))
|
||||
|
||||
err := svc.processChunks(withAttempt(ctx, 1), kb, repo.knowledge,
|
||||
[]types.ParsedChunk{{Content: "body", Seq: 0, Start: 0, End: 4, ParentIndex: -1}})
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, svc.chunkRepo.(*chunkWriteCountingRepo).deletes, "the run passed the entry guard")
|
||||
assert.Empty(t, repo.updates, "the superseded run must not save its final state")
|
||||
assert.Zero(t, enqueuer.postProcess)
|
||||
}
|
||||
|
||||
type failingEnqueuer struct {
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (e *failingEnqueuer) Enqueue(*asynq.Task, ...asynq.Option) (*asynq.TaskInfo, error) {
|
||||
e.calls++
|
||||
return nil, e.err
|
||||
}
|
||||
|
||||
// Once the chunks are indexed the post-process enqueue is the only thing
|
||||
// that moves the row out of "processing", so its failure must fail the task
|
||||
// (asynq retries the idempotent parse) instead of being logged and acked.
|
||||
func TestProcessChunksReturnsErrorWhenPostProcessCannotBeEnqueued(t *testing.T) {
|
||||
queueErr := errors.New("redis unavailable")
|
||||
enqueuer := &failingEnqueuer{err: queueErr}
|
||||
svc, repo, kb, ctx := newIndexingHarness(processingKnowledge(), enqueuer, nil)
|
||||
|
||||
err := svc.processChunks(ctx, kb, repo.knowledge,
|
||||
[]types.ParsedChunk{{Content: "body", Seq: 0, Start: 0, End: 4, ParentIndex: -1}})
|
||||
|
||||
require.ErrorIs(t, err, queueErr)
|
||||
assert.Equal(t, postProcessEnqueueAttempts, enqueuer.calls, "the enqueue is retried in place first")
|
||||
}
|
||||
|
||||
// Post-process of a run a reparse superseded must not enter finalizing: it
|
||||
// would seed a counter for subtasks that all drop themselves as superseded.
|
||||
func TestKnowledgePostProcessSkipsSupersededAttempt(t *testing.T) {
|
||||
const knowledgeID = "knowledge-superseded-post-process"
|
||||
pendingRepo := &wikiEnqueueFailurePendingRepo{}
|
||||
queue := &wikiEnqueueFailureTaskQueue{}
|
||||
svc, repo := newWikiEnqueueTestService(knowledgeID, pendingRepo, queue)
|
||||
svc.spanTracker = newAttemptTracker(2)
|
||||
payload, err := json.Marshal(types.KnowledgePostProcessPayload{
|
||||
TenantID: 7, KnowledgeID: knowledgeID, KnowledgeBaseID: "kb-wiki", Attempt: 1,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
err = svc.Handle(context.Background(), asynq.NewTask(types.TypeKnowledgePostProcess, payload))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, types.ParseStatusProcessing, repo.knowledge.ParseStatus)
|
||||
assert.Zero(t, repo.expectedSubtasks)
|
||||
assert.Zero(t, pendingRepo.seedCalls)
|
||||
assert.Empty(t, queue.taskTypes)
|
||||
}
|
||||
|
||||
// The current attempt still runs post-process normally.
|
||||
func TestKnowledgePostProcessRunsCurrentAttempt(t *testing.T) {
|
||||
const knowledgeID = "knowledge-current-post-process"
|
||||
pendingRepo := &wikiEnqueueFailurePendingRepo{}
|
||||
queue := &wikiEnqueueFailureTaskQueue{}
|
||||
svc, repo := newWikiEnqueueTestService(knowledgeID, pendingRepo, queue)
|
||||
svc.spanTracker = newAttemptTracker(1)
|
||||
payload, err := json.Marshal(types.KnowledgePostProcessPayload{
|
||||
TenantID: 7, KnowledgeID: knowledgeID, KnowledgeBaseID: "kb-wiki", Attempt: 1,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
err = svc.Handle(context.Background(), asynq.NewTask(types.TypeKnowledgePostProcess, payload))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, types.ParseStatusFinalizing, repo.knowledge.ParseStatus)
|
||||
require.NotNil(t, pendingRepo.seededOp)
|
||||
var op WikiPendingOp
|
||||
require.NoError(t, json.Unmarshal(pendingRepo.seededOp.Payload, &op))
|
||||
assert.Equal(t, 1, op.Attempt, "the wiki op records the attempt that owns its slot")
|
||||
}
|
||||
|
|
@ -1282,6 +1282,15 @@ func (s *knowledgeService) triggerManualProcessing(ctx context.Context,
|
|||
) error {
|
||||
clean := strings.TrimSpace(content)
|
||||
if clean == "" {
|
||||
// The caller already marked the row processing; with nothing to
|
||||
// index no later stage would ever move it on.
|
||||
if err := s.repo.UpdateKnowledgeColumns(ctx, knowledge.ID, map[string]interface{}{
|
||||
"parse_status": types.ParseStatusFailed,
|
||||
"error_message": "manual knowledge content is empty",
|
||||
"updated_at": time.Now(),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("mark empty manual knowledge %s failed: %w", knowledge.ID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -80,8 +80,11 @@ func NewHousekeepingService(
|
|||
inspector: inspector,
|
||||
task: task,
|
||||
wikiKicks: make(map[string]time.Time),
|
||||
// SkipIfStillRunning: a sweep over a large backlog can outlast the
|
||||
// 5-minute tick, and overlapping sweeps only repeat the same scans.
|
||||
cron: cron.New(cron.WithSeconds(), cron.WithChain(
|
||||
cron.Recover(cron.DefaultLogger),
|
||||
cron.SkipIfStillRunning(cron.DefaultLogger),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
|
@ -176,6 +179,12 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
|
|||
// that still has a queued/active task referencing it; only rows with
|
||||
// nothing left in the queue are treated as genuinely orphaned.
|
||||
stuck, queueSkipped, wikiHeld := h.filterOutQueued(ctx, stuck)
|
||||
// A Wiki op protects its row only for so long. Re-arming covers a lost
|
||||
// trigger, but a consumer that fails before claiming anything never
|
||||
// consumes the op, and the row would sit in "finalizing" forever.
|
||||
wikiHeld, wikiExpired := splitExpiredWikiHolds(wikiHeld, heartbeat, time.Now().Add(-wikiHoldLimit))
|
||||
queueSkipped -= len(wikiExpired)
|
||||
stuck = append(stuck, wikiExpired...)
|
||||
h.rearmWikiTriggers(ctx, wikiHeld, threshold)
|
||||
|
||||
if len(stuck) > 0 {
|
||||
|
|
@ -184,6 +193,7 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
|
|||
recovered, threshold)
|
||||
}
|
||||
}
|
||||
h.dropExpiredWikiOps(ctx, wikiExpired)
|
||||
if spanSkipped > 0 {
|
||||
// Visibility into "we considered killing N rows but their
|
||||
// span tree showed they're still progressing". Ops can grep
|
||||
|
|
@ -216,6 +226,7 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
|
|||
} else if resSummary.RowsAffected > 0 {
|
||||
logger.Infof(ctx, "[Housekeeping] recovered %d stuck summary rows", resSummary.RowsAffected)
|
||||
}
|
||||
h.recoverStrandedPendingSummaries(ctx, summaryCutoff)
|
||||
|
||||
// Sweep C: rows stuck in "deleting" whose delete task no longer exists
|
||||
// (issues #3338/#3345). The delete dead-letter callback only recovers
|
||||
|
|
@ -272,6 +283,99 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
|
|||
}
|
||||
}
|
||||
|
||||
// wikiHoldLimit bounds how long a durable Wiki ingest op keeps its row out of
|
||||
// the stuck sweep. It is far above any healthy Wiki backlog wait; past it the
|
||||
// op is treated as one its consumer will never take.
|
||||
const wikiHoldLimit = 48 * time.Hour
|
||||
|
||||
// splitExpiredWikiHolds separates Wiki-held rows whose last progress (row
|
||||
// update or span heartbeat) predates cutoff.
|
||||
func splitExpiredWikiHolds(
|
||||
held []types.Knowledge, heartbeat map[string]time.Time, cutoff time.Time,
|
||||
) (kept, expired []types.Knowledge) {
|
||||
for _, k := range held {
|
||||
last := k.UpdatedAt
|
||||
if beat, ok := heartbeat[k.ID]; ok && beat.After(last) {
|
||||
last = beat
|
||||
}
|
||||
if last.Before(cutoff) {
|
||||
expired = append(expired, k)
|
||||
continue
|
||||
}
|
||||
kept = append(kept, k)
|
||||
}
|
||||
return kept, expired
|
||||
}
|
||||
|
||||
// dropExpiredWikiOps deletes the Wiki ingest ops of rows the sweep just failed
|
||||
// past wikiHoldLimit, so the consumer does not later spend a model call on a
|
||||
// document that is no longer waiting for it.
|
||||
func (h *HousekeepingService) dropExpiredWikiOps(ctx context.Context, expired []types.Knowledge) {
|
||||
if len(expired) == 0 {
|
||||
return
|
||||
}
|
||||
ids := make([]string, 0, len(expired))
|
||||
for _, k := range expired {
|
||||
ids = append(ids, k.ID)
|
||||
}
|
||||
res := h.db.WithContext(ctx).
|
||||
Where("task_type = ? AND scope = ? AND op = ? AND dedup_key IN ?",
|
||||
wikiTaskType, wikiTaskScope, WikiOpIngest, ids).
|
||||
Where("dedup_key IN (?)", h.db.Model(&types.Knowledge{}).Select("id").
|
||||
Where("id IN ? AND parse_status = ?", ids, types.ParseStatusFailed)).
|
||||
Delete(&types.TaskPendingOp{})
|
||||
if res.Error != nil {
|
||||
logger.Warnf(ctx, "[Housekeeping] dropping expired wiki ops failed: %v", res.Error)
|
||||
return
|
||||
}
|
||||
if res.RowsAffected > 0 {
|
||||
logger.Infof(ctx, "[Housekeeping] dropped %d wiki ingest op(s) held past %s", res.RowsAffected, wikiHoldLimit)
|
||||
}
|
||||
}
|
||||
|
||||
// recoverStrandedPendingSummaries fails summaries left "pending" on rows
|
||||
// whose parse run is over. Only the summary task moves a summary out of
|
||||
// "pending"; when it gives up without writing a status (knowledge base or
|
||||
// model gone, a refresh failing before it starts) the row keeps a summary
|
||||
// spinner, and the UI polls it, forever. A row whose summary task is still
|
||||
// queued is a backlog and is left alone.
|
||||
func (h *HousekeepingService) recoverStrandedPendingSummaries(ctx context.Context, cutoff time.Time) {
|
||||
var rows []types.Knowledge
|
||||
if err := h.db.WithContext(ctx).Select("id").
|
||||
Where("summary_status = ? AND parse_status IN ? AND updated_at < ?",
|
||||
types.SummaryStatusPending,
|
||||
[]string{types.ParseStatusCompleted, types.ParseStatusFailed, types.ParseStatusCancelled},
|
||||
cutoff).
|
||||
Find(&rows).Error; err != nil {
|
||||
logger.Warnf(ctx, "[Housekeeping] pending summary query failed: %v", err)
|
||||
return
|
||||
}
|
||||
var recovered int64
|
||||
for _, k := range rows {
|
||||
if h.inspector != nil {
|
||||
queued, err := h.inspector.HasQueuedTasksForKnowledge(ctx, k.ID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Housekeeping] summary queue probe failed for %s: %v (deferring)", k.ID, err)
|
||||
continue
|
||||
}
|
||||
if queued {
|
||||
continue
|
||||
}
|
||||
}
|
||||
res := h.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("id = ? AND summary_status = ?", k.ID, types.SummaryStatusPending).
|
||||
Update("summary_status", types.SummaryStatusFailed)
|
||||
if res.Error != nil {
|
||||
logger.Warnf(ctx, "[Housekeeping] pending summary update failed for %s: %v", k.ID, res.Error)
|
||||
continue
|
||||
}
|
||||
recovered += res.RowsAffected
|
||||
}
|
||||
if recovered > 0 {
|
||||
logger.Infof(ctx, "[Housekeeping] recovered %d stranded pending summary row(s)", recovered)
|
||||
}
|
||||
}
|
||||
|
||||
// filterByLastSpanActivity returns the subset of candidates whose most
|
||||
// recent span row predates `cutoff` — i.e. genuinely stuck. Candidates
|
||||
// with no span rows at all also pass through (they're lite-mode or
|
||||
|
|
@ -357,6 +461,9 @@ func (h *HousekeepingService) recoverStalled(
|
|||
"parse_status": types.ParseStatusFailed,
|
||||
"error_message": msg,
|
||||
"pending_subtasks_count": 0,
|
||||
// The run's summary task is gone with it; leaving the
|
||||
// summary pending keeps a spinner on a failed row.
|
||||
"summary_status": summaryStatusClosedExpr(types.SummaryStatusFailed),
|
||||
})
|
||||
if res.Error != nil {
|
||||
logger.Warnf(ctx, "[Housekeeping] knowledge sweep update failed for %s: %v", k.ID, res.Error)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,149 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func insertKnowledgeWithSummary(t *testing.T, db *gorm.DB, id, status, summary string, updatedAt time.Time) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledges (id, parse_status, summary_status, updated_at) VALUES (?, ?, ?, ?)`,
|
||||
id, status, summary, updatedAt,
|
||||
).Error)
|
||||
}
|
||||
|
||||
func readSummaryStatus(t *testing.T, db *gorm.DB, id string) string {
|
||||
t.Helper()
|
||||
var summary string
|
||||
require.NoError(t, db.Raw(`SELECT summary_status FROM knowledges WHERE id = ?`, id).Scan(&summary).Error)
|
||||
return summary
|
||||
}
|
||||
|
||||
func countWikiOps(t *testing.T, db *gorm.DB, knowledgeID string) int64 {
|
||||
t.Helper()
|
||||
var n int64
|
||||
require.NoError(t, db.Raw(`SELECT COUNT(*) FROM task_pending_ops WHERE dedup_key = ?`, knowledgeID).
|
||||
Scan(&n).Error)
|
||||
return n
|
||||
}
|
||||
|
||||
// A stuck row failed by the sweep has lost its summary task with the rest of
|
||||
// the run; an unfinished summary must fail with it, a finished one is kept.
|
||||
func TestHousekeepingRecoverStalledFailsUnfinishedSummary(t *testing.T) {
|
||||
db := setupHousekeepingDB(t)
|
||||
svc := newHousekeepingSvcForTest(db)
|
||||
stale := time.Now().Add(-3 * time.Hour)
|
||||
insertKnowledgeWithSummary(t, db, "k-pending", types.ParseStatusFinalizing, types.SummaryStatusPending, stale)
|
||||
insertKnowledgeWithSummary(t, db, "k-running", types.ParseStatusFinalizing, types.SummaryStatusProcessing, stale)
|
||||
insertKnowledgeWithSummary(t, db, "k-done", types.ParseStatusFinalizing, types.SummaryStatusCompleted, stale)
|
||||
|
||||
svc.runSweep(context.Background())
|
||||
|
||||
for id, want := range map[string]string{
|
||||
"k-pending": types.SummaryStatusFailed,
|
||||
"k-running": types.SummaryStatusFailed,
|
||||
"k-done": types.SummaryStatusCompleted,
|
||||
} {
|
||||
status, _ := readKnowledgeStatus(t, db, id)
|
||||
assert.Equal(t, types.ParseStatusFailed, status, id)
|
||||
assert.Equal(t, want, readSummaryStatus(t, db, id), id)
|
||||
}
|
||||
}
|
||||
|
||||
// Only the summary task moves a summary out of "pending"; when it gives up
|
||||
// without writing a status the row keeps a spinner forever. Finished rows
|
||||
// with nothing queued are failed; a queued summary task, a run still in
|
||||
// flight and a recent row are left alone.
|
||||
func TestHousekeepingRecoversStrandedPendingSummaries(t *testing.T) {
|
||||
db := setupHousekeepingDB(t)
|
||||
svc := newHousekeepingSvcWithInspector(db, fakeTaskInspector{
|
||||
queued: map[string]bool{"k-queued": true},
|
||||
})
|
||||
stale := time.Now().Add(-2 * time.Hour)
|
||||
cutoff := time.Now().Add(-time.Hour)
|
||||
for _, status := range []string{types.ParseStatusCompleted, types.ParseStatusFailed, types.ParseStatusCancelled} {
|
||||
insertKnowledgeWithSummary(t, db, "k-"+status, status, types.SummaryStatusPending, stale)
|
||||
}
|
||||
insertKnowledgeWithSummary(t, db, "k-queued", types.ParseStatusCompleted, types.SummaryStatusPending, stale)
|
||||
insertKnowledgeWithSummary(t, db, "k-finalizing", types.ParseStatusFinalizing, types.SummaryStatusPending, stale)
|
||||
insertKnowledgeWithSummary(t, db, "k-recent", types.ParseStatusCompleted, types.SummaryStatusPending, time.Now())
|
||||
|
||||
svc.recoverStrandedPendingSummaries(context.Background(), cutoff)
|
||||
|
||||
for id, want := range map[string]string{
|
||||
"k-" + types.ParseStatusCompleted: types.SummaryStatusFailed,
|
||||
"k-" + types.ParseStatusFailed: types.SummaryStatusFailed,
|
||||
"k-" + types.ParseStatusCancelled: types.SummaryStatusFailed,
|
||||
"k-queued": types.SummaryStatusPending,
|
||||
"k-finalizing": types.SummaryStatusPending,
|
||||
"k-recent": types.SummaryStatusPending,
|
||||
} {
|
||||
assert.Equal(t, want, readSummaryStatus(t, db, id), id)
|
||||
}
|
||||
}
|
||||
|
||||
// A durable wiki op protects its row only up to wikiHoldLimit: a consumer that
|
||||
// fails before claiming never consumes the op, and the row would otherwise sit
|
||||
// in "finalizing" forever. Past the limit the row is failed and its op
|
||||
// dropped; a younger hold is still honoured.
|
||||
func TestHousekeepingFailsRowsHeldByWikiPastHoldLimit(t *testing.T) {
|
||||
db := setupHousekeepingDB(t)
|
||||
queue := &wikiGuardTaskQueue{}
|
||||
svc := newHousekeepingSvcForTest(db)
|
||||
svc.task = queue
|
||||
for id, updatedAt := range map[string]time.Time{
|
||||
"k-expired": time.Now().Add(-wikiHoldLimit - time.Hour),
|
||||
"k-held": time.Now().Add(-3 * time.Hour),
|
||||
} {
|
||||
kbID := "kb-" + id
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledges (id, tenant_id, knowledge_base_id, parse_status, updated_at)
|
||||
VALUES (?, 7, ?, ?, ?)`, id, kbID, types.ParseStatusFinalizing, updatedAt,
|
||||
).Error)
|
||||
insertWikiPendingOp(t, db, kbID, id)
|
||||
}
|
||||
|
||||
svc.runSweep(context.Background())
|
||||
|
||||
status, msg := readKnowledgeStatus(t, db, "k-expired")
|
||||
assert.Equal(t, types.ParseStatusFailed, status)
|
||||
assert.NotEmpty(t, msg)
|
||||
assert.Zero(t, countWikiOps(t, db, "k-expired"), "the expired op is dropped with its row")
|
||||
|
||||
status, _ = readKnowledgeStatus(t, db, "k-held")
|
||||
assert.Equal(t, types.ParseStatusFinalizing, status)
|
||||
assert.Equal(t, int64(1), countWikiOps(t, db, "k-held"))
|
||||
require.Len(t, queue.tasks, 1, "only the live hold gets its trigger re-armed")
|
||||
var payload WikiIngestPayload
|
||||
require.NoError(t, json.Unmarshal(queue.tasks[0].Payload(), &payload))
|
||||
assert.Equal(t, "kb-k-held", payload.KnowledgeBaseID)
|
||||
}
|
||||
|
||||
// A span heartbeat newer than the limit keeps the hold even when the row
|
||||
// itself has not been written for longer.
|
||||
func TestSplitExpiredWikiHoldsUsesLatestActivity(t *testing.T) {
|
||||
now := time.Now()
|
||||
cutoff := now.Add(-wikiHoldLimit)
|
||||
held := []types.Knowledge{
|
||||
{ID: "row-old-no-beat", UpdatedAt: now.Add(-wikiHoldLimit - time.Hour)},
|
||||
{ID: "row-old-recent-beat", UpdatedAt: now.Add(-wikiHoldLimit - time.Hour)},
|
||||
{ID: "row-recent", UpdatedAt: now.Add(-time.Hour)},
|
||||
}
|
||||
heartbeat := map[string]time.Time{"row-old-recent-beat": now.Add(-10 * time.Hour)}
|
||||
|
||||
kept, expired := splitExpiredWikiHolds(held, heartbeat, cutoff)
|
||||
|
||||
require.Len(t, expired, 1)
|
||||
assert.Equal(t, "row-old-no-beat", expired[0].ID)
|
||||
require.Len(t, kept, 2)
|
||||
assert.Equal(t, "row-old-recent-beat", kept[0].ID)
|
||||
assert.Equal(t, "row-recent", kept[1].ID)
|
||||
}
|
||||
|
|
@ -127,6 +127,14 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
|||
attempt := payload.Attempt
|
||||
if attempt <= 0 {
|
||||
attempt = s.tracker().LatestAttempt(ctx, payload.KnowledgeID)
|
||||
} else if attemptSuperseded(ctx, s.tracker(), payload.KnowledgeID, attempt) {
|
||||
// A reparse started after this run. Entering finalizing here would
|
||||
// seed the counter for subtasks that all drop themselves as
|
||||
// superseded, and the new run's own post-process would then find
|
||||
// the row already finalizing and skip its fan-out.
|
||||
logger.Infof(ctx, "[KnowledgePostProcess] Attempt %d of %s superseded, skipping.",
|
||||
attempt, payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close the multimodal stage span (parent enqueued it as "running"
|
||||
|
|
@ -315,7 +323,7 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
|||
return errors.New("wiki post-process requires atomic finalizing handoff")
|
||||
}
|
||||
pendingOp, buildErr := newWikiIngestPendingOp(
|
||||
ctx, payload.TenantID, payload.KnowledgeBaseID, payload.KnowledgeID,
|
||||
withAttempt(ctx, attempt), payload.TenantID, payload.KnowledgeBaseID, payload.KnowledgeID,
|
||||
)
|
||||
if buildErr != nil {
|
||||
return buildErr
|
||||
|
|
@ -481,15 +489,12 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
|||
logger.Warnf(ctx,
|
||||
"[KnowledgePostProcess] Releasing %d un-enqueued subtask slot(s) for %s (planned=%d actual=%d)",
|
||||
shortfall, payload.KnowledgeID, plannedOwned, actualOwned)
|
||||
// Keep going past a failed release: stopping at the first error
|
||||
// left every remaining slot without an owner.
|
||||
for i := 0; i < shortfall; i++ {
|
||||
rctx, cancel := context.WithTimeout(
|
||||
context.WithoutCancel(ctx), finalizeSubtaskDetachedTimeout)
|
||||
_, _, err := s.knowledgeRepo.FinalizeSubtask(rctx, payload.KnowledgeID)
|
||||
cancel()
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to release subtask slot for %s: %v",
|
||||
if err := releaseSubtaskSlot(ctx, s.knowledgeRepo, payload.KnowledgeID); err != nil {
|
||||
logger.Errorf(ctx, "[KnowledgePostProcess] Failed to release subtask slot for %s: %v",
|
||||
payload.KnowledgeID, err)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -377,6 +377,12 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
|||
logger.Infof(ctx, "Knowledge source replaced, skipping chunk processing: %s", knowledge.ID)
|
||||
return nil
|
||||
}
|
||||
// A reparse started after this run: the cleanup below would wipe the
|
||||
// new attempt's chunks and the final save would put its status back.
|
||||
if s.currentAttemptSuperseded(ctx, knowledge.ID) {
|
||||
logger.Infof(ctx, "Parse attempt superseded, skipping chunk processing: %s", knowledge.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get embedding model for vectorization — only needed when vector/keyword indexing is enabled
|
||||
var embeddingModel embedding.Embedder
|
||||
|
|
@ -780,6 +786,11 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
|||
pendingMultimodal := isImage && options.EnableMultimodel && len(options.StoredImages) > 0
|
||||
pendingPDFMultimodal := !isImage && !isVideo && options.EnableMultimodel && len(options.StoredImages) > 0
|
||||
|
||||
if s.currentAttemptSuperseded(ctx, knowledge.ID) {
|
||||
logger.Infof(ctx, "Parse attempt superseded, skipping completion: %s", knowledge.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
finalizeIndexedKnowledgeState(
|
||||
knowledge,
|
||||
|
|
@ -802,11 +813,19 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
|||
s.beginStage(ctx, knowledge.ID, types.StageMultimodal, types.JSONMap{
|
||||
"image_count": len(options.StoredImages),
|
||||
})
|
||||
s.enqueueImageMultimodalTasks(ctx, knowledge, kb, options.StoredImages, chunks, options.Metadata)
|
||||
if err := s.enqueueImageMultimodalTasks(
|
||||
ctx, knowledge, kb, options.StoredImages, chunks, options.Metadata,
|
||||
); err != nil {
|
||||
// Nothing else moves the row out of "processing"; let asynq
|
||||
// run the (idempotent) parse again, or dead-letter it.
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
s.skipStage(ctx, knowledge.ID, types.StageMultimodal, "skipped")
|
||||
// If there are no multimodal tasks, enqueue the post process task immediately
|
||||
s.enqueueKnowledgePostProcessTask(ctx, knowledge)
|
||||
if err := s.enqueueKnowledgePostProcessTask(ctx, knowledge); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Update tenant's storage usage
|
||||
|
|
@ -953,6 +972,24 @@ func applyRetryableSummaryFailureState(
|
|||
return fallback
|
||||
}
|
||||
|
||||
// saveSummaryState persists only the columns the summary task owns. The task
|
||||
// holds a row snapshot across its LLM call; a full-row save of it wrote the
|
||||
// parse status of that moment back over a cancel, a housekeeping failure or
|
||||
// a reparse that landed meanwhile. Over a reparse it put "finalizing" on the
|
||||
// new run's "processing" row, whose post-process then found the row no
|
||||
// longer processing, skipped its fan-out and left it stuck.
|
||||
func (s *knowledgeService) saveSummaryState(ctx context.Context, knowledge *types.Knowledge) error {
|
||||
if knowledge.UpdatedAt.IsZero() {
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
}
|
||||
return s.repo.UpdateKnowledgeColumns(ctx, knowledge.ID, map[string]interface{}{
|
||||
"description": knowledge.Description,
|
||||
"profile": knowledge.Profile,
|
||||
"summary_status": knowledge.SummaryStatus,
|
||||
"updated_at": knowledge.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
// summaryTaskWillRetry reports whether the current Asynq delivery has another
|
||||
// configured attempt remaining. Calls outside an Asynq worker are terminal.
|
||||
func summaryTaskWillRetry(ctx context.Context) bool {
|
||||
|
|
@ -1320,7 +1357,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
|||
// Update summary status to processing
|
||||
knowledge.SummaryStatus = types.SummaryStatusProcessing
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
if err := s.saveSummaryState(ctx, knowledge); err != nil {
|
||||
logger.Warnf(ctx, "Failed to update summary status to processing: %v", err)
|
||||
}
|
||||
|
||||
|
|
@ -1328,7 +1365,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
|||
markSummaryFailed := func() {
|
||||
knowledge.SummaryStatus = types.SummaryStatusFailed
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
if err := s.saveSummaryState(ctx, knowledge); err != nil {
|
||||
logger.Warnf(ctx, "Failed to update summary status to failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1357,7 +1394,9 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
|||
knowledge.Profile = nil
|
||||
knowledge.SummaryStatus = types.SummaryStatusFailed
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
s.repo.UpdateKnowledge(ctx, knowledge)
|
||||
if err := s.saveSummaryState(ctx, knowledge); err != nil {
|
||||
logger.Warnf(ctx, "Failed to mark summary failed for knowledge without text chunks: %v", err)
|
||||
}
|
||||
summaryOut["skipped"] = "no_text_chunks"
|
||||
return nil
|
||||
}
|
||||
|
|
@ -1375,7 +1414,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
|||
|
||||
if summaryTaskWillRetry(ctx) {
|
||||
applyRetryableSummaryFailureState(knowledge, textChunks, true)
|
||||
if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil {
|
||||
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
|
||||
logger.Warnf(ctx, "Failed to mark summary pending for retry: %v", updateErr)
|
||||
}
|
||||
summaryOut["retrying"] = true
|
||||
|
|
@ -1402,7 +1441,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
|||
}
|
||||
|
||||
fallback := applyRetryableSummaryFailureState(knowledge, textChunks, false)
|
||||
if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil {
|
||||
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
|
||||
logger.Errorf(ctx, "Failed to save terminal summary fallback: %v", updateErr)
|
||||
summaryErr = updateErr
|
||||
return fmt.Errorf("save terminal summary fallback: %w", updateErr)
|
||||
|
|
@ -1444,7 +1483,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
|||
knowledge.Profile = nil
|
||||
knowledge.SummaryStatus = types.SummaryStatusFailed
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil {
|
||||
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
|
||||
logger.Errorf(ctx, "Failed to mark summary as failed: %v", updateErr)
|
||||
summaryErr = updateErr
|
||||
return fmt.Errorf("failed to update knowledge: %w", updateErr)
|
||||
|
|
@ -1485,7 +1524,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
|||
// without hopping to the knowledge-detail page. Capped to keep
|
||||
// span rows compact.
|
||||
summaryOut["summary_preview"] = previewText(summary, 240)
|
||||
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
if err := s.saveSummaryState(ctx, knowledge); err != nil {
|
||||
logger.Errorf(ctx, "Failed to update knowledge description: %v", err)
|
||||
summaryErr = err
|
||||
return fmt.Errorf("failed to update knowledge: %w", err)
|
||||
|
|
@ -2488,7 +2527,7 @@ func (s *knowledgeService) RegenerateKnowledgeSummary(
|
|||
knowledge.Profile = nil
|
||||
knowledge.SummaryStatus = types.SummaryStatusFailed
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil {
|
||||
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
|
||||
return knowledge, updateErr
|
||||
}
|
||||
_ = requestKnowledgeBaseProfileRefresh(ctx, s.task, kb, false)
|
||||
|
|
@ -2499,7 +2538,7 @@ func (s *knowledgeService) RegenerateKnowledgeSummary(
|
|||
})
|
||||
metadataVersion := string(knowledge.CustomMetadata)
|
||||
knowledge.SummaryStatus = types.SummaryStatusProcessing
|
||||
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
if err := s.saveSummaryState(ctx, knowledge); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handleGenerationFailure := func(generationErr error) (*types.Knowledge, error) {
|
||||
|
|
@ -2508,14 +2547,14 @@ func (s *knowledgeService) RegenerateKnowledgeSummary(
|
|||
knowledge.Profile = nil
|
||||
knowledge.SummaryStatus = types.SummaryStatusFailed
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil {
|
||||
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
|
||||
return knowledge, updateErr
|
||||
}
|
||||
return knowledge, generationErr
|
||||
}
|
||||
if summaryTaskWillRetry(ctx) {
|
||||
applyRetryableSummaryFailureState(knowledge, textChunks, true)
|
||||
if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil {
|
||||
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
|
||||
logger.Warnf(ctx, "Failed to mark summary refresh pending for retry: %v", updateErr)
|
||||
}
|
||||
return knowledge, generationErr
|
||||
|
|
@ -2526,7 +2565,7 @@ func (s *knowledgeService) RegenerateKnowledgeSummary(
|
|||
)
|
||||
if staleErr != nil {
|
||||
knowledge.SummaryStatus = types.SummaryStatusFailed
|
||||
_ = s.repo.UpdateKnowledge(ctx, knowledge)
|
||||
_ = s.saveSummaryState(ctx, knowledge)
|
||||
return knowledge, fmt.Errorf("verify summary fallback freshness: %w", staleErr)
|
||||
}
|
||||
if stale {
|
||||
|
|
@ -2534,7 +2573,7 @@ func (s *knowledgeService) RegenerateKnowledgeSummary(
|
|||
}
|
||||
|
||||
applyRetryableSummaryFailureState(knowledge, textChunks, false)
|
||||
if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil {
|
||||
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
|
||||
return knowledge, updateErr
|
||||
}
|
||||
return knowledge, generationErr
|
||||
|
|
@ -2563,7 +2602,7 @@ func (s *knowledgeService) RegenerateKnowledgeSummary(
|
|||
knowledge.Profile = summaryResult.Profile
|
||||
knowledge.SummaryStatus = types.SummaryStatusCompleted
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
if err := s.saveSummaryState(ctx, knowledge); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
summaryChunkContent := buildSummaryChunkContent(summary, summaryResult.Profile)
|
||||
|
|
@ -2622,6 +2661,19 @@ func (s *knowledgeService) ReparseKnowledge(
|
|||
ctx context.Context,
|
||||
knowledgeID string,
|
||||
processOverrides *types.KnowledgeProcessOverrides,
|
||||
) (*types.Knowledge, error) {
|
||||
return s.reparseKnowledge(ctx, knowledgeID, processOverrides, false)
|
||||
}
|
||||
|
||||
// reparseKnowledge implements ReparseKnowledge. tasksDequeued tells it the
|
||||
// caller already dropped the knowledge's queued tasks (ReplaceKnowledgeFile
|
||||
// does, before pointing the row at the new file), which saves a second scan
|
||||
// of every queue.
|
||||
func (s *knowledgeService) reparseKnowledge(
|
||||
ctx context.Context,
|
||||
knowledgeID string,
|
||||
processOverrides *types.KnowledgeProcessOverrides,
|
||||
tasksDequeued bool,
|
||||
) (*types.Knowledge, error) {
|
||||
logger.Info(ctx, "Start re-parsing knowledge")
|
||||
|
||||
|
|
@ -2633,19 +2685,6 @@ func (s *knowledgeService) ReparseKnowledge(
|
|||
|
||||
tenantID := existing.TenantID
|
||||
|
||||
// Allocate a fresh span tree attempt up front. Doing this BEFORE
|
||||
// the cleanup + enqueue means: (a) the UI immediately sees a new
|
||||
// attempt with all five stages back to "pending" instead of the
|
||||
// previous run's "failed" badge lingering; (b) the worker's
|
||||
// fallback path won't double-allocate when payload.Attempt is
|
||||
// already set on the queued task.
|
||||
reparseAttempt := 0
|
||||
if root, n, err := s.tracker().OpenAttempt(ctx, existing.ID, ""); err == nil && root != nil {
|
||||
reparseAttempt = n
|
||||
} else if err != nil {
|
||||
logger.Warnf(ctx, "[Reparse] OpenAttempt failed for %s: %v (will fall back in worker)", existing.ID, err)
|
||||
}
|
||||
|
||||
// When the caller supplies new overrides (e.g. via the reparse confirm
|
||||
// dialog), validate them against this knowledge's file type, then persist
|
||||
// to metadata so both this call's enqueue and the worker re-read the same
|
||||
|
|
@ -2667,15 +2706,60 @@ func (s *knowledgeService) ReparseKnowledge(
|
|||
processOverrides, _ = existing.ProcessOverrides()
|
||||
reparseEff := ResolveProcessConfig(kb, processOverrides)
|
||||
|
||||
var manualContent string
|
||||
if existing.IsManual() {
|
||||
meta, metaErr := existing.ManualMetadata()
|
||||
if metaErr != nil || meta == nil {
|
||||
logger.Errorf(ctx, "Failed to get manual metadata for reparse: %v", metaErr)
|
||||
return nil, werrors.NewBadRequestError("无法获取手工知识内容")
|
||||
}
|
||||
manualContent = meta.Content
|
||||
} else {
|
||||
// Cleanup synchronously; manual knowledge is cleaned up by its worker.
|
||||
logger.Infof(ctx, "Cleaning up existing resources for knowledge: %s", knowledgeID)
|
||||
if err := s.cleanupKnowledgeResources(ctx, existing); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Everything that can reject the reparse has run. From here on the
|
||||
// previous run is superseded, so stop it before announcing the new one.
|
||||
//
|
||||
// A reparse may land while the previous run is still in flight (batch
|
||||
// reparse and the API do not gate on status). Its queued tasks would
|
||||
// otherwise run against the new attempt: an old ProcessDocument wipes the
|
||||
// new chunks and writes "processing" back, an old post-process seeds the
|
||||
// counter for subtasks that all drop themselves as superseded.
|
||||
if !tasksDequeued && isInFlightParseStatus(existing.ParseStatus) {
|
||||
s.dequeueKnowledgeTasks(ctx, existing.ID)
|
||||
}
|
||||
|
||||
// Allocate the new span tree attempt only now. Opening it earlier and
|
||||
// then rejecting the reparse left the previous run's subtasks seeing a
|
||||
// newer attempt: they skipped their drain as superseded and stranded the
|
||||
// row in "finalizing". Opening it before the enqueue still means the UI
|
||||
// shows the fresh attempt immediately and the worker does not allocate a
|
||||
// second one.
|
||||
reparseAttempt := 0
|
||||
if root, n, err := s.tracker().OpenAttempt(ctx, existing.ID, ""); err == nil && root != nil {
|
||||
reparseAttempt = n
|
||||
} else if err != nil {
|
||||
logger.Warnf(ctx, "[Reparse] OpenAttempt failed for %s: %v (will fall back in worker)", existing.ID, err)
|
||||
}
|
||||
|
||||
// Keep wiki's pending queue consistent across both manual and non-manual
|
||||
// paths. The destructive work (swapping old wiki contributions for new)
|
||||
// happens asynchronously inside mapOneDocument — see its oldPageSlugs
|
||||
// handling — once post-process re-enqueues wiki ingest. All we need to
|
||||
// do here is stop any stale pending ingest op from firing against the
|
||||
// pre-reparse chunk set.
|
||||
if kb != nil && kb.IsWikiEnabled() {
|
||||
s.prepareWikiForReparse(ctx, existing)
|
||||
}
|
||||
// pre-reparse chunk set. The op's finalizing slot is not released: the
|
||||
// reset below zeroes the counter. Scrub even when wiki is off now: an op
|
||||
// left by an earlier wiki-enabled run would otherwise drain a slot of
|
||||
// the new attempt.
|
||||
s.prepareWikiForReparse(ctx, existing)
|
||||
recordReparseStarted := func() {
|
||||
recordKBActivity(ctx, s.audit, tenantID, existing.KnowledgeBaseID, types.AuditActionKnowledgeReparseStarted,
|
||||
"knowledge", existing.ID, types.AuditOutcomeAccepted,
|
||||
|
|
@ -2684,12 +2768,6 @@ func (s *knowledgeService) ReparseKnowledge(
|
|||
|
||||
// For manual knowledge, use async manual processing (cleanup + re-indexing in worker)
|
||||
if existing.IsManual() {
|
||||
meta, metaErr := existing.ManualMetadata()
|
||||
if metaErr != nil || meta == nil {
|
||||
logger.Errorf(ctx, "Failed to get manual metadata for reparse: %v", metaErr)
|
||||
return nil, werrors.NewBadRequestError("无法获取手工知识内容")
|
||||
}
|
||||
|
||||
resetKnowledgeForReparse(existing, kb)
|
||||
|
||||
if err := s.repo.UpdateKnowledge(ctx, existing); err != nil {
|
||||
|
|
@ -2701,7 +2779,7 @@ func (s *knowledgeService) ReparseKnowledge(
|
|||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := s.enqueueManualProcessing(ctx, existing, meta.Content, true); err != nil {
|
||||
if _, err := s.enqueueManualProcessing(ctx, existing, manualContent, true); err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue manual reparse task: %v", err)
|
||||
s.markKnowledgeEnqueueFailed(ctx, existing)
|
||||
return existing, werrors.NewInternalServerError("Failed to submit processing task")
|
||||
|
|
@ -2711,15 +2789,6 @@ func (s *knowledgeService) ReparseKnowledge(
|
|||
return existing, nil
|
||||
}
|
||||
|
||||
// For non-manual knowledge, cleanup synchronously then enqueue document processing
|
||||
logger.Infof(ctx, "Cleaning up existing resources for knowledge: %s", knowledgeID)
|
||||
if err := s.cleanupKnowledgeResources(ctx, existing); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Step 2: Update knowledge status and metadata
|
||||
resetKnowledgeForReparse(existing, kb)
|
||||
|
||||
|
|
@ -2977,7 +3046,9 @@ func (s *knowledgeService) CancelKnowledgeParse(
|
|||
"parse_status": types.ParseStatusCancelled,
|
||||
"error_message": "用户已取消解析",
|
||||
"pending_subtasks_count": 0,
|
||||
"updated_at": now,
|
||||
// The summary task is dequeued (or will bail) with the rest.
|
||||
"summary_status": summaryStatusClosedExpr(types.SummaryStatusNone),
|
||||
"updated_at": now,
|
||||
}); err != nil {
|
||||
logger.Errorf(ctx, "CancelKnowledgeParse: failed to mark knowledge cancelled: %v", err)
|
||||
return nil, err
|
||||
|
|
@ -2985,6 +3056,9 @@ func (s *knowledgeService) CancelKnowledgeParse(
|
|||
existing.ParseStatus = types.ParseStatusCancelled
|
||||
existing.ErrorMessage = "用户已取消解析"
|
||||
existing.PendingSubtasksCount = 0
|
||||
if existing.SummaryStatus == types.SummaryStatusPending || existing.SummaryStatus == types.SummaryStatusProcessing {
|
||||
existing.SummaryStatus = types.SummaryStatusNone
|
||||
}
|
||||
existing.UpdatedAt = now
|
||||
logger.Infof(ctx, "Knowledge %s marked as cancelled by user", knowledgeID)
|
||||
|
||||
|
|
@ -3311,15 +3385,20 @@ func (s *knowledgeService) ProcessManualUpdate(ctx context.Context, t *asynq.Tas
|
|||
|
||||
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
|
||||
if err != nil {
|
||||
// Retry: acking leaves the row pending with no task behind it.
|
||||
logger.Errorf(ctx, "ProcessManualUpdate: failed to get tenant: %v", err)
|
||||
return nil
|
||||
return fmt.Errorf("get tenant %d: %w", payload.TenantID, err)
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenantInfo)
|
||||
|
||||
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
|
||||
if errors.Is(err, repository.ErrKnowledgeNotFound) {
|
||||
logger.Warnf(ctx, "ProcessManualUpdate: knowledge not found: %s", payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "ProcessManualUpdate: failed to get knowledge: %v", err)
|
||||
return nil
|
||||
return fmt.Errorf("get knowledge %s: %w", payload.KnowledgeID, err)
|
||||
}
|
||||
if knowledge == nil {
|
||||
logger.Warnf(ctx, "ProcessManualUpdate: knowledge not found: %s", payload.KnowledgeID)
|
||||
|
|
@ -3374,7 +3453,7 @@ func (s *knowledgeService) ProcessManualUpdate(ctx context.Context, t *asynq.Tas
|
|||
markKnowledgeProcessing(knowledge, time.Now())
|
||||
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
logger.Errorf(ctx, "ProcessManualUpdate: failed to update status to processing: %v", err)
|
||||
return nil
|
||||
return fmt.Errorf("mark knowledge %s processing: %w", knowledge.ID, err)
|
||||
}
|
||||
|
||||
// Allocate a fresh span-tracking attempt for this manual (re)index.
|
||||
|
|
@ -3422,15 +3501,20 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
|||
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
|
||||
}
|
||||
|
||||
// 获取任务重试信息,用于判断是否是最后一次重试
|
||||
// 获取任务重试信息,用于判断是否是最后一次重试。Lite 模式的执行器不提供
|
||||
// asynq 的重试计数,改用它注入的 TaskRetryMetadata;否则每次都算最后一次。
|
||||
retryCount, _ := asynq.GetRetryCount(ctx)
|
||||
maxRetry, _ := asynq.GetMaxRetry(ctx)
|
||||
if retried, limit, ok := types.TaskRetryMetadataFromContext(ctx); ok {
|
||||
retryCount, maxRetry = retried, limit
|
||||
}
|
||||
isLastRetry := retryCount >= maxRetry
|
||||
|
||||
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
|
||||
if err != nil {
|
||||
// Retry: acking leaves the row pending with no task behind it.
|
||||
logger.Errorf(ctx, "failed to get tenant: %v", err)
|
||||
return nil
|
||||
return fmt.Errorf("get tenant %d: %w", payload.TenantID, err)
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenantInfo)
|
||||
|
||||
|
|
@ -3439,9 +3523,12 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
|||
|
||||
// 幂等性检查:获取knowledge记录
|
||||
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
|
||||
if errors.Is(err, repository.ErrKnowledgeNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to get knowledge: %v", err)
|
||||
return nil
|
||||
return fmt.Errorf("get knowledge %s: %w", payload.KnowledgeID, err)
|
||||
}
|
||||
|
||||
if knowledge == nil {
|
||||
|
|
@ -3455,6 +3542,15 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
|||
return err
|
||||
}
|
||||
|
||||
// A reparse opened a newer attempt after this task was queued (or while
|
||||
// an earlier delivery of it was running). Its row, chunks and counter
|
||||
// belong to the new run; this task must not touch them.
|
||||
if attemptSuperseded(ctx, s.tracker(), payload.KnowledgeID, payload.Attempt) {
|
||||
logger.Infof(ctx, "Parse attempt %d superseded, skipping stale process task: %s",
|
||||
payload.Attempt, payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 检查是否正在删除 / 已被用户取消 - 如果是则直接退出
|
||||
if knowledge.ParseStatus == types.ParseStatusDeleting {
|
||||
logger.Infof(ctx, "Knowledge is being deleted, aborting processing: %s", payload.KnowledgeID)
|
||||
|
|
@ -3530,7 +3626,7 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
|||
markKnowledgeProcessing(knowledge, time.Now())
|
||||
if err := s.updateKnowledgeUnlessSourceReplaced(ctx, knowledge); err != nil {
|
||||
logger.Errorf(ctx, "failed to update knowledge status to processing: %v", err)
|
||||
return nil
|
||||
return fmt.Errorf("mark knowledge %s processing: %w", knowledge.ID, err)
|
||||
}
|
||||
if s.isKnowledgeSourceReplaced(ctx, knowledge) {
|
||||
logger.Infof(ctx, "Document source replaced, aborting after status update: %s", payload.KnowledgeID)
|
||||
|
|
@ -4150,7 +4246,9 @@ func (s *knowledgeService) failKnowledge(
|
|||
return nil, fmt.Errorf(format, args...)
|
||||
}
|
||||
|
||||
// enqueueImageMultimodalTasks enqueues asynq tasks for multimodal image processing.
|
||||
// enqueueImageMultimodalTasks enqueues asynq tasks for multimodal image
|
||||
// processing. It returns an error only when no path is left to move the
|
||||
// knowledge out of "processing" (see releaseUnownedMultimodalSlots).
|
||||
func (s *knowledgeService) enqueueImageMultimodalTasks(
|
||||
ctx context.Context,
|
||||
knowledge *types.Knowledge,
|
||||
|
|
@ -4158,9 +4256,9 @@ func (s *knowledgeService) enqueueImageMultimodalTasks(
|
|||
images []docparser.StoredImage,
|
||||
chunks []types.ParsedChunk,
|
||||
metadata map[string]string,
|
||||
) {
|
||||
) error {
|
||||
if s.task == nil || len(images) == 0 {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
attempt := attemptFromCtx(ctx)
|
||||
|
|
@ -4178,6 +4276,9 @@ func (s *knowledgeService) enqueueImageMultimodalTasks(
|
|||
} else {
|
||||
counterSeeded = true
|
||||
}
|
||||
} else {
|
||||
liteMultimodalSet(redisKey, int64(len(images)))
|
||||
counterSeeded = true
|
||||
}
|
||||
|
||||
// Resolve the image pipeline settings once for the whole fan-out: the image
|
||||
|
|
@ -4236,7 +4337,7 @@ func (s *knowledgeService) enqueueImageMultimodalTasks(
|
|||
logger.Infof(ctx, "Enqueued image:multimodal task for %s", img.ServingURL)
|
||||
}
|
||||
|
||||
s.releaseUnownedMultimodalSlots(
|
||||
return s.releaseUnownedMultimodalSlots(
|
||||
ctx, knowledge, redisKey, counterSeeded, len(images), enqueued,
|
||||
)
|
||||
}
|
||||
|
|
@ -4258,7 +4359,7 @@ func (s *knowledgeService) releaseUnownedMultimodalSlots(
|
|||
redisKey string,
|
||||
counterSeeded bool,
|
||||
planned, enqueued int,
|
||||
) {
|
||||
) error {
|
||||
if enqueued == 0 {
|
||||
// No task exists to finalize this knowledge, whatever the counter
|
||||
// says. Drive post-process directly so the row completes on the
|
||||
|
|
@ -4272,23 +4373,22 @@ func (s *knowledgeService) releaseUnownedMultimodalSlots(
|
|||
// own 24h TTL.
|
||||
dctx, cancel := context.WithTimeout(
|
||||
context.WithoutCancel(ctx), finalizeSubtaskDetachedTimeout)
|
||||
s.redisClient.Del(dctx, redisKey)
|
||||
s.delMultimodalCounter(dctx, redisKey)
|
||||
cancel()
|
||||
}
|
||||
s.enqueueKnowledgePostProcessTask(ctx, knowledge)
|
||||
return
|
||||
return s.enqueueKnowledgePostProcessTask(ctx, knowledge)
|
||||
}
|
||||
|
||||
shortfall := planned - enqueued
|
||||
if shortfall <= 0 {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
if !counterSeeded {
|
||||
// Seeding failed, so the key is absent and the first image to finish
|
||||
// already drives post-process through the missing-key fallback in
|
||||
// checkAndFinalizeAllImages. Decrementing here would only create the
|
||||
// key below zero and finalize before the siblings are done.
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Warnf(ctx,
|
||||
|
|
@ -4309,15 +4409,28 @@ func (s *knowledgeService) releaseUnownedMultimodalSlots(
|
|||
"Failed to release %d multimodal slot(s) for %s after %d attempts: %v; "+
|
||||
"row will be left to the housekeeping sweep",
|
||||
shortfall, knowledge.ID, multimodalSlotReleaseAttempts, err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
if pending <= 0 {
|
||||
// Every enqueued sibling had already finished, so the release owns the
|
||||
// finalize. Ordering is safe either way: the slots we just drained have
|
||||
// no task behind them, so exactly one path reaches zero.
|
||||
s.redisClient.Del(rctx, redisKey)
|
||||
s.enqueueKnowledgePostProcessTask(ctx, knowledge)
|
||||
if err := s.enqueueKnowledgePostProcessTask(ctx, knowledge); err != nil {
|
||||
return err
|
||||
}
|
||||
s.delMultimodalCounter(rctx, redisKey)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// delMultimodalCounter removes the fan-in counter from Redis, or from the
|
||||
// in-process stand-in in Lite mode.
|
||||
func (s *knowledgeService) delMultimodalCounter(ctx context.Context, redisKey string) {
|
||||
if s.redisClient == nil {
|
||||
liteMultimodalDel(redisKey)
|
||||
return
|
||||
}
|
||||
s.redisClient.Del(ctx, redisKey)
|
||||
}
|
||||
|
||||
// multimodalSlotReleaseAttempts bounds the retry on the release decrement.
|
||||
|
|
@ -4344,6 +4457,9 @@ const multimodalSlotReleaseBackoff = 100 * time.Millisecond
|
|||
func (s *knowledgeService) decrMultimodalSlots(
|
||||
ctx context.Context, redisKey string, by int64,
|
||||
) (int64, error) {
|
||||
if s.redisClient == nil {
|
||||
return liteMultimodalDecrBy(redisKey, by), nil
|
||||
}
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= multimodalSlotReleaseAttempts; attempt++ {
|
||||
pending, err := s.redisClient.DecrBy(ctx, redisKey, by).Result()
|
||||
|
|
@ -4369,11 +4485,15 @@ func (s *knowledgeService) decrMultimodalSlots(
|
|||
// orchestrator, which owns the enrichment fan-out and the promotion out of
|
||||
// "processing". Shared by the no-multimodal path and by the multimodal slot
|
||||
// release, so both build the same payload (attempt, language, tracing).
|
||||
//
|
||||
// The error must reach the caller's task result: once the chunks are indexed
|
||||
// this enqueue is the only thing that moves the row out of "processing", so
|
||||
// swallowing it acked the task with the row stranded until housekeeping.
|
||||
func (s *knowledgeService) enqueueKnowledgePostProcessTask(
|
||||
ctx context.Context, knowledge *types.Knowledge,
|
||||
) {
|
||||
) error {
|
||||
if s.task == nil {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
payload := types.KnowledgePostProcessPayload{
|
||||
TenantID: knowledge.TenantID,
|
||||
|
|
@ -4386,15 +4506,16 @@ func (s *knowledgeService) enqueueKnowledgePostProcessTask(
|
|||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal knowledge post process payload: %v", err)
|
||||
return
|
||||
return fmt.Errorf("marshal post process payload: %w", err)
|
||||
}
|
||||
task := asynq.NewTask(types.TypeKnowledgePostProcess, payloadBytes,
|
||||
knowledgePostProcessTaskOptions()...)
|
||||
if _, err := s.task.Enqueue(task); err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue knowledge post process task: %v", err)
|
||||
return
|
||||
if err := enqueueWithRetry(ctx, s.task, task); err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue knowledge post process task for %s: %v", knowledge.ID, err)
|
||||
return err
|
||||
}
|
||||
logger.Infof(ctx, "Enqueued knowledge post process task for %s", knowledge.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProcessKnowledgeListReparse handles Asynq knowledge list reparse tasks.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,152 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// reparseScrubPendingRepo records the wiki pending-op scrub in the shared
|
||||
// event log so a test can see where it falls relative to dequeue and
|
||||
// OpenAttempt.
|
||||
type reparseScrubPendingRepo struct {
|
||||
interfaces.TaskPendingOpsRepository
|
||||
events *[]string
|
||||
}
|
||||
|
||||
func (r *reparseScrubPendingRepo) DeleteByDedupKey(_ context.Context, _, _, _, dedupKey, op string) error {
|
||||
*r.events = append(*r.events, "scrub:"+op+":"+dedupKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
type failingCleanupChunkRepo struct {
|
||||
replaceFileChunks
|
||||
err error
|
||||
}
|
||||
|
||||
func (r failingCleanupChunkRepo) DeleteChunksByKnowledgeID(context.Context, uint64, string) error {
|
||||
return r.err
|
||||
}
|
||||
|
||||
// newReparseHarness reuses the replace-file harness (single-row repo, event
|
||||
// log, recording inspector and enqueuer) with a tracker and a wiki pending
|
||||
// repo that write into the same event log.
|
||||
func newReparseHarness(t *testing.T, status string) *replaceFileHarness {
|
||||
t.Helper()
|
||||
h := newReplaceFileHarness(t)
|
||||
h.repo.row.ParseStatus = status
|
||||
tracker := newAttemptTracker()
|
||||
tracker.events = &h.events
|
||||
h.svc.spanTracker = tracker
|
||||
h.svc.taskPendingRepo = &reparseScrubPendingRepo{events: &h.events}
|
||||
return h
|
||||
}
|
||||
|
||||
// A rejected reparse must leave the previous run alone: opening a newer
|
||||
// attempt made that run's subtasks drop themselves as superseded without
|
||||
// draining, stranding the row in "finalizing".
|
||||
func TestReparseKnowledgeRejectedLeavesPreviousRunUntouched(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setup func(h *replaceFileHarness)
|
||||
overrides *types.KnowledgeProcessOverrides
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "override validation fails",
|
||||
setup: func(h *replaceFileHarness) {
|
||||
// An image needs a VLM model, which the KB does not have.
|
||||
h.repo.row.FileName = "a.png"
|
||||
h.repo.row.FileType = "png"
|
||||
},
|
||||
overrides: &types.KnowledgeProcessOverrides{},
|
||||
wantErr: "VLM",
|
||||
},
|
||||
{
|
||||
name: "resource cleanup fails",
|
||||
setup: func(h *replaceFileHarness) {
|
||||
h.svc.chunkRepo = failingCleanupChunkRepo{err: errors.New("database unavailable")}
|
||||
},
|
||||
wantErr: "database unavailable",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
h := newReparseHarness(t, types.ParseStatusFinalizing)
|
||||
test.setup(h)
|
||||
|
||||
_, err := h.svc.ReparseKnowledge(h.ctx, h.original.ID, test.overrides)
|
||||
|
||||
require.ErrorContains(t, err, test.wantErr)
|
||||
assert.Empty(t, h.events, "no dequeue, no new attempt, no wiki scrub")
|
||||
assert.Zero(t, h.svc.spanTracker.(*attemptTracker).opened)
|
||||
assert.Equal(t, types.ParseStatusFinalizing, h.repo.row.ParseStatus)
|
||||
assert.Empty(t, h.tasks.payloads)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A reparse over a run that may still own queued tasks drops them before it
|
||||
// announces the new attempt; a finished run has nothing to drop.
|
||||
func TestReparseKnowledgeDequeuesOnlyInFlightRuns(t *testing.T) {
|
||||
scrub := "scrub:" + WikiOpIngest + ":knowledge-1"
|
||||
tests := []struct {
|
||||
status string
|
||||
want []string
|
||||
}{
|
||||
{types.ParseStatusPending, []string{"dequeue:knowledge-1", "open-attempt", scrub, "enqueue"}},
|
||||
{types.ParseStatusProcessing, []string{"dequeue:knowledge-1", "open-attempt", scrub, "enqueue"}},
|
||||
{types.ParseStatusFinalizing, []string{"dequeue:knowledge-1", "open-attempt", scrub, "enqueue"}},
|
||||
{types.ParseStatusCompleted, []string{"open-attempt", scrub, "enqueue"}},
|
||||
{types.ParseStatusFailed, []string{"open-attempt", scrub, "enqueue"}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.status, func(t *testing.T) {
|
||||
h := newReparseHarness(t, test.status)
|
||||
|
||||
_, err := h.svc.ReparseKnowledge(h.ctx, h.original.ID, nil)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.want, h.events)
|
||||
require.Len(t, h.tasks.payloads, 1)
|
||||
assert.Equal(t, 1, h.tasks.payloads[0].Attempt, "the task carries the attempt opened for it")
|
||||
assert.Equal(t, types.ParseStatusPending, h.repo.row.ParseStatus)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ReplaceKnowledgeFile already dropped the queued tasks before swapping the
|
||||
// file, so its reparse must not scan the queues a second time.
|
||||
func TestReplaceKnowledgeFileDequeuesInFlightParseOnce(t *testing.T) {
|
||||
h := newReparseHarness(t, types.ParseStatusProcessing)
|
||||
|
||||
_, err := h.replace(t, "# new body", "notes/a.md", nil)
|
||||
|
||||
require.NoError(t, err)
|
||||
dequeues := 0
|
||||
for _, event := range h.events {
|
||||
if event == "dequeue:knowledge-1" {
|
||||
dequeues++
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 1, dequeues)
|
||||
}
|
||||
|
||||
// An ingest op left by an earlier wiki-enabled run would drain a slot of the
|
||||
// new attempt, so the scrub runs even when the KB has wiki turned off now.
|
||||
func TestReparseKnowledgeScrubsWikiOpWhenWikiDisabled(t *testing.T) {
|
||||
h := newReparseHarness(t, types.ParseStatusCompleted)
|
||||
kb, err := h.svc.kbService.GetKnowledgeBaseByID(h.ctx, "kb-1")
|
||||
require.NoError(t, err)
|
||||
require.False(t, kb.IsWikiEnabled())
|
||||
|
||||
_, err = h.svc.ReparseKnowledge(h.ctx, h.original.ID, nil)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, h.events, "scrub:"+WikiOpIngest+":knowledge-1")
|
||||
}
|
||||
|
|
@ -170,7 +170,7 @@ func (s *knowledgeService) ReplaceKnowledgeFile(ctx context.Context,
|
|||
existing.ID, err)
|
||||
}
|
||||
|
||||
reparsed, err := s.ReparseKnowledge(ctx, existing.ID, nil)
|
||||
reparsed, err := s.reparseKnowledge(ctx, existing.ID, nil, true)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Reparse after replacing the file of knowledge %s failed, restoring source: %v",
|
||||
existing.ID, err)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,124 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// flakyFinalizeRepo fails the first `failures` FinalizeSubtask calls.
|
||||
type flakyFinalizeRepo struct {
|
||||
interfaces.KnowledgeRepository
|
||||
mu sync.Mutex
|
||||
failures int
|
||||
calls int
|
||||
successes int
|
||||
}
|
||||
|
||||
func (r *flakyFinalizeRepo) FinalizeSubtask(context.Context, string) (int, bool, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.calls++
|
||||
if r.calls <= r.failures {
|
||||
return 0, false, errors.New("serialization failure")
|
||||
}
|
||||
r.successes++
|
||||
return 0, false, nil
|
||||
}
|
||||
|
||||
// The release is the only thing that drains a finished task's slot, so one
|
||||
// transient DB error must not strand the row in "finalizing".
|
||||
func TestFinalizeSubtaskDetachedRetriesTransientFailure(t *testing.T) {
|
||||
repo := &flakyFinalizeRepo{failures: subtaskSlotReleaseAttempts - 1}
|
||||
|
||||
finalizeSubtaskDetached(context.Background(), repo, "k-1", "summary", nil, false, true)
|
||||
|
||||
assert.Equal(t, subtaskSlotReleaseAttempts, repo.calls)
|
||||
assert.Equal(t, 1, repo.successes)
|
||||
}
|
||||
|
||||
func TestReleaseSubtaskSlotGivesUpAfterBoundedRetries(t *testing.T) {
|
||||
repo := &flakyFinalizeRepo{failures: subtaskSlotReleaseAttempts + 5}
|
||||
|
||||
err := releaseSubtaskSlot(context.Background(), repo, "k-1")
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, subtaskSlotReleaseAttempts, repo.calls)
|
||||
}
|
||||
|
||||
// The release rides a detached context: a worker whose own context is
|
||||
// already cancelled (shutdown) must still drain its slot.
|
||||
func TestReleaseSubtaskSlotIgnoresCallerCancellation(t *testing.T) {
|
||||
repo := &flakyFinalizeRepo{}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
require.NoError(t, releaseSubtaskSlot(ctx, repo, "k-1"))
|
||||
assert.Equal(t, 1, repo.successes)
|
||||
}
|
||||
|
||||
type shortfallReleaseRepo struct {
|
||||
wikiEnqueueFailureKnowledgeRepo
|
||||
flaky flakyFinalizeRepo
|
||||
}
|
||||
|
||||
func (r *shortfallReleaseRepo) FinalizeSubtask(ctx context.Context, id string) (int, bool, error) {
|
||||
return r.flaky.FinalizeSubtask(ctx, id)
|
||||
}
|
||||
|
||||
// Post-process releases one slot per subtask it planned but could not
|
||||
// enqueue. A release that fails for good must not abandon the rest: each
|
||||
// remaining slot has no other owner.
|
||||
func TestKnowledgePostProcessShortfallReleaseContinuesPastFailure(t *testing.T) {
|
||||
// NEO4J off: the two planned graph-extract slots are never enqueued.
|
||||
t.Setenv("NEO4J_ENABLE", "false")
|
||||
const knowledgeID = "knowledge-shortfall"
|
||||
const kbID = "kb-shortfall"
|
||||
repo := &shortfallReleaseRepo{
|
||||
wikiEnqueueFailureKnowledgeRepo: wikiEnqueueFailureKnowledgeRepo{knowledge: &types.Knowledge{
|
||||
ID: knowledgeID, TenantID: 7, KnowledgeBaseID: kbID, ParseStatus: types.ParseStatusProcessing,
|
||||
}},
|
||||
// The first release exhausts its retries; the second succeeds.
|
||||
flaky: flakyFinalizeRepo{failures: subtaskSlotReleaseAttempts},
|
||||
}
|
||||
chunk := func(id, content string) *types.Chunk {
|
||||
return &types.Chunk{
|
||||
ID: id, TenantID: 7, KnowledgeID: knowledgeID, KnowledgeBaseID: kbID,
|
||||
ChunkType: types.ChunkTypeText, Content: content,
|
||||
}
|
||||
}
|
||||
queue := &wikiEnqueueFailureTaskQueue{}
|
||||
svc := &KnowledgePostProcessService{
|
||||
knowledgeRepo: repo,
|
||||
kbService: &wikiEnqueueFailureKBService{kb: &types.KnowledgeBase{
|
||||
ID: kbID, TenantID: 7,
|
||||
IndexingStrategy: types.IndexingStrategy{GraphEnabled: true},
|
||||
ExtractConfig: &types.ExtractConfig{Enabled: true},
|
||||
}},
|
||||
chunkRepo: &wikiEnqueueFailureChunkRepo{chunks: []*types.Chunk{
|
||||
chunk("c-1", "Contract between Alice and Bob."),
|
||||
chunk("c-2", "Payment is due in thirty days."),
|
||||
}},
|
||||
taskEnqueuer: queue,
|
||||
}
|
||||
payload, err := json.Marshal(types.KnowledgePostProcessPayload{
|
||||
TenantID: 7, KnowledgeID: knowledgeID, KnowledgeBaseID: kbID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
err = svc.Handle(context.Background(), asynq.NewTask(types.TypeKnowledgePostProcess, payload))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 3, repo.expectedSubtasks, "summary plus two graph slots")
|
||||
assert.Equal(t, []string{types.TypeSummaryGeneration}, queue.taskTypes)
|
||||
assert.Equal(t, subtaskSlotReleaseAttempts+1, repo.flaky.calls)
|
||||
assert.Equal(t, 1, repo.flaky.successes, "the second shortfall slot is still released")
|
||||
}
|
||||
|
|
@ -0,0 +1,209 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// summaryColumnsRepo fails the test on a full-row save and records every
|
||||
// column write, so a test can check the summary task only touches the
|
||||
// columns it owns.
|
||||
type summaryColumnsRepo struct {
|
||||
interfaces.KnowledgeRepository
|
||||
t *testing.T
|
||||
knowledge *types.Knowledge
|
||||
writes []map[string]interface{}
|
||||
}
|
||||
|
||||
func (r *summaryColumnsRepo) GetKnowledgeByID(context.Context, uint64, string) (*types.Knowledge, error) {
|
||||
k := *r.knowledge
|
||||
return &k, nil
|
||||
}
|
||||
|
||||
func (r *summaryColumnsRepo) UpdateKnowledge(context.Context, *types.Knowledge) error {
|
||||
r.t.Fatal("the summary task must not save the whole row")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *summaryColumnsRepo) UpdateKnowledgeColumns(_ context.Context, _ string, values map[string]interface{}) error {
|
||||
r.writes = append(r.writes, values)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *summaryColumnsRepo) FinalizeSubtask(context.Context, string) (int, bool, error) {
|
||||
return 0, false, nil
|
||||
}
|
||||
|
||||
type emptySummaryChunkRepo struct {
|
||||
interfaces.ChunkRepository
|
||||
}
|
||||
|
||||
func (emptySummaryChunkRepo) ListChunksByKnowledgeID(context.Context, uint64, string) ([]*types.Chunk, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func summaryKnowledge() *types.Knowledge {
|
||||
return &types.Knowledge{
|
||||
ID: "k-1", TenantID: 1, KnowledgeBaseID: "kb-1",
|
||||
ParseStatus: types.ParseStatusFinalizing, SummaryStatus: types.SummaryStatusPending,
|
||||
}
|
||||
}
|
||||
|
||||
func summaryKB() *types.KnowledgeBase {
|
||||
return &types.KnowledgeBase{ID: "kb-1", TenantID: 1, SummaryModelID: "summary-model"}
|
||||
}
|
||||
|
||||
func summaryGenerationTask(t *testing.T) *asynq.Task {
|
||||
t.Helper()
|
||||
payload, err := json.Marshal(types.SummaryGenerationPayload{
|
||||
TenantID: 1, KnowledgeID: "k-1", KnowledgeBaseID: "kb-1",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return asynq.NewTask(types.TypeSummaryGeneration, payload)
|
||||
}
|
||||
|
||||
func assertSummaryColumnsOnly(t *testing.T, writes []map[string]interface{}) {
|
||||
t.Helper()
|
||||
require.NotEmpty(t, writes)
|
||||
for _, values := range writes {
|
||||
for column := range values {
|
||||
assert.Contains(t, []string{"description", "profile", "summary_status", "updated_at"}, column)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The summary task holds a row snapshot across its LLM call; a full-row save
|
||||
// of it wrote that moment's parse status back over a cancel, a housekeeping
|
||||
// failure or a reparse that landed meanwhile.
|
||||
func TestProcessSummaryGenerationWritesOnlySummaryColumns(t *testing.T) {
|
||||
repo := &summaryColumnsRepo{t: t, knowledge: summaryKnowledge()}
|
||||
svc := &knowledgeService{
|
||||
repo: repo,
|
||||
kbService: &reparseFailureKBService{kb: summaryKB()},
|
||||
chunkService: &wikiEnqueueFailureChunkService{},
|
||||
}
|
||||
|
||||
err := svc.ProcessSummaryGeneration(context.Background(), summaryGenerationTask(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
assertSummaryColumnsOnly(t, repo.writes)
|
||||
last := repo.writes[len(repo.writes)-1]
|
||||
assert.Equal(t, types.SummaryStatusFailed, last["summary_status"], "no text chunks fails the summary")
|
||||
}
|
||||
|
||||
func TestRegenerateKnowledgeSummaryWritesOnlySummaryColumns(t *testing.T) {
|
||||
repo := &summaryColumnsRepo{t: t, knowledge: summaryKnowledge()}
|
||||
svc := &knowledgeService{
|
||||
repo: repo,
|
||||
kbService: &reparseFailureKBService{kb: summaryKB()},
|
||||
chunkRepo: emptySummaryChunkRepo{},
|
||||
}
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
|
||||
_, err := svc.RegenerateKnowledgeSummary(ctx, "k-1")
|
||||
|
||||
require.ErrorIs(t, err, errInsufficientSummaryContent)
|
||||
assertSummaryColumnsOnly(t, repo.writes)
|
||||
}
|
||||
|
||||
// cancellingChunkService cancels the knowledge in the database while the
|
||||
// summary task is running, as a user cancel landing mid-run would.
|
||||
type cancellingChunkService struct {
|
||||
interfaces.ChunkService
|
||||
db *gorm.DB
|
||||
t *testing.T
|
||||
}
|
||||
|
||||
func (s *cancellingChunkService) ListChunksByKnowledgeID(context.Context, string) ([]*types.Chunk, error) {
|
||||
require.NoError(s.t, s.db.Model(&types.Knowledge{}).Where("id = ?", "k-1").
|
||||
Updates(map[string]interface{}{
|
||||
"parse_status": types.ParseStatusCancelled,
|
||||
"pending_subtasks_count": 0,
|
||||
}).Error)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestProcessSummaryGenerationKeepsCancelThatLandedMidRun(t *testing.T) {
|
||||
db := setupKnowledgeSharedAccessDB(t)
|
||||
seed := summaryKnowledge()
|
||||
seed.PendingSubtasksCount = 1
|
||||
seedKnowledge(t, db, seed)
|
||||
svc := &knowledgeService{
|
||||
repo: repository.NewKnowledgeRepository(db),
|
||||
kbService: &reparseFailureKBService{kb: summaryKB()},
|
||||
chunkService: &cancellingChunkService{db: db, t: t},
|
||||
}
|
||||
|
||||
require.NoError(t, svc.ProcessSummaryGeneration(context.Background(), summaryGenerationTask(t)))
|
||||
|
||||
var row types.Knowledge
|
||||
require.NoError(t, db.Where("id = ?", "k-1").First(&row).Error)
|
||||
assert.Equal(t, types.ParseStatusCancelled, row.ParseStatus)
|
||||
assert.Equal(t, types.SummaryStatusFailed, row.SummaryStatus)
|
||||
}
|
||||
|
||||
// A cancel ends the run's summary task with it, so a summary still pending or
|
||||
// processing must not keep a spinner on the cancelled row; a summary that
|
||||
// already finished is kept.
|
||||
func TestCancelKnowledgeParseClosesUnfinishedSummary(t *testing.T) {
|
||||
tests := []struct {
|
||||
summary string
|
||||
want string
|
||||
}{
|
||||
{types.SummaryStatusPending, types.SummaryStatusNone},
|
||||
{types.SummaryStatusProcessing, types.SummaryStatusNone},
|
||||
{types.SummaryStatusCompleted, types.SummaryStatusCompleted},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.summary, func(t *testing.T) {
|
||||
db := setupKnowledgeSharedAccessDB(t)
|
||||
seed := summaryKnowledge()
|
||||
seed.SummaryStatus = test.summary
|
||||
seed.PendingSubtasksCount = 2
|
||||
seedKnowledge(t, db, seed)
|
||||
svc := &knowledgeService{repo: repository.NewKnowledgeRepository(db)}
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
|
||||
got, err := svc.CancelKnowledgeParse(ctx, "k-1")
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.want, got.SummaryStatus)
|
||||
var row types.Knowledge
|
||||
require.NoError(t, db.Where("id = ?", "k-1").First(&row).Error)
|
||||
assert.Equal(t, types.ParseStatusCancelled, row.ParseStatus)
|
||||
assert.Equal(t, test.want, row.SummaryStatus)
|
||||
assert.Zero(t, row.PendingSubtasksCount)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Manual knowledge with nothing to index had no later stage to move it out
|
||||
// of "processing", so it must be failed on the spot.
|
||||
func TestTriggerManualProcessingFailsEmptyContent(t *testing.T) {
|
||||
db := setupKnowledgeSharedAccessDB(t)
|
||||
seed := summaryKnowledge()
|
||||
seed.ParseStatus = types.ParseStatusProcessing
|
||||
seed.Type = types.KnowledgeTypeManual
|
||||
seedKnowledge(t, db, seed)
|
||||
svc := &knowledgeService{repo: repository.NewKnowledgeRepository(db)}
|
||||
before := time.Now().Add(-time.Second)
|
||||
|
||||
err := svc.triggerManualProcessing(context.Background(), summaryKB(), seed, " \n\t ", true)
|
||||
|
||||
require.NoError(t, err)
|
||||
var row types.Knowledge
|
||||
require.NoError(t, db.Where("id = ?", "k-1").First(&row).Error)
|
||||
assert.Equal(t, types.ParseStatusFailed, row.ParseStatus)
|
||||
assert.NotEmpty(t, row.ErrorMessage)
|
||||
assert.True(t, row.UpdatedAt.After(before))
|
||||
}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/hibiken/asynq"
|
||||
)
|
||||
|
||||
// liteMultimodalPending stands in for the Redis multimodal:pending:<kid>
|
||||
// counter in Lite mode. Lite runs every task inside this process, so an
|
||||
// in-memory counter sees every image; without one, each finished image
|
||||
// enqueued post-process, and the first one sealed the enrichment fan-out
|
||||
// before the other images had written their OCR / caption chunks. The
|
||||
// counter is lost on restart, where the Lite startup reset already fails
|
||||
// rows that were still processing.
|
||||
//
|
||||
// Keys and semantics mirror Redis: a missing key reads as zero, so a
|
||||
// decrement on it goes negative and still drives post-process.
|
||||
var liteMultimodalPending = struct {
|
||||
sync.Mutex
|
||||
counts map[string]int64
|
||||
}{counts: map[string]int64{}}
|
||||
|
||||
func liteMultimodalSet(key string, n int64) {
|
||||
liteMultimodalPending.Lock()
|
||||
defer liteMultimodalPending.Unlock()
|
||||
liteMultimodalPending.counts[key] = n
|
||||
}
|
||||
|
||||
func liteMultimodalDecrBy(key string, by int64) int64 {
|
||||
liteMultimodalPending.Lock()
|
||||
defer liteMultimodalPending.Unlock()
|
||||
n := liteMultimodalPending.counts[key] - by
|
||||
liteMultimodalPending.counts[key] = n
|
||||
return n
|
||||
}
|
||||
|
||||
func liteMultimodalDel(key string) {
|
||||
liteMultimodalPending.Lock()
|
||||
defer liteMultimodalPending.Unlock()
|
||||
delete(liteMultimodalPending.counts, key)
|
||||
}
|
||||
|
||||
// postProcessEnqueueAttempts bounds the in-place retry of the post-process
|
||||
// enqueue. That enqueue is the only thing that moves a knowledge out of
|
||||
// "processing" once its images are counted; retrying the whole image task
|
||||
// instead would run the VLM again and write its chunks twice.
|
||||
const (
|
||||
postProcessEnqueueAttempts = 3
|
||||
postProcessEnqueueBackoff = 500 * time.Millisecond
|
||||
)
|
||||
|
||||
// enqueueWithRetry enqueues task, retrying transient failures with a short
|
||||
// linear backoff. It stops early when ctx is done.
|
||||
func enqueueWithRetry(ctx context.Context, enq interfaces.TaskEnqueuer, task *asynq.Task) error {
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= postProcessEnqueueAttempts; attempt++ {
|
||||
_, err := enq.Enqueue(task)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
lastErr = err
|
||||
if attempt == postProcessEnqueueAttempts {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-time.After(time.Duration(attempt) * postProcessEnqueueBackoff):
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("enqueue %s: %w (last error: %v)", task.Type(), ctx.Err(), lastErr)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("enqueue %s after %d attempts: %w", task.Type(), postProcessEnqueueAttempts, lastErr)
|
||||
}
|
||||
|
|
@ -0,0 +1,287 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// liteCounter reads the in-process multimodal counter the way Redis would
|
||||
// report it: present or not, and its value.
|
||||
func liteCounter(knowledgeID string) (int64, bool) {
|
||||
liteMultimodalPending.Lock()
|
||||
defer liteMultimodalPending.Unlock()
|
||||
n, ok := liteMultimodalPending.counts[multimodalPendingKey(knowledgeID)]
|
||||
return n, ok
|
||||
}
|
||||
|
||||
// useLiteCounter gives a test its own counter key and removes it afterwards;
|
||||
// the Lite counter is process-global.
|
||||
func useLiteCounter(t *testing.T, knowledgeID string) string {
|
||||
t.Helper()
|
||||
key := multimodalPendingKey(knowledgeID)
|
||||
liteMultimodalDel(key)
|
||||
t.Cleanup(func() { liteMultimodalDel(key) })
|
||||
return key
|
||||
}
|
||||
|
||||
func liteImagePayload(knowledgeID string, attempt int) types.ImageMultimodalPayload {
|
||||
return types.ImageMultimodalPayload{
|
||||
TenantID: 1,
|
||||
KnowledgeID: knowledgeID,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
ImageURL: "local://images/a.png",
|
||||
Language: "en-US",
|
||||
Attempt: attempt,
|
||||
}
|
||||
}
|
||||
|
||||
func postProcessPayloads(t *testing.T, tasks []*asynq.Task) []types.KnowledgePostProcessPayload {
|
||||
t.Helper()
|
||||
var out []types.KnowledgePostProcessPayload
|
||||
for _, task := range tasks {
|
||||
if task.Type() != types.TypeKnowledgePostProcess {
|
||||
continue
|
||||
}
|
||||
var payload types.KnowledgePostProcessPayload
|
||||
require.NoError(t, json.Unmarshal(task.Payload(), &payload))
|
||||
out = append(out, payload)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Lite mode has no Redis, so the fan-out seeds the in-process counter with
|
||||
// one slot per image; without it the first finished image sealed post-process
|
||||
// before its siblings had written their chunks.
|
||||
func TestEnqueueImageMultimodalTasksSeedsLiteCounter(t *testing.T) {
|
||||
enqueuer := &slotReleaseEnqueuer{}
|
||||
svc := &knowledgeService{task: enqueuer}
|
||||
knowledge, kb, images, chunks := slotReleaseFixture(3)
|
||||
knowledge.ID = "lite-seed"
|
||||
useLiteCounter(t, knowledge.ID)
|
||||
|
||||
err := svc.enqueueImageMultimodalTasks(context.Background(), knowledge, kb, images, chunks, nil)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 3, enqueuer.imageEnqueued)
|
||||
assert.Zero(t, enqueuer.postProcess)
|
||||
n, ok := liteCounter(knowledge.ID)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, int64(3), n)
|
||||
}
|
||||
|
||||
// A Lite fan-out that loses one image task releases that slot, so the
|
||||
// surviving image is the one that reaches zero and drives post-process.
|
||||
func TestLiteMultimodalShortfallLetsLastImageFinalize(t *testing.T) {
|
||||
enqueuer := &slotReleaseEnqueuer{failAt: map[int]bool{0: true}}
|
||||
svc := &knowledgeService{task: enqueuer}
|
||||
knowledge, kb, images, chunks := slotReleaseFixture(2)
|
||||
knowledge.ID = "lite-shortfall"
|
||||
useLiteCounter(t, knowledge.ID)
|
||||
|
||||
require.NoError(t, svc.enqueueImageMultimodalTasks(context.Background(), knowledge, kb, images, chunks, nil))
|
||||
|
||||
n, _ := liteCounter(knowledge.ID)
|
||||
assert.Equal(t, int64(1), n, "the un-enqueued slot is released")
|
||||
assert.Zero(t, enqueuer.postProcess)
|
||||
|
||||
images2 := &orphanTaskEnqueuer{}
|
||||
imageSvc := &ImageMultimodalService{taskEnqueuer: images2}
|
||||
require.NoError(t, imageSvc.checkAndFinalizeAllImages(context.Background(), liteImagePayload(knowledge.ID, 1)))
|
||||
|
||||
assert.Len(t, postProcessPayloads(t, images2.enqueued), 1)
|
||||
_, ok := liteCounter(knowledge.ID)
|
||||
assert.False(t, ok, "counter is removed once post-process is enqueued")
|
||||
}
|
||||
|
||||
// With no image task on the queue, the fan-out itself drives post-process;
|
||||
// if that enqueue fails the parse task must fail so asynq retries it.
|
||||
func TestEnqueueImageMultimodalTasksLiteReturnsPostProcessEnqueueError(t *testing.T) {
|
||||
queueErr := errors.New("queue unavailable")
|
||||
enqueuer := &failingEnqueuer{err: queueErr}
|
||||
svc := &knowledgeService{task: enqueuer}
|
||||
knowledge, kb, images, chunks := slotReleaseFixture(2)
|
||||
knowledge.ID = "lite-nothing-enqueued"
|
||||
useLiteCounter(t, knowledge.ID)
|
||||
// A cancelled context ends the in-place retry after the first attempt.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
err := svc.enqueueImageMultimodalTasks(ctx, knowledge, kb, images, chunks, nil)
|
||||
|
||||
require.ErrorContains(t, err, queueErr.Error())
|
||||
_, ok := liteCounter(knowledge.ID)
|
||||
assert.False(t, ok, "the seeded counter is cleared when no image task exists")
|
||||
}
|
||||
|
||||
// Lite mode counts every image before sealing: the first of two images must
|
||||
// not enqueue post-process, the second does and clears the counter, and the
|
||||
// post-process task carries the attempt so it can skip itself if superseded.
|
||||
func TestCheckAndFinalizeAllImagesLiteWaitsForEveryImage(t *testing.T) {
|
||||
const knowledgeID = "lite-fan-in"
|
||||
key := useLiteCounter(t, knowledgeID)
|
||||
liteMultimodalSet(key, 2)
|
||||
enqueuer := &orphanTaskEnqueuer{}
|
||||
svc := &ImageMultimodalService{taskEnqueuer: enqueuer}
|
||||
|
||||
require.NoError(t, svc.checkAndFinalizeAllImages(context.Background(), liteImagePayload(knowledgeID, 4)))
|
||||
|
||||
assert.Empty(t, enqueuer.enqueued, "one image is still outstanding")
|
||||
n, _ := liteCounter(knowledgeID)
|
||||
assert.Equal(t, int64(1), n)
|
||||
|
||||
require.NoError(t, svc.checkAndFinalizeAllImages(context.Background(), liteImagePayload(knowledgeID, 4)))
|
||||
|
||||
payloads := postProcessPayloads(t, enqueuer.enqueued)
|
||||
require.Len(t, payloads, 1)
|
||||
assert.Equal(t, 4, payloads[0].Attempt)
|
||||
assert.Equal(t, knowledgeID, payloads[0].KnowledgeID)
|
||||
assert.Equal(t, "en-US", payloads[0].Language)
|
||||
_, ok := liteCounter(knowledgeID)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
// A failed post-process enqueue is returned, and the counter is kept at zero
|
||||
// so the retried image task finds it drained and enqueues again.
|
||||
func TestCheckAndFinalizeAllImagesReturnsEnqueueErrorAndKeepsCounter(t *testing.T) {
|
||||
const knowledgeID = "lite-enqueue-fails"
|
||||
key := useLiteCounter(t, knowledgeID)
|
||||
liteMultimodalSet(key, 1)
|
||||
queueErr := errors.New("queue unavailable")
|
||||
svc := &ImageMultimodalService{taskEnqueuer: &failingEnqueuer{err: queueErr}}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
err := svc.checkAndFinalizeAllImages(ctx, liteImagePayload(knowledgeID, 1))
|
||||
|
||||
require.ErrorContains(t, err, queueErr.Error())
|
||||
_, ok := liteCounter(knowledgeID)
|
||||
require.True(t, ok, "the counter must survive a failed enqueue")
|
||||
|
||||
enqueuer := &orphanTaskEnqueuer{}
|
||||
svc.taskEnqueuer = enqueuer
|
||||
require.NoError(t, svc.checkAndFinalizeAllImages(context.Background(), liteImagePayload(knowledgeID, 1)))
|
||||
assert.Len(t, postProcessPayloads(t, enqueuer.enqueued), 1, "the retry still finalizes")
|
||||
}
|
||||
|
||||
type failIfCalledKnowledgeRepo struct {
|
||||
interfaces.KnowledgeRepository
|
||||
t *testing.T
|
||||
}
|
||||
|
||||
func (r failIfCalledKnowledgeRepo) GetKnowledgeByIDOnly(context.Context, string) (*types.Knowledge, error) {
|
||||
r.t.Fatal("a superseded image must not be processed")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func imageMultimodalTask(t *testing.T, payload types.ImageMultimodalPayload) *asynq.Task {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(payload)
|
||||
require.NoError(t, err)
|
||||
return asynq.NewTask(types.TypeImageMultimodal, raw)
|
||||
}
|
||||
|
||||
// A reparse re-seeded the counter for its own images; a stale image from the
|
||||
// previous attempt must not count against it.
|
||||
func TestImageMultimodalHandleSupersededAttemptLeavesCounter(t *testing.T) {
|
||||
const knowledgeID = "lite-image-superseded"
|
||||
key := useLiteCounter(t, knowledgeID)
|
||||
liteMultimodalSet(key, 1)
|
||||
enqueuer := &orphanTaskEnqueuer{}
|
||||
svc := &ImageMultimodalService{
|
||||
knowledgeRepo: failIfCalledKnowledgeRepo{t: t},
|
||||
taskEnqueuer: enqueuer,
|
||||
spanTracker: newAttemptTracker(2),
|
||||
}
|
||||
|
||||
err := svc.Handle(context.Background(), imageMultimodalTask(t, liteImagePayload(knowledgeID, 1)))
|
||||
|
||||
require.NoError(t, err)
|
||||
n, _ := liteCounter(knowledgeID)
|
||||
assert.Equal(t, int64(1), n)
|
||||
assert.Empty(t, enqueuer.enqueued)
|
||||
}
|
||||
|
||||
// When the orphan check cannot read the row on the last attempt no retry
|
||||
// follows, so the image is still counted (here it is the last one and seals
|
||||
// post-process) and the read error is still reported. Earlier attempts leave
|
||||
// the counter for the retry.
|
||||
func TestImageMultimodalHandleCountsImageWhenOrphanCheckFailsOnFinalAttempt(t *testing.T) {
|
||||
readErr := errors.New("db unavailable")
|
||||
tests := []struct {
|
||||
name string
|
||||
retried int
|
||||
wantCounted bool
|
||||
wantPostCount int
|
||||
}{
|
||||
{name: "final attempt", retried: 3, wantCounted: true, wantPostCount: 1},
|
||||
{name: "retry remains", retried: 1},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
knowledgeID := "lite-orphan-read-" + test.name
|
||||
key := useLiteCounter(t, knowledgeID)
|
||||
liteMultimodalSet(key, 1)
|
||||
enqueuer := &orphanTaskEnqueuer{}
|
||||
svc := &ImageMultimodalService{
|
||||
knowledgeRepo: &orphanKnowledgeRepo{err: readErr},
|
||||
taskEnqueuer: enqueuer,
|
||||
}
|
||||
ctx := types.WithTaskRetryMetadata(context.Background(), test.retried, 3)
|
||||
|
||||
err := svc.Handle(ctx, imageMultimodalTask(t, liteImagePayload(knowledgeID, 0)))
|
||||
|
||||
require.ErrorIs(t, err, readErr)
|
||||
assert.Len(t, postProcessPayloads(t, enqueuer.enqueued), test.wantPostCount)
|
||||
n, ok := liteCounter(knowledgeID)
|
||||
if test.wantCounted {
|
||||
assert.False(t, ok, "the last image drained the counter")
|
||||
} else {
|
||||
assert.Equal(t, int64(1), n, "a retry will count the image")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type flakyEnqueuer struct {
|
||||
failures int
|
||||
calls int
|
||||
}
|
||||
|
||||
func (e *flakyEnqueuer) Enqueue(*asynq.Task, ...asynq.Option) (*asynq.TaskInfo, error) {
|
||||
e.calls++
|
||||
if e.calls <= e.failures {
|
||||
return nil, errors.New("transient")
|
||||
}
|
||||
return &asynq.TaskInfo{ID: "ok"}, nil
|
||||
}
|
||||
|
||||
func TestEnqueueWithRetryRecoversFromTransientFailure(t *testing.T) {
|
||||
enqueuer := &flakyEnqueuer{failures: 1}
|
||||
|
||||
err := enqueueWithRetry(context.Background(), enqueuer, asynq.NewTask(types.TypeKnowledgePostProcess, nil))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2, enqueuer.calls)
|
||||
}
|
||||
|
||||
func TestEnqueueWithRetryStopsWhenContextDone(t *testing.T) {
|
||||
enqueuer := &flakyEnqueuer{failures: postProcessEnqueueAttempts}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
started := time.Now()
|
||||
|
||||
err := enqueueWithRetry(ctx, enqueuer, asynq.NewTask(types.TypeKnowledgePostProcess, nil))
|
||||
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
assert.Equal(t, 1, enqueuer.calls)
|
||||
assert.Less(t, time.Since(started), postProcessEnqueueBackoff)
|
||||
}
|
||||
|
|
@ -353,6 +353,10 @@ type WikiPendingOp struct {
|
|||
KnowledgeID string `json:"knowledge_id"`
|
||||
// Ingest fields
|
||||
Language string `json:"language,omitempty"`
|
||||
// Attempt is the parse attempt whose finalizing counter owns this op's
|
||||
// slot. An op that outlived a reparse must not release a slot of the
|
||||
// newer attempt. Zero on ops queued before this field existed.
|
||||
Attempt int `json:"attempt,omitempty"`
|
||||
// Retract fields
|
||||
DocTitle string `json:"doc_title,omitempty"`
|
||||
DocSummary string `json:"doc_summary,omitempty"`
|
||||
|
|
@ -587,6 +591,7 @@ func newWikiIngestPendingOp(
|
|||
Op: WikiOpIngest,
|
||||
KnowledgeID: knowledgeID,
|
||||
Language: lang,
|
||||
Attempt: attemptFromCtx(ctx),
|
||||
}
|
||||
payloadBytes, err := json.Marshal(op)
|
||||
if err != nil {
|
||||
|
|
@ -1262,12 +1267,17 @@ func (s *wikiIngestService) trimPendingList(ctx context.Context, ids []int64) er
|
|||
// already zero: FinalizeSubtask guards both the decrement (count > 0) and
|
||||
// the promote (parse_status = finalizing AND count = 0), so an op enqueued
|
||||
// before this accounting shipped is a harmless no-op.
|
||||
func (s *wikiIngestService) finalizeWikiSubtask(ctx context.Context, knowledgeID string) {
|
||||
func (s *wikiIngestService) finalizeWikiSubtask(ctx context.Context, knowledgeID string, attempt int) {
|
||||
// Wiki is only finalized when its op reaches a terminal state, so this is
|
||||
// always an intended drain (retErr=nil, final=true). Detached context: the
|
||||
// wiki batch worker may be mid-shutdown or have a cancelled ctx when this
|
||||
// runs; a swallowed failure would strand the parent in "finalizing".
|
||||
finalizeSubtaskDetached(ctx, s.knowledgeRepo, knowledgeID, "wiki", nil, false, true)
|
||||
//
|
||||
// An op from a superseded attempt skips the drain: reparse zeroed that
|
||||
// attempt's counter, and draining now would release a slot of the new
|
||||
// run, promoting it to completed before its own enrichment finished.
|
||||
superseded := attemptSuperseded(ctx, s.tracker(), knowledgeID, attempt)
|
||||
finalizeSubtaskDetached(ctx, s.knowledgeRepo, knowledgeID, "wiki", nil, superseded, true)
|
||||
}
|
||||
|
||||
// requeueFailedOps records in-batch failures.
|
||||
|
|
@ -1326,7 +1336,7 @@ func (s *wikiIngestService) requeueFailedOps(ctx context.Context, payload WikiIn
|
|||
// for deleted knowledge that has no counter to drain). The
|
||||
// matching +1 was seeded by KnowledgePostProcess.SetFinalizing.
|
||||
if op.Op == WikiOpIngest {
|
||||
s.finalizeWikiSubtask(ctx, op.KnowledgeID)
|
||||
s.finalizeWikiSubtask(ctx, op.KnowledgeID, op.Attempt)
|
||||
}
|
||||
logger.Warnf(ctx, "wiki ingest: dropping op %s (%s) after %d failures (limit %d)", op.KnowledgeID, op.DocTitle, count, wikiMaxFailRetries)
|
||||
if s.deadLetterRepo != nil {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,128 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The op records the parse attempt whose finalizing counter owns its slot,
|
||||
// so a consumer can tell an op that outlived a reparse from a current one.
|
||||
func TestNewWikiIngestPendingOpRecordsAttempt(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
want int
|
||||
}{
|
||||
{"attempt from context", withAttempt(context.Background(), 5), 5},
|
||||
{"no attempt", context.Background(), 0},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
pendingOp, err := newWikiIngestPendingOp(test.ctx, 7, "kb-1", "knowledge-1")
|
||||
require.NoError(t, err)
|
||||
var op WikiPendingOp
|
||||
require.NoError(t, json.Unmarshal(pendingOp.Payload, &op))
|
||||
assert.Equal(t, test.want, op.Attempt)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An op from a superseded attempt must not drain: reparse zeroed that
|
||||
// attempt's counter, so the drain would release a slot of the new run and
|
||||
// promote it before its own enrichment finished.
|
||||
func TestFinalizeWikiSubtaskSkipsSupersededAttempt(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
attempt int
|
||||
wantDrains int
|
||||
}{
|
||||
{name: "superseded attempt", attempt: 1},
|
||||
{name: "current attempt", attempt: 2, wantDrains: 1},
|
||||
{name: "op queued before attempts were recorded", attempt: 0, wantDrains: 1},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
repo := &flakyFinalizeRepo{}
|
||||
svc := &wikiIngestService{knowledgeRepo: repo, spanTracker: newAttemptTracker(2)}
|
||||
|
||||
svc.finalizeWikiSubtask(context.Background(), "k-1", test.attempt)
|
||||
|
||||
assert.Equal(t, test.wantDrains, repo.successes)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A synthesis model that exists but cannot be built fails identically on
|
||||
// every trigger and before any op is claimed, so no op ever spends its retry
|
||||
// budget. On the last delivery the KB's pending ingest ops are released
|
||||
// instead of holding their documents in "finalizing"; earlier deliveries
|
||||
// still retry.
|
||||
func TestWikiIngestReleasesOpsWhenModelUnusableOnFinalAttempt(t *testing.T) {
|
||||
payload, err := json.Marshal(WikiIngestPayload{TenantID: 7, KnowledgeBaseID: "kb-1"})
|
||||
require.NoError(t, err)
|
||||
buildErr := errors.New("base URL rejected by SSRF guard")
|
||||
tests := []struct {
|
||||
name string
|
||||
retried int
|
||||
wantErr bool
|
||||
wantDrained bool
|
||||
}{
|
||||
{name: "final attempt", retried: 3, wantDrained: true},
|
||||
{name: "retry remains", retried: 1, wantErr: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
pending := &wikiUnavailablePendingRepo{drainKeys: []string{"k-1"}}
|
||||
svc := &wikiIngestService{
|
||||
kbService: &wikiGuardKBService{kb: &types.KnowledgeBase{
|
||||
ID: "kb-1", IndexingStrategy: types.IndexingStrategy{WikiEnabled: true},
|
||||
WikiConfig: &types.WikiConfig{SynthesisModelID: "m-1"},
|
||||
}},
|
||||
modelService: &wikiUnavailableModelService{err: buildErr},
|
||||
pendingRepo: pending,
|
||||
}
|
||||
ctx := types.WithTaskRetryMetadata(context.Background(), test.retried, 3)
|
||||
|
||||
err := svc.ProcessWikiIngest(ctx, asynq.NewTask(types.TypeWikiIngest, payload))
|
||||
|
||||
if test.wantErr {
|
||||
require.ErrorIs(t, err, buildErr)
|
||||
assert.Empty(t, pending.drained)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{wikiTaskType + "|" + wikiTaskScope + "|kb-1|" + WikiOpIngest}, pending.drained)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type panickingKnowledgeService struct {
|
||||
interfaces.KnowledgeService
|
||||
}
|
||||
|
||||
func (panickingKnowledgeService) GetKnowledgeByIDOnly(context.Context, string) (*types.Knowledge, error) {
|
||||
panic("unexpected nil row")
|
||||
}
|
||||
|
||||
// errgroup does not recover panics: one escaping a map worker crashed the
|
||||
// process before the batch settled its claims, and the op hit the same panic
|
||||
// on every claim. As an error it goes through the fail_count budget instead.
|
||||
func TestMapOneDocumentRecoveredTurnsPanicIntoError(t *testing.T) {
|
||||
svc := &wikiIngestService{knowledgeSvc: panickingKnowledgeService{}}
|
||||
|
||||
result, updates, err := svc.mapOneDocumentRecovered(context.Background(), nil,
|
||||
WikiIngestPayload{TenantID: 7, KnowledgeBaseID: "kb-1"},
|
||||
WikiPendingOp{Op: WikiOpIngest, KnowledgeID: "k-1"}, nil)
|
||||
|
||||
require.ErrorContains(t, err, "panicked")
|
||||
assert.Nil(t, result)
|
||||
assert.Nil(t, updates)
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime/debug"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
|
@ -325,6 +326,16 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||
}
|
||||
if err != nil {
|
||||
exitStatus = "get_chat_model_failed"
|
||||
if isFinalAsynqAttempt(ctx) {
|
||||
// The model row exists but cannot be built (a base URL the SSRF
|
||||
// guard rejects, an unknown provider, ...). That fails the same
|
||||
// way on every trigger and before any op is claimed, so no op
|
||||
// ever spends its fail_count budget: without this the KB's
|
||||
// documents stayed in "finalizing" forever while housekeeping
|
||||
// kept re-arming the trigger.
|
||||
return s.releaseIngestForUnavailableWiki(ctx, kb.ID,
|
||||
"synthesis model "+synthesisModelID+" unusable: "+err.Error())
|
||||
}
|
||||
return fmt.Errorf("wiki ingest: get chat model: %w", err)
|
||||
}
|
||||
|
||||
|
|
@ -393,6 +404,14 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||
}
|
||||
|
||||
logger.Infof(ctx, "wiki ingest: batch processing %d ops for KB %s", len(pendingOps), payload.KnowledgeBaseID)
|
||||
// The parse attempt each document's op was queued under, for the slot
|
||||
// release after reduce (see finalizeWikiSubtask).
|
||||
opAttempts := make(map[string]int, len(pendingOps))
|
||||
for _, op := range pendingOps {
|
||||
if op.Op == WikiOpIngest {
|
||||
opAttempts[op.KnowledgeID] = op.Attempt
|
||||
}
|
||||
}
|
||||
|
||||
// Crash/abort safety net (standard/claim mode only). If this batch exits
|
||||
// abnormally — panic, ctx timeout, or an early error return — BEFORE it
|
||||
|
|
@ -528,7 +547,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||
mapMu.Unlock()
|
||||
|
||||
logger.Infof(mapCtx, "wiki ingest: processing document '%s' (%s)", op.DocTitle, op.KnowledgeID)
|
||||
result, updates, err := s.mapOneDocument(mapCtx, chatModel, payload, op, batchCtx)
|
||||
result, updates, err := s.mapOneDocumentRecovered(mapCtx, chatModel, payload, op, batchCtx)
|
||||
if err != nil {
|
||||
mapMu.Lock()
|
||||
ingestFailed++
|
||||
|
|
@ -571,7 +590,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||
// "finalizing" until the housekeeping sweep marks it
|
||||
// failed. The matching +1 was seeded by
|
||||
// KnowledgePostProcess.SetFinalizing.
|
||||
s.finalizeWikiSubtask(mapCtx, op.KnowledgeID)
|
||||
s.finalizeWikiSubtask(mapCtx, op.KnowledgeID, op.Attempt)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
|
@ -651,6 +670,14 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||
// Serialize same-slug read-modify-write across concurrent batches
|
||||
// (standard mode). runs fn directly in Lite mode.
|
||||
acquired, lockErr := s.withSlugLock(reduceCtx, payload.KnowledgeBaseID, slug, func() error {
|
||||
// errgroup does not recover panics; see mapOneDocumentRecovered.
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logger.Errorf(reduceCtx, "wiki ingest: reduce panicked for slug %s: %v\n%s",
|
||||
slug, r, debug.Stack())
|
||||
reduceErr = fmt.Errorf("wiki reduce panicked for slug %s: %v", slug, r)
|
||||
}
|
||||
}()
|
||||
changed, affectedType, additionFailed, reduceErr = s.reduceSlugUpdates(
|
||||
reduceCtx, chatModel, payload.KnowledgeBaseID, slug, updates, payload.TenantID, batchCtx, kidToWikiSpan)
|
||||
return reduceErr
|
||||
|
|
@ -809,7 +836,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||
// held — the retry (or the dead-letter drain in requeueFailedOps)
|
||||
// releases it once the op reaches a real terminal state.
|
||||
if _, unapplied := unappliedSlugKIDs[r.KnowledgeID]; !unapplied {
|
||||
s.finalizeWikiSubtask(ctx, r.KnowledgeID)
|
||||
s.finalizeWikiSubtask(ctx, r.KnowledgeID, opAttempts[r.KnowledgeID])
|
||||
}
|
||||
if r.WikiSpan == nil {
|
||||
continue
|
||||
|
|
@ -1179,6 +1206,29 @@ func (s *wikiIngestService) ProcessWikiFinalize(ctx context.Context, t *asynq.Ta
|
|||
return nil
|
||||
}
|
||||
|
||||
// mapOneDocumentRecovered runs mapOneDocument and turns a panic into a map
|
||||
// failure. errgroup does not recover panics, so one escaping a map worker
|
||||
// crashed the process before the batch settled its claims; the op was
|
||||
// claimed again later, hit the same panic, and its document never left
|
||||
// "finalizing" (in Lite mode the startup recovery crash-looped the server).
|
||||
// As a failure it goes through the fail_count budget and, at worst, the
|
||||
// dead-letter path, which releases the document's slot.
|
||||
func (s *wikiIngestService) mapOneDocumentRecovered(
|
||||
ctx context.Context,
|
||||
chatModel chat.Chat,
|
||||
payload WikiIngestPayload,
|
||||
op WikiPendingOp,
|
||||
batchCtx *WikiBatchContext,
|
||||
) (result *docIngestResult, updates []SlugUpdate, err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logger.Errorf(ctx, "wiki ingest: map panicked for knowledge %s: %v\n%s", op.KnowledgeID, r, debug.Stack())
|
||||
result, updates, err = nil, nil, fmt.Errorf("wiki map panicked: %v", r)
|
||||
}
|
||||
}()
|
||||
return s.mapOneDocument(ctx, chatModel, payload, op, batchCtx)
|
||||
}
|
||||
|
||||
func (s *wikiIngestService) mapOneDocument(
|
||||
ctx context.Context,
|
||||
chatModel chat.Chat,
|
||||
|
|
|
|||
|
|
@ -2,10 +2,14 @@ package router
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/middleware/asynqdl"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
|
|
@ -20,6 +24,10 @@ import (
|
|||
type SyncTaskExecutor struct {
|
||||
mu sync.RWMutex
|
||||
handlers map[string]func(context.Context, *asynq.Task) error
|
||||
// onFinalFailure mirrors the asynq dead-letter callback: it runs once a
|
||||
// task exhausts its retries, so a document whose task gave up is marked
|
||||
// failed instead of spinning until the housekeeping sweep.
|
||||
onFinalFailure func(context.Context, *asynq.Task, error)
|
||||
}
|
||||
|
||||
func NewSyncTaskExecutor() *SyncTaskExecutor {
|
||||
|
|
@ -35,39 +43,110 @@ func (e *SyncTaskExecutor) RegisterHandler(pattern string, handler func(context.
|
|||
e.handlers[pattern] = handler
|
||||
}
|
||||
|
||||
// SetFinalFailureHook installs the callback run after a task's last failed
|
||||
// attempt. It receives the error of that attempt, including asynq.SkipRetry.
|
||||
func (e *SyncTaskExecutor) SetFinalFailureHook(fn func(context.Context, *asynq.Task, error)) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.onFinalFailure = fn
|
||||
}
|
||||
|
||||
// syncTaskOptions is the subset of asynq options the executor honours.
|
||||
type syncTaskOptions struct {
|
||||
delay time.Duration
|
||||
maxRetry int
|
||||
timeout time.Duration
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
// resolveSyncTaskOptions merges the options given to asynq.NewTask with the
|
||||
// ones given to Enqueue, the latter winning, as asynq.Client does.
|
||||
//
|
||||
// Unlike asynq, a task with neither Timeout nor Deadline gets no default
|
||||
// timeout: Lite has always run those unbounded (large imports on a laptop),
|
||||
// and the document pipeline sets its own timeouts explicitly.
|
||||
func resolveSyncTaskOptions(task *asynq.Task, opts []asynq.Option) syncTaskOptions {
|
||||
resolved := syncTaskOptions{maxRetry: 25} // asynq default
|
||||
all := append(append([]asynq.Option{}, asynqTaskOptions(task)...), opts...)
|
||||
for _, opt := range all {
|
||||
switch opt.Type() {
|
||||
case asynq.ProcessInOpt:
|
||||
if d, ok := opt.Value().(time.Duration); ok {
|
||||
resolved.delay = d
|
||||
}
|
||||
case asynq.ProcessAtOpt:
|
||||
if at, ok := opt.Value().(time.Time); ok {
|
||||
resolved.delay = time.Until(at)
|
||||
}
|
||||
case asynq.MaxRetryOpt:
|
||||
if n, ok := opt.Value().(int); ok {
|
||||
resolved.maxRetry = n
|
||||
}
|
||||
case asynq.TimeoutOpt:
|
||||
if d, ok := opt.Value().(time.Duration); ok {
|
||||
resolved.timeout = d
|
||||
}
|
||||
case asynq.DeadlineOpt:
|
||||
if at, ok := opt.Value().(time.Time); ok {
|
||||
resolved.deadline = at
|
||||
}
|
||||
}
|
||||
}
|
||||
if resolved.maxRetry < 0 {
|
||||
resolved.maxRetry = 0
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
// asynqTaskOptions returns the options passed to asynq.NewTask. asynq keeps
|
||||
// them in an unexported field and only merges them inside Client.Enqueue, so
|
||||
// an executor standing in for the client has to read the field itself.
|
||||
// Without this, every Lite task ran with 25 retries and no timeout, since
|
||||
// callers put MaxRetry / Timeout on NewTask. TestAsynqTaskOptionsReadsNewTaskOptions
|
||||
// breaks if an asynq upgrade renames the field.
|
||||
func asynqTaskOptions(task *asynq.Task) []asynq.Option {
|
||||
if task == nil {
|
||||
return nil
|
||||
}
|
||||
field := reflect.ValueOf(task).Elem().FieldByName("opts")
|
||||
if !field.IsValid() || field.Type() != reflect.TypeOf([]asynq.Option(nil)) {
|
||||
return nil
|
||||
}
|
||||
return *(*[]asynq.Option)(unsafe.Pointer(field.UnsafeAddr()))
|
||||
}
|
||||
|
||||
// attemptContext bounds one attempt the way asynq does: by the task's
|
||||
// Timeout, and by its Deadline when that comes first.
|
||||
func (o syncTaskOptions) attemptContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
var deadline time.Time
|
||||
if o.timeout > 0 {
|
||||
deadline = time.Now().Add(o.timeout)
|
||||
}
|
||||
if !o.deadline.IsZero() && (deadline.IsZero() || o.deadline.Before(deadline)) {
|
||||
deadline = o.deadline
|
||||
}
|
||||
if deadline.IsZero() {
|
||||
return context.WithCancel(ctx)
|
||||
}
|
||||
return context.WithDeadline(ctx, deadline)
|
||||
}
|
||||
|
||||
// Enqueue satisfies interfaces.TaskEnqueuer.
|
||||
// Instead of queuing to Redis, it dispatches the task to a goroutine.
|
||||
// Supports ProcessIn (delay) and MaxRetry options for parity with asynq.
|
||||
// Supports ProcessIn / ProcessAt (delay), MaxRetry, Timeout and Deadline for
|
||||
// parity with asynq, whether they were given here or to asynq.NewTask.
|
||||
func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, opts ...asynq.Option) (*asynq.TaskInfo, error) {
|
||||
e.mu.RLock()
|
||||
handler, ok := e.handlers[task.Type()]
|
||||
onFinalFailure := e.onFinalFailure
|
||||
e.mu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("sync task executor: no handler registered for type %q", task.Type())
|
||||
}
|
||||
|
||||
var delay time.Duration
|
||||
maxRetry := 25 // asynq default
|
||||
maxRetrySet := false
|
||||
for _, opt := range opts {
|
||||
switch opt.Type() {
|
||||
case asynq.ProcessInOpt:
|
||||
if d, ok := opt.Value().(time.Duration); ok {
|
||||
delay = d
|
||||
}
|
||||
case asynq.MaxRetryOpt:
|
||||
if n, ok := opt.Value().(int); ok {
|
||||
maxRetry = n
|
||||
maxRetrySet = true
|
||||
}
|
||||
}
|
||||
}
|
||||
// Callers that explicitly pass MaxRetry(0) want no retries.
|
||||
// Without the flag we can't distinguish "not set" from "set to 0".
|
||||
if maxRetrySet && maxRetry < 0 {
|
||||
maxRetry = 0
|
||||
}
|
||||
options := resolveSyncTaskOptions(task, opts)
|
||||
maxRetry := options.maxRetry
|
||||
|
||||
taskID := uuid.New().String()
|
||||
info := &asynq.TaskInfo{
|
||||
|
|
@ -77,8 +156,8 @@ func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, opts ...asynq.Option) (*asy
|
|||
}
|
||||
|
||||
go func() {
|
||||
if delay > 0 {
|
||||
time.Sleep(delay)
|
||||
if options.delay > 0 {
|
||||
time.Sleep(options.delay)
|
||||
}
|
||||
|
||||
// Tag as a background worker execution so the per-model concurrency
|
||||
|
|
@ -89,6 +168,7 @@ func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, opts ...asynq.Option) (*asy
|
|||
logger.Infof(ctx, "[SyncTask] Executing task type=%s id=%s", task.Type(), taskID)
|
||||
|
||||
var lastErr error
|
||||
var attemptCtx context.Context
|
||||
for attempt := 0; attempt <= maxRetry; attempt++ {
|
||||
if attempt > 0 {
|
||||
backoff := time.Duration(attempt) * 5 * time.Second
|
||||
|
|
@ -100,18 +180,38 @@ func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, opts ...asynq.Option) (*asy
|
|||
time.Sleep(backoff)
|
||||
}
|
||||
|
||||
attemptCtx := types.WithTaskRetryMetadata(ctx, attempt, maxRetry)
|
||||
var cancel context.CancelFunc
|
||||
attemptCtx, cancel = options.attemptContext(types.WithTaskRetryMetadata(ctx, attempt, maxRetry))
|
||||
// An unrecovered panic here would take down the whole process.
|
||||
lastErr = asynqdl.CallRecovered(attemptCtx, task, handler)
|
||||
cancel()
|
||||
if lastErr == nil {
|
||||
logger.Infof(ctx, "[SyncTask] Task completed type=%s id=%s elapsed=%v",
|
||||
task.Type(), taskID, time.Since(start))
|
||||
return
|
||||
}
|
||||
if errors.Is(lastErr, asynq.SkipRetry) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
logger.Errorf(ctx, "[SyncTask] Task failed (exhausted retries) type=%s id=%s elapsed=%v err=%v",
|
||||
task.Type(), taskID, time.Since(start), lastErr)
|
||||
if onFinalFailure != nil {
|
||||
// The attempt's own context may be past its deadline; the
|
||||
// callback only writes status, so give it a fresh bound.
|
||||
cbCtx, cancel := context.WithTimeout(context.WithoutCancel(attemptCtx), 30*time.Second)
|
||||
defer cancel()
|
||||
func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logger.Errorf(ctx, "[SyncTask] final-failure hook panicked for type=%s id=%s: %v",
|
||||
task.Type(), taskID, r)
|
||||
}
|
||||
}()
|
||||
onFinalFailure(cbCtx, task, lastErr)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
|
||||
return info, nil
|
||||
|
|
@ -125,6 +225,7 @@ type SyncTaskParams struct {
|
|||
KnowledgeBaseService interfaces.KnowledgeBaseService
|
||||
TagService interfaces.KnowledgeTagService
|
||||
DataSourceService interfaces.DataSourceService
|
||||
SpanTracker service.SpanTracker
|
||||
ChunkExtractor interfaces.TaskHandler `name:"chunkExtractor"`
|
||||
DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"`
|
||||
ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"`
|
||||
|
|
@ -139,6 +240,10 @@ type SyncTaskParams struct {
|
|||
// RegisterSyncHandlers registers all task handlers on the SyncTaskExecutor.
|
||||
// Used in Lite mode instead of RunAsynqServer.
|
||||
func RegisterSyncHandlers(params SyncTaskParams) {
|
||||
// Same callback the asynq dead-letter middleware runs in standard mode.
|
||||
if failer := newDeadLetterKnowledgeFailer(params.KnowledgeService, params.SpanTracker); failer != nil {
|
||||
params.Executor.SetFinalFailureHook(failer)
|
||||
}
|
||||
params.Executor.RegisterHandler(types.TypeChunkExtract, params.ChunkExtractor.Handle)
|
||||
params.Executor.RegisterHandler(types.TypeDataTableSummary, params.DataTableSummary.Handle)
|
||||
params.Executor.RegisterHandler(types.TypeDocumentProcess, params.KnowledgeService.ProcessDocument)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,237 @@
|
|||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAsynqTaskOptionsReadsNewTaskOptions(t *testing.T) {
|
||||
require.Nil(t, asynqTaskOptions(nil))
|
||||
require.Empty(t, asynqTaskOptions(asynq.NewTask("test:no-opts", nil)))
|
||||
|
||||
task := asynq.NewTask("test:opts", nil, asynq.MaxRetry(3), asynq.Timeout(time.Minute))
|
||||
opts := asynqTaskOptions(task)
|
||||
require.Len(t, opts, 2)
|
||||
require.Equal(t, asynq.MaxRetryOpt, opts[0].Type())
|
||||
require.Equal(t, 3, opts[0].Value())
|
||||
require.Equal(t, asynq.TimeoutOpt, opts[1].Type())
|
||||
require.Equal(t, time.Minute, opts[1].Value())
|
||||
}
|
||||
|
||||
func TestResolveSyncTaskOptions(t *testing.T) {
|
||||
t.Run("defaults", func(t *testing.T) {
|
||||
got := resolveSyncTaskOptions(asynq.NewTask("test:defaults", nil), nil)
|
||||
require.Equal(t, 25, got.maxRetry)
|
||||
require.Zero(t, got.timeout)
|
||||
require.True(t, got.deadline.IsZero())
|
||||
require.Zero(t, got.delay)
|
||||
})
|
||||
|
||||
t.Run("NewTask options honoured", func(t *testing.T) {
|
||||
deadline := time.Now().Add(time.Hour)
|
||||
task := asynq.NewTask("test:newtask", nil,
|
||||
asynq.MaxRetry(2), asynq.Timeout(90*time.Second), asynq.Deadline(deadline), asynq.ProcessIn(time.Second))
|
||||
got := resolveSyncTaskOptions(task, nil)
|
||||
require.Equal(t, 2, got.maxRetry)
|
||||
require.Equal(t, 90*time.Second, got.timeout)
|
||||
require.True(t, got.deadline.Equal(deadline))
|
||||
require.Equal(t, time.Second, got.delay)
|
||||
})
|
||||
|
||||
t.Run("Enqueue options override NewTask", func(t *testing.T) {
|
||||
task := asynq.NewTask("test:override", nil, asynq.MaxRetry(5), asynq.Timeout(time.Minute))
|
||||
got := resolveSyncTaskOptions(task, []asynq.Option{asynq.MaxRetry(1), asynq.Timeout(time.Hour)})
|
||||
require.Equal(t, 1, got.maxRetry)
|
||||
require.Equal(t, time.Hour, got.timeout)
|
||||
})
|
||||
|
||||
t.Run("explicit zero and negative MaxRetry", func(t *testing.T) {
|
||||
require.Equal(t, 0, resolveSyncTaskOptions(asynq.NewTask("t", nil, asynq.MaxRetry(0)), nil).maxRetry)
|
||||
negative := resolveSyncTaskOptions(asynq.NewTask("t", nil), []asynq.Option{asynq.MaxRetry(-3)})
|
||||
require.Equal(t, 0, negative.maxRetry)
|
||||
})
|
||||
|
||||
t.Run("ProcessAt converts to a delay", func(t *testing.T) {
|
||||
at := asynq.ProcessAt(time.Now().Add(time.Hour))
|
||||
got := resolveSyncTaskOptions(asynq.NewTask("t", nil), []asynq.Option{at})
|
||||
require.Greater(t, got.delay, 59*time.Minute)
|
||||
require.LessOrEqual(t, got.delay, time.Hour)
|
||||
})
|
||||
|
||||
t.Run("does not mutate NewTask options", func(t *testing.T) {
|
||||
task := asynq.NewTask("t", nil, asynq.MaxRetry(4))
|
||||
_ = resolveSyncTaskOptions(task, []asynq.Option{asynq.MaxRetry(1)})
|
||||
require.Len(t, asynqTaskOptions(task), 1)
|
||||
require.Equal(t, 4, resolveSyncTaskOptions(task, nil).maxRetry)
|
||||
})
|
||||
}
|
||||
|
||||
type deadlineObservation struct {
|
||||
deadline time.Time
|
||||
ok bool
|
||||
}
|
||||
|
||||
func observeHandlerDeadline(t *testing.T, task *asynq.Task, opts ...asynq.Option) deadlineObservation {
|
||||
t.Helper()
|
||||
executor := NewSyncTaskExecutor()
|
||||
observed := make(chan deadlineObservation, 1)
|
||||
executor.RegisterHandler(task.Type(), func(ctx context.Context, _ *asynq.Task) error {
|
||||
d, ok := ctx.Deadline()
|
||||
observed <- deadlineObservation{deadline: d, ok: ok}
|
||||
return nil
|
||||
})
|
||||
_, err := executor.Enqueue(task, opts...)
|
||||
require.NoError(t, err)
|
||||
select {
|
||||
case got := <-observed:
|
||||
return got
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for sync task")
|
||||
return deadlineObservation{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncTaskExecutorAppliesNewTaskTimeout(t *testing.T) {
|
||||
start := time.Now()
|
||||
got := observeHandlerDeadline(t, asynq.NewTask("test:timeout", nil, asynq.Timeout(time.Minute)))
|
||||
require.True(t, got.ok, "handler context should carry a deadline")
|
||||
require.WithinDuration(t, start.Add(time.Minute), got.deadline, 5*time.Second)
|
||||
}
|
||||
|
||||
func TestSyncTaskExecutorAppliesEarlierDeadline(t *testing.T) {
|
||||
deadline := time.Now().Add(30 * time.Second)
|
||||
got := observeHandlerDeadline(t,
|
||||
asynq.NewTask("test:deadline", nil, asynq.Timeout(time.Hour)), asynq.Deadline(deadline))
|
||||
require.True(t, got.ok)
|
||||
require.True(t, got.deadline.Equal(deadline), "deadline = %v, want %v", got.deadline, deadline)
|
||||
}
|
||||
|
||||
func TestSyncTaskExecutorNoDeadlineWithoutTimeout(t *testing.T) {
|
||||
got := observeHandlerDeadline(t, asynq.NewTask("test:no-timeout", nil))
|
||||
require.False(t, got.ok, "handler context should not carry a deadline, got %v", got.deadline)
|
||||
}
|
||||
|
||||
type finalFailureCall struct {
|
||||
task *asynq.Task
|
||||
err error
|
||||
// Context state sampled inside the hook; the executor cancels the
|
||||
// hook's context once it returns.
|
||||
ctxErr error
|
||||
hasDeadline bool
|
||||
}
|
||||
|
||||
func newFailingExecutor(taskType string, handlerErr error) (*SyncTaskExecutor, *atomic.Int32, chan finalFailureCall) {
|
||||
executor := NewSyncTaskExecutor()
|
||||
calls := &atomic.Int32{}
|
||||
executor.RegisterHandler(taskType, func(context.Context, *asynq.Task) error {
|
||||
calls.Add(1)
|
||||
return handlerErr
|
||||
})
|
||||
hook := make(chan finalFailureCall, 4)
|
||||
executor.SetFinalFailureHook(func(ctx context.Context, task *asynq.Task, err error) {
|
||||
_, hasDeadline := ctx.Deadline()
|
||||
hook <- finalFailureCall{task: task, err: err, ctxErr: ctx.Err(), hasDeadline: hasDeadline}
|
||||
})
|
||||
return executor, calls, hook
|
||||
}
|
||||
|
||||
func waitFinalFailure(t *testing.T, hook chan finalFailureCall) finalFailureCall {
|
||||
t.Helper()
|
||||
select {
|
||||
case got := <-hook:
|
||||
return got
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("timed out waiting for final-failure hook")
|
||||
return finalFailureCall{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncTaskExecutorNewTaskMaxRetryZeroRunsOnce(t *testing.T) {
|
||||
boom := errors.New("boom")
|
||||
executor, calls, hook := newFailingExecutor("test:max-retry-zero", boom)
|
||||
task := asynq.NewTask("test:max-retry-zero", []byte("p"), asynq.MaxRetry(0))
|
||||
_, err := executor.Enqueue(task)
|
||||
require.NoError(t, err)
|
||||
|
||||
got := waitFinalFailure(t, hook)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
require.Same(t, task, got.task)
|
||||
require.ErrorIs(t, got.err, boom)
|
||||
// The hook gets its own bounded context, not a cancelled attempt ctx.
|
||||
require.NoError(t, got.ctxErr)
|
||||
require.True(t, got.hasDeadline)
|
||||
|
||||
select {
|
||||
case extra := <-hook:
|
||||
t.Fatalf("final-failure hook called twice: %v", extra.err)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncTaskExecutorSkipRetryStopsImmediately(t *testing.T) {
|
||||
handlerErr := fmt.Errorf("bad payload: %w", asynq.SkipRetry)
|
||||
executor, calls, hook := newFailingExecutor("test:skip-retry", handlerErr)
|
||||
// Default MaxRetry (25) would otherwise back off for 5s before attempt 2.
|
||||
_, err := executor.Enqueue(asynq.NewTask("test:skip-retry", nil))
|
||||
require.NoError(t, err)
|
||||
|
||||
got := waitFinalFailure(t, hook)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
require.ErrorIs(t, got.err, asynq.SkipRetry)
|
||||
require.EqualError(t, got.err, handlerErr.Error())
|
||||
}
|
||||
|
||||
func TestSyncTaskExecutorFinalFailureHookNotCalledOnSuccess(t *testing.T) {
|
||||
executor, calls, hook := newFailingExecutor("test:success", nil)
|
||||
done := make(chan struct{})
|
||||
executor.RegisterHandler("test:success", func(context.Context, *asynq.Task) error {
|
||||
calls.Add(1)
|
||||
close(done)
|
||||
return nil
|
||||
})
|
||||
_, err := executor.Enqueue(asynq.NewTask("test:success", nil, asynq.MaxRetry(0)))
|
||||
require.NoError(t, err)
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for sync task")
|
||||
}
|
||||
select {
|
||||
case got := <-hook:
|
||||
t.Fatalf("final-failure hook called on success: %v", got.err)
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestSyncTaskExecutorRecoversPanickingFinalFailureHook(t *testing.T) {
|
||||
executor := NewSyncTaskExecutor()
|
||||
executor.RegisterHandler("test:hook-panic", func(context.Context, *asynq.Task) error {
|
||||
return errors.New("boom")
|
||||
})
|
||||
hookEntered := make(chan struct{}, 2)
|
||||
executor.SetFinalFailureHook(func(context.Context, *asynq.Task, error) {
|
||||
hookEntered <- struct{}{}
|
||||
panic("hook exploded")
|
||||
})
|
||||
for i := 0; i < 2; i++ {
|
||||
_, err := executor.Enqueue(asynq.NewTask("test:hook-panic", nil, asynq.MaxRetry(0)))
|
||||
require.NoError(t, err)
|
||||
select {
|
||||
case <-hookEntered:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for final-failure hook")
|
||||
}
|
||||
}
|
||||
// An unrecovered panic in the executor goroutine would kill the test
|
||||
// binary; give it a moment to surface before declaring success.
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
|
|
@ -418,6 +418,14 @@ func newDeadLetterKnowledgeFailer(ks interfaces.KnowledgeService, tracker servic
|
|||
default:
|
||||
return
|
||||
}
|
||||
// The row belongs to a newer run (a reparse cancelled this task or
|
||||
// raced it): failing it would kill a run that is still healthy.
|
||||
if tracker != nil && probe.Attempt > 0 &&
|
||||
tracker.LatestAttempt(ctx, probe.KnowledgeID) > probe.Attempt {
|
||||
logger.Infof(ctx, "dead-letter callback: attempt %d of knowledge %s superseded, leaving row alone",
|
||||
probe.Attempt, probe.KnowledgeID)
|
||||
return
|
||||
}
|
||||
errMsg := "task " + t.Type() + " exhausted retries: " + taskErr.Error()
|
||||
// 8KB is the same cap the dead-letter row uses for last_error.
|
||||
if len(errMsg) > 8192 {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,96 @@
|
|||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type finalizedAttempt struct {
|
||||
knowledgeID string
|
||||
attempt int
|
||||
status string
|
||||
}
|
||||
|
||||
// attemptTracker is a SpanTracker stub: only the two methods the dead-letter
|
||||
// callback uses are implemented; anything else panics via the nil embed.
|
||||
type attemptTracker struct {
|
||||
service.SpanTracker
|
||||
latest int
|
||||
|
||||
mu sync.Mutex
|
||||
finalized []finalizedAttempt
|
||||
}
|
||||
|
||||
func (a *attemptTracker) LatestAttempt(context.Context, string) int { return a.latest }
|
||||
|
||||
func (a *attemptTracker) FinalizeAttempt(
|
||||
_ context.Context, knowledgeID string, attempt int, status string, _ types.JSONMap, _, _ string,
|
||||
) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.finalized = append(a.finalized, finalizedAttempt{knowledgeID: knowledgeID, attempt: attempt, status: status})
|
||||
}
|
||||
|
||||
func TestDeadLetterCallbackRespectsSupersededAttempt(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "attempt.db")), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
require.NoError(t, db.AutoMigrate(&types.Knowledge{}))
|
||||
repo := repository.NewKnowledgeRepository(db)
|
||||
|
||||
for _, tc := range []struct {
|
||||
id string
|
||||
payloadAttempt int
|
||||
latestAttempt int
|
||||
wantFailed bool
|
||||
wantFinalized []finalizedAttempt
|
||||
}{
|
||||
{id: "superseded", payloadAttempt: 1, latestAttempt: 2, wantFailed: false},
|
||||
{
|
||||
id: "latest", payloadAttempt: 2, latestAttempt: 2, wantFailed: true,
|
||||
wantFinalized: []finalizedAttempt{{"latest", 2, types.SpanStatusFailed}},
|
||||
},
|
||||
// Legacy payloads without an attempt cannot be compared, so the row
|
||||
// is still failed (and no span is finalized).
|
||||
{id: "legacy", payloadAttempt: 0, latestAttempt: 3, wantFailed: true},
|
||||
} {
|
||||
t.Run(tc.id, func(t *testing.T) {
|
||||
require.NoError(t, db.Create(&types.Knowledge{
|
||||
ID: tc.id, TenantID: 7, KnowledgeBaseID: "kb", ParseStatus: types.ParseStatusProcessing,
|
||||
}).Error)
|
||||
tracker := &attemptTracker{latest: tc.latestAttempt}
|
||||
callback := newDeadLetterKnowledgeFailer(transferFailureKnowledge{repo: repo}, tracker)
|
||||
payload, err := json.Marshal(deadLetterKnowledgePayload{
|
||||
TenantID: 7, KnowledgeBaseID: "kb", KnowledgeID: tc.id, Attempt: tc.payloadAttempt,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
callback(context.Background(), asynq.NewTask(types.TypeDocumentProcess, payload), errors.New("timeout"))
|
||||
|
||||
row, err := repo.GetKnowledgeByID(context.Background(), 7, tc.id)
|
||||
require.NoError(t, err)
|
||||
if tc.wantFailed {
|
||||
require.Equal(t, types.ParseStatusFailed, row.ParseStatus)
|
||||
require.Contains(t, row.ErrorMessage, "exhausted retries: timeout")
|
||||
} else {
|
||||
require.Equal(t, types.ParseStatusProcessing, row.ParseStatus)
|
||||
require.Empty(t, row.ErrorMessage)
|
||||
}
|
||||
require.Equal(t, tc.wantFinalized, tracker.finalized)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -232,7 +232,8 @@ info, err := s.task.Enqueue(task)
|
|||
- `TypeDocumentProcess`:`MaxRetry(3)` → 初始 + 3 次重试共 4 次尝试;每次尝试受 `DocumentProcessTimeout`(默认 2 小时,环境变量 `WEKNORA_DOCUMENT_PROCESS_TIMEOUT`)约束,其中单次 docreader 调用另受 `WEKNORA_DOCREADER_CALL_TIMEOUT`(默认 30 分钟)约束。
|
||||
- 处理函数内的 panic 会被转换为错误交给重试与死信流程,最后一次失败时文档标为 `failed`;Lite 模式的执行器同样捕获 panic,不会导致进程退出。
|
||||
- Payload 携带 `Attempt`(重新解析时取历史最大 attempt+1);Span Tracker 用 attempt 隔离每轮处理的进度树,新 attempt 会"取代"(supersede)旧任务的收尾动作。
|
||||
- 处理函数区分"是否最后一次 asynq 尝试"(`isLastRetry`):非最后一次的失败直接返回错误让 asynq 重试,最后一次才把 `ParseStatus` 落为 `failed` 并写 `ErrorMessage`。
|
||||
- 处理函数区分"是否最后一次 asynq 尝试"(`isLastRetry`):非最后一次的失败直接返回错误让 asynq 重试,最后一次才把 `ParseStatus` 落为 `failed` 并写 `ErrorMessage`。读租户、读知识行或写 `processing` 状态时遇到数据库瞬时错误也返回错误重试,不再直接确认任务;只有知识行确实不存在时才静默结束。
|
||||
- 重新解析:只有覆盖配置校验、旧资源清理都通过后才分配新 attempt,被拒绝的重新解析不会影响正在进行的上一轮。上一轮仍在进行(`pending` / `processing` / `finalizing`)时,先取消它排队中的任务并通知运行中的任务停止。属于旧 attempt 的任务一律跳过:`ProcessDocument`、分块写库、后处理、图片多模态任务不再写行、删 chunk 或扣计数;Wiki 操作带着入队时的 attempt,过期后不再释放新一轮的计数;死信回调也不会把新一轮标为 `failed`。
|
||||
|
||||
## 处理配置:KB 默认值 + 单次上传覆盖 {#_5-处理配置-kb-默认值-单次上传覆盖}
|
||||
|
||||
|
|
@ -394,7 +395,7 @@ promoted, err := s.knowledgeRepo.SetFinalizing(ctx, payload.KnowledgeID, expecte
|
|||
2. 生成 Caption(VLM,prompt 由 `buildVLMCaptionPrompt` 按 `DescriptionLanguage/CustomInstructions` 组装)与 OCR 文本;
|
||||
3. 结果写回所属文本 Chunk 的 `ImageInfo`(JSON),并创建/更新两个**子 Chunk**:`ChunkTypeImageCaption` 与 `ChunkTypeImageOCR`,`ParentChunkID` 指向文本块,随后单独 `indexChunks` 入向量索引 —— 使"搜图片描述也能召回原文块";
|
||||
4. `shouldDropOrphanedMultimodal` 检查父块是否已被删除/取代,孤儿任务直接丢弃;
|
||||
5. `checkAndFinalizeAllImages`:全部图片处理完毕后,`enqueueKnowledgePostProcessTask` 触发 [后处理编排(knowledge_post_process.go,Stage: postprocess)](#_6-6-后处理编排-knowledge-post-process-go-stage-postprocess) 的后处理编排。
|
||||
5. `checkAndFinalizeAllImages`:全部图片处理完毕后,`enqueueKnowledgePostProcessTask` 触发 [后处理编排(knowledge_post_process.go,Stage: postprocess)](#_6-6-后处理编排-knowledge-post-process-go-stage-postprocess) 的后处理编排。后处理任务入队会就地重试 3 次,仍失败时本次任务返回错误交给重试,不会确认任务后让文档停在 `processing`。最后一次尝试时即使读取知识行失败,这张图片也会计入完成数。Lite 模式没有 Redis,计数器保存在进程内存中,所有图片都完成后才进入后处理。
|
||||
|
||||
## 状态机 {#_7-状态机}
|
||||
|
||||
|
|
@ -467,11 +468,11 @@ task stuck in processing at docreader stage: no progress since 2026-09-22T09:37:
|
|||
|
||||
阈值 `staleThreshold() = max(1h, DocumentProcessTimeout) + 10min`。
|
||||
|
||||
**Sweep B —— 摘要卡死恢复**:`summary_status = 'processing' AND updated_at < 1 小时前` → 置 `failed`。
|
||||
**Sweep B —— 摘要卡死恢复**:`summary_status = 'processing' AND updated_at < 1 小时前` → 置 `failed`。`summary_status = 'pending'` 而解析已结束(`completed` / `failed` / `cancelled`)、超过 1 小时且队列中没有它的任务时,同样置为 `failed`,避免摘要任务提前放弃后前端一直显示"生成摘要中"。Sweep A 回收卡死文档、用户取消解析时,也会一并结束未完成的摘要状态(前者置 `failed`,后者置 `none`)。
|
||||
|
||||
**Sweep C —— 删除卡死恢复**:`parse_status = 'deleting'` 且超过阈值、队列中也没有覆盖它的 `knowledge:list_delete` 任务时,置为 `failed` 并写明原因,文档重新出现在列表中,用户可以再次删除。探测队列失败时顺延到下一轮,Lite 模式没有排队任务,按实际情况直接恢复。
|
||||
|
||||
**Wiki 队列兜底**:只因 Wiki 持久队列未消费而停在 `finalizing` 的文档,巡检会为对应知识库重新触发一次 Wiki 生成(同一知识库每个阈值周期最多一次)。Wiki 任务触发时若发现知识库已关闭 Wiki、没有合成模型或模型已删除,会清空尚未认领的 Wiki 操作并释放对应文档,使其正常结束 `finalizing`。
|
||||
**Wiki 队列兜底**:只因 Wiki 持久队列未消费而停在 `finalizing` 的文档,巡检会为对应知识库重新触发一次 Wiki 生成(同一知识库每个阈值周期最多一次)。Wiki 任务触发时若发现知识库已关闭 Wiki、没有合成模型或模型已删除,会清空尚未认领的 Wiki 操作并释放对应文档,使其正常结束 `finalizing`。合成模型存在但无法构建(例如地址被 SSRF 校验拒绝)时,Wiki 任务在最后一次重试也按同样方式释放文档。Wiki 操作最多保护文档 48 小时:超过 48 小时没有任何进展的文档按 Sweep A 回收为 `failed`,它的 Wiki 操作随之删除。
|
||||
|
||||
## 删除清理链路(knowledge_delete.go) {#_9-删除清理链路-knowledge-delete-go}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
WeKnora 有两种任务执行模式,通过部署形态选择:
|
||||
|
||||
- **asynq 模式(标准部署)**:任务经 `asynq.Client` 序列化为 JSON payload 写入 Redis 队列,由多个独立的 `asynq.Server`(worker pool)消费。`internal/router/task.go` 中 `RunAsynqServer()` 构建统一的 `asynq.ServeMux` 并在 6 个 pool 上运行。
|
||||
- **Lite 模式(单机 / macOS App,无 Redis)**:`internal/router/sync_task.go` 的 `SyncTaskExecutor` 实现同一个 `interfaces.TaskEnqueuer` 接口,`Enqueue` 直接把任务派发到 goroutine 执行,支持 `ProcessIn`(延迟)与 `MaxRetry` 选项;重试为线性退避(`attempt * 5s`,上限 30s)。handler 内的 panic 会被捕获并按失败处理,不会导致进程退出。
|
||||
- **Lite 模式(单机 / macOS App,无 Redis)**:`internal/router/sync_task.go` 的 `SyncTaskExecutor` 实现同一个 `interfaces.TaskEnqueuer` 接口,`Enqueue` 直接把任务派发到 goroutine 执行,支持 `ProcessIn` / `ProcessAt`(延迟)、`MaxRetry`、`Timeout` 与 `Deadline` 选项,写在 `asynq.NewTask` 或 `Enqueue` 上都生效(后者优先)。没有设置超时的任务不限时,这一点与 asynq 默认 30 分钟不同。重试为线性退避(`attempt * 5s`,上限 30s),返回 `asynq.SkipRetry` 的任务不再重试。handler 内的 panic 会被捕获并按失败处理,不会导致进程退出。重试耗尽后执行与标准模式死信回调相同的收尾:文档类任务会把知识标为 `failed`。
|
||||
|
||||
```go
|
||||
// internal/router/sync_task.go
|
||||
|
|
@ -24,7 +24,7 @@ WeKnora 有两种任务执行模式,通过部署形态选择:
|
|||
| asynq broker | 所有任务队列(pending list、scheduled/retry ZSET、archived ZSET)都存储在 Redis 中;dequeue 原子(`BRPOPLPUSH`),保证一个任务只被一个 worker 执行 | `internal/router/task.go` `getAsynqRedisClientOpt()` |
|
||||
| 任务巡检数据源 | `asynq.Inspector` + 直接的 `LPos`/`ZRank`/`ZRevRank` 分页读取 | `internal/router/task_inspector.go` |
|
||||
| Wiki ingest 互斥锁 | `wiki:active:<kbID>`、finalize 锁、slug 锁均为 `SetNX` + TTL | `internal/application/service/wiki_ingest.go`、`wiki_ingest_batch.go` |
|
||||
| 多模态子任务计数器 | 图片子任务完成计数(DECR),最后一个 attempt 触发 finalize | `image_multimodal` 相关服务 |
|
||||
| 多模态子任务计数器 | 图片子任务完成计数(DECR),最后一个 attempt 触发 finalize;Lite 模式改用进程内计数器 | `image_multimodal` 相关服务 |
|
||||
| 限流 | 滑动窗口限流 ZSET(见可观测性文档) | `internal/ratelimit/limiter.go` |
|
||||
|
||||
Redis 连接参数来自环境变量 `REDIS_ADDR` / `REDIS_USERNAME` / `REDIS_PASSWORD` / `REDIS_DB` / TLS 配置。读写超时由 `WEKNORA_REDIS_OP_TIMEOUT_MS` 控制,默认 500ms(写超时为其 2 倍以吸收队头阻塞):
|
||||
|
|
|
|||
Loading…
Reference in New Issue