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:
wizardchen
2026-05-27 14:05:47 +08:00
committed by lyingbug
parent 04f56f9cda
commit c9941a6688
17 changed files with 1369 additions and 438 deletions
+50
View File
@@ -0,0 +1,50 @@
package types
import (
"database/sql/driver"
"encoding/json"
"errors"
)
// JSONMap is a map[string]any that round-trips through Postgres JSONB
// columns via GORM. The standard library's database/sql doesn't know how
// to scan JSONB into a typed map, so we hand-roll Value() / Scan().
//
// Lives here (not in /utils) because the only callers are types whose
// schemas already declare JSONB columns — keeping the helper next to its
// users avoids a circular import in any package that already pulls in
// /types.
type JSONMap map[string]any
// Value implements driver.Valuer. Returns nil when the map is nil so
// JSONB columns store SQL NULL instead of "null".
func (m JSONMap) Value() (driver.Value, error) {
if m == nil {
return nil, nil
}
return json.Marshal(m)
}
// Scan implements sql.Scanner. Accepts both []byte (real JSONB) and
// string (some drivers under sqlmock); anything else is a programming
// error.
func (m *JSONMap) Scan(src any) error {
if src == nil {
*m = nil
return nil
}
var raw []byte
switch v := src.(type) {
case []byte:
raw = v
case string:
raw = []byte(v)
default:
return errors.New("JSONMap.Scan: unsupported source type")
}
if len(raw) == 0 {
*m = nil
return nil
}
return json.Unmarshal(raw, m)
}
+117
View File
@@ -0,0 +1,117 @@
package types
import "time"
// Span kinds — kept narrow because every kind has dedicated rendering on
// the frontend timeline:
//
// - SpanKindRoot — the per-(knowledge, attempt) trace root. Always
// the parent_span_id ancestor of every other span
// in that attempt. UI uses it for total elapsed.
// - SpanKindStage — one of the 5 canonical stages (DocReader, etc.).
// UI renders these as the timeline segments.
// - SpanKindSubSpan — anything inside a stage (e.g. multimodal.image[i]).
// UI shows them as collapsible children.
// - SpanKindGeneration — a SubSpan that wraps an LLM/VLM call. Same UI
// treatment as SubSpan but tagged so we can stitch
// to the matching Langfuse generation.
const (
SpanKindRoot = "root"
SpanKindStage = "stage"
SpanKindSubSpan = "subspan"
SpanKindGeneration = "generation"
)
// Span statuses. We deliberately distinguish "failed" (this span itself
// errored) from "cancelled" (an upstream span failed and we abandoned this
// one without running it) so the UI can render the cause differently —
// "you broke X, so we never ran Y" vs. "Y itself broke".
const (
SpanStatusPending = "pending"
SpanStatusRunning = "running"
SpanStatusDone = "done"
SpanStatusFailed = "failed"
SpanStatusSkipped = "skipped" // intentionally not run (e.g. multimodal on a text-only doc)
SpanStatusCancelled = "cancelled" // not run because an upstream span failed
)
// Stage names — the closed set the UI builds its 5-segment timeline from.
// Adding a stage requires a coordinated frontend release. SubSpan names
// are free-form (e.g. "multimodal.image[0]") and don't go through this
// list.
const (
StageDocReader = "docreader"
StageChunking = "chunking"
StageEmbedding = "embedding"
StageMultimodal = "multimodal"
StagePostProcess = "postprocess"
)
// AllStages is the canonical, ordered stage list. Used by the API layer
// to synthesize "pending" placeholders so the timeline always renders five
// segments even before parsing starts.
var AllStages = []string{
StageDocReader,
StageChunking,
StageEmbedding,
StageMultimodal,
StagePostProcess,
}
// StageDependencies declares the DAG between stages. Used by the tracker
// to cascade-cancel dependents when a stage fails — a Chunking failure
// silently turns Embedding/Multimodal/PostProcess into "cancelled" so the
// timeline shows a clear blast radius instead of three pending spinners.
//
// Important: Multimodal does NOT depend on Embedding. They share Chunking
// as their upstream and are otherwise independent (Multimodal kicks off
// regardless of vector indexing config). PostProcess joins both before
// running its handlers.
var StageDependencies = map[string][]string{
StageDocReader: nil,
StageChunking: {StageDocReader},
StageEmbedding: {StageChunking},
StageMultimodal: {StageChunking},
StagePostProcess: {StageEmbedding, StageMultimodal},
}
// KnowledgeProcessingSpan is one row in knowledge_processing_spans.
//
// Field tags pull double duty: GORM (storage) and JSON (API). ErrorDetail
// is excluded by default — handlers must opt in for admin views, matching
// how the dead-letter middleware already protects raw stack traces.
type KnowledgeProcessingSpan struct {
ID int64 `gorm:"primaryKey;column:id" json:"-"`
KnowledgeID string `gorm:"column:knowledge_id" json:"knowledge_id"`
Attempt int `gorm:"column:attempt" json:"attempt"`
SpanID string `gorm:"column:span_id;size:64" json:"span_id"`
ParentSpanID string `gorm:"column:parent_span_id;size:64" json:"parent_span_id,omitempty"`
Name string `gorm:"column:name;size:64" json:"name"`
Kind string `gorm:"column:kind;size:16" json:"kind"`
Status string `gorm:"column:status;size:16" json:"status"`
Input JSONMap `gorm:"column:input;type:jsonb" json:"input,omitempty"`
Output JSONMap `gorm:"column:output;type:jsonb" json:"output,omitempty"`
Metadata JSONMap `gorm:"column:metadata;type:jsonb" json:"metadata,omitempty"`
ErrorCode string `gorm:"column:error_code;size:64" json:"error_code,omitempty"`
ErrorMessage string `gorm:"column:error_message;type:text" json:"error_message,omitempty"`
ErrorDetail string `gorm:"column:error_detail;type:text" json:"-"`
StartedAt *time.Time `gorm:"column:started_at" json:"started_at,omitempty"`
FinishedAt *time.Time `gorm:"column:finished_at" json:"finished_at,omitempty"`
DurationMs int64 `gorm:"column:duration_ms" json:"duration_ms,omitempty"`
CreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`
}
// TableName pins the table because GORM's default pluralization
// ("knowledge_processing_spans") happens to match — explicit beats
// implicit.
func (KnowledgeProcessingSpan) TableName() string {
return "knowledge_processing_spans"
}
// SpanTreeNode is the API-only tree projection. The repo returns flat
// rows; the handler/tracker assembles SpanTreeNode for the response.
type SpanTreeNode struct {
KnowledgeProcessingSpan
Children []*SpanTreeNode `json:"children,omitempty"`
}
-64
View File
@@ -1,64 +0,0 @@
package types
import "time"
// ProcessingStage names — kept as a closed set on the Go side so the
// frontend timeline can rely on exactly five segments. Adding a new stage
// requires a coordinated frontend release; rename in this file is breaking.
const (
ProcessingStageDocReader = "docreader"
ProcessingStageChunking = "chunking"
ProcessingStageEmbedding = "embedding"
ProcessingStageMultimodal = "multimodal"
ProcessingStagePostProcess = "postprocess"
)
// AllProcessingStages is the canonical, ordered list. Used by the API
// to fill in pending entries when no row exists yet for a stage so the
// timeline always renders five segments even before parsing starts.
var AllProcessingStages = []string{
ProcessingStageDocReader,
ProcessingStageChunking,
ProcessingStageEmbedding,
ProcessingStageMultimodal,
ProcessingStagePostProcess,
}
// ProcessingStageStatus values. Distinct from Knowledge.parse_status —
// each stage row tracks its own state independently of the parent.
const (
ProcessingStagePending = "pending" // not started yet
ProcessingStageRunning = "running" // currently executing
ProcessingStageDone = "done"
ProcessingStageFailed = "failed"
ProcessingStageSkipped = "skipped" // e.g. multimodal skipped for image-free docs
)
// KnowledgeProcessingStage is one row in knowledge_processing_stages.
//
// We intentionally keep it as a flat struct with both Go and JSON tags so
// the same type round-trips through GORM (DB layer) and the API response.
// Sensitive ErrorDetail (full stack) is excluded from the default JSON
// output via "-" — handlers must opt in explicitly for admin views.
type KnowledgeProcessingStage struct {
ID int64 `gorm:"primaryKey;column:id" json:"-"`
KnowledgeID string `gorm:"column:knowledge_id;index" json:"knowledge_id"`
Stage string `gorm:"column:stage;size:32" json:"stage"`
Status string `gorm:"column:status;size:16" json:"status"`
StartedAt *time.Time `gorm:"column:started_at" json:"started_at,omitempty"`
FinishedAt *time.Time `gorm:"column:finished_at" json:"finished_at,omitempty"`
DurationMs int64 `gorm:"column:duration_ms" json:"duration_ms,omitempty"`
ErrorCode string `gorm:"column:error_code;size:64" json:"error_code,omitempty"`
ErrorMessage string `gorm:"column:error_message;type:text" json:"error_message,omitempty"`
ErrorDetail string `gorm:"column:error_detail;type:text" json:"-"`
Attempt int `gorm:"column:attempt" json:"attempt"`
CreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`
}
// TableName pins the GORM table since the natural pluralization
// ("knowledge_processing_stages") happens to match what the migration
// creates — but explicit beats implicit here.
func (KnowledgeProcessingStage) TableName() string {
return "knowledge_processing_stages"
}
+16
View File
@@ -44,6 +44,13 @@ type DocumentProcessPayload struct {
EnableQuestionGeneration bool `json:"enable_question_generation"` // 是否启用问题生成
QuestionCount int `json:"question_count,omitempty"` // 每个chunk生成的问题数量
Language string `json:"language,omitempty"` // Request locale for {{language}} in prompt templates
// Attempt is the per-knowledge attempt number this task belongs to.
// Set on enqueue (initial parse → attempt 1; reparse → max+1) so
// every span recorded by this task lands on the right attempt
// branch. Asynq retries within an attempt keep the same value so
// retried spans overwrite the previous attempt's row rather than
// fan out into a new attempt for every retry.
Attempt int `json:"attempt,omitempty"`
}
// FAQImportPayload represents the FAQ import task payload (including dry run mode)
@@ -176,6 +183,14 @@ type ImageMultimodalPayload struct {
EnableCaption bool `json:"enable_caption"`
Language string `json:"language,omitempty"` // Request locale for {{language}} in prompt templates
ImageSourceType string `json:"image_source_type,omitempty"` // Source type of the image (e.g., "scanned_pdf")
// Attempt links this image task back to the parent ProcessDocument
// attempt so the worker can record its image[i] subspan under the
// same attempt's multimodal stage span.
Attempt int `json:"attempt,omitempty"`
// ImageIndex is the 0-based ordinal of this image inside the
// parent's image set. Used as the subspan name suffix
// ("multimodal.image[3]") so the timeline preserves order.
ImageIndex int `json:"image_index,omitempty"`
}
// KnowledgePostProcessPayload represents the knowledge post process task payload.
@@ -185,6 +200,7 @@ type KnowledgePostProcessPayload struct {
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Language string `json:"language,omitempty"` // Request locale for {{language}} in prompt templates
Attempt int `json:"attempt,omitempty"`
}
// KBCloneTaskStatus represents the status of a knowledge base clone task