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:
@@ -70,6 +70,10 @@ type ImageMultimodalService struct {
|
||||
// tenant's StorageEngineConfig.MinIO is empty). Mirrors the write-side
|
||||
// fallback in knowledgeService.resolveFileService.
|
||||
fileSvc interfaces.FileService
|
||||
|
||||
// spanTracker records this image's subspan under the parent attempt's
|
||||
// multimodal stage. nil-safe — falls back to no-op via tracker().
|
||||
spanTracker SpanTracker
|
||||
}
|
||||
|
||||
func NewImageMultimodalService(
|
||||
@@ -84,6 +88,7 @@ func NewImageMultimodalService(
|
||||
taskEnqueuer interfaces.TaskEnqueuer,
|
||||
redisClient *redis.Client,
|
||||
fileSvc interfaces.FileService,
|
||||
spanTracker SpanTracker,
|
||||
) interfaces.TaskHandler {
|
||||
return &ImageMultimodalService{
|
||||
chunkService: chunkService,
|
||||
@@ -97,9 +102,19 @@ func NewImageMultimodalService(
|
||||
taskEnqueuer: taskEnqueuer,
|
||||
redisClient: redisClient,
|
||||
fileSvc: fileSvc,
|
||||
spanTracker: spanTracker,
|
||||
}
|
||||
}
|
||||
|
||||
// tracker returns a usable SpanTracker — falls back to a no-op when the
|
||||
// service was constructed without one.
|
||||
func (s *ImageMultimodalService) tracker() SpanTracker {
|
||||
if s.spanTracker == nil {
|
||||
return noopSpanTracker{}
|
||||
}
|
||||
return s.spanTracker
|
||||
}
|
||||
|
||||
// Handle implements asynq handler for TypeImageMultimodal.
|
||||
func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) error {
|
||||
var payload types.ImageMultimodalPayload
|
||||
@@ -115,6 +130,26 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
|
||||
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
|
||||
}
|
||||
|
||||
// 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
|
||||
// tracker is a no-op so we silently fall back to the existing
|
||||
// counter-based finalize semantics.
|
||||
tracker := s.tracker()
|
||||
var imgSpan *Span
|
||||
if payload.Attempt > 0 {
|
||||
parent := tracker.LookupStage(ctx, payload.KnowledgeID, payload.Attempt, types.StageMultimodal)
|
||||
if parent != nil {
|
||||
name := fmt.Sprintf("multimodal.image[%d]", payload.ImageIndex)
|
||||
imgSpan = tracker.BeginSubSpan(ctx, parent, name, types.SpanKindGeneration, types.JSONMap{
|
||||
"image_url": payload.ImageURL,
|
||||
"image_source_type": payload.ImageSourceType,
|
||||
"enable_ocr": payload.EnableOCR,
|
||||
"enable_caption": payload.EnableCaption,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// finalize-once semantics: on success we always decrement the parent's
|
||||
// pending counter. On failure we only decrement when this is the last
|
||||
// asynq retry, so a permanently-failing single image cannot leave the
|
||||
@@ -123,6 +158,22 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
|
||||
// so we don't double-count and prematurely trigger post-process.
|
||||
var handleErr error
|
||||
defer func() {
|
||||
// Finalize the image subspan with the actual outcome — not the
|
||||
// finalize-counter outcome. The counter logic counts a "tried"
|
||||
// image regardless of inner success; the span surface tells the
|
||||
// UI whether THIS specific image worked.
|
||||
if imgSpan != nil {
|
||||
if handleErr == nil {
|
||||
tracker.EndSpan(ctx, imgSpan, types.JSONMap{
|
||||
"chunk_id": payload.ChunkID,
|
||||
})
|
||||
} else if isFinalAsynqAttempt(ctx) {
|
||||
tracker.FailSpan(ctx, imgSpan,
|
||||
"MULTIMODAL_VLM_FAILED",
|
||||
handleErr.Error(),
|
||||
handleErr)
|
||||
}
|
||||
}
|
||||
if handleErr == nil || isFinalAsynqAttempt(ctx) {
|
||||
s.checkAndFinalizeAllImages(ctx, payload)
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user