Skip to content

feat(cli): genai span attributes checked against the pinned semantic conventions #588

Closed

Description

@dan-petty

Context & Rationale

SpanHandle.record_llm_metrics (telemetry/tracer.py:436-471) says it records "standard OpenTelemetry GenAI attributes" (:450), but it names no convention and nothing checks it. At ef21785, src/ holds 36 distinct gen_ai.* string literals: 34 attribute keys and two span names, gen_ai.chat (ai/client/unified.py:683) and gen_ai.stream (:783). Emitters:

  • ai/client/unified.py:64-103,360-375,455,485-494,556-558,682-690,759,782-810,850
  • ai/client/structured.py:238-243
  • ai/direct.py:105,150,195,228
  • telemetry/tracer.py:451-471

The GenAI conventions now live in open-telemetry/semantic-conventions-genai. It has no tagged release (0 tags on 2026-10-01; HEAD b31e9e8, 2026-09-30). Its model/gen-ai/registry.yaml defines 79 attribute keys, and model/gen-ai/metrics.yaml defines metric names under the same prefix, such as gen_ai.client.operation.duration (:21). Its model/manifest.yaml depends on core semantic-conventions v1.44.0, which defines server.address and server.port. Our 34 keys compare to the registry as follows:

  • 8 are current: operation.name, request.model, request.temperature, request.top_p, response.finish_reasons, response.model, usage.input_tokens and usage.output_tokens.
  • 3 were renamed: gen_ai.system is now gen_ai.provider.name, and gen_ai.usage.prompt_tokens and gen_ai.usage.completion_tokens are now input_tokens and output_tokens.
  • 23 are private keys in the convention's namespace, such as gen_ai.request.priority, gen_ai.ttft_seconds and gen_ai.usage.cost_usd.
  • gen_ai.provider.name is never emitted (grep -rn gen_ai.provider.name src: 0). The inference span requires it (spans.yaml:171, gen_ai.inference.client, and :260-262).

The installed opentelemetry-semantic-conventions 0.65b0 is not a usable oracle. It comes in through opentelemetry-sdk and is not declared in pyproject.toml. It defines 11 of our 34 keys and marks all 11 deprecated: 3 renamed and 8 "moved to the GenAI repository". It is also behind the GenAI repository. For example, it still lists gen_ai.usage.cache_creation.input_tokens, which the GenAI registry now names gen_ai.usage.cache_write.input_tokens (registry.yaml:308).

Weaver v0.26.1 is the version the GenAI repository pins (versions.env). weaver registry resolve is deprecated there ("use 'weaver registry generate' or 'weaver registry package' instead", docs/usage.md:60-61). weaver registry package needs the registry's manifest.yaml and writes resolved.yaml and manifest.yaml to its output directory (src/registry/package.rs:146-147). PyYAML is already a pinned dependency (pyproject.toml:21).

Some keys are written twice, and some values are wrong:

  • Old and new token keys are written together (tracer.py:457-462, unified.py:92-97). Two token-rate keys are also written together (tracer.py:469-471, unified.py:70-75).
  • gen_ai.server.address holds the backend_info display string, such as ollama (localhost:11434), not a host (unified.py:87). _extract_server_from_backend_info (unified.py:55-61) returns the text inside the parentheses. That is a netloc such as localhost:11434, so the port still has to be split off. On the stream path it reads self.backend_info (:831), which lists every configured Ollama host, comma-joined (:255).
  • gen_ai.response.model holds backend_info on the wrapper span (unified.py:487) or the literal "cache" (:556). The inference span already writes res.model (:91), which comes from the provider's reply (ollama.py:380, claude.py:117, openai.py:150).
  • Every LLM span is INTERNAL, the trace_span default (tracer.py:1377). The convention's inference span is CLIENT, and tracer.py:132-137 already supports client.
  • record_llm_metrics has no caller in src/. Only tests/test_telemetry.py:268-302,579-598 call it, and :295-302 pin the renamed and private keys as "GenAI standard attributes".
  • The chat-path test stub (tests/test_ai_request_priority.py:185) returns no token counts and a backend_info with no port, so today no test sees usage keys or a port on an LLM span.

