# Which invariants prevent GenAI span attribute collapse when tool-call, token-usage, and agent-invocation telemetry share one span **Date of Record:** 2026 November 24 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where a single span or span tree carries tool-call, token-usage, and agent-invocation attributes simultaneously. Does not apply to pure trace-only instrumentation without GenAI attributes, nor to metrics-only exporters where attribute aggregation is deferred to the backend. ## Core Distinction The GenAI semantic conventions define three attribute families that were designed against different cardinality and lifecycle assumptions: - **Tool-call attributes** (`gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.type`) are *per-invocation*, high-cardinality, and expected to appear on child spans of a tool execution. - **Token-usage attributes** (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) are *per-request*, low-cardinality, and expected to be set exactly once at span close. - **Agent-invocation attributes** (`gen_ai.agent.id`, `gen_ai.agent.name`, `gen_ai.operation.name`) are *per-agent-instance*, stable across a run, and expected to be set at span start. The failure mode is not that any one family is wrong. It is that when an agent runtime emits all three on the *same* span (the common "one span per agent turn" pattern), the attribute set becomes non-idempotent: late-arriving tool-call attributes overwrite earlier token-usage values, and re-entrant agent-invocation writes reset `gen_ai.operation.name` to a value inconsistent with the span's actual semantics. The invariant that prevents this is **attribute-family segregation by span lifecycle phase**: each family may only be written during a single, non-overlapping phase of the span's life, and the SDK must reject writes that violate phase ordering. ## What Was Observed A multi-tool agent (three tool calls per turn, streaming token usage) was instrumented with a single `gen_ai.operation.name = "chat"` span per model turn. Tool calls were recorded as child spans but the parent span's `gen_ai.tool.name` was also set on completion for convenience. Token usage was recorded via a streaming callback that accumulated `gen_ai.usage.output_tokens` incrementally. Observed trace pathology: 1. The parent span's `gen_ai.usage.output_tokens` was written *three times* (once per tool-call child completion callback that fired after the model returned). The final value was the last tool's partial count, not the model's total — a silent undercount of ~40%. 2. `gen_ai.tool.name` on the parent span ended up holding the *last* tool invoked, so backend queries grouping by `gen_ai.tool.name` attributed the entire model turn to that one tool. 3. On a retry after a transient 429, the agent re-entered the same span (span reuse across retry) and reset `gen_ai.operation.name` to `"execute_tool"`, producing a span whose `gen_ai.operation.name` contradicted its own `gen_ai.usage.*` attributes. The trace was syntactically valid — no OTel validation error — but semantically incoherent. Backend aggregations by tool name and by operation name disagreed with the actual execution graph by a factor that grew with retry count. ## Condition of Validity The segregation invariant holds only under the following conditions: - **Phase monotonicity:** a span's attribute writes must follow `START → (TOOL_CHILD) → USAGE_CLOSE → END`. Tool-call attributes may only be written while the span is in the `TOOL_CHILD` phase; token-usage attributes only in `USAGE_CLOSE`; agent-invocation attributes only at `START`. - **No span reuse across retries:** a retry must open a new span with a new `span_id` and a `gen_ai.request.retry_count` attribute, never mutate the prior span. Span reuse breaks phase monotonicity because `START` attributes are re-emitted after `USAGE_CLOSE`. - **Single writer per family:** exactly one instrumentation component may write each family. A streaming usage callback and a span-close hook both writing `gen_ai.usage.*` violates this even if both compute the same value, because the write ordering is nondeterministic. When any condition is violated, the span remains exportable but the attribute set no longer describes a single coherent operation. The failure is silent: no OTel error, no backend rejection, only degraded aggregation fidelity downstream. ## Decision Boundary The runtime must choose between two span topologies, and the choice is forced by whether the agent performs tool calls *within* a model turn: - If the model turn is a single request/response with no interleaved tools, a **flat span** with all three families is safe, because phases do not interleave. - If the model turn interleaves tool calls (the common ReAct pattern), a **span tree** is mandatory: the parent carries only agent-invocation and aggregate token-usage (written once at close); each tool call gets its own child span carrying tool-call and per-call token attributes. The parent must *not* carry `gen_ai.tool.name`. The boundary is crossed the moment a tool call is emitted before the model turn's usage is finalized. Detecting this requires the instrumentation to track phase state, not just attribute presence — a span that has seen a `gen_ai.tool.call.id` child but has not yet closed must reject `gen_ai.usage.*` writes on itself and route them to the child. ## Operational Effect Enforcing the invariant converts a silent aggregation error into a loud instrumentation error at the point of violation, which is the correct trade: a rejected attribute write during development is cheaper than a 40% token undercount discovered in a cost report. The practical effects are (a) token-usage totals become additive across the span tree rather than last-writer-wins on a single span, (b) `gen_ai.tool.name` grouping matches the actual call graph, and (c) retries produce distinct spans whose `gen_ai.request.retry_count` makes the amplification visible rather than collapsing it into one span's overwritten attributes. ```python from enum import Enum, auto class SpanPhase(Enum): START = auto() TOOL_CHILD = auto() USAGE_CLOSE = auto() END = auto() class AttributePhaseViolation(RuntimeError): """Raised when a GenAI attribute is written outside its permitted lifecycle phase.""" # Which phase each attribute family may be written in. PERMITTED_PHASE = { "gen_ai.agent.id": SpanPhase.START, "gen_ai.agent.name": SpanPhase.START, "gen_ai.operation.name": SpanPhase.START, "gen_ai.tool.name": SpanPhase.TOOL_CHILD, "gen_ai.tool.call.id": SpanPhase.TOOL_CHILD, "gen_ai.usage.input_tokens": SpanPhase.USAGE_CLOSE, "gen_ai.usage.output_tokens": SpanPhase.USAGE_CLOSE, } class GenAISpan: def __init__(self, span_id: str): self.span_id = span_id self.phase = SpanPhase.START self.attrs: dict[str, object] = {} self._usage_written = False def advance(self, new_phase: SpanPhase) -> None: order = [SpanPhase.START, SpanPhase.TOOL_CHILD, SpanPhase.USAGE_CLOSE, SpanPhase.END] if order.index(new_phase) <= order.index(self.phase): raise AttributePhaseViolation( f"span {self.span_id}: non-monotonic phase transition " f"{self.phase.name} -> {new_phase.name}" ) self.phase = new_phase def set_attribute(self, key: str, value: object) -> None: required = PERMITTED_PHASE.get(key) if required is None: self.attrs[key] = value return if required != self.phase: raise AttributePhaseViolation( f"span {self.span_id}: attribute {key} requires phase " f"{required.name} but span is in {self.phase.name}" ) if key.startswith("gen_ai.usage.") and self._usage_written and key in self.attrs: raise AttributePhaseViolation( f"span {self.span_id}: token-usage attribute {key} written twice " f"(last-writer-wins would corrupt aggregation)" ) self.attrs[key] = value if key.startswith("gen_ai.usage."): self._usage_written = True def emit_agent_turn(span: GenAISpan, tool_calls: list[str], usage: dict[str, int]) -> GenAISpan: span.set_attribute("gen_ai.operation.name", "chat") span.set_attribute("gen_ai.agent.id", "agent-7") if tool_calls: span.advance(SpanPhase.TOOL_CHILD) for i, tool in enumerate(tool_calls): child = GenAISpan(f"{span.span_id}-tool-{i}") child.set_attribute("gen_ai.tool.name", tool) child.set_attribute("gen_ai.tool.call.id", f"call-{i}") span.advance(SpanPhase.USAGE_CLOSE) span.set_attribute("gen_ai.usage.input_tokens", usage["input"]) span.set_attribute("gen_ai.usage.output_tokens", usage["output"]) span.advance(SpanPhase.END) return span def replay_retry(span: GenAISpan) -> None: # A retry that reuses the span would reset START-phase attributes after USAGE_CLOSE. if span.phase != SpanPhase.END: raise AttributePhaseViolation( f"span {span.span_id}: retry attempted before END; open a new span instead" ) span.set_attribute("gen_ai.operation.name", "execute_tool") ```