feat: add knowledge parse cancellation with finalizing post-process state
Lets users stop an in-flight document parse to free up LLM / worker
resources without losing the chunks and index already written. The
core insight is that the previous parse_status=completed flipped as
soon as primary chunks landed, while the most expensive subtasks
(graph extract = N LLM calls per chunk, plus summary, question
generation) were still running in the background — so "completed"
wasn't actually terminal from a resource standpoint.
State machine
pending -> processing -> finalizing -> completed
|
+-> cancelled (any of the three
in-flight states)
+-> failed
+-> deleting
`finalizing` is the new post-process fan-out window. parse_status
only promotes to `completed` once pending_subtasks_count (a new
column tracking summary + question + per-chunk graph extract)
drains to zero via atomic FinalizeSubtask. Wiki ingest is
intentionally excluded from the counter — it's a KB-scoped
debounced batch and would otherwise pin parse_status in
`finalizing` for the wiki batch window.
Backend
- New ParseStatusFinalizing + pending_subtasks_count column with
migration 000056.
- knowledgeRepository.SetFinalizing transitions processing -> finalizing
conditionally so a racing cancel cannot be clobbered.
- knowledgeRepository.FinalizeSubtask atomically decrements the
counter and self-promotes the row to completed when it hits zero.
- KnowledgePostProcess restructured to compute expected subtask
count up front, flip to finalizing (or completed when no
enrichment is enabled), and only then fan out subtasks. Subtask
handlers (summary, question, graph extract) defer-decrement on
terminal exit using the existing isFinalAsynqAttempt convention.
- New POST /api/v1/knowledge/{id}/cancel-parse handler accepting
pending / processing / finalizing. Marks the row cancelled,
zeroes the counter, best-effort dequeues asynq tasks via a new
TaskInspector abstraction (asynq-mode walks pending/scheduled/
retry queues; Lite-mode noop), and scrubs wiki ingest pending op.
- SpanTracker.AbortAttempt flat-sweeps every still-running span
for the attempt via a new repo.CancelAllOpenSpans helper so the
trace viewer's striped bars all flip to cancelled, even leaf
generations whose parent stage already EndSpan'd (multimodal
fan-out pattern). knowledge_post_process closes its postSpan
via SkipSpan on the cancel/deleting entry guard so a worker
that opens a span AFTER the cancel sweep doesn't leak it.
- Housekeeping and resetPendingTasks sweep finalizing rows
identically to processing so a crash/restart can't strand them.
- DeleteKnowledge/DeleteKnowledgeList proactively dequeue
downstream tasks via the same TaskInspector path.
- ChunkExtractService gets a cancel entry guard so the most
expensive enrichment (graph extract) bails immediately when the
parent knowledge is aborted.
Frontend
- New cancelKnowledgeParse API client + "Stop parsing" entry in
both list view and card view more menus, gated on
pending/processing/finalizing.
- Polling predicate refactored to a shared isParseInFlight helper
that recognises `finalizing` (previously the doc list silently
stopped polling once parse_status flipped from processing).
- Knowledge processing timeline: isPolling includes finalizing,
new isHardTerminal short-circuits LIVE for cancelled/failed/
completed so stranded child spans cannot pin LIVE on.
- DocumentListView.computeStatus distinguishes finalizing
("增强中") from completed and shows the previous "生成摘要中"
copy when summary_status is still pending under finalizing.
Added cancelled badge as well.
- i18n: statusFinalizing / statusCancelled / cancelParse* keys
across zh-CN, en-US, ko-KR, ru-RU.
Docs / SDK
- docs/api/knowledge.md: documents the new finalizing state,
cancel-parse semantics, and which statuses accept cancel.
- client (Go SDK): CancelKnowledgeParse with docstring listing
the cancellable statuses.
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
@@ -308,6 +309,102 @@ func (r *knowledgeRepository) UpdateKnowledgeColumns(
|
||||
return r.db.WithContext(ctx).Model(&types.Knowledge{}).Where("id = ?", id).Updates(values).Error
|
||||
}
|
||||
|
||||
// FinalizeSubtask atomically decrements pending_subtasks_count and, when
|
||||
// the counter reaches zero while parse_status is still 'finalizing',
|
||||
// flips the row to 'completed' in the same statement so concurrent
|
||||
// subtask completions can't race the promotion.
|
||||
//
|
||||
// Returns (newCount, promoted, error). promoted is true iff this caller
|
||||
// was the one whose UPDATE flipped 'finalizing'→'completed'.
|
||||
//
|
||||
// The implementation is two statements (atomic decrement, then a guarded
|
||||
// promote UPDATE) because GORM does not expose a portable RETURNING
|
||||
// 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.
|
||||
func (r *knowledgeRepository) FinalizeSubtask(
|
||||
ctx context.Context, id string,
|
||||
) (int, bool, error) {
|
||||
now := time.Now()
|
||||
// 1) Atomic decrement, clamped at zero. The `pending_subtasks_count > 0`
|
||||
// guard is purely a safety net for accounting bugs — under normal
|
||||
// operation each subtask handler decrements at most once per task,
|
||||
// so the counter cannot go negative.
|
||||
res := r.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("id = ? AND pending_subtasks_count > 0", id).
|
||||
Updates(map[string]interface{}{
|
||||
"pending_subtasks_count": gorm.Expr("pending_subtasks_count - 1"),
|
||||
"updated_at": now,
|
||||
})
|
||||
if res.Error != nil {
|
||||
return 0, false, res.Error
|
||||
}
|
||||
|
||||
// 2) Re-read to discover the new count and current parse_status.
|
||||
// Reading after the UPDATE gives us a value that is at worst one
|
||||
// decrement stale relative to other callers — the promote step
|
||||
// below is guarded by the same condition at SQL level, so the
|
||||
// stale read only causes us to attempt a no-op promote.
|
||||
var snap struct {
|
||||
PendingSubtasksCount int `gorm:"column:pending_subtasks_count"`
|
||||
ParseStatus string `gorm:"column:parse_status"`
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Select("pending_subtasks_count", "parse_status").
|
||||
Where("id = ?", id).Take(&snap).Error; err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
|
||||
if snap.PendingSubtasksCount != 0 || snap.ParseStatus != types.ParseStatusFinalizing {
|
||||
return snap.PendingSubtasksCount, false, nil
|
||||
}
|
||||
|
||||
// 3) Guarded promote. The WHERE clause ensures only ONE caller wins
|
||||
// when multiple subtasks decrement to zero in the same instant,
|
||||
// and that cancel/delete cannot be clobbered by a late promote.
|
||||
promoteRes := r.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("id = ? AND parse_status = ? AND pending_subtasks_count = 0",
|
||||
id, types.ParseStatusFinalizing).
|
||||
Updates(map[string]interface{}{
|
||||
"parse_status": types.ParseStatusCompleted,
|
||||
"processed_at": now,
|
||||
"updated_at": now,
|
||||
})
|
||||
if promoteRes.Error != nil {
|
||||
return snap.PendingSubtasksCount, false, promoteRes.Error
|
||||
}
|
||||
return snap.PendingSubtasksCount, promoteRes.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
// SetFinalizing atomically transitions a row from 'processing' to
|
||||
// 'finalizing' and seeds pending_subtasks_count. Used by
|
||||
// KnowledgePostProcess.Handle as the single durable handoff between
|
||||
// the synchronous parse stage and the asynchronous enrichment fan-out.
|
||||
//
|
||||
// The transition is conditional on parse_status='processing' so a row
|
||||
// that the user cancelled / deleted between ProcessDocument finishing
|
||||
// and post-process starting will NOT get hijacked into finalizing.
|
||||
// Returns whether the transition happened.
|
||||
func (r *knowledgeRepository) SetFinalizing(
|
||||
ctx context.Context, id string, expectedSubtasks int,
|
||||
) (bool, error) {
|
||||
if expectedSubtasks < 0 {
|
||||
expectedSubtasks = 0
|
||||
}
|
||||
now := time.Now()
|
||||
res := r.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("id = ? AND parse_status = ?", id, types.ParseStatusProcessing).
|
||||
Updates(map[string]interface{}{
|
||||
"parse_status": types.ParseStatusFinalizing,
|
||||
"pending_subtasks_count": expectedSubtasks,
|
||||
"updated_at": now,
|
||||
})
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
// CountKnowledgeByKnowledgeBaseID counts the number of knowledge items in a knowledge base
|
||||
func (r *knowledgeRepository) CountKnowledgeByKnowledgeBaseID(
|
||||
ctx context.Context,
|
||||
|
||||
@@ -3,6 +3,7 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"gorm.io/gorm"
|
||||
@@ -29,6 +30,14 @@ type KnowledgeSpanRepository interface {
|
||||
// cascade an upstream failure across a stage's downstream subtree
|
||||
// without iterating in Go memory.
|
||||
CancelDescendants(ctx context.Context, knowledgeID string, attempt int, parentSpanID, reason string) (int64, error)
|
||||
// CancelAllOpenSpans flips every non-terminal (pending/running) span
|
||||
// for (knowledgeID, attempt) to "cancelled" in one statement,
|
||||
// regardless of tree position. Used by the user-cancel path where
|
||||
// fan-out stages (e.g. "多模态识别") flip themselves to done as soon
|
||||
// as they finish dispatching, while their async children are still
|
||||
// running — a tree walk that stops at terminal parents would miss
|
||||
// those orphan leaves.
|
||||
CancelAllOpenSpans(ctx context.Context, knowledgeID string, attempt int, errorCode, reason string) (int64, error)
|
||||
}
|
||||
|
||||
type knowledgeSpanRepository struct {
|
||||
@@ -189,3 +198,33 @@ func (r *knowledgeSpanRepository) CancelDescendants(ctx context.Context, knowled
|
||||
}
|
||||
return totalAffected, nil
|
||||
}
|
||||
|
||||
// CancelAllOpenSpans is the "abort the attempt" counterpart to
|
||||
// CancelDescendants. It avoids the BFS entirely so spans whose parent
|
||||
// is already terminal (typical for stage fan-outs that EndSpan as soon
|
||||
// as they finish dispatching async work) still get flipped to cancelled.
|
||||
// We deliberately do NOT touch finished_at / duration_ms here — the
|
||||
// span row remains observable in the trace tree with its original
|
||||
// start time and gets a cancelled status + reason, which is enough
|
||||
// for the UI to drop the running-bar styling.
|
||||
func (r *knowledgeSpanRepository) CancelAllOpenSpans(
|
||||
ctx context.Context, knowledgeID string, attempt int, errorCode, reason string,
|
||||
) (int64, error) {
|
||||
now := time.Now()
|
||||
updates := map[string]any{
|
||||
"status": types.SpanStatusCancelled,
|
||||
"error_code": errorCode,
|
||||
"error_message": reason,
|
||||
"finished_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
res := r.db.WithContext(ctx).Model(&types.KnowledgeProcessingSpan{}).
|
||||
Where("knowledge_id = ? AND attempt = ? AND status IN ?",
|
||||
knowledgeID, attempt,
|
||||
[]string{types.SpanStatusPending, types.SpanStatusRunning}).
|
||||
Updates(updates)
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return res.RowsAffected, nil
|
||||
}
|
||||
|
||||
@@ -154,6 +154,7 @@ type ChunkExtractService struct {
|
||||
template *types.PromptTemplateStructured
|
||||
modelService interfaces.ModelService
|
||||
knowledgeBaseRepo interfaces.KnowledgeBaseRepository
|
||||
knowledgeRepo interfaces.KnowledgeRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
// spanTracker records this graph-extract task's subspan under the
|
||||
@@ -167,6 +168,7 @@ func NewChunkExtractService(
|
||||
config *config.Config,
|
||||
modelService interfaces.ModelService,
|
||||
knowledgeBaseRepo interfaces.KnowledgeBaseRepository,
|
||||
knowledgeRepo interfaces.KnowledgeRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
graphEngine interfaces.RetrieveGraphRepository,
|
||||
spanTracker SpanTracker,
|
||||
@@ -175,6 +177,7 @@ func NewChunkExtractService(
|
||||
template: config.ExtractManager.ExtractGraph,
|
||||
modelService: modelService,
|
||||
knowledgeBaseRepo: knowledgeBaseRepo,
|
||||
knowledgeRepo: knowledgeRepo,
|
||||
chunkRepo: chunkRepo,
|
||||
graphEngine: graphEngine,
|
||||
spanTracker: spanTracker,
|
||||
@@ -220,6 +223,15 @@ func (s *ChunkExtractService) Handle(ctx context.Context, t *asynq.Task) error {
|
||||
var handleErr error
|
||||
graphOut := types.JSONMap{}
|
||||
defer func() {
|
||||
// Decrement the parent's enrichment counter on terminal exit so a
|
||||
// completed (or terminally-failed) per-chunk extract releases its
|
||||
// slot in pending_subtasks_count. KnowledgeID is the new (post-#? )
|
||||
// payload field; legacy in-flight tasks without it are skipped.
|
||||
if (handleErr == nil || isFinalAsynqAttempt(ctx)) && p.KnowledgeID != "" && s.knowledgeRepo != nil {
|
||||
if _, _, ferr := s.knowledgeRepo.FinalizeSubtask(ctx, p.KnowledgeID); ferr != nil {
|
||||
logger.Warnf(ctx, "graph extract: FinalizeSubtask failed for %s: %v", p.KnowledgeID, ferr)
|
||||
}
|
||||
}
|
||||
if gSpan == nil {
|
||||
return
|
||||
}
|
||||
@@ -230,6 +242,22 @@ func (s *ChunkExtractService) Handle(ctx context.Context, t *asynq.Task) error {
|
||||
}
|
||||
}()
|
||||
|
||||
// Short-circuit when the parent knowledge has been cancelled / deleted.
|
||||
// Each graph extract is per-chunk and runs one LLM call — the most
|
||||
// expensive enrichment fan-out in the pipeline. Skipping on cancel
|
||||
// is the whole point of the finalizing-state machinery above.
|
||||
if p.KnowledgeID != "" && s.knowledgeRepo != nil {
|
||||
if k, kerr := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, p.KnowledgeID); kerr == nil && k != nil {
|
||||
switch k.ParseStatus {
|
||||
case types.ParseStatusCancelled, types.ParseStatusDeleting:
|
||||
logger.Infof(ctx, "graph extract: knowledge %s aborted (%s), skipping chunk %s",
|
||||
p.KnowledgeID, k.ParseStatus, p.ChunkID)
|
||||
graphOut["skipped"] = "knowledge_" + k.ParseStatus
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chunk, err := s.chunkRepo.GetChunkByID(ctx, p.TenantID, p.ChunkID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to get chunk: %v", err)
|
||||
|
||||
@@ -130,6 +130,18 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
|
||||
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
|
||||
}
|
||||
|
||||
// Short-circuit when the parent knowledge has been cancelled by the user
|
||||
// or marked for deletion. Skip the VLM call entirely so we don't burn
|
||||
// model quota on already-aborted work.
|
||||
if k, kerr := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, payload.KnowledgeID); kerr == nil && k != nil {
|
||||
switch k.ParseStatus {
|
||||
case types.ParseStatusCancelled, types.ParseStatusDeleting:
|
||||
logger.Infof(ctx, "[ImageMultimodal] Knowledge %s aborted (%s), skipping image %s",
|
||||
payload.KnowledgeID, k.ParseStatus, payload.ImageURL)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Open a per-image subspan under the parent attempt's multimodal
|
||||
// stage. If the parent stage row is missing (legacy in-flight
|
||||
// task, or the upstream code shipped without span tracking), the
|
||||
|
||||
@@ -53,6 +53,7 @@ type knowledgeService struct {
|
||||
fileSvc interfaces.FileService
|
||||
modelService interfaces.ModelService
|
||||
task interfaces.TaskEnqueuer
|
||||
taskInspector interfaces.TaskInspector
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
redisClient *redis.Client
|
||||
kbShareService interfaces.KBShareService
|
||||
@@ -93,6 +94,7 @@ func NewKnowledgeService(
|
||||
fileSvc interfaces.FileService,
|
||||
modelService interfaces.ModelService,
|
||||
task interfaces.TaskEnqueuer,
|
||||
taskInspector interfaces.TaskInspector,
|
||||
graphEngine interfaces.RetrieveGraphRepository,
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
ownership retriever.TenantStoreOwnership,
|
||||
@@ -118,6 +120,7 @@ func NewKnowledgeService(
|
||||
fileSvc: fileSvc,
|
||||
modelService: modelService,
|
||||
task: task,
|
||||
taskInspector: taskInspector,
|
||||
graphEngine: graphEngine,
|
||||
retrieveEngine: retrieveEngine,
|
||||
ownership: ownership,
|
||||
@@ -297,6 +300,33 @@ func (s *knowledgeService) isKnowledgeDeleting(ctx context.Context, tenantID uin
|
||||
return knowledge.ParseStatus == types.ParseStatusDeleting
|
||||
}
|
||||
|
||||
// isKnowledgeAborted returns (true, status) when the knowledge has been
|
||||
// marked as deleting OR cancelled so async pipeline workers should bail
|
||||
// out. Status is returned so callers can branch on cleanup behavior:
|
||||
// deleting → existing cleanup of partial chunks/index applies;
|
||||
// cancelled → keep partially written data per user expectation.
|
||||
//
|
||||
// When the row is missing or unreadable we conservatively return
|
||||
// (true, ParseStatusDeleting): the existing deleting branch already
|
||||
// handles cleanup-or-no-op semantics safely.
|
||||
func (s *knowledgeService) isKnowledgeAborted(
|
||||
ctx context.Context, tenantID uint64, knowledgeID string,
|
||||
) (bool, string) {
|
||||
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to check knowledge abort status (assuming deleted): %v", err)
|
||||
return true, types.ParseStatusDeleting
|
||||
}
|
||||
if knowledge == nil {
|
||||
return true, types.ParseStatusDeleting
|
||||
}
|
||||
switch knowledge.ParseStatus {
|
||||
case types.ParseStatusDeleting, types.ParseStatusCancelled:
|
||||
return true, knowledge.ParseStatus
|
||||
}
|
||||
return false, knowledge.ParseStatus
|
||||
}
|
||||
|
||||
// checkStorageEngineConfigured verifies that the knowledge base has a storage engine configured
|
||||
// (either at the KB level or via the tenant default).
|
||||
//
|
||||
|
||||
@@ -75,6 +75,17 @@ func (s *knowledgeService) DeleteKnowledge(ctx context.Context, id string) error
|
||||
logger.Infof(ctx, "Marked knowledge %s as deleting (previous status: %s)", id, originalStatus)
|
||||
}
|
||||
|
||||
// Best-effort: purge any queued downstream tasks for this knowledge
|
||||
// (multimodal / post-process / question / summary / graph extract).
|
||||
// Worker checkpoints already drop them on the floor, but dequeuing
|
||||
// here avoids waking workers just to no-op when the parse was still
|
||||
// in flight at delete time. No-op in Lite mode and on completed rows
|
||||
// (no queued descendants anyway).
|
||||
if originalStatus == types.ParseStatusPending ||
|
||||
originalStatus == types.ParseStatusProcessing {
|
||||
s.dequeueKnowledgeTasks(ctx, id)
|
||||
}
|
||||
|
||||
// Resolve file service for this KB before spawning goroutines
|
||||
kb, _ := s.kbService.GetKnowledgeBaseByID(ctx, knowledge.KnowledgeBaseID)
|
||||
kbFileSvc := s.resolveFileService(ctx, kb)
|
||||
@@ -392,8 +403,12 @@ func (s *knowledgeService) DeleteKnowledgeList(ctx context.Context, ids []string
|
||||
return err
|
||||
}
|
||||
|
||||
// Mark all as deleting first to prevent async task conflicts
|
||||
// Mark all as deleting first to prevent async task conflicts.
|
||||
// Remember which entries still had queued / in-flight downstream tasks
|
||||
// so we can dequeue them in one pass after marking.
|
||||
var inFlightIDs []string
|
||||
for _, knowledge := range knowledgeList {
|
||||
prev := knowledge.ParseStatus
|
||||
knowledge.ParseStatus = types.ParseStatusDeleting
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
@@ -401,9 +416,19 @@ func (s *knowledgeService) DeleteKnowledgeList(ctx context.Context, ids []string
|
||||
Errorf("DeleteKnowledgeList failed to mark as deleting")
|
||||
// Continue with deletion even if marking fails
|
||||
}
|
||||
if prev == types.ParseStatusPending || prev == types.ParseStatusProcessing {
|
||||
inFlightIDs = append(inFlightIDs, knowledge.ID)
|
||||
}
|
||||
}
|
||||
logger.Infof(ctx, "Marked %d knowledge entries as deleting", len(knowledgeList))
|
||||
|
||||
// Best-effort dequeue of downstream tasks for in-flight entries.
|
||||
// See DeleteKnowledge for the rationale; loop is per-knowledge because
|
||||
// the inspector only filters by knowledge_id, not by ID set.
|
||||
for _, kid := range inFlightIDs {
|
||||
s.dequeueKnowledgeTasks(ctx, kid)
|
||||
}
|
||||
|
||||
// Pre-resolve file services per KB so goroutines don't need DB access
|
||||
kbFileServices := make(map[string]interfaces.FileService)
|
||||
for _, knowledge := range knowledgeList {
|
||||
|
||||
@@ -116,9 +116,16 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
|
||||
// Knowledge rows with no spans at all (lite mode, in-flight tasks
|
||||
// from before this code shipped) fall back to the simple
|
||||
// updated_at check — they have no heartbeat to consult.
|
||||
// Include 'finalizing' alongside 'processing': finalizing rows still
|
||||
// consume LLM compute via enrichment subtasks (summary/question/graph),
|
||||
// and the same stall modes (subtask worker dies, retry budget exhausted
|
||||
// without decrementing the counter) leave the row hanging just as
|
||||
// visibly. Housekeeping promotes both states to 'failed' once the
|
||||
// span heartbeat is older than the threshold.
|
||||
var candidates []types.Knowledge
|
||||
if err := h.db.WithContext(ctx).
|
||||
Where("parse_status = ? AND updated_at < ?", types.ParseStatusProcessing, cutoff).
|
||||
Where("parse_status IN ? AND updated_at < ?",
|
||||
[]string{types.ParseStatusProcessing, types.ParseStatusFinalizing}, cutoff).
|
||||
Find(&candidates).Error; err != nil {
|
||||
logger.Warnf(ctx, "[Housekeeping] knowledge candidate query failed: %v", err)
|
||||
return
|
||||
@@ -131,10 +138,12 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
|
||||
stuckIDs = append(stuckIDs, k.ID)
|
||||
}
|
||||
res := h.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("id IN ? AND parse_status = ?", stuckIDs, types.ParseStatusProcessing).
|
||||
Where("id IN ? AND parse_status IN ?", stuckIDs,
|
||||
[]string{types.ParseStatusProcessing, types.ParseStatusFinalizing}).
|
||||
Updates(map[string]interface{}{
|
||||
"parse_status": types.ParseStatusFailed,
|
||||
"error_message": "task stuck in processing > " + threshold.String() + ", recovered by housekeeping",
|
||||
"parse_status": types.ParseStatusFailed,
|
||||
"error_message": "task stuck in processing > " + threshold.String() + ", recovered by housekeeping",
|
||||
"pending_subtasks_count": 0,
|
||||
})
|
||||
if res.Error != nil {
|
||||
logger.Warnf(ctx, "[Housekeeping] knowledge sweep update failed: %v", res.Error)
|
||||
|
||||
@@ -27,6 +27,7 @@ CREATE TABLE IF NOT EXISTS knowledges (
|
||||
knowledge_base_id VARCHAR(64),
|
||||
parse_status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
||||
summary_status VARCHAR(32) NOT NULL DEFAULT 'none',
|
||||
pending_subtasks_count INTEGER NOT NULL DEFAULT 0,
|
||||
error_message TEXT,
|
||||
title TEXT,
|
||||
file_type TEXT,
|
||||
|
||||
@@ -100,6 +100,24 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
||||
return nil
|
||||
}
|
||||
|
||||
// Skip post-processing entirely when the knowledge has been cancelled
|
||||
// by the user or marked for deletion. We must NOT enqueue summary /
|
||||
// question / graph / wiki child tasks for an aborted knowledge. We
|
||||
// MUST also close postSpan before returning, otherwise it stays in
|
||||
// running state forever and the trace viewer shows an orange bar
|
||||
// long after the user cancelled (the AbortAttempt sweep ran before
|
||||
// we opened postSpan, so the sweep didn't catch this row).
|
||||
switch knowledge.ParseStatus {
|
||||
case types.ParseStatusCancelled, types.ParseStatusDeleting:
|
||||
logger.Infof(ctx,
|
||||
"[KnowledgePostProcess] Knowledge %s aborted (%s), skipping post-processing.",
|
||||
payload.KnowledgeID, knowledge.ParseStatus,
|
||||
)
|
||||
s.tracker().SkipSpan(ctx, postSpan,
|
||||
"knowledge "+knowledge.ParseStatus+" before postprocess started")
|
||||
return nil
|
||||
}
|
||||
|
||||
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
|
||||
if err != nil || kb == nil {
|
||||
return fmt.Errorf("get knowledge base %s: %w", payload.KnowledgeBaseID, err)
|
||||
@@ -119,42 +137,121 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Update ParseStatus to Completed
|
||||
// (Except if it's already completed or if it was marked as failed/deleting, but we'll just set it to completed if it's processing)
|
||||
if knowledge.ParseStatus == types.ParseStatusProcessing {
|
||||
knowledge.ParseStatus = types.ParseStatusCompleted
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
// 3. Compute the enrichment subtask count up front so we can flip to
|
||||
// "finalizing" with the right counter BEFORE spawning any subtasks.
|
||||
// Each subtask handler atomically decrements pending_subtasks_count
|
||||
// on its terminal exit; the row promotes itself to "completed" when
|
||||
// the counter hits zero (see knowledgeRepository.FinalizeSubtask).
|
||||
//
|
||||
// Wiki ingest is NOT counted here — it's a KB-scoped debounced
|
||||
// batch with its own dedup queue; per-knowledge accounting is not
|
||||
// meaningful for it.
|
||||
willSpawnSummary := len(textChunks) > 0
|
||||
willSpawnQuestion := willSpawnSummary && kb.NeedsEmbeddingModel() &&
|
||||
kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled
|
||||
graphChunkCount := 0
|
||||
if kb.IsGraphEnabled() {
|
||||
graphChunkCount = len(textChunks)
|
||||
}
|
||||
expectedSubtasks := 0
|
||||
if willSpawnSummary {
|
||||
expectedSubtasks++
|
||||
}
|
||||
if willSpawnQuestion {
|
||||
expectedSubtasks++
|
||||
}
|
||||
expectedSubtasks += graphChunkCount
|
||||
|
||||
// Setup summary status
|
||||
if len(textChunks) > 0 {
|
||||
knowledge.SummaryStatus = types.SummaryStatusPending
|
||||
} else {
|
||||
knowledge.SummaryStatus = types.SummaryStatusNone
|
||||
switch {
|
||||
case knowledge.ParseStatus != types.ParseStatusProcessing:
|
||||
// The row was already in some other state (deleting / cancelled /
|
||||
// failed / completed) when we arrived. Don't touch parse_status
|
||||
// and don't spawn enrichment — the upstream that put the row in
|
||||
// that state has already decided this attempt is over.
|
||||
logger.Infof(ctx, "[KnowledgePostProcess] Knowledge %s is in %s, skipping enrichment fan-out.",
|
||||
payload.KnowledgeID, knowledge.ParseStatus)
|
||||
s.tracker().EndSpan(ctx, postSpan, types.JSONMap{
|
||||
"skipped": "non_processing_status",
|
||||
"observed_status": knowledge.ParseStatus,
|
||||
})
|
||||
s.tracker().FinalizeAttempt(ctx, payload.KnowledgeID, attempt,
|
||||
types.SpanStatusDone, types.JSONMap{
|
||||
"skipped": "non_processing_status",
|
||||
"observed_status": knowledge.ParseStatus,
|
||||
}, "", "")
|
||||
return nil
|
||||
case expectedSubtasks == 0:
|
||||
// Nothing to enrich — fast path keeps the previous behavior so
|
||||
// users without summary/question/graph see 'completed' immediately.
|
||||
updates := map[string]interface{}{
|
||||
"parse_status": types.ParseStatusCompleted,
|
||||
"updated_at": time.Now(),
|
||||
}
|
||||
|
||||
if err := s.knowledgeRepo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to update knowledge status to completed: %v", err)
|
||||
if len(textChunks) > 0 {
|
||||
updates["summary_status"] = types.SummaryStatusNone
|
||||
}
|
||||
if err := s.knowledgeRepo.UpdateKnowledgeColumns(ctx, payload.KnowledgeID, updates); err != nil {
|
||||
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to mark %s completed (no subtasks): %v",
|
||||
payload.KnowledgeID, err)
|
||||
} else {
|
||||
logger.Infof(ctx, "[KnowledgePostProcess] Knowledge %s marked as completed.", payload.KnowledgeID)
|
||||
logger.Infof(ctx, "[KnowledgePostProcess] Knowledge %s marked completed (no enrichment subtasks).",
|
||||
payload.KnowledgeID)
|
||||
}
|
||||
default:
|
||||
// Flip processing → finalizing in one statement so a parallel
|
||||
// cancel/delete cannot race us into completed.
|
||||
promoted, err := s.knowledgeRepo.SetFinalizing(ctx, payload.KnowledgeID, expectedSubtasks)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[KnowledgePostProcess] SetFinalizing failed for %s: %v",
|
||||
payload.KnowledgeID, err)
|
||||
}
|
||||
if promoted {
|
||||
// Reflect summary status separately so the UI shows the
|
||||
// summary as queued for users who already had it visible.
|
||||
summaryStatus := types.SummaryStatusNone
|
||||
if willSpawnSummary {
|
||||
summaryStatus = types.SummaryStatusPending
|
||||
}
|
||||
if err := s.knowledgeRepo.UpdateKnowledgeColumn(ctx,
|
||||
payload.KnowledgeID, "summary_status", summaryStatus); err != nil {
|
||||
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to update summary_status for %s: %v",
|
||||
payload.KnowledgeID, err)
|
||||
}
|
||||
logger.Infof(ctx,
|
||||
"[KnowledgePostProcess] Knowledge %s entered finalizing (pending_subtasks=%d).",
|
||||
payload.KnowledgeID, expectedSubtasks)
|
||||
} else {
|
||||
// Row was no longer 'processing' (cancel / delete won the race).
|
||||
// Skip enrichment entirely so we don't waste LLM quota on a row
|
||||
// the user already abandoned.
|
||||
logger.Infof(ctx,
|
||||
"[KnowledgePostProcess] Knowledge %s no longer in processing, skipping enrichment fan-out.",
|
||||
payload.KnowledgeID)
|
||||
s.tracker().EndSpan(ctx, postSpan, types.JSONMap{
|
||||
"skipped": "knowledge_no_longer_processing",
|
||||
})
|
||||
s.tracker().FinalizeAttempt(ctx, payload.KnowledgeID, attempt,
|
||||
types.SpanStatusDone, types.JSONMap{
|
||||
"skipped": "knowledge_no_longer_processing",
|
||||
}, "", "")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Spawn Summary and Question Tasks
|
||||
enqueuedSummary := false
|
||||
enqueuedQuestion := false
|
||||
if len(textChunks) > 0 {
|
||||
if willSpawnSummary {
|
||||
s.enqueueSummaryGenerationTask(ctx, payload, attempt)
|
||||
enqueuedSummary = true
|
||||
// Question generation only makes sense for RAG indexing (improves chunk recall).
|
||||
// Skip when only Wiki/Graph is enabled without vector/keyword search.
|
||||
if kb.NeedsEmbeddingModel() {
|
||||
if willSpawnQuestion {
|
||||
enqueuedQuestion = s.enqueueQuestionGenerationIfEnabled(ctx, payload, kb, attempt)
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Spawn Graph RAG Tasks — only when graph indexing is enabled in IndexingStrategy
|
||||
enqueuedGraph := false
|
||||
if kb.IsGraphEnabled() {
|
||||
if graphChunkCount > 0 {
|
||||
logger.Infof(ctx, "[KnowledgePostProcess] Spawning Graph RAG extract tasks for %d text-like chunks", len(textChunks))
|
||||
for i, chunk := range textChunks {
|
||||
err := NewChunkExtractTask(ctx, s.taskEnqueuer, payload.TenantID, chunk.ID, kb.SummaryModelID,
|
||||
@@ -163,7 +260,7 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
||||
logger.Errorf(ctx, "[KnowledgePostProcess] Failed to create chunk extract task for %s: %v", chunk.ID, err)
|
||||
}
|
||||
}
|
||||
enqueuedGraph = len(textChunks) > 0
|
||||
enqueuedGraph = true
|
||||
}
|
||||
|
||||
// 6. Spawn Wiki Ingest Task if wiki indexing is enabled in IndexingStrategy
|
||||
|
||||
@@ -240,10 +240,12 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
||||
attribute.Int("chunk_count", len(chunks)),
|
||||
)
|
||||
|
||||
// Check if knowledge is being deleted before processing
|
||||
if s.isKnowledgeDeleting(ctx, knowledge.TenantID, knowledge.ID) {
|
||||
logger.Infof(ctx, "Knowledge is being deleted, aborting chunk processing: %s", knowledge.ID)
|
||||
span.AddEvent("aborted: knowledge is being deleted")
|
||||
// Check if knowledge is being deleted/cancelled before processing.
|
||||
// Both statuses short-circuit identically here — there's nothing to clean
|
||||
// up yet so the branch is purely "stop early".
|
||||
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
|
||||
logger.Infof(ctx, "Knowledge aborted (%s), skipping chunk processing: %s", status, knowledge.ID)
|
||||
span.AddEvent("aborted: knowledge " + status)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -455,10 +457,11 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
||||
}
|
||||
}
|
||||
|
||||
// Check if knowledge is being deleted before writing to database
|
||||
if s.isKnowledgeDeleting(ctx, knowledge.TenantID, knowledge.ID) {
|
||||
logger.Infof(ctx, "Knowledge is being deleted, aborting before saving chunks: %s", knowledge.ID)
|
||||
span.AddEvent("aborted: knowledge is being deleted before saving")
|
||||
// Check if knowledge is being deleted/cancelled before writing chunks.
|
||||
// Nothing has been persisted yet, so both branches just bail.
|
||||
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
|
||||
logger.Infof(ctx, "Knowledge aborted (%s), skipping chunk write: %s", status, knowledge.ID)
|
||||
span.AddEvent("aborted: knowledge " + status + " before saving")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -550,14 +553,17 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
||||
}
|
||||
}
|
||||
|
||||
// Check again before batch indexing (this is a heavy operation)
|
||||
if s.isKnowledgeDeleting(ctx, knowledge.TenantID, knowledge.ID) {
|
||||
logger.Infof(ctx, "Knowledge is being deleted, cleaning up and aborting before indexing: %s", knowledge.ID)
|
||||
// Clean up the chunks we just created
|
||||
if err := s.chunkService.DeleteChunksByKnowledgeID(ctx, knowledge.ID); err != nil {
|
||||
logger.Warnf(ctx, "Failed to cleanup chunks after deletion detected: %v", err)
|
||||
// Check again before batch indexing (heavy operation).
|
||||
// deleting → row is going away anyway, drop the chunks we just wrote.
|
||||
// cancelled → user wants to keep what was already persisted, just stop.
|
||||
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
|
||||
logger.Infof(ctx, "Knowledge aborted (%s) before indexing: %s", status, knowledge.ID)
|
||||
if status == types.ParseStatusDeleting {
|
||||
if err := s.chunkService.DeleteChunksByKnowledgeID(ctx, knowledge.ID); err != nil {
|
||||
logger.Warnf(ctx, "Failed to cleanup chunks after deletion detected: %v", err)
|
||||
}
|
||||
}
|
||||
span.AddEvent("aborted: knowledge is being deleted before indexing")
|
||||
span.AddEvent("aborted: knowledge " + status + " before indexing")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -597,17 +603,21 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
||||
"storage_bytes": totalStorageSize,
|
||||
})
|
||||
|
||||
// Final check before marking as completed - if deleted during processing, don't update status
|
||||
if s.isKnowledgeDeleting(ctx, knowledge.TenantID, knowledge.ID) {
|
||||
logger.Infof(ctx, "Knowledge was deleted during processing, skipping completion update: %s", knowledge.ID)
|
||||
// Clean up the data we just created since the knowledge is being deleted
|
||||
if err := s.chunkService.DeleteChunksByKnowledgeID(ctx, knowledge.ID); err != nil {
|
||||
logger.Warnf(ctx, "Failed to cleanup chunks after deletion detected: %v", err)
|
||||
// Final check before marking as completed.
|
||||
// deleting → drop chunks+index we just wrote.
|
||||
// cancelled → keep persisted data; the row stays in cancelled status
|
||||
// and downstream stages skip via the entry guards.
|
||||
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
|
||||
logger.Infof(ctx, "Knowledge aborted (%s) after indexing: %s", status, knowledge.ID)
|
||||
if status == types.ParseStatusDeleting {
|
||||
if err := s.chunkService.DeleteChunksByKnowledgeID(ctx, knowledge.ID); err != nil {
|
||||
logger.Warnf(ctx, "Failed to cleanup chunks after deletion detected: %v", err)
|
||||
}
|
||||
if err := retrieveEngine.DeleteByKnowledgeIDList(ctx, []string{knowledge.ID}, embeddingModel.GetDimensions(), kb.Type); err != nil {
|
||||
logger.Warnf(ctx, "Failed to cleanup index after deletion detected: %v", err)
|
||||
}
|
||||
}
|
||||
if err := retrieveEngine.DeleteByKnowledgeIDList(ctx, []string{knowledge.ID}, embeddingModel.GetDimensions(), kb.Type); err != nil {
|
||||
logger.Warnf(ctx, "Failed to cleanup index after deletion detected: %v", err)
|
||||
}
|
||||
span.AddEvent("aborted: knowledge was deleted during processing")
|
||||
span.AddEvent("aborted: knowledge " + status + " during processing")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
@@ -899,6 +909,14 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
||||
var summaryErr error
|
||||
summaryOut := types.JSONMap{}
|
||||
defer func() {
|
||||
// Decrement the parent's enrichment counter on every terminal
|
||||
// exit (success OR final retry failure). Intermediate retries
|
||||
// skip the decrement so the counter cannot drain prematurely.
|
||||
if (summaryErr == nil || isFinalAsynqAttempt(ctx)) && payload.KnowledgeID != "" {
|
||||
if _, _, ferr := s.repo.FinalizeSubtask(ctx, payload.KnowledgeID); ferr != nil {
|
||||
logger.Warnf(ctx, "summary: FinalizeSubtask failed for %s: %v", payload.KnowledgeID, ferr)
|
||||
}
|
||||
}
|
||||
if span == nil {
|
||||
return
|
||||
}
|
||||
@@ -935,6 +953,16 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
||||
summaryErr = err
|
||||
return nil
|
||||
}
|
||||
// Short-circuit when the user cancelled parsing or the row is being deleted.
|
||||
if knowledge != nil {
|
||||
switch knowledge.ParseStatus {
|
||||
case types.ParseStatusCancelled, types.ParseStatusDeleting:
|
||||
logger.Infof(ctx, "Summary generation: knowledge aborted (%s), skipping: %s",
|
||||
knowledge.ParseStatus, payload.KnowledgeID)
|
||||
summaryOut["skipped"] = "knowledge_" + knowledge.ParseStatus
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Update summary status to processing
|
||||
knowledge.SummaryStatus = types.SummaryStatusProcessing
|
||||
@@ -1172,6 +1200,16 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
||||
// what we already log to stdout.
|
||||
var qSpan *Span
|
||||
var qErr error
|
||||
// Decrement enrichment counter on terminal exit (success OR final
|
||||
// retry failure). Runs AFTER the stats-log defer below — defers
|
||||
// unwind LIFO, so this one declared first executes last.
|
||||
defer func() {
|
||||
if (qErr == nil || isFinalAsynqAttempt(ctx)) && payload.KnowledgeID != "" {
|
||||
if _, _, ferr := s.repo.FinalizeSubtask(ctx, payload.KnowledgeID); ferr != nil {
|
||||
logger.Warnf(ctx, "question: FinalizeSubtask failed for %s: %v", payload.KnowledgeID, ferr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
logger.Infof(
|
||||
ctx,
|
||||
@@ -1287,6 +1325,16 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
||||
qErr = err
|
||||
return nil
|
||||
}
|
||||
// Short-circuit when the user cancelled parsing or the row is being deleted.
|
||||
if knowledge != nil {
|
||||
switch knowledge.ParseStatus {
|
||||
case types.ParseStatusCancelled, types.ParseStatusDeleting:
|
||||
exitStatus = "knowledge_" + knowledge.ParseStatus
|
||||
logger.Infof(ctx, "Question generation: knowledge aborted (%s), skipping: %s",
|
||||
knowledge.ParseStatus, payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Get text chunks for this knowledge
|
||||
chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)
|
||||
@@ -1591,6 +1639,10 @@ func (s *knowledgeService) ReparseKnowledge(ctx context.Context, knowledgeID str
|
||||
existing.Description = ""
|
||||
existing.ProcessedAt = nil
|
||||
existing.EmbeddingModelID = kb.EmbeddingModelID
|
||||
// Reset the enrichment counter so a leftover value from a
|
||||
// previous attempt (e.g. cancelled before all subtasks decremented)
|
||||
// cannot block the new finalizing transition later.
|
||||
existing.PendingSubtasksCount = 0
|
||||
|
||||
if err := s.repo.UpdateKnowledge(ctx, existing); err != nil {
|
||||
logger.Errorf(ctx, "Failed to update knowledge status before reparse: %v", err)
|
||||
@@ -1621,6 +1673,9 @@ func (s *knowledgeService) ReparseKnowledge(ctx context.Context, knowledgeID str
|
||||
existing.Description = ""
|
||||
existing.ProcessedAt = nil
|
||||
existing.EmbeddingModelID = kb.EmbeddingModelID
|
||||
// Reset the enrichment counter so a leftover value from a previous
|
||||
// attempt cannot block the new finalizing transition later.
|
||||
existing.PendingSubtasksCount = 0
|
||||
|
||||
if err := s.repo.UpdateKnowledge(ctx, existing); err != nil {
|
||||
logger.Errorf(ctx, "Failed to update knowledge status before reparse: %v", err)
|
||||
@@ -1785,6 +1840,117 @@ func (s *knowledgeService) ReparseKnowledge(ctx context.Context, knowledgeID str
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
// CancelKnowledgeParse marks an in-progress parse as cancelled by the user.
|
||||
//
|
||||
// Semantics (kept aligned with the existing deleting path, but partial work
|
||||
// is preserved instead of cleaned up):
|
||||
// - parse_status is set to "cancelled"; partial chunks/index already written
|
||||
// to the database remain on disk. The user can re-trigger parsing via the
|
||||
// existing ReparseKnowledge API, which overwrites status back to pending.
|
||||
// - Any in-flight worker reads the new status at its next checkpoint and
|
||||
// bails (see processChunks / ProcessDocument / downstream handlers).
|
||||
// - The asynq inspector (if available) dequeues pending / scheduled / retry
|
||||
// tasks for this knowledge_id across the default / critical / low queues
|
||||
// and signals active workers to stop. Lite mode (no Redis) skips the
|
||||
// dequeue step — the checkpoint-based abort is the only stop signal there.
|
||||
// - Idempotent: re-calling on an already-cancelled row is a no-op.
|
||||
//
|
||||
// Errors:
|
||||
// - ParseStatusCompleted / ParseStatusFailed: the parse has already finished.
|
||||
// - ParseStatusDeleting: a delete is in progress; cancel cannot supersede it.
|
||||
func (s *knowledgeService) CancelKnowledgeParse(
|
||||
ctx context.Context, knowledgeID string,
|
||||
) (*types.Knowledge, error) {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
existing, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "CancelKnowledgeParse: failed to load knowledge: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
if existing == nil {
|
||||
return nil, werrors.NewNotFoundError("knowledge not found")
|
||||
}
|
||||
|
||||
switch existing.ParseStatus {
|
||||
case types.ParseStatusCancelled:
|
||||
// Idempotent — still attempt the dequeue in case earlier calls
|
||||
// raced an enqueue, but skip the row update / span close path.
|
||||
s.dequeueKnowledgeTasks(ctx, knowledgeID)
|
||||
return existing, nil
|
||||
case types.ParseStatusCompleted, types.ParseStatusFailed:
|
||||
return nil, werrors.NewBadRequestError("解析已结束,无法取消")
|
||||
case types.ParseStatusDeleting:
|
||||
return nil, werrors.NewBadRequestError("知识正在删除中,无法取消解析")
|
||||
case types.ParseStatusPending, types.ParseStatusProcessing, types.ParseStatusFinalizing:
|
||||
// Cancellable. `finalizing` is the post-process fan-out window
|
||||
// where graph-extract / summary / question subtasks are still
|
||||
// running; cancel here stops the LLM cost they would burn.
|
||||
default:
|
||||
// Unknown status — let it through but log. Should never happen
|
||||
// outside test fixtures or hand-edited rows.
|
||||
logger.Warnf(ctx, "CancelKnowledgeParse: unexpected status %q for %s, proceeding",
|
||||
existing.ParseStatus, knowledgeID)
|
||||
}
|
||||
|
||||
// Flip the row to cancelled and zero the enrichment counter in one
|
||||
// update so a late subtask FinalizeSubtask call can't race-promote
|
||||
// the row back to completed. Persisted partial data is left in
|
||||
// place — the user can reuse it on the next reparse attempt.
|
||||
now := time.Now()
|
||||
if err := s.repo.UpdateKnowledgeColumns(ctx, existing.ID, map[string]interface{}{
|
||||
"parse_status": types.ParseStatusCancelled,
|
||||
"error_message": "用户已取消解析",
|
||||
"pending_subtasks_count": 0,
|
||||
"updated_at": now,
|
||||
}); err != nil {
|
||||
logger.Errorf(ctx, "CancelKnowledgeParse: failed to mark knowledge cancelled: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
existing.ParseStatus = types.ParseStatusCancelled
|
||||
existing.ErrorMessage = "用户已取消解析"
|
||||
existing.PendingSubtasksCount = 0
|
||||
existing.UpdatedAt = now
|
||||
logger.Infof(ctx, "Knowledge %s marked as cancelled by user", knowledgeID)
|
||||
|
||||
// Close the active attempt span tree so the UI stops showing "进行中"
|
||||
// for the cancelled run. AbortAttempt cascade-cancels every still-
|
||||
// running descendant (multimodal per-image, postprocess subtasks,
|
||||
// graph chunks) BEFORE closing the root, otherwise the trace
|
||||
// viewer would leave those striped/running bars hanging forever
|
||||
// because workers exit via their abort-guard without ever calling
|
||||
// FailSpan on their own subspan. Best-effort: nil tracker / missing
|
||||
// attempt no-ops.
|
||||
if attempt := s.tracker().LatestAttempt(ctx, knowledgeID); attempt > 0 {
|
||||
s.tracker().AbortAttempt(ctx, knowledgeID, attempt,
|
||||
"USER_CANCELLED", "用户已取消解析", "用户已取消解析")
|
||||
}
|
||||
|
||||
// Best-effort dequeue. Failures here don't block the cancel — the
|
||||
// downstream tasks will still self-abort at their entry guards.
|
||||
s.dequeueKnowledgeTasks(ctx, knowledgeID)
|
||||
// Wiki ingest lives in its own per-KB pending queue (task_pending_ops)
|
||||
// rather than asynq, so dequeueKnowledgeTasks above can't see it.
|
||||
// Mirror the deletion path's scrub so a cancelled knowledge doesn't
|
||||
// get picked up by the next 30s batch and burn a wiki LLM call on a
|
||||
// doc the user already abandoned. The in-flight worker would skip it
|
||||
// at isWikiKnowledgeAborted anyway, but scrubbing avoids waking the
|
||||
// batch in the first place.
|
||||
s.scrubWikiPendingIngest(ctx, existing.KnowledgeBaseID, knowledgeID, "cancel")
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
// dequeueKnowledgeTasks asks the task inspector to remove any queued
|
||||
// tasks for this knowledge and signal active workers to stop. Safe to
|
||||
// call when the inspector is a no-op (Lite mode).
|
||||
func (s *knowledgeService) dequeueKnowledgeTasks(ctx context.Context, knowledgeID string) {
|
||||
if s.taskInspector == nil {
|
||||
return
|
||||
}
|
||||
if _, _, err := s.taskInspector.CancelTasksForKnowledge(ctx, knowledgeID); err != nil {
|
||||
logger.Warnf(ctx, "CancelKnowledgeParse: dequeue best-effort failed for %s: %v", knowledgeID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *knowledgeService) updateChunkVector(ctx context.Context, kbID string, chunks []*types.Chunk) error {
|
||||
// Get embedding model from knowledge base
|
||||
sourceKB, err := s.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
@@ -2038,6 +2204,10 @@ func (s *knowledgeService) ProcessManualUpdate(ctx context.Context, t *asynq.Tas
|
||||
logger.Infof(ctx, "ProcessManualUpdate: being deleted, skipping: %s", payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
if knowledge.ParseStatus == types.ParseStatusCancelled {
|
||||
logger.Infof(ctx, "ProcessManualUpdate: cancelled by user, skipping: %s", payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
@@ -2049,6 +2219,12 @@ func (s *knowledgeService) ProcessManualUpdate(ctx context.Context, t *asynq.Tas
|
||||
return nil
|
||||
}
|
||||
|
||||
// Re-check abort status right before marking processing — see the same
|
||||
// note in ProcessDocument for the cancel race this guards.
|
||||
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
|
||||
logger.Infof(ctx, "ProcessManualUpdate: knowledge aborted (%s), skipping: %s", status, knowledge.ID)
|
||||
return nil
|
||||
}
|
||||
// Update status to processing
|
||||
knowledge.ParseStatus = "processing"
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
@@ -2117,11 +2293,15 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
return nil
|
||||
}
|
||||
|
||||
// 检查是否正在删除 - 如果是则直接退出,避免与删除操作冲突
|
||||
// 检查是否正在删除 / 已被用户取消 - 如果是则直接退出
|
||||
if knowledge.ParseStatus == types.ParseStatusDeleting {
|
||||
logger.Infof(ctx, "Knowledge is being deleted, aborting processing: %s", payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
if knowledge.ParseStatus == types.ParseStatusCancelled {
|
||||
logger.Infof(ctx, "Knowledge cancelled by user, aborting processing: %s", payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 检查任务状态 - 幂等性处理
|
||||
if knowledge.ParseStatus == types.ParseStatusCompleted {
|
||||
@@ -2159,6 +2339,14 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
return nil
|
||||
}
|
||||
|
||||
// Re-check abort status right before flipping to "processing" — closes
|
||||
// the race where the user cancels between the entry guard above and
|
||||
// this write (otherwise the worker would overwrite cancelled→processing
|
||||
// and downstream checkpoints would treat the run as live).
|
||||
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
|
||||
logger.Infof(ctx, "Knowledge aborted (%s) before marking processing: %s", status, knowledge.ID)
|
||||
return nil
|
||||
}
|
||||
knowledge.ParseStatus = "processing"
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
|
||||
@@ -102,6 +102,14 @@ type SpanTracker interface {
|
||||
// done; output/error are written verbatim.
|
||||
FinalizeAttempt(ctx context.Context, knowledgeID string, attempt int, status string,
|
||||
output types.JSONMap, errorCode, errorMessage string)
|
||||
|
||||
// AbortAttempt cascade-cancels every still-running descendant of the
|
||||
// attempt's root span and then closes the root as cancelled. Used by
|
||||
// the user-initiated cancel path so the trace viewer doesn't leave
|
||||
// stranded subspans (multimodal images, postprocess subtasks)
|
||||
// looking like they're still in flight forever after the user
|
||||
// stopped the parse. Idempotent.
|
||||
AbortAttempt(ctx context.Context, knowledgeID string, attempt int, errorCode, errorMessage, reason string)
|
||||
}
|
||||
|
||||
type spanTracker struct {
|
||||
@@ -724,6 +732,43 @@ func (t *spanTracker) FinalizeAttempt(ctx context.Context, knowledgeID string, a
|
||||
t.touchKnowledgeHeartbeat(ctx, knowledgeID, types.SpanKindRoot)
|
||||
}
|
||||
|
||||
// AbortAttempt is the user-cancel counterpart to FinalizeAttempt. It
|
||||
// flips every still-running / still-pending span for this attempt to
|
||||
// cancelled — regardless of tree position — and then closes the root.
|
||||
//
|
||||
// Why a flat sweep instead of CancelDescendants' BFS: fan-out stages
|
||||
// (e.g. 多模态识别) call EndSpan on the stage as soon as they finish
|
||||
// DISPATCHING their async per-image work, so by the time the user
|
||||
// hits cancel the stage row is already status=done but its image[*]
|
||||
// children are still status=running. A BFS that stops at terminal
|
||||
// parents would orphan those leaves. The flat sweep doesn't care
|
||||
// about the tree shape — anything not-yet-terminal gets flipped.
|
||||
func (t *spanTracker) AbortAttempt(ctx context.Context, knowledgeID string, attempt int,
|
||||
errorCode, errorMessage, reason string,
|
||||
) {
|
||||
if knowledgeID == "" || attempt <= 0 {
|
||||
return
|
||||
}
|
||||
if reason == "" {
|
||||
reason = "user cancelled"
|
||||
}
|
||||
if errorCode == "" {
|
||||
errorCode = "USER_CANCELLED"
|
||||
}
|
||||
if n, err := t.repo.CancelAllOpenSpans(ctx, knowledgeID, attempt, errorCode, reason); err != nil {
|
||||
logger.Warnf(ctx, "[SpanTracker] AbortAttempt sweep failed kid=%s attempt=%d: %v",
|
||||
knowledgeID, attempt, err)
|
||||
// Fall through to FinalizeAttempt anyway — closing the root
|
||||
// is more important than perfectly closing every child.
|
||||
} else if n > 0 {
|
||||
logger.Infof(ctx,
|
||||
"[SpanTracker] AbortAttempt swept %d open span(s) for kid=%s attempt=%d",
|
||||
n, knowledgeID, attempt)
|
||||
}
|
||||
t.FinalizeAttempt(ctx, knowledgeID, attempt,
|
||||
types.SpanStatusCancelled, nil, errorCode, errorMessage)
|
||||
}
|
||||
|
||||
// noopSpanTracker collapses every method to a no-op for tests/lite.
|
||||
type noopSpanTracker struct{}
|
||||
|
||||
@@ -743,3 +788,4 @@ func (noopSpanTracker) SkipSpan(_ context.Context, _ *Span, _ string)
|
||||
func (noopSpanTracker) LookupStage(_ context.Context, _ string, _ int, _ string) *Span { return nil }
|
||||
func (noopSpanTracker) FinalizeAttempt(_ context.Context, _ string, _ int, _ string, _ types.JSONMap, _, _ string) {
|
||||
}
|
||||
func (noopSpanTracker) AbortAttempt(_ context.Context, _ string, _ int, _, _, _ string) {}
|
||||
|
||||
@@ -1786,7 +1786,11 @@ func (s *wikiIngestService) isKnowledgeGone(ctx context.Context, kbID, knowledge
|
||||
if err != nil || kn == nil {
|
||||
return true
|
||||
}
|
||||
return kn.ParseStatus == types.ParseStatusDeleting
|
||||
switch kn.ParseStatus {
|
||||
case types.ParseStatusDeleting, types.ParseStatusCancelled:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// filterLiveUpdates drops additions/summaries whose source knowledge has been
|
||||
|
||||
Reference in New Issue
Block a user