# How should an instance attribute a GenAI span to the model that actually answered when the tool call and the completion share one trace context **Date of Record:** 2026 November 22 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*` attributes) and that interleave model inference, tool invocation, and sub-agent handoffs within a single trace. Does not cover pure single-shot inference telemetry where one span maps to one provider call. ## Core Distinction The GenAI semantic conventions define attributes like `gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, and `gen_ai.usage.output_tokens` on a span that represents *one inference operation*. The conventions are explicit that `gen_ai.response.model` records the model that actually served the response, which may differ from `gen_ai.request.model` (routing, fallback, alias resolution). They are *not* explicit about what a span means when an agent orchestrator wraps a tool call and a completion inside a single logical "step." The non-obvious boundary is this: **a span whose `gen_ai.operation.name` is `chat` but whose duration encloses a tool call is not a valid GenAI inference span.** It is an agent-step span that happens to carry GenAI attributes. When the runtime conflates the two, token accounting and model attribution silently attach to the wrong wall-clock interval, and the span's `gen_ai.response.model` describes the model that *planned* the tool call, not the model that *consumed* the tool result. The invariant that must hold: *every span carrying `gen_ai.usage.*` tokens must enclose exactly the provider round-trip that produced those tokens, and no tool execution.* ## What Was Observed A coding agent emits one span per reasoning step. Each step: (1) call the model with the current transcript, (2) if the model returns a tool call, execute the tool, (3) append the tool result, (4) re-invoke the model. The runtime wraps all four phases in a single span `agent.step` with `gen_ai.operation.name = chat`. The failure trace, for a step where the model requested a 9-second `pytest` run: 1. Span starts. `gen_ai.request.model = "claude-sonnet-4"` set from the orchestrator's configured default. 2. Model call #1 returns a tool call. Provider reports `input_tokens = 8,200`, `output_tokens = 140`. Runtime accumulates into span attributes. 3. Tool executes for 9,100 ms. The span's duration now includes 9.1 s of subprocess time. 4. Model call #2 runs against a transcript that now includes 6,400 tokens of test output. Provider reports `input_tokens = 14,600`, `output_tokens = 90`. Runtime *adds* these to the same span: `input_tokens = 22,800`. 5. Span closes. `gen_ai.response.model` is set from call #2's response header — which, because the provider had failed over to `claude-sonnet-4-5` mid-step, differs from the request model. Downstream consequences observed in the trace store: - **Attribution skew:** the span's `gen_ai.response.model` names the second model, but 8,200 of the 22,800 input tokens were billed to the first. Per-model cost dashboards undercount the first model by 100% on this step. - **Latency poisoning:** the 9.1 s tool time inflates the `chat` span's p99. The model provider's own p99 is ~1.4 s; the trace store reports ~10.6 s for "model latency." SLO burn alerts fire on the inference path when the actual regression is in the tool sandbox. - **Cache-miss misdiagnosis:** call #2's input (14,600) is not a superset of call #1's (8,200) because the tool result replaced a truncation marker; the runtime's prompt-cache hit-rate computation assumes monotonic growth within a span and reports a spurious 0% hit rate. ## Condition of Validity The one-span-per-step model is only valid when the step contains exactly one provider round-trip and zero tool executions. It is *invalid* whenever any of the following hold within the span's lifetime: - More than one `gen_ai.request.model` value is observed (fallback, retry, or escalation). - More than one `gen_ai.response.model` value is observed. - Any child span with a non-`gen_ai.*` operation (tool, subprocess, HTTP fetch) overlaps the span's wall-clock interval. - `gen_ai.usage.input_tokens` is written more than once (accumulation across calls). A conforming emitter must detect these conditions at span close and refuse to emit the span as a GenAI inference span. The correct emission is: one `gen_ai.chat` span per provider call, with tool execution as a *sibling* span under the agent-step parent, and the agent-step span carrying no `gen_ai.usage.*` attributes at all. ## Decision Boundary The decision the runtime must make at span-close time is whether to emit the accumulated span as-is (fast, lossy) or to split it retroactively into per-call child spans (correct, requires buffering). The boundary is determined by the invariant above, evaluated as a predicate over the span's recorded events: - If the span recorded exactly one `gen_ai.request.model` write, one `gen_ai.response.model` write, and zero overlapping non-GenAI child spans → emit as a single GenAI span. Valid. - Otherwise → the accumulated attributes are *unattributable*. The runtime must either (a) have buffered per-call attributes at call time and emit child spans, or (b) mark the parent span with an explicit `gen_ai.attribution.status = "aggregated"` and drop `gen_ai.response.model` entirely, because naming one model would be a lie. Option (b) is the safe degradation when buffering was not implemented. The critical rule: **never emit `gen_ai.response.model` on a span that saw more than one response.** A missing attribute is recoverable; a wrong one propagates into cost allocation, routing policy, and eval dashboards and is not recoverable without replay. ## Operational Effect Once the invariant is enforced, three second-order effects appear that are easy to miss: 1. **Span cardinality rises.** A 40-step agent run that previously emitted 40 spans now emits ~120 (40 step parents, ~80 chat children, plus tool spans). Trace backends with per-trace span caps (commonly 1,000) start truncating long runs. The cap must be raised or the step parent must be sampled out while children are kept — which inverts the usual head-sampling assumption. 2. **Parent-child duration no longer sums.** The step parent's duration now legitimately exceeds the sum of its chat children by exactly the tool time. Dashboards that computed "model time as fraction of step time" by summing children must be rewritten to subtract tool spans explicitly, or they will report the fraction as <100% and trigger false "overhead" alerts. 3. **Fallback is now visible as two spans, not one.** A step that fell back from `claude-sonnet-4` to `claude-sonnet-4-5` produces two chat children with different `gen_ai.response.model` values. This is the *desired* signal — it is what makes per-model cost attribution correct — but it means any consumer that assumed one chat span per step (e.g., a replay harness that re-issues the step's recorded request) will now see two requests and must replay both in order, preserving the tool result between them. The final guardrail: the runtime must treat attribution as a *close-time assertion*, not a best-effort write. If the assertion fails, the span is emitted in degraded form and a counter is incremented, so that the fraction of unattributable spans is itself a monitored metric. ```python from dataclasses import dataclass, field from typing import Optional class GenAIAttributionError(RuntimeError): """Raised when a span cannot be validly attributed to a single model round-trip.""" @dataclass class GenAISpan: name: str request_models: list[str] = field(default_factory=list) response_models: list[str] = field(default_factory=list) input_tokens: int = 0 output_tokens: int = 0 overlapping_tool_ms: float = 0.0 attribution_status: Optional[str] = None def record_request(self, model: str, input_tokens: int) -> None: self.request_models.append(model) self.input_tokens += input_tokens def record_response(self, model: str, output_tokens: int) -> None: self.response_models.append(model) self.output_tokens += output_tokens def record_tool_overlap(self, ms: float) -> None: self.overlapping_tool_ms += ms def finalize_genai_span(span: GenAISpan, strict: bool = True) -> GenAISpan: """ Enforce the attribution invariant at span close: - exactly one request model and one response model - zero overlapping tool execution - tokens written once (single round-trip) If violated, either raise (strict) or degrade by stripping gen_ai.response.model so no false attribution is emitted. """ distinct_req = set(span.request_models) distinct_resp = set(span.response_models) violations = [] if len(distinct_req) > 1: violations.append(f"multiple request models: {sorted(distinct_req)}") if len(distinct_resp) > 1: violations.append(f"multiple response models: {sorted(distinct_resp)}") if span.overlapping_tool_ms > 0.0: violations.append(f"tool overlap {span.overlapping_tool_ms:.1f}ms inside GenAI span") if len(span.request_models) > 1 or len(span.response_models) > 1: violations.append("token attributes accumulated across >1 round-trip") if not violations: span.attribution_status = "single_round_trip" return span if strict: raise GenAIAttributionError( "GenAI span cannot be attributed to a single model round-trip: " + "; ".join(violations) + ". Split into per-call child spans or emit with attribution_status='aggregated'." ) # Degraded emission: keep tokens (they are real), drop model attribution. span.response_models = [] span.attribution_status = "aggregated" return span def emit_agent_step(spans: list[GenAISpan], strict: bool = True) -> list[GenAISpan]: out = [] for s in spans: out.append(finalize_genai_span(s, strict=strict)) return out ```