Repository navigation
feat: adopt OpenTelemetry GenAI semantic conventions for Coder Agents traces - #32411
Conversation
… traces
Rename the chat turn, model call, and tool call spans to invoke_agent,
chat {model}, and execute_tool {tool}, and add gen_ai.* attributes,
token usage with cache breakdown, and chat owner attribution. Add
--chat-trace-content-capture-enabled to opt in to recording prompts,
responses, and tool payloads on those spans.
Refs CODAGT-1523
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: be6fe7c55b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…ment tracing Clip message part text to fit the attribute limit instead of cutting the encoded JSON, record an error finish reason for partial responses, map finish reasons to GenAI values, and document the GenAI span mapping in the chatd architecture.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 47e0be7e33
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Start chat spans as clients with the model set at creation for samplers, record an error finish reason after a silence timeout, capture text that never received an end part, keep oversized tool payloads valid JSON, map finish reasons to the GenAI enum, and leave out file and citation parts that the message schema cannot represent without their bytes.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 57a0695052
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
… tool results only on success
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 77f40ef249
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…JSON-encode text tool payloads
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 60b5871922
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e03733200b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Tagging @cstyan as a secondary reviewer to check for any bad OTEL patterns |
mafredri
left a comment
There was a problem hiding this comment.
Reviewed e1c43b94d098261ad64170b0c5b07d7e3d7a2e8a against semconv v1.41.0, the production call paths, and the pinned provider adapters. One P1 concern, one P2 accounting limitation, and six P3 corrections. These conclusions are code/spec analysis, not live-provider measurements.
P1: The metadata-only guarantee needs qualification or enforcement. With --trace, runOne logs tool error-result content at INFO, and tracing.SlogSink attaches it to the active tool span. Replacing the span exception with errToolResult does not suppress that event. The regression test checks the status description but does not exercise the deployment logging sink.
P2: Anthropic input usage can represent context occupancy rather than cumulative usage. Native web search can produce larger cumulative input/cache counts in the final message_delta. The gateway preserves those fields, but the pinned Fantasy Anthropic adapter deliberately restores the initial message_start counts for context occupancy, as TestStream_FinishUsesMessageStartInputUsage documents. usageAttributes consequently exports the initial counts as gen_ai.usage.input_tokens, while output remains cumulative. This undercounts multi-iteration usage. Could we expose accounting usage separately from occupancy, or document the limitation here rather than promise token-spend attribution without qualification? The addition of cache reads/writes itself is correct for ordinary single-iteration usage.
P3: Compatible-provider cache writes are emitted as zero when unavailable to Fantasy. OpenRouter can report prompt_tokens_details.cache_write_tokens, but the production openaicompat route inherits OpenAI usage hooks that extract cache reads, not writes. usageAttributes then asserts gen_ai.usage.cache_creation.input_tokens=0. The inclusive input total remains correct; the breakdown does not. Populate reported writes or avoid asserting zero for an unsupported breakdown.
P3: Preserve observed model finish reasons. genAIFinishReason maps missing/unknown reasons to stop, and endModelCall replaces an observed reason with error when application validation rejects the response. The v1.41.0 span attribute is a string array describing why the model stopped, not the closed enum claimed by the comment. A length response that fails object parsing should retain length; operation failure can still use status and error.type. Omit unavailable reasons rather than manufacture a normal stop.
P3: Clarify configured versus effective request parameters. On the native OpenAI Chat Completions path, the supported MaxCompletionTokens provider option overrides the general call cap after SetInferenceRequest records it. A general cap of 32000 and an override of 4096 therefore produces a wire limit of 4096 but a span limit of 32000. The default Responses transport is unaffected by that override. Temperature stripped by a reasoning-model adapter has the same generic-call-versus-wire distinction. Record effective values or explicitly qualify which request layer these attributes describe.
P3: Native structured-output calls omit gen_ai.output.type. The selected conventions conditionally require this attribute when the request includes an applicable output format. Native OpenAI GenerateObject calls for titles, status labels, and summaries send JSON-schema formatting, but tracedModel.GenerateObject never records json. This should be conditional on the actual request format, not assumed for every provider or text/tool fallback.
P3: Qualify the exporter instructions. The new page suggests standard OTEL_EXPORTER_OTLP_* configuration without stating that this exporter is OTLP/gRPC only. A protocol variable cannot switch it to HTTP. Its explicit WithInsecure() also overrides environment-derived HTTPS/insecure selection, although certificate-derived TLS credentials take precedence. Document the actual transport and supported TLS configuration; this is a documentation issue with the existing exporter, not a request to expand its scope here.
P3: Preserve available IDs on non-streaming Responses calls. Both tracedModel.Generate and tracedModel.GenerateObject ignore ResponsesProviderMetadata.ResponseID, despite the documentation promising a provider-reported response ID when available. This affects non-streaming title/status/summary calls. Streaming advisor and compaction calls already record the ID.
The main span hierarchy and metric preservation look correct. The Google cache addition is also correct: production Google uses the OpenAI-compatible client, whose usage hooks subtract cached reads. The built-in/function and MCP/extension split is defensible and matches the actual VS Code Copilot Chat mapping; I would not treat it as a definite convention violation.
🤖 Created with the help of Coder Agents.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
mafredri
left a comment
There was a problem hiding this comment.
Follow-up on 21f9eb483bb4c6e7717741570970ee50c453627f. The code fixes address the previous finish-reason, response-ID, native JSON-output, and asserted-zero findings. Two P2 documentation concerns remain, plus a scope/acceptance question that needs an explicit answer.
Scope/acceptance question: CODAGT-1523
CODAGT-1523 explicitly requests:
- Opt-in prompt and response capture on the inference span for the step or turn that produced them.
- Opt-in tool inputs and results on each tool execution span.
- Metadata-only tracing remaining available without enabling that capture.
The PR still says Closes CODAGT-1523, while its decision log defers content capture to a follow-up.
Is this PR intended to complete those requirements, or only the semantic-convention mapping? If capture is intentionally deferred, which linked follow-up ticket owns the outstanding requirements, and has the acceptance scope of CODAGT-1523 been changed accordingly?
Please answer this explicitly before treating CODAGT-1523 as complete. Reconcile the issue scope and PR closure, or remove the closure claim and track the remaining work. These are requirements already written in the issue, not a suggestion to add unrelated scope. Saying capture is optional under the OpenTelemetry conventions does not resolve this acceptance question.
P2: Dropping log events does not remove all tool content from the trace
The narrower statement that gen_ai.* attributes contain metadata is accurate. The subsequent claim that tool arguments are not recorded as attributes, and the advice to drop log: events when the backend must not hold content, miss Gateway child spans.
With a configured external-auth MCP server, a valid owner link, and a model invocation of an injected tool, the Gateway MCP tool-call span records the first 100 characters of the arguments in mcp_input. These spans are exported in the same chat trace. Dropping events whose names start with log: does not remove that span attribute.
Please scope the no-payload statement to gen_ai.* attributes and account for Gateway tool attributes in the filtering advice. The earlier blanket guarantee has been narrowed, so this is now a P2 documentation concern rather than the previous P1.
P2: Gateway cost accounting does not avoid the Anthropic streaming limitation
The token-limit section now acknowledges first-iteration input counts, but recommends Gateway cost control as the alternative. Its Anthropic streaming recorder has the same gap: it records initial input/cache usage from message_start, then only output usage from message_delta, discarding the larger cumulative input/cache counts from native server-tool iterations.
RecordTokenUsage prices those records, and recordTokenUsageAndSpend stores their costs and increments daily spend. Nothing subsequently recovers the missing cumulative input. Switching from span totals to the cost API therefore does not solve this particular undercount.
Please carry that limitation into the recommendation. Also attribute the missing counts to the client/recorder rather than the provider: Anthropic reports cumulative input, and OpenRouter reports cache writes. Correcting Gateway accounting can be separate work; this PR needs accurate guidance.
The requested-versus-effective request parameters are now explicitly documented, and the gRPC/TLS instructions match the exporter. I found no new Go logic regression in the update. Full chatloop/advisor tests, targeted chatd tracing/model-resolution tests, and the diff whitespace check passed. The remaining findings are code-traced production paths, not live-provider measurements.
🤖 Created with the help of Coder Agents.
|
@mafredri on the CODAGT-1523 scope question: the issue was drafted with agent help, and the draft added requirements the customer did not ask for, including the Content capture and correlation section. Please ignore those parts. The source of truth is the Slack thread, which asks for:
The thread never asks for prompt, response, or tool payload capture. This PR implements that scope, so it closes CODAGT-1523 as intended. I added a comment on the Linear issue saying the same. If the customer later needs content, for example tool arguments for their semantic-analysis example, that will be a separate request confirmed with them. The two P2 documentation findings (Gateway (Coder Agents on behalf of @f0ssel) |
|
@mafredri addressed both P2 documentation findings in ebabef1:
(Coder Agents on behalf of @f0ssel) |
Aligns Coder Agents traces with the OpenTelemetry GenAI semantic conventions so customers can ingest per-user model usage, spend, and tool activity without custom mapping. Scope follows the requesting team's Slack ask: agent spans, inference spans with token usage, GenAI attributes, per-user attribution, and visibility into tools that cannot be reached.
Closes CODAGT-1523.
Changes
chat_turnbecomesinvoke_agent coder,streambecomeschat {model}, andtool_callbecomesexecute_tool {tool}. Every stage span now carries astageattribute with the old stage name, which matches the Prometheusstagelabel. Metrics are unchanged.gen_ai.operation.name,gen_ai.conversation.id(the chat ID),user.id(the chat owner), andcoder.organization.id,coder.workspace.id,coder.chat.parent_id,coder.chat.root_id.chatspans areCLIENTspans with the provider, request model, andgen_ai.request.streamset at creation (so samplers can see them), plus requested max tokens and temperature, response ID (including OpenAI Responses metadata on non-streaming calls), the finish reason the provider reported (omitted when none, kept when Coder rejects the response),gen_ai.output.type=jsonfor native OpenAI structured output, and token usage with cache read/write (only when nonzero) and reasoning breakdown.gen_ai.usage.input_tokensincludes cached tokens, as the spec requires. Fantasy reports them separately (Google providers use the OpenAI-compatible client, which does the same).execute_toolspans carry the tool name, call ID, and type (functionfor built-in tools,extensionfor MCP and caller tools), all set at creation.chatspan: assistant streams (stage=stream), and, asstage=model_call, the advisor, compaction summaries plus titles, status labels, and chat summaries (viaStageTracer.TraceModelCallsinresolveModelCall).model_callhas no histogram, so thestreammetric is unchanged.error.type. A tool that returns an error result, as MCP clients do for an unreachable server, ends its span witherror.type=tool_errorwithout recording the result text.docs/coder-agents/platform-controls/opentelemetry-tracing.md.coderd/x/chatd/ARCHITECTURE.mdgains a GenAI semantic conventions subsection under Lifecycle tracing.Existing attributes (
provider,model,chat_id,tool_name, ...) are kept so current queries on attributes keep working. Queries on span names need to switch to thestageattribute or the new names.Decision log
semantic-conventions-genai. The PR uses the Go constants fromgo.opentelemetry.io/otel/semconv/v1.41.0, which is already in the module graph. No experiment gate: chatd is already underx/, and the docs page notes that the conventions may change.stageattribute keeps lifecycle identity stable for dashboards and tests.gen_ai.agent.name=coderfor root chats and subagents alike.chat_kindandcoder.chat.parent_idtell them apart.openai,anthropic,azure.ai.openai,aws.bedrock,gcp.gemini). Anthropic providers with Bedrock settings reportaws.bedrock. Theinvoke_agentspan gets the provider afterprepareresolves the turn's model, since the turn span starts first. Other types (openrouter,openai-compat,vercel,copilot) are passed through as-is.gen_ai.input.messages,gen_ai.output.messages, and tool arguments/results are opt-in in the conventions and not needed for usage and spend attribution, so they are left for a follow-up behind an explicit deployment flag.gen_ai.client.token.usage,gen_ai.client.operation.duration), an aggregated token total on theinvoke_agentspan, a cost attribute, span links between subagent and parent traces, and correlation IDs with AI Gateway interceptions (an open question in the issue). Subagent turns join the parent only throughcoder.chat.root_id; a span link needs the spawning span context persisted across chats and runners. Spans carry tokens, not cost; cost stays in the existing cost API.Generated by Coder Agents on behalf of @f0ssel.