Logfire: instrument_pydantic_ai() (telemetry/logfire.py:217) turns on pydantic-ai's instrumentation. Pydantic-ai writes gen_ai.provider.name and still writes gen_ai.system beside it (pydantic-ai 2.35.0, _instrumentation.py:287-288). Its spans are bridged into the same internal span buffer as our own spans (LogfireOTelBridgeProcessor, logfire.py:39-86). Nothing calls the pydantic-ai paths (ai/direct.py) at runtime yet (see #606), so the clash between the two vocabularies is latent, not live.

Nothing outside tests reads these keys. grep -rn gen_ai k8s docs/TELEMETRY.md finds nothing. docs/ROADMAP.md and the task files for #588, #590, #598, #599 and #606 mention them only as planning text. Tests read them in tests/test_telemetry.py and tests/test_ai_request_priority.py:202. tests/test_pydantic_ai_result.py:65-66 reads pydantic-ai's own RunUsage keys, which this item does not change. Hand-written mappings like _ATTRIBUTE_NORMALIZATION (tracer.py:668-689, no GenAI entries) are how the keys drifted. vibes hit the same defect (observations/systems/19-self-consistency-is-not-conformance.md): every collector accepted its private vocabulary in a valid envelope, and no GenAI-aware backend could chart it. vibes fixed it with a snapshot pinned to a commit (tools/semconv_snapshot.py).

Scope & Deliverables

Deliverable: one PR that does three things. It pins the GenAI conventions, checks every gen_ai.* literal in src/ against them inside the gate, and renames the emitters so the check passes.

  1. Snapshot. src/devops_cli/telemetry/semconv_genai.json, committed. It holds:
    • source: the repo, a 40-hex commit and the weaver version;
    • attributes: every non-deprecated attribute key in the resolved registry. That is the gen_ai.* keys plus the core keys the registry references, such as server.address. The reducer does not filter by prefix;
    • metrics: every non-deprecated metric name;
    • spans: each span type's kind and required attributes.
      Lists are sorted. Only this reduced table is committed, never raw weaver output.
  2. Refresh. devops telemetry semconv refresh --commit <sha> runs weaver registry package --v2 -r https://github.com/open-telemetry/semantic-conventions-genai.git@<sha>[model] -o <tmp>. It reads <tmp>/resolved.yaml with PyYAML, reduces it and rewrites the snapshot. The weaver call uses an argument list and a bounded timeout. It writes nothing and exits non-zero when weaver is not on PATH, when --commit is not a 40-hex SHA, or when weaver fails or times out. A person runs it; the gate never does.
  3. Check. A test in the gate reads the raw text of src/devops_cli/**/*.py, comments and docstrings included. It finds quoted strings that start with gen_ai.. It fails, naming file:line, on any that is not a current attribute key or metric name in the snapshot, and on any f-string that starts with gen_ai. (a dynamic key).
  4. Rename, with no key written twice. Apply the table below.
    • Delete record_llm_metrics.
    • _set_response_span_attributes (unified.py:84, called at :427) becomes the only writer of gen_ai.usage.*, gen_ai.response.model and gen_ai.response.finish_reasons, and it writes them only on ai.llm.dispatch. On the stream span, _record_first_token (:752-760) writes gen_ai.response.time_to_first_chunk.
    • _record_chat_telemetry (:485) keeps only llm.cached, llm.wall_seconds and llm.processing_seconds on its wrapper span, so a request's usage is counted once.
  5. Inference spans. Create ai.llm.dispatch (unified.py:377) and the stream span with kind="client".
    • Both carry gen_ai.operation.name="chat", gen_ai.provider.name and gen_ai.request.model.
    • server.address is the host part of the netloc. server.port is set when the netloc has a port. Neither is set when the backend lists several hosts or is cache.
    • The stream span also carries gen_ai.request.stream=true and gen_ai.response.time_to_first_chunk.
  6. Docs.
    • Add a short "LLM span attributes" section to docs/TELEMETRY.md. It names the pinned commit, the llm.* prefix for private keys and the refresh command.
    • Add a CHANGELOG entry that lists every old key and its new name, so people can update external queries.
    • Rewrite the task file docs/agent/tasks/task-588-*.md to match this body. It still says v0.2.24 and two PRs.

