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,
|
||||
|
||||
Reference in New Issue
Block a user