Skip to content

feat(telemetry): optional span content capture with Langfuse/GenAI attributes - #1720

Open
DustinReynoldsPE wants to merge 6 commits into
alibaba:mainfrom
DustinReynoldsPE:pr/span-content
Open

DustinReynoldsPE wants to merge 6 commits into
alibaba:mainfrom
DustinReynoldsPE:pr/span-content

Conversation

@DustinReynoldsPE

Copy link
Copy Markdown

What

Spans today carry only metadata (model, duration, tokens). This adds opt-in content capture behind OCR_TRACE_CONTENT=1, plus trace-level attributes from OCR_TRACE_{NAME,ENV,SESSION,RELEASE,TAGS}:

  • llm.request spans → langfuse.observation.type=generation with the request messages as input, completion + tool_calls as output, reasoning_content in metadata, gen_ai.* usage attrs and langfuse.observation.usage_details (incl. cache tokens)
  • tool.execute.* spans → langfuse.observation.type=tool with args/result as input/output
  • trace-level langfuse.trace.name, langfuse.environment, langfuse.session.id, langfuse.release, langfuse.tags stamped on every span (Langfuse accepts them from any span)

Wired at every existing StartLLMSpan/StartToolSpan call 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 — pass
  • make test — pass, full suite (go test -race), all 24 packages
  • New langfuse_test.go covers enabled path (attribute assertions on a recording span), disabled no-op path, and the session-id fallback order
  • Verified end-to-end against a live Langfuse v4 instance: a real ocr review produced a trace with GENERATION observations carrying input/output/reasoning_content and TOOL observations carrying args/results

AI 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.

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.
@CLAassistant

CLAassistant commented Oct 12, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 5 issue(s) in this PR.

  • ✅ Successfully posted inline: 5 comment(s)

Comment thread internal/agent/agent.go Outdated
totalTokens = resp.Usage.TotalTokens
}
telemetry.RecordLLMResult(llmSpan, duration, totalTokens, nil)
telemetry.RecordLLMOutput(llmSpan, resp.Content(), nil, resp.ReasoningContent(), resp.Usage)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
telemetry.RecordLLMOutput(llmSpan, resp.Content(), nil, resp.ReasoningContent(), resp.Usage)
telemetry.RecordLLMOutput(llmSpan, resp.VisibleContent(), nil, resp.ReasoningContent(), resp.Usage)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread internal/agent/agent.go Outdated
totalTokens = resp.Usage.TotalTokens
}
telemetry.RecordLLMResult(llmSpan, duration, totalTokens, nil)
telemetry.RecordLLMOutput(llmSpan, resp.Content(), resp.ToolCalls(), resp.ReasoningContent(), resp.Usage)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
telemetry.RecordLLMOutput(llmSpan, resp.Content(), resp.ToolCalls(), resp.ReasoningContent(), resp.Usage)
telemetry.RecordLLMOutput(llmSpan, resp.VisibleContent(), resp.ToolCalls(), resp.ReasoningContent(), resp.Usage)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread internal/telemetry/langfuse.go Outdated
Comment on lines +18 to +19
func applyTraceAttrs(span trace.Span) {
cfg := ResolveConfig("")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread internal/telemetry/langfuse.go Outdated
Comment on lines +67 to +69
if sessionID != "" && ResolveConfig("").TraceSession == "" {
SetAttr(span, "langfuse.session.id", sessionID)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

  1. When OCR_TRACE_SESSION is set, applyTraceAttrs sets it correctly, and RecordLLMInput correctly skips — this works.
  2. When OCR_TRACE_SESSION is empty, applyTraceAttrs skips it (guarded by != ""), and RecordLLMInput sets it from sessionID — 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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Comment on lines +93 to +95
if sessionID != "" && resolvedConfig().TraceSession == "" {
runtimeSession.Store(&sessionID)
SetAttr(span, "langfuse.session.id", sessionID)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread internal/diff/relocation.go Outdated
totalTokens = resp.Usage.TotalTokens
}
telemetry.RecordLLMResult(llmSpan, duration, totalTokens, nil)
telemetry.RecordLLMOutput(llmSpan, resp.Content(), nil, resp.ReasoningContent(), resp.Usage)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 34e8b98 — relocation.go now passes resp.VisibleContent() to RecordLLMOutput, same as the other call sites.

Comment on lines +68 to +69
if os.Getenv("OCR_TRACE_CONTENT") == "1" {
cfg.SpanContent = true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 NanaseInori left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chaojixinren

Copy link
Copy Markdown
Contributor

@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.
@DustinReynoldsPE

Copy link
Copy Markdown
Author

Merged upstream main (6386895) into pr/span-content — the merge conflicts in internal/llmloop/loop.go and internal/telemetry/shutdown.go are resolved (d7aaee9). Upstream's Task/Run refactor is kept; the session-ID context propagation and content-capture calls were reapplied on top, and the session telemetry tests were migrated to the new API. go build, go vet, and the tests for the touched packages all pass locally.

@DustinReynoldsPE

Copy link
Copy Markdown
Author

Addressed the P2 session-identity finding in e51f090 (rebased onto main as d7aaee9):

  • llmloop.Run now inherits an existing run-session ID from the context (telemetry.SessionIDFromContext) instead of overwriting it with a fresh UUID; the explicit fallback for callers without a run identity remains (loop.go).
  • RecordLLMInput writes the effective session ID; the per-conversation UUID moved to a separate observation attribute, gen_ai.conversation.id, on the llm.request spans, and stays the ChatRequest.SessionID prompt-cache key.
  • Regression: TestRun_InheritsRunSessionID drives two conversations under one run-session context and asserts every span carries the run ID while each conversation's UUID stays distinct; TestRun_SessionIDFallback covers the no-run-identity path. Both run under -race with the rest of the package suites green.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants