Repository navigation
feat(telemetry): optional span content capture with Langfuse/GenAI attributes - #1720
DustinReynoldsPE wants to merge 6 commits into
Conversation
OCR_TRACE_CONTENT=1 marks llm.request spans as Langfuse generations with
request messages, completion + tool_calls output, reasoning_content, and
usage_details (incl. cache tokens), and tool.execute spans as tool
observations with args/result. OCR_TRACE_{NAME,ENV,SESSION,RELEASE,TAGS}
stamp langfuse trace-level attributes on every span. Off by default — no
behavior change without the flag.
|
🔍 OpenCodeReview found 5 issue(s) in this PR.
|
| totalTokens = resp.Usage.TotalTokens | ||
| } | ||
| telemetry.RecordLLMResult(llmSpan, duration, totalTokens, nil) | ||
| telemetry.RecordLLMOutput(llmSpan, resp.Content(), nil, resp.ReasoningContent(), resp.Usage) |
There was a problem hiding this comment.
Inconsistent use of resp.Content() vs resp.VisibleContent(). Content() falls back to ReasoningContent when visible content is empty, which means reasoning text could be recorded twice in telemetry: once as content in the output map and again as reasoning_content metadata. The loop.go call sites correctly use resp.VisibleContent() to avoid this duplication. This should match that pattern for consistency.
Suggestion:
| telemetry.RecordLLMOutput(llmSpan, resp.Content(), nil, resp.ReasoningContent(), resp.Usage) | |
| telemetry.RecordLLMOutput(llmSpan, resp.VisibleContent(), nil, resp.ReasoningContent(), resp.Usage) |
There was a problem hiding this comment.
Applied in c3f6ad4 — this call site now uses resp.VisibleContent(), matching the loop.go sites, so a reasoning-only response can no longer double-record reasoning as both content and reasoning_content.
| totalTokens = resp.Usage.TotalTokens | ||
| } | ||
| telemetry.RecordLLMResult(llmSpan, duration, totalTokens, nil) | ||
| telemetry.RecordLLMOutput(llmSpan, resp.Content(), resp.ToolCalls(), resp.ReasoningContent(), resp.Usage) |
There was a problem hiding this comment.
Same issue as in executeGroupPlanPhase: resp.Content() can fall back to reasoning content, causing duplication in telemetry. Use resp.VisibleContent() for consistency with the loop.go call sites.
Suggestion:
| telemetry.RecordLLMOutput(llmSpan, resp.Content(), resp.ToolCalls(), resp.ReasoningContent(), resp.Usage) | |
| telemetry.RecordLLMOutput(llmSpan, resp.VisibleContent(), resp.ToolCalls(), resp.ReasoningContent(), resp.Usage) |
There was a problem hiding this comment.
Applied in c3f6ad4 — same fix: resp.VisibleContent() here and in executeGroupPlanPhase, consistent with the loop.go call sites.
| TraceEnv string // langfuse.environment applied to every span | ||
| TraceSession string // langfuse.session.id applied to every span | ||
| TraceRelease string // langfuse.release applied to every span | ||
| TraceTags string // langfuse.tags applied to every span |
There was a problem hiding this comment.
TraceTags is stored and emitted as a raw string attribute. Langfuse expects langfuse.tags to be a JSON array of strings (e.g., ["tag1","tag2"]). If a user sets OCR_TRACE_TAGS=my-tag, it will be sent as the literal string "my-tag" rather than ["my-tag"], which Langfuse may not interpret correctly. Consider either parsing the string into a JSON array at config time (e.g., splitting by comma and marshaling), or documenting the expected format clearly so users provide valid JSON.
There was a problem hiding this comment.
Fixed in c3f6ad4 — OCR_TRACE_TAGS is now parsed as a comma-separated list and emitted via attribute.StringSlice, so langfuse.tags arrives as a real OTel string array (e.g. ["a","b"]) rather than a scalar string. A test now asserts the array form.
| func applyTraceAttrs(span trace.Span) { | ||
| cfg := ResolveConfig("") |
There was a problem hiding this comment.
ResolveConfig("") is called on every StartSpan, which means on every span creation it allocates a new Config struct and calls os.Getenv six times (plus the existing env reads in resolveEnv). Since StartSpan is on the hot path (every LLM request, every tool call), this adds unnecessary per-span overhead. The config values are effectively static for the process lifetime (environment variables don't change at runtime). Consider caching the resolved config in a package-level variable (e.g., via sync.Once) or passing the config explicitly.
There was a problem hiding this comment.
Fixed in c3f6ad4 — the resolved Config is now captured once in Init and held in an atomic.Pointer; applyTraceAttrs, SpanContentEnabled, and RecordLLMInput read the cached copy instead of re-resolving env vars on every span. Callers that never run Init (unit tests) fall back to a live ResolveConfig, preserving existing behavior.
| if sessionID != "" && ResolveConfig("").TraceSession == "" { | ||
| SetAttr(span, "langfuse.session.id", sessionID) | ||
| } |
There was a problem hiding this comment.
There is a potential ordering issue with langfuse.session.id. applyTraceAttrs is called inside StartSpan (via StartLLMSpan) and unconditionally sets langfuse.session.id from cfg.TraceSession. Then RecordLLMInput is called immediately after and conditionally overwrites it with sessionID only when cfg.TraceSession == "". This means:
- When
OCR_TRACE_SESSIONis set,applyTraceAttrssets it correctly, andRecordLLMInputcorrectly skips — this works. - When
OCR_TRACE_SESSIONis empty,applyTraceAttrsskips it (guarded by!= ""), andRecordLLMInputsets it fromsessionID— this also works.
However, applyTraceAttrs runs on every span (including tool spans via StartToolSpan → StartSpan), while RecordLLMInput only runs on LLM spans. For non-LLM spans, if OCR_TRACE_SESSION is not set, no session ID will be attributed even though a session is active. If Langfuse requires session ID on every span for proper grouping, tool spans will be missing it. Consider documenting this behavior or propagating session ID through context so all spans can receive it.
There was a problem hiding this comment.
Fixed in c3f6ad4 — RecordLLMInput now stores the runtime session ID once (when OCR_TRACE_SESSION is unset), and applyTraceAttrs stamps it on every subsequent span, so tool and structural spans carry the session as well. LLM requests precede tool calls in all current flows, so the ID is populated before non-LLM spans start. Shutdown clears it. Added TestRuntimeSessionPropagatesToSpans, which verifies a tool.execute.* span inherits the session.
- Use VisibleContent at agent.go LLM sites so reasoning is not recorded twice (Content falls back to ReasoningContent) - Emit langfuse.tags as a string array, not a raw string - Resolve telemetry config once at Init instead of per span - Propagate the runtime session ID to non-LLM spans when OCR_TRACE_SESSION is unset
| if sessionID != "" && resolvedConfig().TraceSession == "" { | ||
| runtimeSession.Store(&sessionID) | ||
| SetAttr(span, "langfuse.session.id", sessionID) |
There was a problem hiding this comment.
The runtime session ID is stored globally, but OCR runs multiple review subtasks concurrently. One subtask can overwrite another’s session ID, causing subsequent tool spans to be associated with the wrong session.
Could we propagate the session ID through context instead and add a concurrent-session regression test?
There was a problem hiding this comment.
Fixed in 34e8b98 — the global is gone. The session ID now travels on the context via telemetry.WithSessionID: Agent.Run injects a.SessionID() at the entry point, and the per-conversation loop in llmloop injects its generated UUID right where it's created. applyTraceAttrs reads the ID from the span's context, so sibling spans (LLM rounds, grace round, tool calls) in one conversation all carry the same ID and concurrent subtasks can't overwrite each other. RecordLLMInput still stamps the ID on its own generation span. Added TestConcurrentSessionsDoNotBleed as the regression test.
| totalTokens = resp.Usage.TotalTokens | ||
| } | ||
| telemetry.RecordLLMResult(llmSpan, duration, totalTokens, nil) | ||
| telemetry.RecordLLMOutput(llmSpan, resp.Content(), nil, resp.ReasoningContent(), resp.Usage) |
There was a problem hiding this comment.
One remaining instance of the reasoning duplication issue: resp.Content() can fall back to reasoning content, so it may be recorded twice here.
Could we use resp.VisibleContent() as in the other call sites?
There was a problem hiding this comment.
Fixed in 34e8b98 — relocation.go now passes resp.VisibleContent() to RecordLLMOutput, same as the other call sites.
| if os.Getenv("OCR_TRACE_CONTENT") == "1" { | ||
| cfg.SpanContent = true |
There was a problem hiding this comment.
Could we also update the telemetry documentation across all five languages? It currently states that prompts and responses are never exported, which contradicts the new OCR_TRACE_CONTENT=1 behavior.
The docs should also mention the potential exposure of sensitive content.
There was a problem hiding this comment.
Done in 34e8b98 — the "Content logging" section in all five locales (en/zh/ja/ko/ru) now documents OCR_TRACE_CONTENT=1: it opts in to attaching prompts, completions, reasoning, tool payloads and usage to llm.request/tool.execute.* spans as langfuse.observation.*/gen_ai.* attributes, exported to the configured collector. Each locale's text calls out that captured content can include source code, diffs and potential secrets, and advises enabling it only with a trusted collector (e.g. self-hosted Langfuse) and treating the traces as sensitive. The troubleshooting row that claimed prompts are never attached was updated in all five files as well.
Reviewer feedback on the span-content PR: - langfuse.session.id was kept in a package-global atomic, so concurrent review subtasks could overwrite each other's ID and associate spans with the wrong session. The ID now travels on the context via WithSessionID; applyTraceAttrs reads it there, and both session ID sources (agent run, per-conversation loop) inject it at the context origin. Adds a concurrent-session regression test. - diff/relocation.go recorded resp.Content(), which can fall back to reasoning content and double-record it; use resp.VisibleContent() like the other call sites. - telemetry docs claimed prompts/responses are never exported; with OCR_TRACE_CONTENT=1 they are. Documented the flag, the exported attributes and the sensitive-content risk in all five locales.
NanaseInori
left a comment
There was a problem hiding this comment.
Reviewed the full diff, telemetry helpers, main-loop call chain, and existing review replies. The Langfuse search found this feature, #1719's exporter-header work and merged #667's endpoint-path fix; those change transport configuration rather than the span-content instrumentation here. Opt-in content capture has a clear debugging use case, and the updated five-locale documentation correctly warns that captured content may contain secrets.
[P2] Keep the trace's session identity stable across main-loop calls. Agent.Run places a.SessionID() in the telemetry context, so structural/plan/filter spans use the OCR run's session. However, RunMainTask unconditionally replaces that value with its new uuid.NewString(), then RecordLLMInput writes the same new UUID onto its LLM spans. The caller creates main.loop with the original context immediately before invoking RunMainTask, without starting a new trace.
With OCR_TRACE_SESSION unset, one run therefore produces this hierarchy:
main.loop session = OCR run ID
llm.request session = fresh conversation UUID
tool.execute.file_read session = fresh conversation UUID
review-filter request session = OCR run ID
A subsequent main-loop review round generates another UUID. Langfuse treats session.id as a trace-level identity and requires it to be propagated consistently for observation filtering/aggregation. Filtering by the OCR run ID will omit its main generations and tool observations, defeating correlation with the saved session. This is a semantic identity split even though the former shared-global data race has been fixed.
Please preserve an already inherited run-session ID in the loop, use the same effective value in RecordLLMInput, and put any per-conversation UUID in a separate observation attribute. A fallback for callers without a run identity can remain explicit. Add a regression exercising the real Agent -> main.loop -> RunMainTask chain, including two rounds/groups, and assert one session identity for a shared trace. The current concurrent test starts independent contexts and cannot detect this nested overwrite.
References: Langfuse trace-level mapping and propagation, main-loop call site, new context override.
Validation: source and test inspection against Langfuse's documented mapping. I did not run the repository suite or a live Langfuse export. Previously fixed reasoning duplication, tag array typing, config caching and global-session races are not repeated as open findings.
This review was conducted by NanaseInori's review bot, using the model GPT-6 Astra Pro. If you need a human review, please manually @NanaseInori.
|
@DustinReynoldsPE resolve conflicts plz. |
Resolve conflicts in llmloop/loop.go and telemetry/shutdown.go: keep upstream's Task/Run refactor and reapply the session-ID context propagation and content-capture calls on top. Update the session telemetry tests to the Task/ExecuteTool API and reset activeCfg on Shutdown so reinitialization rebuilds config.
|
Merged upstream |
|
Addressed the P2 session-identity finding in e51f090 (rebased onto main as d7aaee9):
|
What
Spans today carry only metadata (model, duration, tokens). This adds opt-in content capture behind
OCR_TRACE_CONTENT=1, plus trace-level attributes fromOCR_TRACE_{NAME,ENV,SESSION,RELEASE,TAGS}:llm.requestspans →langfuse.observation.type=generationwith the request messages asinput, completion +tool_callsasoutput,reasoning_contentin metadata,gen_ai.*usage attrs andlangfuse.observation.usage_details(incl. cache tokens)tool.execute.*spans →langfuse.observation.type=toolwith args/result as input/outputlangfuse.trace.name,langfuse.environment,langfuse.session.id,langfuse.release,langfuse.tagsstamped on every span (Langfuse accepts them from any span)Wired at every existing
StartLLMSpan/StartToolSpancall site: main review loop, grace round, plan, review filter, relocation,code_comment(sync + async) and the generic tool path.Why
Debugging a review today means digging through session JSONL. With an OTLP-capable backend that understands these conventions (Langfuse accepts
gen_ai.*/langfuse.*directly), each review lands as a queryable trace — generations, thinking content, tool calls — while the run is live. Off by default: no attribute or behavior change without the flag, and the helpers early-return on nil/noop spans.Pairs naturally with
OTEL_EXPORTER_OTLP_HEADERS(#1719) for auth'd collectors.Test plan
make check— passmake test— pass, full suite (go test -race), all 24 packageslangfuse_test.gocovers enabled path (attribute assertions on a recording span), disabled no-op path, and the session-id fallback orderocr reviewproduced a trace with GENERATION observations carrying input/output/reasoning_contentand TOOL observations carrying args/resultsAI assistance disclosure
This contribution was prepared with AI assistance (Devin, Cognition — SWE-2 model). I reviewed the change end to end, ran the checks above myself, and can explain any line of it.