feat(knowledge): instrument postprocess subspans + polish timeline UI

Backend: summary, question, and graph-extract async tasks now record
real processing time as subspans hanging off the (closed) postprocess
stage, so the trace viewer no longer caps the postprocess row at the
~10 ms enqueue duration. Carries Attempt through SummaryGeneration /
QuestionGeneration / ExtractChunk payloads so cross-process workers
can resolve the right parent attempt.

Frontend: drawer now uses attach="body" so the secondary 820px detail
drawer escapes the 654px container of the main drawer; timeline
timestamps include date prefix (MM-DD, or YYYY-MM-DD across years);
"updated X ago" caption only shows during live polling.

Tests: 4 new cases covering postprocess subspan attaching under a
closed parent, missing-parent fallthrough, and Attempt JSON round-trip
on the three task payloads.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
wizardchen
2026-05-27 21:33:16 +08:00
committed by lyingbug
parent 5ffc755e76
commit bd029b6d19
11 changed files with 2415 additions and 537 deletions
+62 -7
View File
@@ -87,15 +87,21 @@ func NewChunkExtractTask(
tenantID uint64,
chunkID string,
modelID string,
knowledgeID string,
attempt int,
chunkIndex int,
) error {
if strings.ToLower(os.Getenv("NEO4J_ENABLE")) != "true" {
logger.Warn(ctx, "NEO4J is not enabled, skip chunk extract task")
return nil
}
taskPayload := types.ExtractChunkPayload{
TenantID: tenantID,
ChunkID: chunkID,
ModelID: modelID,
TenantID: tenantID,
ChunkID: chunkID,
ModelID: modelID,
KnowledgeID: knowledgeID,
Attempt: attempt,
ChunkIndex: chunkIndex,
}
langfuse.InjectTracing(ctx, &taskPayload)
payload, err := json.Marshal(taskPayload)
@@ -150,6 +156,10 @@ type ChunkExtractService struct {
knowledgeBaseRepo interfaces.KnowledgeBaseRepository
chunkRepo interfaces.ChunkRepository
graphEngine interfaces.RetrieveGraphRepository
// spanTracker records this graph-extract task's subspan under the
// parent attempt's postprocess stage so the trace viewer shows real
// per-chunk graph extraction time rather than the upstream's enqueue.
spanTracker SpanTracker
}
// NewChunkExtractService creates a new chunk extract service
@@ -159,20 +169,25 @@ func NewChunkExtractService(
knowledgeBaseRepo interfaces.KnowledgeBaseRepository,
chunkRepo interfaces.ChunkRepository,
graphEngine interfaces.RetrieveGraphRepository,
spanTracker SpanTracker,
) interfaces.TaskHandler {
// generator := chatpipeline.NewQAPromptGenerator(chatpipeline.NewFormater(), config.ExtractManager.ExtractGraph)
// ctx := context.Background()
// logger.Debugf(ctx, "chunk extract system prompt: %s", generator.System(ctx))
// logger.Debugf(ctx, "chunk extract user prompt: %s", generator.User(ctx, "demo"))
return &ChunkExtractService{
template: config.ExtractManager.ExtractGraph,
modelService: modelService,
knowledgeBaseRepo: knowledgeBaseRepo,
chunkRepo: chunkRepo,
graphEngine: graphEngine,
spanTracker: spanTracker,
}
}
func (s *ChunkExtractService) tracker() SpanTracker {
if s.spanTracker == nil {
return noopSpanTracker{}
}
return s.spanTracker
}
// Handle handles the chunk extraction task
func (s *ChunkExtractService) Handle(ctx context.Context, t *asynq.Task) error {
var p types.ExtractChunkPayload
@@ -184,24 +199,59 @@ func (s *ChunkExtractService) Handle(ctx context.Context, t *asynq.Task) error {
ctx = logger.WithField(ctx, "extract", p.ChunkID)
ctx = context.WithValue(ctx, types.TenantIDContextKey, p.TenantID)
// Open a postprocess subspan keyed by chunk ordinal so the trace
// shows real per-chunk graph extraction time. Skipped silently when
// upstream didn't pass the parent attempt (legacy in-flight tasks)
// or when the postprocess stage span isn't found.
var gSpan *Span
if p.KnowledgeID != "" && p.Attempt > 0 {
parent := s.tracker().LookupStage(ctx, p.KnowledgeID, p.Attempt, types.StagePostProcess)
if parent != nil {
gSpan = s.tracker().BeginSubSpan(ctx, parent,
fmt.Sprintf("postprocess.graph.chunk[%d]", p.ChunkIndex),
types.SpanKindSubSpan,
types.JSONMap{
"chunk_id": p.ChunkID,
"chunk_index": p.ChunkIndex,
"model_id": p.ModelID,
})
}
}
var handleErr error
graphOut := types.JSONMap{}
defer func() {
if gSpan == nil {
return
}
if handleErr != nil {
s.tracker().FailSpan(ctx, gSpan, "GRAPH_EXTRACT_FAILED", handleErr.Error(), handleErr)
} else {
s.tracker().EndSpan(ctx, gSpan, graphOut)
}
}()
chunk, err := s.chunkRepo.GetChunkByID(ctx, p.TenantID, p.ChunkID)
if err != nil {
logger.Errorf(ctx, "failed to get chunk: %v", err)
handleErr = err
return err
}
kb, err := s.knowledgeBaseRepo.GetKnowledgeBaseByID(ctx, chunk.KnowledgeBaseID)
if err != nil {
logger.Errorf(ctx, "failed to get knowledge base: %v", err)
handleErr = err
return err
}
if kb.ExtractConfig == nil {
logger.Warnf(ctx, "failed to get extract config")
graphOut["skipped"] = "no_extract_config"
return err
}
chatModel, err := s.modelService.GetChatModel(ctx, p.ModelID)
if err != nil {
logger.Errorf(ctx, "failed to get chat model: %v", err)
handleErr = err
return err
}
@@ -219,12 +269,14 @@ func (s *ChunkExtractService) Handle(ctx context.Context, t *asynq.Task) error {
extractor := chatpipeline.NewExtractor(chatModel, template)
graph, err := extractor.Extract(ctx, chunk.Content)
if err != nil {
handleErr = err
return err
}
chunk, err = s.chunkRepo.GetChunkByID(ctx, p.TenantID, p.ChunkID)
if err != nil {
logger.Warnf(ctx, "graph ignore chunk %s: %v", p.ChunkID, err)
graphOut["skipped"] = "chunk_disappeared"
return nil
}
@@ -236,8 +288,11 @@ func (s *ChunkExtractService) Handle(ctx context.Context, t *asynq.Task) error {
[]*types.GraphData{graph},
); err != nil {
logger.Errorf(ctx, "failed to add graph: %v", err)
handleErr = err
return err
}
graphOut["nodes_added"] = len(graph.Node)
graphOut["relations_added"] = len(graph.Relation)
return nil
}
+42
View File
@@ -219,6 +219,48 @@ func (s *knowledgeService) skipStage(ctx context.Context, kid, name, reason stri
s.tracker().SkipSpan(ctx, span, reason)
}
// beginPostprocessSubspan opens a subspan beneath the postprocess stage
// span for (kid, attempt). Async post-pipeline tasks (summary, question,
// graph, wiki) call this on entry so their actual processing time shows
// up in the trace tree under postprocess instead of the stage looking
// like an instant ~10ms enqueue.
//
// Returns nil when:
// - attempt <= 0 (legacy in-flight task without span tracking)
// - the postprocess stage span is missing (parse predates tracker, or
// the upstream BeginStage call failed)
//
// Callers must tolerate nil — pair every begin with a deferred
// endPostprocessSubspan / failPostprocessSubspan that no-ops on nil.
func (s *knowledgeService) beginPostprocessSubspan(
ctx context.Context, knowledgeID string, attempt int, name string, input types.JSONMap,
) *Span {
if attempt <= 0 || knowledgeID == "" || name == "" {
return nil
}
parent := s.tracker().LookupStage(ctx, knowledgeID, attempt, types.StagePostProcess)
if parent == nil {
return nil
}
return s.tracker().BeginSubSpan(ctx, parent, name, types.SpanKindSubSpan, input)
}
func (s *knowledgeService) endPostprocessSubspan(ctx context.Context, span *Span, output types.JSONMap) {
if span == nil {
return
}
s.tracker().EndSpan(ctx, span, output)
}
func (s *knowledgeService) failPostprocessSubspan(
ctx context.Context, span *Span, code, msg string, err error,
) {
if span == nil {
return
}
s.tracker().FailSpan(ctx, span, code, msg, err)
}
// getParserEngineOverridesFromContext returns parser engine overrides from tenant in context (e.g. MinerU endpoint, API key).
// Used when building document ReadRequest so UI-configured values take precedence over env.
func (s *knowledgeService) getParserEngineOverridesFromContext(ctx context.Context) map[string]string {
@@ -143,12 +143,12 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
enqueuedSummary := false
enqueuedQuestion := false
if len(textChunks) > 0 {
s.enqueueSummaryGenerationTask(ctx, payload)
s.enqueueSummaryGenerationTask(ctx, payload, attempt)
enqueuedSummary = true
// Question generation only makes sense for RAG indexing (improves chunk recall).
// Skip when only Wiki/Graph is enabled without vector/keyword search.
if kb.NeedsEmbeddingModel() {
enqueuedQuestion = s.enqueueQuestionGenerationIfEnabled(ctx, payload, kb)
enqueuedQuestion = s.enqueueQuestionGenerationIfEnabled(ctx, payload, kb, attempt)
}
}
@@ -156,8 +156,9 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
enqueuedGraph := false
if kb.IsGraphEnabled() {
logger.Infof(ctx, "[KnowledgePostProcess] Spawning Graph RAG extract tasks for %d text-like chunks", len(textChunks))
for _, chunk := range textChunks {
err := NewChunkExtractTask(ctx, s.taskEnqueuer, payload.TenantID, chunk.ID, kb.SummaryModelID)
for i, chunk := range textChunks {
err := NewChunkExtractTask(ctx, s.taskEnqueuer, payload.TenantID, chunk.ID, kb.SummaryModelID,
payload.KnowledgeID, attempt, i)
if err != nil {
logger.Errorf(ctx, "[KnowledgePostProcess] Failed to create chunk extract task for %s: %v", chunk.ID, err)
}
@@ -190,7 +191,7 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
return nil
}
func (s *KnowledgePostProcessService) enqueueSummaryGenerationTask(ctx context.Context, payload types.KnowledgePostProcessPayload) {
func (s *KnowledgePostProcessService) enqueueSummaryGenerationTask(ctx context.Context, payload types.KnowledgePostProcessPayload, attempt int) {
if s.taskEnqueuer == nil {
return
}
@@ -200,6 +201,7 @@ func (s *KnowledgePostProcessService) enqueueSummaryGenerationTask(ctx context.C
KnowledgeBaseID: payload.KnowledgeBaseID,
KnowledgeID: payload.KnowledgeID,
Language: payload.Language,
Attempt: attempt,
}
langfuse.InjectTracing(ctx, &taskPayload)
payloadBytes, err := json.Marshal(taskPayload)
@@ -216,7 +218,7 @@ func (s *KnowledgePostProcessService) enqueueSummaryGenerationTask(ctx context.C
}
}
func (s *KnowledgePostProcessService) enqueueQuestionGenerationIfEnabled(ctx context.Context, payload types.KnowledgePostProcessPayload, kb *types.KnowledgeBase) bool {
func (s *KnowledgePostProcessService) enqueueQuestionGenerationIfEnabled(ctx context.Context, payload types.KnowledgePostProcessPayload, kb *types.KnowledgeBase, attempt int) bool {
if s.taskEnqueuer == nil {
return false
}
@@ -239,6 +241,7 @@ func (s *KnowledgePostProcessService) enqueueQuestionGenerationIfEnabled(ctx con
KnowledgeID: payload.KnowledgeID,
QuestionCount: questionCount,
Language: payload.Language,
Attempt: attempt,
}
langfuse.InjectTracing(ctx, &taskPayload)
payloadBytes, err := json.Marshal(taskPayload)
@@ -887,15 +887,37 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
}
// Open a subspan under the parent attempt's postprocess stage so the
// trace surface shows the real summary-generation duration (LLM call
// + chunk write + index) instead of just the upstream's enqueue time.
// Closes via the deferred handler below — every return path lands in
// the defer, including the early returns ahead.
span := s.beginPostprocessSubspan(ctx, payload.KnowledgeID, payload.Attempt, "postprocess.summary",
types.JSONMap{"language": payload.Language})
var summaryErr error
summaryOut := types.JSONMap{}
defer func() {
if span == nil {
return
}
if summaryErr != nil {
s.failPostprocessSubspan(ctx, span, "SUMMARY_FAILED", summaryErr.Error(), summaryErr)
} else {
s.endPostprocessSubspan(ctx, span, summaryOut)
}
}()
// Get knowledge base
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
if err != nil {
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
summaryErr = err
return nil
}
if kb.SummaryModelID == "" {
logger.Warn(ctx, "Knowledge base summary model ID is empty, skipping summary generation")
summaryOut["skipped"] = "no_summary_model"
return nil
}
@@ -903,6 +925,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
if err != nil {
logger.Errorf(ctx, "Failed to get knowledge: %v", err)
summaryErr = err
return nil
}
@@ -927,6 +950,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
if err != nil {
logger.Errorf(ctx, "Failed to get chunks: %v", err)
markSummaryFailed()
summaryErr = err
return nil
}
@@ -937,6 +961,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
textChunks = append(textChunks, chunk)
}
}
summaryOut["text_chunks"] = len(textChunks)
if len(textChunks) == 0 {
logger.Infof(ctx, "No text chunks found for knowledge: %s", payload.KnowledgeID)
@@ -944,6 +969,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
knowledge.SummaryStatus = types.SummaryStatusCompleted
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
summaryOut["skipped"] = "no_text_chunks"
return nil
}
@@ -957,6 +983,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
if err != nil {
logger.Errorf(ctx, "Failed to get chat model: %v", err)
markSummaryFailed()
summaryErr = err
return fmt.Errorf("failed to get chat model: %w", err)
}
@@ -974,8 +1001,11 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
knowledge.UpdatedAt = time.Now()
if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil {
logger.Errorf(ctx, "Failed to mark summary as failed: %v", updateErr)
summaryErr = updateErr
return fmt.Errorf("failed to update knowledge: %w", updateErr)
}
summaryOut["fallback"] = "insufficient_content"
summaryErr = err
return nil
}
// For other errors (LLM API issues etc.), fall back to the first chunk.
@@ -987,6 +1017,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
summary = string(runes[:500])
}
}
summaryOut["fallback"] = "first_chunk"
}
}
@@ -994,8 +1025,10 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
knowledge.Description = summary
knowledge.SummaryStatus = types.SummaryStatusCompleted
knowledge.UpdatedAt = time.Now()
summaryOut["summary_chars"] = len([]rune(summary))
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
logger.Errorf(ctx, "Failed to update knowledge description: %v", err)
summaryErr = err
return fmt.Errorf("failed to update knowledge: %w", err)
}
@@ -1034,6 +1067,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
// Save summary chunk
if err := s.chunkService.CreateChunks(ctx, []*types.Chunk{summaryChunk}); err != nil {
logger.Errorf(ctx, "Failed to create summary chunk: %v", err)
summaryErr = err
return fmt.Errorf("failed to create summary chunk: %w", err)
}
@@ -1041,6 +1075,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
if err != nil {
logger.Errorf(ctx, "Failed to get tenant info: %v", err)
summaryErr = err
return fmt.Errorf("failed to get tenant info: %w", err)
}
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenantInfo)
@@ -1049,12 +1084,14 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
ctx, s.retrieveEngine, s.ownership, tenantInfo.ID, kb.VectorStoreID)
if err != nil {
logger.Errorf(ctx, "Failed to init retrieve engine: %v", err)
summaryErr = err
return fmt.Errorf("failed to init retrieve engine: %w", err)
}
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get embedding model: %v", err)
summaryErr = err
return fmt.Errorf("failed to get embedding model: %w", err)
}
@@ -1070,13 +1107,16 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
if err := retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfo); err != nil {
logger.Errorf(ctx, "Failed to index summary chunk: %v", err)
summaryErr = err
return fmt.Errorf("failed to index summary chunk: %w", err)
}
logger.Infof(ctx, "Successfully created and indexed summary chunk for knowledge: %s", payload.KnowledgeID)
summaryOut["summary_chunk_indexed"] = true
}
logger.Infof(ctx, "Successfully generated summary for knowledge: %s", payload.KnowledgeID)
summaryOut["status"] = "completed"
return nil
}
@@ -1101,6 +1141,12 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
indexEntriesPrepared := 0
indexBatchAttempted := false
indexBatchSucceeded := false
// Postprocess subspan for the trace viewer. Opened lazily after we
// unmarshal the payload (so we have payload.Attempt) and closed in
// the defer below alongside the stats log so the span output mirrors
// what we already log to stdout.
var qSpan *Span
var qErr error
defer func() {
logger.Infof(
ctx,
@@ -1125,6 +1171,39 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
indexBatchAttempted,
indexBatchSucceeded,
)
if qSpan != nil {
out := types.JSONMap{
"status": exitStatus,
"total_chunks": totalChunks,
"text_chunks": totalTextChunks,
"empty_content_chunks": emptyContentChunks,
"llm_attempts": llmCallAttempts,
"llm_success": llmCallSuccess,
"llm_empty": llmCallEmpty,
"llm_failed": llmCallFailed,
"questions_generated": generatedQuestionsTotal,
"chunk_update_failed": chunkUpdateFailed,
"metadata_set_failed": chunkMetadataSetFailed,
"index_entries_prepared": indexEntriesPrepared,
"index_batch_attempted": indexBatchAttempted,
"index_batch_succeeded": indexBatchSucceeded,
"retry": retryCount,
"max_retry": maxRetry,
}
// Treat any non-success exitStatus as a failed run; the
// existing stats-string already enumerates them. qErr stays
// optional for callers that want to surface a Go error.
if exitStatus != "success" || qErr != nil {
msg := exitStatus
var detailErr error = qErr
if qErr != nil {
msg = qErr.Error()
}
s.failPostprocessSubspan(ctx, qSpan, "QUESTION_FAILED", msg, detailErr)
} else {
s.endPostprocessSubspan(ctx, qSpan, out)
}
}
}()
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
@@ -1135,6 +1214,14 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
logger.Infof(ctx, "Processing question generation for knowledge: %s", payload.KnowledgeID)
// Open the postprocess.question subspan now that we have payload.Attempt.
// Closes via the defer above.
qSpan = s.beginPostprocessSubspan(ctx, payload.KnowledgeID, payload.Attempt, "postprocess.question",
types.JSONMap{
"question_count": payload.QuestionCount,
"language": payload.Language,
})
// Set tenant context
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
if payload.Language != "" {
@@ -1144,7 +1231,8 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
if strings.TrimSpace(s.config.Conversation.GenerateQuestionsPrompt) == "" {
exitStatus = "prompt_not_configured"
logger.Errorf(ctx, "GenerateQuestionsPrompt is empty: configure conversation.generate_questions_prompt_id")
return fmt.Errorf("generate questions prompt not configured")
qErr = fmt.Errorf("generate questions prompt not configured")
return qErr
}
// Get knowledge base
@@ -1152,6 +1240,7 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
if err != nil {
exitStatus = "kb_not_found"
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
qErr = err
return nil
}
@@ -1160,6 +1249,7 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
if err != nil {
exitStatus = "knowledge_not_found"
logger.Errorf(ctx, "Failed to get knowledge: %v", err)
qErr = err
return nil
}
@@ -2,6 +2,7 @@ package service
import (
"context"
"encoding/json"
"errors"
"testing"
@@ -271,3 +272,140 @@ func TestSpanTracker_FailSpan_CascadesDependentSubspans(t *testing.T) {
assert.Equal(t, types.SpanStatusCancelled, statusBy["embedding.batch[0]"],
"subspan under the cascaded stage must also be cancelled")
}
// TestPostprocessSubspan_AttachesUnderPostProcessStage covers the contract
// that the async post-pipeline tasks (summary, question, graph) rely on:
// after the parsing pipeline closes the postprocess stage span, an
// out-of-band worker can still LookupStage + BeginSubSpan to record its
// real processing time as a child of postprocess. Without this guarantee
// the trace viewer's postprocess row stays at the ~10ms enqueue duration
// even when summary generation takes 20 s.
func TestPostprocessSubspan_AttachesUnderPostProcessStage(t *testing.T) {
tracker, db := setupSpanTrackerTest(t)
ctx := context.Background()
repo := repository.NewKnowledgeSpanRepository(db)
// Set up the parent attempt with a closed postprocess stage — the
// async worker must still find it via LookupStage.
_, attempt, err := tracker.OpenAttempt(ctx, "kid", "lf-trace")
require.NoError(t, err)
post := tracker.BeginStage(ctx, "kid", attempt, types.StagePostProcess, types.JSONMap{
"chunks_total": 20,
})
require.NotNil(t, post)
tracker.EndSpan(ctx, post, types.JSONMap{"enqueued_summary": true})
// Simulate ProcessSummaryGeneration entering: lookup parent +
// BeginSubSpan (the same call shape as beginPostprocessSubspan).
parent := tracker.LookupStage(ctx, "kid", attempt, types.StagePostProcess)
require.NotNil(t, parent, "lookup must succeed even after EndSpan closed the parent")
assert.Equal(t, types.StagePostProcess, parent.Name)
assert.Equal(t, types.SpanKindStage, parent.Kind)
sumSpan := tracker.BeginSubSpan(ctx, parent, "postprocess.summary", types.SpanKindSubSpan,
types.JSONMap{"language": "zh-CN"})
require.NotNil(t, sumSpan)
assert.Equal(t, parent.SpanID, sumSpan.ParentSpanID,
"subspan must hang off the postprocess stage's span_id")
assert.Equal(t, types.SpanKindSubSpan, sumSpan.Kind)
tracker.EndSpan(ctx, sumSpan, types.JSONMap{
"text_chunks": 20,
"summary_chars": 142,
})
// Verify the row landed under the right parent with the right name.
rows, err := repo.ListByAttempt(ctx, "kid", attempt)
require.NoError(t, err)
var found *types.KnowledgeProcessingSpan
for i := range rows {
if rows[i].Name == "postprocess.summary" {
cp := rows[i]
found = &cp
break
}
}
require.NotNil(t, found, "summary subspan row must persist")
assert.Equal(t, parent.SpanID, found.ParentSpanID,
"persisted parent_span_id matches LookupStage result")
assert.Equal(t, types.SpanStatusDone, found.Status)
assert.NotNil(t, found.Output, "EndSpan must record the output map")
}
// TestPostprocessSubspan_MissingParentFallsThrough covers the legacy
// path: an in-flight async task may carry attempt=0 (queued before the
// span-tracking field was added) or hit a knowledge whose postprocess
// stage row is missing (parse predates tracker). LookupStage returning
// nil must NOT crash the handler — the caller is expected to skip span
// recording and continue normal processing.
func TestPostprocessSubspan_MissingParentFallsThrough(t *testing.T) {
tracker, _ := setupSpanTrackerTest(t)
ctx := context.Background()
// No OpenAttempt → no rows for kid. LookupStage must return nil.
parent := tracker.LookupStage(ctx, "kid-without-attempt", 7, types.StagePostProcess)
assert.Nil(t, parent, "missing parent attempt yields nil, not an error")
// Open an attempt but never begin postprocess. Lookup must still nil.
_, attempt, err := tracker.OpenAttempt(ctx, "kid-no-postprocess", "")
require.NoError(t, err)
parent = tracker.LookupStage(ctx, "kid-no-postprocess", attempt, types.StagePostProcess)
assert.Nil(t, parent, "missing postprocess stage row yields nil")
}
// TestChunkExtractPayload_AttemptRoundTrip verifies the new fields
// added to ExtractChunkPayload survive JSON marshal/unmarshal so a
// cross-process asynq worker can recover the parent attempt + chunk
// ordinal on the receiving side. Skipping this would let a typo in
// the JSON tag silently zero the attempt and disable span recording.
func TestChunkExtractPayload_AttemptRoundTrip(t *testing.T) {
in := types.ExtractChunkPayload{
TenantID: 42,
ChunkID: "chunk-x",
ModelID: "m1",
KnowledgeID: "kid-7",
Attempt: 3,
ChunkIndex: 9,
}
bytes, err := json.Marshal(in)
require.NoError(t, err)
var out types.ExtractChunkPayload
require.NoError(t, json.Unmarshal(bytes, &out))
assert.Equal(t, in.KnowledgeID, out.KnowledgeID)
assert.Equal(t, in.Attempt, out.Attempt)
assert.Equal(t, in.ChunkIndex, out.ChunkIndex)
}
// TestSummaryQuestionPayload_AttemptRoundTrip mirrors the above for the
// summary + question payloads to keep the contract documented.
func TestSummaryQuestionPayload_AttemptRoundTrip(t *testing.T) {
sumIn := types.SummaryGenerationPayload{
TenantID: 42,
KnowledgeBaseID: "kb-1",
KnowledgeID: "kid-7",
Language: "zh-CN",
Attempt: 5,
}
sumBytes, err := json.Marshal(sumIn)
require.NoError(t, err)
var sumOut types.SummaryGenerationPayload
require.NoError(t, json.Unmarshal(sumBytes, &sumOut))
assert.Equal(t, 5, sumOut.Attempt)
qIn := types.QuestionGenerationPayload{
TenantID: 42,
KnowledgeBaseID: "kb-1",
KnowledgeID: "kid-7",
QuestionCount: 3,
Language: "zh-CN",
Attempt: 5,
}
qBytes, err := json.Marshal(qIn)
require.NoError(t, err)
var qOut types.QuestionGenerationPayload
require.NoError(t, json.Unmarshal(qBytes, &qOut))
assert.Equal(t, 5, qOut.Attempt)
}