Rename table (proposed):

Today Becomes
gen_ai.system gen_ai.provider.name: claude becomes anthropic; other provider ids are unchanged
gen_ai.usage.prompt_tokens, gen_ai.usage.completion_tokens removed; only gen_ai.usage.input_tokens and gen_ai.usage.output_tokens remain
gen_ai.usage.total_tokens removed (it is input plus output)
gen_ai.server.address (holds backend_info) server.address (host) and server.port (int), split from the netloc that _extract_server_from_backend_info returns, for example with urllib.parse.urlsplit("//" + netloc)
gen_ai.response.model = backend_info or "cache" gen_ai.response.model = res.model when known, otherwise unset
gen_ai.ttft_seconds, gen_ai.time_to_first_token_ms gen_ai.response.time_to_first_chunk (seconds)
gen_ai.tokens_per_second, gen_ai.token_rate_tok_per_sec llm.tokens_per_second
gen_ai.wall_seconds, gen_ai.processing_seconds llm.wall_seconds, llm.processing_seconds (already used, unified.py:79-81)
gen_ai.duration_seconds removed with record_llm_metrics
gen_ai.server.served_by llm.served_by
gen_ai.usage.cost_usd llm.usage.cost_usd
gen_ai.cached llm.cached
gen_ai.request.priority llm.request.priority
gen_ai.request.enable_thinking, gen_ai.enable_thinking llm.request.enable_thinking
gen_ai.request.message_count, gen_ai.messages_count llm.request.message_count
gen_ai.request.system_prompt_length llm.request.system_prompt_length
gen_ai.prompt_preview, gen_ai.response_preview llm.prompt_preview, llm.response_preview
gen_ai.thinking llm.response.thinking
gen_ai.sanitize llm.stream.sanitize
gen_ai.stream_chunks_count llm.stream.chunk_count
span gen_ai.chat, span gen_ai.stream ai.llm.chat, ai.llm.stream

Acceptance criteria:

  1. Snapshot shape. source.repo is open-telemetry/semantic-conventions-genai, source.commit is 40 hex characters and source.weaver is set. attributes includes gen_ai.provider.name, gen_ai.response.time_to_first_chunk and server.address, and excludes gen_ai.system. metrics includes gen_ai.client.operation.duration. spans["gen_ai.inference.client"] has kind client, and its required list includes gen_ai.operation.name and gen_ai.provider.name. Verified by a unit test with tuple assertions.
  2. Reducer. It is fed a trimmed resolved.yaml that the PR author produced once with weaver registry package --v2 (weaver v0.26.1), committed under tests/fixtures/. The fixture holds at least one deprecated attribute and one deprecated metric. The reducer drops both, returns sorted output and gives identical bytes on two runs. Verified by a unit test that starts no subprocess and makes no network call.
  3. Refusal. In each of these cases, refresh exits non-zero with a message naming the cause and leaves the snapshot unchanged:
    • shutil.which("weaver") is monkeypatched to return None;
    • --commit main is passed;
    • a stubbed weaver run fails;
    • a stubbed weaver run times out.
      Verified by CLI-runner unit tests.
  4. Check. The scan test passes on the PR. Given a tmp_path source, it fails and names file:line for each of "gen_ai.system", f"gen_ai.{x}" and a comment # was "gen_ai.system". It passes for "gen_ai.client.operation.duration". Verified by unit tests. The scan over src/ takes under 1 s, measured with pytest --durations.
  5. Inference spans. Both tests capture the OTLP payload by patching _send_payload, as tests/test_ai_request_priority.py:168-170 does, and assert with tuples.
    • Chat. Drive LLMClient.chat with _ollama_messages stubbed (as in tests/test_ai_request_priority.py:166-202) to return LLMResponse("OK", backend_info="ollama (example.com:11434)", model="test-model", prompt_tokens=12, completion_tokens=3, total_tokens=15). Assert that ai.llm.dispatch is SPAN_KIND_CLIENT and carries every attribute the snapshot lists as required for gen_ai.inference.client. Assert that its (server.address, server.port, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.response.model) equal ("example.com", 11434, 12, 3, "test-model"). Assert that ai.llm.chat is SPAN_KIND_INTERNAL and has no key that starts with gen_ai.usage. or gen_ai.response..
    • Stream. Drive chat_messages_stream with _dispatch_stream stubbed and one Ollama URL, http://example.com:11434. Assert that ai.llm.stream is SPAN_KIND_CLIENT, carries every required attribute, has (server.address, server.port) equal to ("example.com", 11434), has gen_ai.request.stream set to true and has gen_ai.response.time_to_first_chunk as a float. With two Ollama URLs configured, assert that server.address and server.port are absent.
  6. Removed code. grep -rn record_llm_metrics src tests finds nothing. tests/test_telemetry.py:268-302,579-598 are deleted or rewritten against _set_response_span_attributes, and tests/test_ai_request_priority.py:202 asserts llm.request.priority. These test changes land in the same commit as the code. Verified by grep and uv run devops ci.
  7. Gate. uv run devops ci passes. That includes docs check with the CLI reference regenerated for devops telemetry semconv refresh. The new tests add under 1 s in total, measured with pytest --durations.
  8. Person-run check (needs network and weaver v0.26.1 on PATH). Run uv run devops telemetry semconv refresh --commit "$(jq -r .source.commit src/devops_cli/telemetry/semconv_genai.json)", then git diff --exit-code src/devops_cli/telemetry/semconv_genai.json. It shows no change.
  9. Docs. docs/TELEMETRY.md has the new section, the CHANGELOG lists each old key and its new name, and the task file matches this body. Checked in review.

