fix(knowledge): close root span on terminal state, enrich stage metadata

The root span created by OpenAttempt was never closed: PostProcess only
ended the postprocess stage, so the root row stayed at status=running
forever even after parse_status flipped to completed/failed. The
timeline rendered "进行中" indefinitely on the root, defeating the
whole "is the document done" question the timeline is meant to answer.

- SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg):
  closes the root row idempotently. Re-closing a terminal root no-ops
  so success / cascade-fail / dead-letter paths can fire without
  coordination.
- PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess)
  on the success path. Async downstream work (summary/question/wiki/
  graph) still records its own spans; their completion extends the
  trace's wall-clock end-time but doesn't reopen the root.
- FailSpan auto-closes the root when a MAIN pipeline stage fails
  (docreader / chunking / embedding / multimodal / postprocess).
  Cascade-cancelled siblings stay closed-with-the-cascade as before.
- Dead-letter callback (router/task.go) accepts the SpanTracker via
  DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a
  document-related task exhausts retries. The probe payload now
  extracts the Attempt field that Document/Manual/PostProcess
  payloads already thread through.

Stage spans were also being recorded with nil input/output, leaving
the new detail panel with timestamps only. Each Begin/End site now
emits useful work metrics:
- DocReader input: file_name, file_type, is_url, url
              output: text_length, images_found, is_audio, pages
- Chunking input: chunks_planned
            output: chunks_written, total_text_chars
- Embedding input: chunks_to_embed, model_id, dim
             output: vectors_written, storage_bytes
- Multimodal input: image_count, enable_ocr, enable_caption
- PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph

i18n: add knowledgeStages.root ("Knowledge processing") so the UI
can render a localized name instead of the raw span identifier.
This commit is contained in:
wizardchen
2026-05-27 16:54:09 +08:00
committed by lyingbug
parent c5722234ef
commit 4db6e69b4e
8 changed files with 218 additions and 20 deletions
+16 -2
View File
@@ -34,6 +34,7 @@ type AsynqTaskParams struct {
KnowledgePostProcess interfaces.TaskHandler `name:"knowledgePostProcess"`
WikiIngest interfaces.TaskHandler `name:"wikiIngest"`
DeadLetterRepo interfaces.TaskDeadLetterRepository
SpanTracker service.SpanTracker
}
// defaultRedisOpTimeout is the previous hard-coded read timeout. The 100ms
@@ -165,7 +166,7 @@ func RunAsynqServer(params AsynqTaskParams) *asynq.ServeMux {
// a permanently-failing task left its parent knowledge stranded in
// "processing" until housekeeping cron caught it minutes later — the
// UI signal users actually see.
knowledgeFailer := newDeadLetterKnowledgeFailer(params.KnowledgeService)
knowledgeFailer := newDeadLetterKnowledgeFailer(params.KnowledgeService, params.SpanTracker)
mux.Use(asynqdl.MiddlewareWithCallback(params.DeadLetterRepo, knowledgeFailer))
// Install Langfuse middleware BEFORE handler registration so every task
@@ -236,6 +237,12 @@ func RunAsynqServer(params AsynqTaskParams) *asynq.ServeMux {
// depend on the full payload schema and survive future field churn.
type deadLetterKnowledgePayload struct {
KnowledgeID string `json:"knowledge_id,omitempty"`
// Attempt threads through DocumentProcess / ManualProcess /
// KnowledgePostProcess payloads (added when span tracking shipped)
// — extracted here so the dead-letter callback can also close the
// matching root span as failed. Older in-flight payloads without
// this field decode as 0 and the tracker call no-ops.
Attempt int `json:"attempt,omitempty"`
}
// taskTypesAffectingKnowledgeStatus enumerates the asynq task types whose
@@ -269,7 +276,7 @@ var taskTypesAffectingKnowledgeStatus = map[string]struct{}{
// errors are logged and swallowed. The dead-letter record is the source of
// truth — this is purely a UX shortcut so users don't wait for the
// housekeeping cron's next sweep.
func newDeadLetterKnowledgeFailer(ks interfaces.KnowledgeService) asynqdl.OnDeadLetter {
func newDeadLetterKnowledgeFailer(ks interfaces.KnowledgeService, tracker service.SpanTracker) asynqdl.OnDeadLetter {
if ks == nil {
return nil
}
@@ -303,6 +310,13 @@ func newDeadLetterKnowledgeFailer(ks interfaces.KnowledgeService) asynqdl.OnDead
logger.Warnf(ctx, "dead-letter callback: failed to mark knowledge %s as failed: %v", probe.KnowledgeID, err)
return
}
// Close the matching root span so the timeline stops showing
// "进行中" after dead-letter exhaustion. Best-effort: nil
// tracker / missing attempt / missing root all no-op cleanly.
if tracker != nil && probe.Attempt > 0 {
tracker.FinalizeAttempt(ctx, probe.KnowledgeID, probe.Attempt,
types.SpanStatusFailed, nil, "TASK_TIMEOUT", errMsg)
}
logger.Infof(ctx, "dead-letter callback: marked knowledge %s as failed (task=%s)", probe.KnowledgeID, t.Type())
}
}