feat(observability): extend Langfuse tracing across asynq pipeline

Previously the Langfuse integration only traced in-process HTTP requests
(chat / search / eval), so file uploads and every downstream asynq task
(document parse, chunk embedding, OCR/VLM, summary / question gen, wiki
ingest, datasource sync, etc.) produced either disconnected shallow
traces or no observation at all.

This change threads one trace end-to-end:

- tracer: add SPAN observation type and StartSpan; add ResumeTrace so a
  worker can attach to an upstream trace without emitting a duplicate
  trace-create; StartGeneration now auto-picks parentObservationId from
  ctx so nested trace -> span -> generation trees render correctly.
- types.TracingContext + LangfuseTracingCarrier: embed on all 17 asynq
  payloads so trace_id / parent_obs_id / user_id / session_id serialise
  into every job.
- langfuse.InjectTracing: injected at 28 enqueue sites before json.Marshal
  so the HTTP-layer trace survives the Redis hop.
- langfuse.AsynqMiddleware: mux.Use hook that peeks the payload, either
  resumes the upstream trace or opens a standalone asynq.<type> trace
  for scheduled jobs, and wraps the handler in a SPAN with task metadata
  (id / queue / retry / payload_bytes) plus ERROR level on failure.
- GinMiddleware.shouldTrace: whitelist ingestion / knowledge-mutation /
  FAQ / wiki / datasource endpoints so the root trace actually starts.
- Tests: tracer_test.go covers span nesting, error status, and
  ResumeTrace no-trace-create guarantee; asynq_test.go covers
  InjectTracing round-trip, middleware resume path, and standalone
  trace fallback.
- Docs: docs/Langfuse\u96c6\u6210.md now lists the covered task types
  and documents the cross-process propagation model.