Key questions:

  1. What is the oracle? The GenAI repository at a pinned commit, resolved by weaver. Not the installed package: it marks every key it has as deprecated, and it is behind the GenAI repository (cache_creation versus cache_write). (proposed)
  2. Which weaver command? weaver registry package --v2, reading resolved.yaml from its output directory. weaver registry resolve, which the earlier draft named, is deprecated (weaver PR feat(release): v0.2.27 #1255; docs/usage.md:60-61 at v0.26.1). If weaver cannot fetch a bare SHA through .git@<sha>[model], use the GitHub archive URL for that SHA, which weaver also accepts. (proposed)
  3. Weaver on PATH only, or also the otel/weaver image? PATH only, refusing otherwise with the release URL. Refresh is rare and run by a person, and one way of running it is simpler to test. Upstream pins v0.26.1 (versions.env), and the snapshot records the version used. (proposed)
  4. Which commit to pin first? GenAI repository HEAD when the PR is built (b31e9e8 on 2026-09-30), not vibes' older 8ffdf568. (proposed)
  5. A separate devops ci verify step, or a pytest test? A pytest test. A new step would start the CLI, which costs about 5 to 6 s CPU cold on this checkout (devops telemetry --help), against the 5-minute budget. A regex over the 484 source files takes about 0.06 s, or under 0.6 s including interpreter start. Parsing every file with ast took 1.5 to 7.4 s across runs under load, so the test uses a regex. (proposed)
  6. Should the snapshot carry renamed-key hints? No. The check needs only membership in the current key set. "Moved" keys are current in the GenAI repository, so they pass without a special rule, and renamed keys fail. vibes found that 58 of 60 upstream deprecations say reason: uncategorized, so hints would need prose parsing. The rename table above covers today's keys. (proposed)
  7. Write usage through pydantic-ai's RunUsage.opentelemetry_attributes()? No, for three reasons. It writes gen_ai.usage.cache_creation.input_tokens (pydantic-ai 2.35.0, usage.py:228), which the GenAI registry no longer defines. It drops zero counts. And keys written inside a dependency are invisible to the src/ scan. Write the two token keys directly. (proposed)
  8. Where do the private keys go? Under llm.*, the prefix this code already uses for private timing keys (unified.py:67,77,79,81). OTel defines no llm namespace; 0.65b0 has no llm.* attribute. (proposed)
  9. Adopt the convention's {operation} {model} span name? No. Keep fixed names outside gen_ai.; the operation travels in gen_ai.operation.name and the CLIENT kind. Fixed names keep lookups such as tests/test_ai_request_priority.py:196 stable. Only the two spans that make the request are inference spans. The wrapper spans (ai.llm.chat, ai.client.chat_structured and pydantic_ai.direct.*) stay INTERNAL and do not set gen_ai.operation.name, so each call is counted once. (proposed)
  10. Which gen_ai.provider.name values? Map claude to anthropic. That is the convention's well-known value (registry.yaml:29-32), it is what pydantic-ai writes, and the convention refines the inference span for it (anthropic.inference.client, a span refinement at spans.yaml:842). Pass ollama, openai, gateway, copilot and github_copilot through unchanged; the convention allows custom values. The existing provider attribute (unified.py:369) keeps our own id. (proposed)
  11. Wire up record_llm_metrics or delete it? Delete it. It has no caller, and before 1.0 the codebase keeps no shims. This also settles the same sub-task in feat(ai): ollama model residency per-pod model budget, keep-alive, ms/token #598. (proposed)
  12. Fix gen_ai.response.finish_reasons, which is hard-coded to ["stop"] (unified.py:101), here? No. feat(ai): finish reasons and stream completeness for model replies #599 (v0.2.25) reads real finish reasons. The key itself is current, so the check passes. (proposed)
  13. Declare opentelemetry-semantic-conventions in pyproject.toml? No. Nothing imports it, and server.address and server.port are written as literals. (proposed)
  14. Do GenAI metrics (gen_ai.client.token.usage, gen_ai.client.operation.duration) belong here? No; this item covers span attributes only. The snapshot does list the convention's metric names, so a metric named from it passes the check. feat(ai): ollama model residency per-pod model budget, keep-alive, ms/token #598 adds a time-per-output-token histogram named from the convention. (proposed)
  15. Who reads the old keys? Nothing outside tests: k8s/, docs/TELEMETRY.md and the dashboards have 0 hits. External saved queries in Jaeger or Logfire will break, and the CHANGELOG entry lists every rename. (proposed)
  16. Do comments and docstrings count in the scan? Yes. The regex reads raw text, and old names belong only in the CHANGELOG. This keeps the scan to one rule with no exemptions. (proposed)
  17. What if the netloc has no port, as for api.anthropic.com? Leave server.port unset. backend_info drops the URL scheme, so a default port would be a guess. The convention makes server.port conditionally required when server.address is set, so this is a known gap for default-port endpoints; carrying the scheme in backend_info is out of scope. (proposed)

Constraint:

  • The check has no allowlist, prefix exemption or "known violations" list. A hand-written table is how these keys drifted.
  • An old key is never kept beside its replacement.
  • Tests never touch the network and never run weaver. Only a person runs refresh.
  • The weaver call uses an argument list and a bounded timeout (AGENTS.md:43).
  • New tests use structural tuple assertions (until test(cli): retire the tuple-assert mandate and detect opaque tuple asserts and presence-only tests #851 settles that) and add at most 1 s to the gate.

Strategic Alignment

Activity

  1. added this to the v0.2.23 milestone on Sep 25, 2026
  2. added
    type/feature
    scope/cli
    priority/p1-high
    on Sep 25, 2026
  3. modified the milestones: v0.2.23, v0.2.24 on Sep 28, 2026
  4. modified the milestones: v0.2.23, v0.2.25 on Oct 1, 2026
  5. dan-petty commented on Oct 1, 2026

    @dan-petty
    OwnerAuthor

    Retargeted from the shipped v0.2.23 to v0.2.25. It is still valid (checked 2026-10-01), and a P1 left open in a shipped release keeps precedence over P1 work committed later.

  6. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Closed by #941, merged into release/v0.2.25.

    GitHub only acts on closing keywords when a pull request merges into the default branch, so this was closed by devops gh issues close-merged.

  7. added a commit that references this issue on Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/clitype/feature

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions