fix(knowledge): infer synthesized stage status from parse_status

Pre-tracker historical knowledge has zero rows in
knowledge_processing_spans but parse_status correctly reads
"completed" or "failed". The /spans handler was synthesizing five
"pending" placeholders unconditionally, so legacy completed documents
rendered as if they were stuck waiting in the queue forever.

buildSpanTree now takes parse_status and chooses the placeholder
status accordingly:
- ParseStatusCompleted -> done
- ParseStatusFailed    -> failed
- everything else      -> pending (existing behaviour)

Real rows always take precedence; this only changes what we put in
the gaps. So healthy in-flight parses (parse_status=processing,
some real rows, some still pending) keep showing pending placeholders
exactly as before — the synthesized "completed" inference only fires
when the parse already hit terminal state.

Adds TestBuildSpanTree_LegacyCompletedRendersAsDone covering both
the completed-legacy and failed-legacy branches.
This commit is contained in:
wizardchen
2026-05-27 17:35:58 +08:00
committed by lyingbug
parent 01d00c2a36
commit 5ffc755e76
2 changed files with 63 additions and 10 deletions
+36 -7
View File
@@ -617,8 +617,12 @@ func (h *KnowledgeHandler) GetKnowledgeSpans(c *gin.Context) {
// Build tree: index by SpanID, then attach to parents. Stages
// missing from the DB are synthesized as "pending" placeholders
// under a synthetic (or real, if present) root so the timeline
// always renders five segments.
tree, currentStageName, lastErr := buildSpanTree(knowledge.ID, currentAttempt, rows)
// always renders five segments. parse_status threads through so
// pre-tracker historical knowledge (no rows but parse_status is
// already terminal) renders as done/failed instead of pending —
// otherwise legacy completed documents would forever look like
// they're still waiting in the queue.
tree, currentStageName, lastErr := buildSpanTree(knowledge.ID, currentAttempt, rows, knowledge.ParseStatus)
resp := gin.H{
"knowledge_id": knowledge.ID,
@@ -647,7 +651,15 @@ func (h *KnowledgeHandler) GetKnowledgeSpans(c *gin.Context) {
// the five timeline segments. Returns the root, the current_stage name
// (the running stage if any), and the most recent failed span if one
// exists.
func buildSpanTree(knowledgeID string, attempt int, rows []types.KnowledgeProcessingSpan) (
//
// parseStatus is the knowledge.parse_status string. When the spans table
// has zero rows for this attempt (legacy data parsed before tracking, or
// a fresh knowledge before the pipeline starts), the placeholder status
// is inferred from parseStatus: completed → done, failed → failed,
// otherwise pending. Without this, every historical knowledge would
// render as "all 5 stages pending" forever despite having actually
// completed parsing.
func buildSpanTree(knowledgeID string, attempt int, rows []types.KnowledgeProcessingSpan, parseStatus string) (
root *types.SpanTreeNode, currentStage string, lastFailure *types.KnowledgeProcessingSpan,
) {
now := time.Now()
@@ -675,6 +687,20 @@ func buildSpanTree(knowledgeID string, attempt int, rows []types.KnowledgeProces
}
}
// Pick the synthesized stage status from parse_status. Without this,
// historical knowledge that completed before span tracking was wired
// would render as "5 pending stages" forever — the rows simply
// weren't recorded, but parse_status correctly reads "completed".
// The synthesized stages don't carry duration/timing data; they
// just communicate the inferred terminal state.
syntheticStatus := types.SpanStatusPending
switch parseStatus {
case types.ParseStatusCompleted:
syntheticStatus = types.SpanStatusDone
case types.ParseStatusFailed:
syntheticStatus = types.SpanStatusFailed
}
// Synthesize root if no rows came back so the API contract stays
// stable (frontend always expects a `trace` object).
if rootRow == nil {
@@ -684,7 +710,7 @@ func buildSpanTree(knowledgeID string, attempt int, rows []types.KnowledgeProces
SpanID: "",
Name: "knowledge_processing",
Kind: types.SpanKindRoot,
Status: types.SpanStatusPending,
Status: syntheticStatus,
CreatedAt: now,
UpdatedAt: now,
}}
@@ -692,8 +718,11 @@ func buildSpanTree(knowledgeID string, attempt int, rows []types.KnowledgeProces
root = nodes[rootRow.SpanID]
}
// Synthesize missing stage rows as "pending" children of root so
// the timeline always shows 5 segments.
// Synthesize missing stage rows as children of root so the timeline
// always shows 5 segments. Status mirrors the synthesized root —
// pending while the pipeline is still running, done/failed for
// historical knowledge whose terminal state we know but whose
// per-stage timing was never recorded.
for _, name := range types.AllStages {
if _, ok := stageRowByName[name]; ok {
continue
@@ -703,7 +732,7 @@ func buildSpanTree(knowledgeID string, attempt int, rows []types.KnowledgeProces
Attempt: attempt,
Name: name,
Kind: types.SpanKindStage,
Status: types.SpanStatusPending,
Status: syntheticStatus,
CreatedAt: now,
UpdatedAt: now,
}
+27 -3
View File
@@ -21,7 +21,7 @@ func TestBuildSpanTree_AssemblesParentChild(t *testing.T) {
{KnowledgeID: "kid", Attempt: 1, SpanID: "img0", ParentSpanID: "mm", Name: "multimodal.image[0]", Kind: types.SpanKindGeneration, Status: types.SpanStatusRunning, StartedAt: &now},
}
tree, currentStage, lastFail := buildSpanTree("kid", 1, rows)
tree, currentStage, lastFail := buildSpanTree("kid", 1, rows, types.ParseStatusProcessing)
require := assert.New(t)
require.NotNil(tree)
require.Equal("root", tree.SpanID)
@@ -64,7 +64,7 @@ func TestBuildSpanTree_AssemblesParentChild(t *testing.T) {
// always gets a `trace` with five pending stage children, never a
// nil/empty response.
func TestBuildSpanTree_NoRows_SynthesizesPlaceholderRoot(t *testing.T) {
tree, currentStage, lastFail := buildSpanTree("kid-empty", 0, nil)
tree, currentStage, lastFail := buildSpanTree("kid-empty", 0, nil, "")
a := assert.New(t)
a.NotNil(tree)
a.Equal(types.SpanKindRoot, tree.Kind)
@@ -80,6 +80,30 @@ func TestBuildSpanTree_NoRows_SynthesizesPlaceholderRoot(t *testing.T) {
}
}
// TestBuildSpanTree_LegacyCompletedRendersAsDone records the regression
// for historical knowledge parsed before span tracking was wired: rows
// is empty but parse_status is "completed", so the synthesized timeline
// must reflect the actual terminal state instead of looking forever
// "pending". Same contract for failed parses — synthesizes "failed".
func TestBuildSpanTree_LegacyCompletedRendersAsDone(t *testing.T) {
a := assert.New(t)
completedTree, _, _ := buildSpanTree("kid-legacy", 0, nil, types.ParseStatusCompleted)
a.Equal(types.SpanStatusDone, completedTree.Status,
"legacy completed knowledge with no rows must render the synthesized root as done")
a.Len(completedTree.Children, len(types.AllStages))
for _, child := range completedTree.Children {
a.Equal(types.SpanStatusDone, child.Status,
"legacy completed knowledge: every synthesized stage placeholder must be done, not pending")
}
failedTree, _, _ := buildSpanTree("kid-legacy-fail", 0, nil, types.ParseStatusFailed)
a.Equal(types.SpanStatusFailed, failedTree.Status)
for _, child := range failedTree.Children {
a.Equal(types.SpanStatusFailed, child.Status)
}
}
// TestBuildSpanTree_LastFailureSurfaces records that a failed stage is
// reported as last_error so the UI can highlight the responsible step
// even if a later stage was cancelled by cascade.
@@ -91,7 +115,7 @@ func TestBuildSpanTree_LastFailureSurfaces(t *testing.T) {
{KnowledgeID: "kid", Attempt: 1, SpanID: "doc", ParentSpanID: "root", Name: types.StageDocReader, Kind: types.SpanKindStage, Status: types.SpanStatusFailed, ErrorCode: "DOCREADER_TIMEOUT", ErrorMessage: "slow", StartedAt: &now, FinishedAt: &finished},
{KnowledgeID: "kid", Attempt: 1, SpanID: "chunk", ParentSpanID: "root", Name: types.StageChunking, Kind: types.SpanKindStage, Status: types.SpanStatusCancelled, ErrorCode: "UPSTREAM_FAILED"},
}
_, _, lastFail := buildSpanTree("kid", 1, rows)
_, _, lastFail := buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
a := assert.New(t)
a.NotNil(lastFail)
a.Equal(types.StageDocReader, lastFail.Name,