No behavioural change when Langfuse is disabled (all new code paths are
no-ops and carriers serialise to empty strings with omitempty).
This commit is contained in:
wizardchen
2026-04-24 12:23:30 +08:00
committed by lyingbug
parent 59fbf77524
commit beca2b89a3
23 changed files with 1077 additions and 40 deletions
+2
View File
@@ -314,6 +314,8 @@ type SyncResult struct {
// DataSourceSyncPayload represents the asynq task payload for data source sync
type DataSourceSyncPayload struct {
TracingContext
// Data source ID to sync
DataSourceID string `json:"data_source_id"`
+13
View File
@@ -21,6 +21,7 @@ const (
// ExtractChunkPayload represents the extract chunk task payload
type ExtractChunkPayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
ChunkID string `json:"chunk_id"`
ModelID string `json:"model_id"`
@@ -28,6 +29,7 @@ type ExtractChunkPayload struct {
// DocumentProcessPayload represents the document process task payload
type DocumentProcessPayload struct {
TracingContext
RequestId string `json:"request_id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeID string `json:"knowledge_id"`
@@ -46,6 +48,7 @@ type DocumentProcessPayload struct {
// FAQImportPayload represents the FAQ import task payload (including dry run mode)
type FAQImportPayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
TaskID string `json:"task_id"`
KBID string `json:"kb_id"`
@@ -60,6 +63,7 @@ type FAQImportPayload struct {
// QuestionGenerationPayload represents the question generation task payload
type QuestionGenerationPayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
KnowledgeID string `json:"knowledge_id"`
@@ -70,6 +74,7 @@ type QuestionGenerationPayload struct {
// SummaryGenerationPayload represents the summary generation task payload
type SummaryGenerationPayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
KnowledgeID string `json:"knowledge_id"`
@@ -78,6 +83,7 @@ type SummaryGenerationPayload struct {
// KBClonePayload represents the knowledge base clone task payload
type KBClonePayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
TaskID string `json:"task_id"`
SourceID string `json:"source_id"`
@@ -86,6 +92,7 @@ type KBClonePayload struct {
// IndexDeletePayload represents the index delete task payload
type IndexDeletePayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
EmbeddingModelID string `json:"embedding_model_id"`
@@ -96,6 +103,7 @@ type IndexDeletePayload struct {
// KBDeletePayload represents the knowledge base delete task payload
type KBDeletePayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
EffectiveEngines []RetrieverEngineParams `json:"effective_engines"`
@@ -103,12 +111,14 @@ type KBDeletePayload struct {
// KnowledgeListDeletePayload represents the batch knowledge delete task payload
type KnowledgeListDeletePayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
KnowledgeIDs []string `json:"knowledge_ids"`
}
// KnowledgeMovePayload represents the knowledge move task payload
type KnowledgeMovePayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
TaskID string `json:"task_id"`
KnowledgeIDs []string `json:"knowledge_ids"`
@@ -136,6 +146,7 @@ type KnowledgeMoveProgress struct {
// ManualProcessPayload represents the manual knowledge processing task payload.
// Used for both create (publish) and update operations.
type ManualProcessPayload struct {
TracingContext
RequestId string `json:"request_id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeID string `json:"knowledge_id"`
@@ -146,6 +157,7 @@ type ManualProcessPayload struct {
// ImageMultimodalPayload represents the image multimodal processing task payload.
type ImageMultimodalPayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
@@ -160,6 +172,7 @@ type ImageMultimodalPayload struct {
// KnowledgePostProcessPayload represents the knowledge post process task payload.
type KnowledgePostProcessPayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
+60
View File
@@ -0,0 +1,60 @@
package types
// TracingContext is an embeddable struct that carries observability context
// (currently Langfuse trace/span ids plus user/session hints) across process
// boundaries — specifically, from an HTTP request into an asynq task payload
// and back out inside the worker.
//
// It lives in the types package, not the langfuse package, so that:
//
// - asynq payload structs can embed it without pulling the langfuse
// package into every service/handler import graph;
// - the langfuse package can remain a leaf dependency that only types
// (and its own tests) reference directly.
//
// The JSON tags all use the "lf_" prefix and omitempty so that payloads
// constructed before the Langfuse feature landed remain byte-compatible
// (empty fields collapse to nothing in the serialized output) and so that
// Langfuse-specific columns don't collide with business fields that may
// happen to be named similarly.
type TracingContext struct {
// LangfuseTraceID is the id of the root trace that originated this task.
// When set, workers attach their observations to the same trace instead
// of creating a standalone one, which is what makes the Langfuse UI
// show the asynq work as a child of the originating HTTP request.
LangfuseTraceID string `json:"lf_trace_id,omitempty"`
// LangfuseParentObservationID, when set, points to the span that
// enclosed the enqueue call. The worker's own span/generation will list
// it as parentObservationId so Langfuse renders the tree as:
// http-trace → http-span → asynq-span → generation.
LangfuseParentObservationID string `json:"lf_parent_obs_id,omitempty"`
// LangfuseUserID preserves the userId / tenant label across the async
// boundary so that orphan async traces (when no upstream trace id is
// available) still show up in the Langfuse "Users" view under the
// right tenant.
LangfuseUserID string `json:"lf_user_id,omitempty"`
// LangfuseSessionID preserves the sessionId for the same reason.
LangfuseSessionID string `json:"lf_session_id,omitempty"`
}
// SetLangfuseTracing overwrites the embedded TracingContext. Method is
// exported so helpers in internal/tracing/langfuse can populate it via the
// LangfuseTracingCarrier interface without reflection.
func (tc *TracingContext) SetLangfuseTracing(other TracingContext) {
*tc = other
}
// GetLangfuseTracing returns a copy of the embedded TracingContext.
func (tc TracingContext) GetLangfuseTracing() TracingContext {
return tc
}
// LangfuseTracingCarrier is implemented automatically by any struct that
// embeds TracingContext (thanks to Go's method promotion rules). The asynq
// enqueue helper in internal/tracing/langfuse uses this interface to inject
// the current trace/span ids into the payload without caring about the
// concrete payload type.
type LangfuseTracingCarrier interface {
SetLangfuseTracing(TracingContext)
GetLangfuseTracing() TracingContext
}