feat(tracing): migrate langfuse client to OTLP/OTel wire protocol

Migrate WeKnora's Langfuse tracing from the legacy /api/public/ingestion
batch API to the OpenTelemetry Go SDK emitting OTLP/HTTP to
/api/public/otel/v1/traces — the Langfuse v3+ standard ingestion protocol.

Why: Langfuse v3 deprecated the legacy ingestion API in favor of OTLP, and
OTel-only backends (e.g. the LiteFuse Doris fork) dropped it entirely, so the
legacy client was incompatible. Migrating to the OTel SDK also adds W3C
traceparent cross-service propagation: an upstream caller's trace id is
inherited so its run and the WeKnora call land under one trace in the UI.

What:
- Manager owns an OTel TracerProvider backed by an otlptracehttp exporter
  (Basic auth + the x-langfuse-ingestion-version gate header). Spans are
  buffered by BatchSpanProcessor and exported complete on End, so a long
  trace no longer fragments across flush batches.
- *Trace/*Span/*Generation wrap OTel spans; the public API (StartTrace/
  Span/Generation, handles, InjectTracing, asynq/gin middleware, Config,
  TokenUsage) is unchanged, so callers (agent/chat/handler/scheduler/asynqdl)
  need no edits.
- W3C traceparent: GinMiddleware extracts traceparent from incoming requests;
  AsynqMiddleware + InjectTracing propagate it across the asynq payload.
  types.TracingContext gains a LangfuseTraceparent field.
- logger.CloneContext preserves the active OTel span across context rebuilds
  so child spans (agent engine, summary generation) stitch to the HTTP trace
  instead of orphaning into separate traces.
- StartSpan/StartGeneration re-establish the parent from the *Trace handle
  when the ctx lost the active OTel span, covering background/derived contexts.

Compatibility: works with Langfuse v3+ (cloud / self-hosted / the bundled
docker-compose profile) and LiteFuse. Drops Langfuse v2 (legacy-only) support.
Uses the OTel Go SDK already (indirectly) in go.mod, promoting
otlptracehttp to direct; no third-party langfuse-go library.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
shenk-b
2026-07-17 11:41:45 +08:00
committed by lyingbug
parent 1a2021b3f8
commit 5ee96019e0
16 changed files with 654 additions and 1013 deletions
+185 -227
View File
@@ -2,41 +2,44 @@ package langfuse
import (
"context"
"encoding/json"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
// Trace represents an active root observation. A Trace is conceptually one
// "request" (e.g. a chat turn). Generations and spans attached to it roll up
// as children in the Langfuse UI.
// as children in the Langfuse UI. It wraps an OpenTelemetry root span; its
// ID is the OTel trace id (W3C 32-hex), which — when the request carried a
// traceparent header — is the upstream caller's trace id (sop3 correlation).
type Trace struct {
ID string
span trace.Span
manager *Manager
sampled bool
}
// Generation represents a single model invocation (LLM / embedding / VLM).
// Generation represents a single model invocation (LLM / embedding / VLM / ASR).
type Generation struct {
ID string
TraceID string
ParentObservationID string
manager *Manager
sampled bool
startTime time.Time
model string
name string
ID string
span trace.Span
manager *Manager
model string
name string
}
// Span represents a logical unit of work that isn't itself an LLM call — for
// example an asynq task execution, a pipeline stage, or a document-processing
// step. Generations and nested spans attach to it via parentObservationId.
// step. Generations and nested spans attach as children via the OTel span
// context (parenting is automatic through trace.SpanFromContext).
type Span struct {
ID string
TraceID string
ParentObservationID string
manager *Manager
sampled bool
startTime time.Time
name string
ID string
span trace.Span
manager *Manager
name string
}
// TraceOptions configures a new trace.
@@ -67,268 +70,223 @@ type SpanOptions struct {
Metadata map[string]interface{}
}
// StartTrace opens a new trace, stores its ID in the returned ctx, and returns
// a handle callers can finish with FinishTrace. When the manager is disabled
// or sampling excludes the trace, the returned *Trace is non-nil but all
// methods are no-ops so callers don't need nil checks.
// StartTrace opens a root span. When ctx carries a remote SpanContext (from a
// W3C traceparent extracted by GinMiddleware), the root span inherits the
// upstream trace id — this is what makes a sop3 run and its WeKnora call land
// under the same trace in LiteFuse. The returned *Trace is non-nil even when
// disabled (methods are no-ops), so callers don't need nil checks.
func (m *Manager) StartTrace(ctx context.Context, opts TraceOptions) (context.Context, *Trace) {
if m == nil || !m.cfg.Enabled {
return ctx, &Trace{}
if !m.Enabled() {
return ctx, &Trace{manager: m}
}
sampled := m.sample()
id := newID()
t := &Trace{ID: id, manager: m, sampled: sampled}
if sampled {
env := opts.Environment
if env == "" {
env = m.cfg.Environment
}
release := opts.Release
if release == "" {
release = m.cfg.Release
}
body := traceBody{
ID: id,
Timestamp: isoTime(time.Now()),
Name: opts.Name,
UserID: opts.UserID,
SessionID: opts.SessionID,
Input: opts.Input,
Metadata: opts.Metadata,
Tags: opts.Tags,
Environment: env,
Release: release,
}
m.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(time.Now()),
Type: "trace-create",
Body: body,
})
name := opts.Name
attrs := []attribute.KeyValue{attribute.String(attrObsType, obsTypeTrace)}
if opts.Name != "" {
attrs = append(attrs, attribute.String(attrTraceName, opts.Name))
}
if opts.UserID != "" {
attrs = append(attrs, attribute.String(attrUserID, opts.UserID))
}
if opts.SessionID != "" {
attrs = append(attrs, attribute.String(attrSessionID, opts.SessionID))
}
env := opts.Environment
if env == "" {
env = m.cfg.Environment
}
if env != "" {
attrs = append(attrs, attribute.String(attrEnvironment, env))
}
rel := opts.Release
if rel == "" {
rel = m.cfg.Release
}
if rel != "" {
attrs = append(attrs, attribute.String(attrRelease, rel))
}
attrs = append(attrs, jsonAttr(attrTraceInput, opts.Input))
attrs = append(attrs, jsonAttr(attrTraceMetadata, opts.Metadata))
if len(opts.Tags) > 0 {
attrs = append(attrs, jsonAttr(attrTraceTags, opts.Tags))
}
ctx, span := m.tracer.Start(ctx, name, trace.WithTimestamp(time.Now()), trace.WithAttributes(attrs...))
t := &Trace{ID: span.SpanContext().TraceID().String(), span: span, manager: m}
return withTrace(ctx, t), t
}
// Finish updates the trace with its final output. Safe to call on a disabled
// trace (no-op).
// trace (no-op). The trace's metadata attribute (request_id, http.method,
// etc.) is set once at StartTrace and left untouched here — overwriting it
// with the finish metadata would lose the open's correlation fields.
func (t *Trace) Finish(output interface{}, metadata map[string]interface{}) {
if t == nil || t.manager == nil || !t.sampled {
_ = metadata
if t == nil || t.manager == nil || !t.manager.Enabled() || t.span == nil {
return
}
// "trace-create" events are also used to update traces in Langfuse —
// the server merges repeated events by ID. See the ingestion API docs.
body := traceBody{
ID: t.ID,
Output: output,
Metadata: metadata,
}
t.manager.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(time.Now()),
Type: "trace-create",
Body: body,
})
t.span.SetAttributes(jsonAttr(attrTraceOutput, output))
t.span.End()
}
// ResumeTrace reconstructs a *Trace handle from an upstream-provided trace id
// (and optional parent observation id), without emitting a new trace-create
// event. Used by the asynq middleware to graft async work onto the HTTP-level
// trace that originated it: the HTTP layer already issued trace-create, and
// the worker only needs to add child observations.
//
// When traceID is empty the returned *Trace is nil, signalling the caller
// should fall back to StartTrace if it wants a standalone root.
func (m *Manager) ResumeTrace(ctx context.Context, traceID, parentObservationID string) (context.Context, *Trace) {
if m == nil || !m.cfg.Enabled || traceID == "" {
// ResumeTrace reconstructs a *Trace handle from an externally-provided W3C
// trace id (and optional parent span id), without creating a new root span —
// the originating process (e.g. an HTTP request that already opened a trace)
// owns the root. Used to graft async work onto an existing trace: it sets a
// remote SpanContext on ctx so any child span/generation started under it
// inherits the upstream trace id. When traceID is empty the returned *Trace
// is nil, signalling the caller should fall back to StartTrace.
func (m *Manager) ResumeTrace(ctx context.Context, traceID, parentSpanID string) (context.Context, *Trace) {
if m == nil || !m.Enabled() || traceID == "" {
return ctx, nil
}
t := &Trace{ID: traceID, manager: m, sampled: true}
ctx = withTrace(ctx, t)
if parentObservationID != "" {
ctx = withParentObservation(ctx, parentObservationID)
tid, err := trace.TraceIDFromHex(traceID)
if err != nil {
// Not a W3C 32-hex trace id (legacy UUID, etc.); cannot resume.
return ctx, nil
}
return ctx, t
var sid trace.SpanID
if parentSpanID != "" {
if s, err := trace.SpanIDFromHex(parentSpanID); err == nil {
sid = s
}
}
sc := trace.NewSpanContext(trace.SpanContextConfig{
TraceID: tid,
SpanID: sid,
TraceFlags: trace.FlagsSampled,
Remote: true,
})
ctx = trace.ContextWithRemoteSpanContext(ctx, sc)
t := &Trace{ID: traceID, manager: m}
return withTrace(ctx, t), t
}
// StartSpan opens a SPAN observation under the trace (and optional parent
// observation) carried by ctx. When no trace is present, a shallow trace is
// auto-created, mirroring StartGeneration's behaviour. Returns a ctx whose
// parentObservationId is set to this span's id, so any nested span or
// generation will properly attach as a child.
// reestablishParentSpan re-injects the active trace's root span as the OTel
// parent when ctx carries a *Trace but no active OTel span. This happens when
// a context rebuild drops the OTel span while the *Trace handle survives on
// the exported key (e.g. a background goroutine derived from a non-request
// context, or a CloneContext that predates/missed the span fix). Without
// this, child spans (e.g. a summary generation) start a fresh root and orphan
// off the HTTP trace.
func (m *Manager) reestablishParentSpan(ctx context.Context) context.Context {
if !m.Enabled() {
return ctx
}
if sp := trace.SpanFromContext(ctx); sp.IsRecording() {
return ctx // already has an active span
}
if t, ok := traceFromCtx(ctx); ok && t != nil && t.span != nil {
return trace.ContextWithSpan(ctx, t.span)
}
return ctx
}
// StartSpan opens a child span under the trace/span carried by ctx. When no
// trace is present, OTel creates a fresh root (mirroring StartGeneration's
// auto-trace behaviour). Returns a ctx whose active span is this span.
func (m *Manager) StartSpan(ctx context.Context, opts SpanOptions) (context.Context, *Span) {
if m == nil || !m.cfg.Enabled {
return ctx, &Span{}
if !m.Enabled() {
return ctx, &Span{manager: m}
}
trace, ok := traceFromCtx(ctx)
if !ok || trace == nil {
newCtx, t := m.StartTrace(ctx, TraceOptions{Name: opts.Name})
ctx = m.reestablishParentSpan(ctx)
if _, ok := traceFromCtx(ctx); !ok {
// No active trace: open a shallow root so the span isn't orphaned.
newCtx, _ := m.StartTrace(ctx, TraceOptions{Name: opts.Name})
ctx = newCtx
trace = t
}
if !trace.sampled {
return ctx, &Span{}
attrs := []attribute.KeyValue{
attribute.String(attrObsType, obsTypeSpan),
jsonAttr(attrObsInput, opts.Input),
jsonAttr(attrObsMetadata, opts.Metadata),
}
parent, _ := parentObservationFromCtx(ctx)
now := time.Now()
s := &Span{
ID: newID(),
TraceID: trace.ID,
ParentObservationID: parent,
manager: m,
sampled: true,
startTime: now,
name: opts.Name,
}
body := observationBody{
ID: s.ID,
TraceID: s.TraceID,
ParentObservationID: parent,
Type: "SPAN",
Name: opts.Name,
StartTime: isoTime(now),
Input: opts.Input,
Metadata: opts.Metadata,
}
m.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(now),
Type: "span-create",
Body: body,
})
ctx = withParentObservation(ctx, s.ID)
return ctx, s
ctx, span := m.tracer.Start(ctx, opts.Name, trace.WithTimestamp(time.Now()), trace.WithAttributes(attrs...))
return ctx, &Span{ID: span.SpanContext().SpanID().String(), span: span, manager: m, name: opts.Name}
}
// Finish updates a span with its final output, extra metadata and any error.
// A non-nil err marks the span as ERROR level in Langfuse.
// A non-nil err marks the span as ERROR. The span's metadata attribute is set
// once at StartSpan and left untouched here.
func (s *Span) Finish(output interface{}, metadata map[string]interface{}, err error) {
if s == nil || s.manager == nil || !s.sampled {
_ = metadata
if s == nil || s.manager == nil || !s.manager.Enabled() || s.span == nil {
return
}
level := "DEFAULT"
var statusMsg string
s.span.SetAttributes(jsonAttr(attrObsOutput, output))
if err != nil {
level = "ERROR"
statusMsg = err.Error()
s.span.RecordError(err)
s.span.SetStatus(codes.Error, err.Error())
}
body := observationBody{
ID: s.ID,
TraceID: s.TraceID,
Type: "SPAN",
EndTime: isoTime(time.Now()),
Output: output,
Metadata: metadata,
Level: level,
StatusMessage: statusMsg,
}
s.manager.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(time.Now()),
Type: "span-update",
Body: body,
})
s.span.End()
}
// StartGeneration opens a generation observation under the trace carried by
// ctx (or a newly auto-created trace if none is present). If a parent span
// is present on ctx, the generation attaches under it via parentObservationId
// so the Langfuse tree shows: trace → span → generation.
// ctx (or a newly auto-created trace). If a parent span is present on ctx,
// the generation attaches under it via the OTel span context.
func (m *Manager) StartGeneration(ctx context.Context, opts GenerationOptions) (context.Context, *Generation) {
if m == nil || !m.cfg.Enabled {
return ctx, &Generation{}
if !m.Enabled() {
return ctx, &Generation{manager: m, model: opts.Model, name: opts.Name}
}
// If the caller hasn't opened a trace yet, create a shallow auto-trace so
// the generation has a parent. This keeps single-shot internal callers
// (e.g. test connections) observable.
trace, ok := traceFromCtx(ctx)
if !ok || trace == nil {
newCtx, t := m.StartTrace(ctx, TraceOptions{Name: opts.Name})
ctx = m.reestablishParentSpan(ctx)
if _, ok := traceFromCtx(ctx); !ok {
newCtx, _ := m.StartTrace(ctx, TraceOptions{Name: opts.Name})
ctx = newCtx
trace = t
}
if !trace.sampled {
return ctx, &Generation{}
attrs := []attribute.KeyValue{
attribute.String(attrObsType, obsTypeGeneration),
attribute.String(attrObsModel, opts.Model),
jsonAttr(attrObsInput, opts.Input),
jsonAttr(attrObsMetadata, opts.Metadata),
jsonAttr(attrObsModelParams, opts.ModelParameters),
}
parent, _ := parentObservationFromCtx(ctx)
now := time.Now()
ctx, span := m.tracer.Start(ctx, opts.Name, trace.WithTimestamp(time.Now()), trace.WithAttributes(attrs...))
g := &Generation{
ID: newID(),
TraceID: trace.ID,
ParentObservationID: parent,
manager: m,
sampled: true,
startTime: now,
model: opts.Model,
name: opts.Name,
ID: span.SpanContext().SpanID().String(),
span: span,
manager: m,
model: opts.Model,
name: opts.Name,
}
body := observationBody{
ID: g.ID,
TraceID: g.TraceID,
ParentObservationID: parent,
Type: "GENERATION",
Name: opts.Name,
StartTime: isoTime(now),
Input: opts.Input,
Metadata: opts.Metadata,
Model: opts.Model,
ModelParameters: opts.ModelParameters,
}
m.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(now),
Type: "generation-create",
Body: body,
})
return ctx, g
}
// Finish updates a generation with its final output, token usage and any
// error. A non-nil err marks the observation as ERROR level in Langfuse.
// error. A non-nil err marks the observation as ERROR.
func (g *Generation) Finish(output interface{}, usage *TokenUsage, err error) {
if g == nil || g.manager == nil || !g.sampled {
if g == nil || g.manager == nil || !g.manager.Enabled() || g.span == nil {
return
}
level := "DEFAULT"
var statusMsg string
attrs := []attribute.KeyValue{jsonAttr(attrObsOutput, output)}
if usage != nil {
attrs = append(attrs, jsonAttr(attrObsUsageDetails, usage))
}
g.span.SetAttributes(attrs...)
if err != nil {
level = "ERROR"
statusMsg = err.Error()
g.span.RecordError(err)
g.span.SetStatus(codes.Error, err.Error())
}
body := observationBody{
ID: g.ID,
TraceID: g.TraceID,
Type: "GENERATION",
EndTime: isoTime(time.Now()),
Output: output,
Usage: usage,
Level: level,
StatusMessage: statusMsg,
}
g.manager.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(time.Now()),
Type: "generation-update",
Body: body,
})
g.span.End()
}
// MarkCompletionStart records the time at which the first token was received
// in a streaming generation. Langfuse surfaces this as time-to-first-token.
func (g *Generation) MarkCompletionStart(t time.Time) {
if g == nil || g.manager == nil || !g.sampled {
if g == nil || g.manager == nil || !g.manager.Enabled() || g.span == nil {
return
}
body := observationBody{
ID: g.ID,
TraceID: g.TraceID,
Type: "GENERATION",
CompletionStart: isoTime(t),
}
g.manager.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(time.Now()),
Type: "generation-update",
Body: body,
})
g.span.SetAttributes(attribute.String(attrObsCompletionStart, isoTime(t)))
}
// jsonAttr serializes v to a compact JSON string and wraps it as a string
// OTel attribute — matching how langfuse-python stores structured fields
// (input/output/metadata/usage) on spans. nil/zero values return an empty
// KeyValue (harmless on SetAttributes).
func jsonAttr(key string, v interface{}) attribute.KeyValue {
if v == nil {
return attribute.KeyValue{Key: attribute.Key(key)}
}
b, err := json.Marshal(v)
if err != nil || len(b) == 0 || string(b) == "null" {
logger.Warnf(context.Background(), "[Langfuse] marshal attr %s failed: %v", key, err)
return attribute.KeyValue{Key: attribute.Key(key)}
}
return attribute.String(key, string(b))
}