Skip to content

feat: adopt OpenTelemetry GenAI semantic conventions for Coder Agents traces - #32411

Merged
f0ssel merged 21 commits into
mainfrom
garrett/codagt-1523-adopt-opentelemetry-genai-semantic
Nov 24, 2026
Merged

f0ssel merged 21 commits into
mainfrom
garrett/codagt-1523-adopt-opentelemetry-genai-semantic

Conversation

@f0ssel

@f0ssel f0ssel commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

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

  • Span names follow the conventions: chat_turn becomes invoke_agent coder, stream becomes chat {model}, and tool_call becomes execute_tool {tool}. Every stage span now carries a stage attribute with the old stage name, which matches the Prometheus stage label. Metrics are unchanged.
  • GenAI spans carry gen_ai.operation.name, gen_ai.conversation.id (the chat ID), user.id (the chat owner), and coder.organization.id, coder.workspace.id, coder.chat.parent_id, coder.chat.root_id.
  • chat spans are CLIENT spans with the provider, request model, and gen_ai.request.stream set 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=json for native OpenAI structured output, and token usage with cache read/write (only when nonzero) and reasoning breakdown. gen_ai.usage.input_tokens includes cached tokens, as the spec requires. Fantasy reports them separately (Google providers use the OpenAI-compatible client, which does the same).
  • execute_tool spans carry the tool name, call ID, and type (function for built-in tools, extension for MCP and caller tools), all set at creation.
  • Every model call records a chat span: assistant streams (stage=stream), and, as stage=model_call, the advisor, compaction summaries plus titles, status labels, and chat summaries (via StageTracer.TraceModelCalls in resolveModelCall). model_call has no histogram, so the stream metric is unchanged.
  • Failed spans get error.type. A tool that returns an error result, as MCP clients do for an unreachable server, ends its span with error.type=tool_error without recording the result text.
  • GenAI attributes carry metadata only; prompts, responses, and tool payloads are not recorded. The docs note that other spans and events in the trace, such as AI Gateway spans and server log events, can contain content.
  • Docs state known limits: Anthropic server-tool responses undercount input tokens in both spans and AI Gateway cost control (the client keeps first-iteration occupancy), the OpenAI-compatible client drops reported cache writes, request attributes are what Coder requested, and the exporter is OTLP/gRPC, plaintext unless a certificate is configured.
  • New docs page: docs/coder-agents/platform-controls/opentelemetry-tracing.md.
  • coderd/x/chatd/ARCHITECTURE.md gains 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 the stage attribute or the new names.

Decision log
  • Convention version: semconv v1.41.0, the last core release that ships the GenAI attributes. Later releases moved them to semantic-conventions-genai. The PR uses the Go constants from go.opentelemetry.io/otel/semconv/v1.41.0, which is already in the module graph. No experiment gate: chatd is already under x/, and the docs page notes that the conventions may change.
  • Rename vs. attributes only: spans are renamed because the conventions define the span names. The stage attribute keeps lifecycle identity stable for dashboards and tests.
  • Agent name: gen_ai.agent.name=coder for root chats and subagents alike. chat_kind and coder.chat.parent_id tell them apart.
  • Provider name mapping: configured provider type to well-known values (openai, anthropic, azure.ai.openai, aws.bedrock, gcp.gemini). Anthropic providers with Bedrock settings report aws.bedrock. The invoke_agent span gets the provider after prepare resolves the turn's model, since the turn span starts first. Other types (openrouter, openai-compat, vercel, copilot) are passed through as-is.
  • No content capture: 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.
  • Out of scope: GenAI metrics (gen_ai.client.token.usage, gen_ai.client.operation.duration), an aggregated token total on the invoke_agent span, 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 through coder.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.
  • Identity snapshot: chat identity is taken when the turn opens. A workspace created mid-turn appears on spans from the next turn.

Generated by Coder Agents on behalf of @f0ssel.

… 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
@linear-code

linear-code Bot commented Nov 18, 2026

Copy link
Copy Markdown

CODAGT-1523

@f0ssel

f0ssel commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T13:29:52.245272Z 21f9eb4 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment thread coderd/x/chatd/ARCHITECTURE.md Resolved
Comment thread coderd/x/chatd/chatloop/genai.go Resolved
Comment thread coderd/x/chatd/chatloop/chatloop.go Resolved
…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.
@f0ssel

