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:
@@ -95,6 +95,14 @@ type KnowledgeService interface {
|
||||
) (*types.Knowledge, error)
|
||||
// ReparseKnowledge deletes existing document content and re-parses the knowledge asynchronously.
|
||||
ReparseKnowledge(ctx context.Context, knowledgeID string) (*types.Knowledge, error)
|
||||
// CancelKnowledgeParse marks an in-progress parse as cancelled by the
|
||||
// user. The knowledge row and any partially written chunks/index are
|
||||
// kept; downstream queued tasks for the same knowledge are best-effort
|
||||
// dequeued and active workers are signalled to stop at their next
|
||||
// checkpoint. Idempotent — returns the existing row when the knowledge
|
||||
// is already cancelled. Returns an error when the knowledge is in a
|
||||
// terminal state (completed / failed) or being deleted.
|
||||
CancelKnowledgeParse(ctx context.Context, knowledgeID string) (*types.Knowledge, error)
|
||||
// CloneKnowledgeBase clones knowledge to another knowledge base.
|
||||
CloneKnowledgeBase(ctx context.Context, srcID, dstID string) error
|
||||
// UpdateImageInfo updates image information for a knowledge chunk.
|
||||
@@ -214,6 +222,17 @@ type KnowledgeRepository interface {
|
||||
// statement so callers that flip several related fields (e.g. parse_status +
|
||||
// error_message) cannot leave the row in a half-updated state.
|
||||
UpdateKnowledgeColumns(ctx context.Context, id string, values map[string]interface{}) error
|
||||
// FinalizeSubtask atomically decrements pending_subtasks_count for the
|
||||
// given knowledge and promotes parse_status from "finalizing" to
|
||||
// "completed" when the count reaches zero. Returns the post-decrement
|
||||
// count, whether this caller's UPDATE was the one that promoted the
|
||||
// row, and any error.
|
||||
FinalizeSubtask(ctx context.Context, id string) (int, bool, error)
|
||||
// SetFinalizing atomically transitions a row from "processing" to
|
||||
// "finalizing" and writes the initial pending_subtasks_count. Returns
|
||||
// whether the transition took place (false when the row's parse_status
|
||||
// was no longer "processing", e.g. user cancelled / deleted in flight).
|
||||
SetFinalizing(ctx context.Context, id string, expectedSubtasks int) (bool, error)
|
||||
// CountKnowledgeByKnowledgeBaseID counts the number of knowledge items in a knowledge base.
|
||||
CountKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) (int64, error)
|
||||
// CountKnowledgeByStatus counts the number of knowledge items with the specified parse status.
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package interfaces
|
||||
|
||||
import "context"
|
||||
|
||||
// TaskInspector abstracts queue inspection / cancellation against the
|
||||
// task backend. It is best-effort: implementations may scan a finite
|
||||
// number of tasks per call and return whatever count they could
|
||||
// affect. Lite mode (no Redis) ships a no-op implementation because
|
||||
// SyncTaskExecutor dispatches inline goroutines that cannot be
|
||||
// dequeued before they start.
|
||||
//
|
||||
// Use cases today: user-initiated cancel of an in-progress knowledge
|
||||
// parse, which must remove downstream multimodal / post-process /
|
||||
// question / summary tasks already enqueued against the same
|
||||
// knowledge_id, plus signal active workers to stop at their next
|
||||
// checkpoint.
|
||||
type TaskInspector interface {
|
||||
// CancelTasksForKnowledge removes pending/scheduled/retry tasks
|
||||
// whose payload references the given knowledge ID, and signals
|
||||
// active workers running such tasks to stop. Returns rough
|
||||
// counts of (deletedFromQueue, activeCancelled) for observability.
|
||||
// Errors are returned but callers should treat the operation as
|
||||
// best-effort: the row-level abort flag remains the source of
|
||||
// truth, this just prevents wasted work.
|
||||
CancelTasksForKnowledge(ctx context.Context, knowledgeID string) (deleted int, cancelled int, err error)
|
||||
}
|
||||
@@ -37,13 +37,30 @@ const (
|
||||
// ParseStatusPending indicates the knowledge is waiting to be processed
|
||||
ParseStatusPending = "pending"
|
||||
// ParseStatusProcessing indicates the knowledge is being processed
|
||||
// (DocReader / chunking / embedding stage).
|
||||
ParseStatusProcessing = "processing"
|
||||
// ParseStatusCompleted indicates the knowledge has been processed successfully
|
||||
// ParseStatusFinalizing indicates the primary parse has finished but
|
||||
// enrichment subtasks (summary, question generation, graph extract)
|
||||
// are still in flight. The user-facing intuition behind this state is
|
||||
// "the document is queryable for vector search but is still spending
|
||||
// resources" — cancel-parse can interrupt enrichment from here.
|
||||
// pending_subtasks_count holds the outstanding subtask count; the
|
||||
// last subtask to finish atomically promotes the row to completed.
|
||||
ParseStatusFinalizing = "finalizing"
|
||||
// ParseStatusCompleted indicates the knowledge has been processed
|
||||
// successfully AND every enrichment subtask has reached a terminal
|
||||
// state. No further resources will be spent on the document until
|
||||
// the user explicitly re-parses it.
|
||||
ParseStatusCompleted = "completed"
|
||||
// ParseStatusFailed indicates the knowledge processing failed
|
||||
ParseStatusFailed = "failed"
|
||||
// ParseStatusDeleting indicates the knowledge is being deleted (used to prevent async task conflicts)
|
||||
ParseStatusDeleting = "deleting"
|
||||
// ParseStatusCancelled indicates parsing was cancelled by the user.
|
||||
// Same short-circuit semantics as ParseStatusDeleting for in-flight and
|
||||
// queued downstream tasks, but the knowledge row and any already-written
|
||||
// chunks/index are kept so the user can re-trigger parsing via reparse.
|
||||
ParseStatusCancelled = "cancelled"
|
||||
)
|
||||
|
||||
// Summary status constants for async summary generation
|
||||
@@ -112,6 +129,10 @@ type Knowledge struct {
|
||||
Channel string `json:"channel" gorm:"type:varchar(50);default:'web'"`
|
||||
// Parse status of the knowledge
|
||||
ParseStatus string `json:"parse_status"`
|
||||
// PendingSubtasksCount is the outstanding enrichment subtask count
|
||||
// (summary + question + graph chunks). Only meaningful while
|
||||
// ParseStatus == "finalizing"; defaults to 0 in any terminal state.
|
||||
PendingSubtasksCount int `json:"pending_subtasks_count" gorm:"type:int;not null;default:0"`
|
||||
// Summary status for async summary generation
|
||||
SummaryStatus string `json:"summary_status" gorm:"type:varchar(32);default:none"`
|
||||
// Enable status of the knowledge
|
||||
|
||||
Reference in New Issue
Block a user