refactor(knowledge): replace flat stage table with langfuse-style span tree
Addresses review feedback that the PR② design had four shortcomings:
1. The pipeline is a DAG, not a sequence — Embedding and Multimodal
are independent of each other, both downstream of Chunking, both
upstream of PostProcess. The flat (knowledge_id, stage) table
couldn't represent that, so a Chunking failure left dependents
stranded as "pending" forever instead of being marked as
impossible-to-run.
2. No history across attempts. A reparse erased the previous run's
status before the new run started, leaving operators with no way
to investigate "why did this fail twice?".
3. Stages had only status + duration. Operators want to know how big
the work was — pages parsed, chunks created, tokens embedded, VLM
calls made — to distinguish "slow because the file is huge" from
"slow because the docreader is wedged".
4. Multimodal fans out N image tasks; Embedding fans out M batches;
PostProcess fans out into Summary/Question/Wiki/Graph. Each unit
is interesting on its own (Langfuse already captures this for
LLM calls). The flat model couldn't express it.
The redesign mirrors Langfuse's trace/span/generation hierarchy:
* Migration 000053 supersedes 000052: knowledge_processing_spans
table with (knowledge_id, attempt, span_id) primary key, plus
parent_span_id, kind ∈ {root, stage, subspan, generation},
status ∈ {pending,running,done,failed,skipped,cancelled}, and
JSONB input/output/metadata fields.
* SpanTracker (replacing StageTracker) exposes OpenAttempt /
BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan /
LookupStage. Cross-process workers (image_multimodal) get the
parent's attempt + span via payload + LookupStage so subspans
attach correctly.
* StageDependencies declares the DAG; FailSpan now cascades —
descendants of the failed span and dependent stages are flipped
to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear
blast radius instead of orphan spinners.
* Reparse now calls OpenAttempt up front so the timeline reflects
"new attempt, all pending" instead of letting the previous run's
status linger until the worker picks up the task.
* Image_multimodal records each image as a generation subspan with
its own success/failure on the parent attempt's multimodal stage.
The finalize-on-last-attempt counter logic is preserved unchanged.
* GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns
a tree shape with synthesized pending placeholders so the
frontend always renders five timeline segments. ?attempt=N
enables history navigation.
This commit is contained in:
@@ -65,11 +65,11 @@ type knowledgeService struct {
|
||||
wikiRepo interfaces.WikiPageRepository
|
||||
wikiService interfaces.WikiPageService
|
||||
|
||||
// stageTracker records per-stage progress for the parsing pipeline.
|
||||
// Best-effort: a nil tracker (e.g. test harness) is safely handled
|
||||
// because every call site goes through the StageTracker interface
|
||||
// which has a no-op fallback. See knowledge_stage_tracker.go.
|
||||
stageTracker StageTracker
|
||||
// spanTracker records the per-attempt span tree for the parsing
|
||||
// pipeline. Best-effort: a nil tracker (test harness) is safely
|
||||
// handled because the public surface is the SpanTracker interface,
|
||||
// which has a no-op fallback. See knowledge_span_tracker.go.
|
||||
spanTracker SpanTracker
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -102,7 +102,7 @@ func NewKnowledgeService(
|
||||
wikiRepo interfaces.WikiPageRepository,
|
||||
wikiService interfaces.WikiPageService,
|
||||
taskPendingRepo interfaces.TaskPendingOpsRepository,
|
||||
stageTracker StageTracker,
|
||||
spanTracker SpanTracker,
|
||||
) (interfaces.KnowledgeService, error) {
|
||||
return &knowledgeService{
|
||||
config: config,
|
||||
@@ -127,18 +127,96 @@ func NewKnowledgeService(
|
||||
wikiRepo: wikiRepo,
|
||||
wikiService: wikiService,
|
||||
taskPendingRepo: taskPendingRepo,
|
||||
stageTracker: stageTracker,
|
||||
spanTracker: spanTracker,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// stage returns a usable StageTracker — falls back to a no-op when the
|
||||
// tracker returns a usable SpanTracker — falls back to a no-op when the
|
||||
// service was constructed without one (test harness, lite mode w/o repo).
|
||||
// All pipeline call sites go through this so they never need a nil check.
|
||||
func (s *knowledgeService) stage() StageTracker {
|
||||
if s.stageTracker == nil {
|
||||
return noopStageTracker{}
|
||||
func (s *knowledgeService) tracker() SpanTracker {
|
||||
if s.spanTracker == nil {
|
||||
return noopSpanTracker{}
|
||||
}
|
||||
return s.stageTracker
|
||||
return s.spanTracker
|
||||
}
|
||||
|
||||
// attemptCtxKey scopes the per-task attempt number to a single execution.
|
||||
// Set once at the start of ProcessDocument / ProcessManualUpdate /
|
||||
// KnowledgePostProcess so every nested tracker call within the same task
|
||||
// can locate the right attempt without threading it through signatures.
|
||||
type attemptCtxKey struct{}
|
||||
|
||||
// withAttempt returns a child ctx tagged with the given attempt number.
|
||||
// Pass through every call site that may invoke the tracker.
|
||||
func withAttempt(ctx context.Context, attempt int) context.Context {
|
||||
if attempt <= 0 {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, attemptCtxKey{}, attempt)
|
||||
}
|
||||
|
||||
// attemptFromCtx extracts the attempt number stored by withAttempt;
|
||||
// returns 0 when missing (legacy paths or tests). Tracker call sites
|
||||
// treat 0 as "skip recording" since we have no attempt to anchor under.
|
||||
func attemptFromCtx(ctx context.Context) int {
|
||||
if v, ok := ctx.Value(attemptCtxKey{}).(int); ok {
|
||||
return v
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// beginStage / endStage / failStage / skipStage are the by-name shims
|
||||
// the pipeline uses so call sites don't have to thread *Span values
|
||||
// through the existing function signatures. Each helper looks up the
|
||||
// stage from (kid, attempt-from-ctx, stageName) at write time — costs
|
||||
// one extra DB read per terminal transition (≤ a dozen per knowledge),
|
||||
// which is dwarfed by the work the stages themselves do.
|
||||
func (s *knowledgeService) beginStage(ctx context.Context, kid, name string, input types.JSONMap) {
|
||||
a := attemptFromCtx(ctx)
|
||||
if a <= 0 {
|
||||
return
|
||||
}
|
||||
s.tracker().BeginStage(ctx, kid, a, name, input)
|
||||
}
|
||||
|
||||
func (s *knowledgeService) endStage(ctx context.Context, kid, name string, output types.JSONMap) {
|
||||
a := attemptFromCtx(ctx)
|
||||
if a <= 0 {
|
||||
return
|
||||
}
|
||||
span := s.tracker().LookupStage(ctx, kid, a, name)
|
||||
if span == nil {
|
||||
return
|
||||
}
|
||||
s.tracker().EndSpan(ctx, span, output)
|
||||
}
|
||||
|
||||
func (s *knowledgeService) failStage(ctx context.Context, kid, name, code, msg string, err error) {
|
||||
a := attemptFromCtx(ctx)
|
||||
if a <= 0 {
|
||||
return
|
||||
}
|
||||
span := s.tracker().LookupStage(ctx, kid, a, name)
|
||||
if span == nil {
|
||||
return
|
||||
}
|
||||
s.tracker().FailSpan(ctx, span, code, msg, err)
|
||||
}
|
||||
|
||||
func (s *knowledgeService) skipStage(ctx context.Context, kid, name, reason string) {
|
||||
a := attemptFromCtx(ctx)
|
||||
if a <= 0 {
|
||||
return
|
||||
}
|
||||
span := s.tracker().LookupStage(ctx, kid, a, name)
|
||||
if span == nil {
|
||||
// No begin recorded — synthesize a span row for skipped state.
|
||||
// Use BeginStage with no input then SkipSpan to keep schema
|
||||
// invariants (started_at / kind set).
|
||||
span = s.tracker().BeginStage(ctx, kid, a, name, nil)
|
||||
}
|
||||
s.tracker().SkipSpan(ctx, span, reason)
|
||||
}
|
||||
|
||||
// getParserEngineOverridesFromContext returns parser engine overrides from tenant in context (e.g. MinerU endpoint, API key).
|
||||
|
||||
Reference in New Issue
Block a user