f0ssel commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment thread coderd/x/chatd/chatloop/chatloop.go Resolved
Comment thread coderd/x/chatd/chatloop/chatloop.go Resolved
Comment thread coderd/x/chatd/chatloop/genai.go Resolved
Comment thread coderd/x/chatd/chatloop/genai.go Resolved
Comment thread coderd/x/chatd/chatloop/stage.go Resolved
Comment thread coderd/x/chatd/chatloop/stage.go Resolved
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.
@f0ssel

f0ssel commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment thread coderd/x/chatd/chatloop/genai.go Resolved
Comment thread coderd/x/chatd/chatloop/chatloop.go Resolved
@f0ssel

f0ssel commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment thread coderd/x/chatd/chatloop/genai.go Resolved
Comment thread coderd/x/chatd/chatloop/genai.go Resolved
@f0ssel

f0ssel commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment thread coderd/x/chatd/chatloop/genai.go Resolved
Comment thread coderd/x/chatd/chatloop/chatloop.go Resolved
@f0ssel

f0ssel commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

@codex review

@f0ssel

f0ssel commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment thread coderd/x/chatd/modelcall.go Resolved
Comment thread coderd/x/chatd/chatloop/compaction.go Resolved
@f0ssel

f0ssel commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: e1c43b94d0

ℹ️ 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".

@f0ssel
f0ssel marked this pull request as ready for review November 20, 2026 15:27
@f0ssel
f0ssel requested a review from mafredri November 20, 2026 15:27
@f0ssel
f0ssel requested a review from cstyan November 20, 2026 15:27
@f0ssel

f0ssel commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Tagging @cstyan as a secondary reviewer to check for any bad OTEL patterns

@f0ssel f0ssel assigned garrettatcoder and unassigned f0ssel Nov 20, 2026

@mafredri mafredri left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@f0ssel

f0ssel commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 21f9eb483b

ℹ️ 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".

@f0ssel
f0ssel requested review from mafredri and removed request for cstyan November 23, 2026 20:10

@mafredri mafredri left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@f0ssel

f0ssel commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

@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:

  • GenAI-convention agent spans, inference spans with token usage, and GenAI attributes ("Agent spans", "Model inference spans and token usage", "GenAI attribute definitions")
  • Per-user model usage and spend ("get Otto's per-user model usage and spend metrics into our telemetry pipelines & stores")
  • Client-side instrumentation, so they still see cases "where clients are unable to reach gateways or tools"

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 mcp_input attributes, and Gateway cost accounting having the same Anthropic gap) are still open, and I'll address them separately.

(Coder Agents on behalf of @f0ssel)

@f0ssel

f0ssel commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

@mafredri addressed both P2 documentation findings in ebabef1:

  • Gateway cost accounting: in scope, since the customer asked for per-user usage and spend. The token-limit section now says AI Gateway cost control has the same Anthropic gap, so it no longer recommends it as the fix. It also attributes both gaps to the client rather than the provider: Anthropic reports cumulative input and OpenRouter reports cache writes, but the client drops them.
  • mcp_input on Gateway spans: content handling is outside what the customer asked for, so I did not add filtering guidance. Instead I removed the content-filtering advice I had added. The page now only says gen_ai.* attributes contain metadata only, and that other spans and events in the trace, such as AI Gateway spans and server log events, can contain parts of that content. That removes the inaccurate guarantee without expanding scope.

(Coder Agents on behalf of @f0ssel)

@f0ssel
f0ssel requested a review from mafredri November 24, 2026 15:37
@f0ssel
f0ssel merged commit 74a15cb into main Nov 24, 2026
34 checks passed
@f0ssel
f0ssel deleted the garrett/codagt-1523-adopt-opentelemetry-genai-semantic branch November 24, 2026 16:41
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 24, 2026

This branch had an error being deployed

1 failed and 1 inactive (outdated) deployments
docs-preview — ebabef18 Deployed Nov 24, 2026 by f0ssel via cleanup #428
main — e1c43b94 Deployed Nov 20, 2026 by f0ssel via cla #261277
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants