# Which invariants prevent tool-call span attribute collapse when a single agent span fans out to multiple provider LLM calls **Date of Record:** 2026 November 24 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions where one logical agent step (a `gen_ai.agent`/`invoke_agent` span) issues multiple nested model calls and tool calls, some of which are retried, cached, or routed to fallback providers. Does not apply to single-shot inference spans with one model call and no tool fan-out. ## Core Distinction The GenAI semantic conventions define attributes like `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and `gen_ai.tool.name` at the *model-call span* level. The failure mode examined here is not "attributes are missing" but **attribute collapse**: when a parent agent span aggregates child model-call spans, the aggregator (whether an SDK helper, a collector processor, or a homegrown span processor) writes a single scalar value into the parent for attributes that are only meaningful per-child. The parent ends up claiming `gen_ai.request.model = "gpt-4o"` when two of its five children actually ran on a fallback model, and `gen_ai.usage.input_tokens` reflects only the last child rather than the sum—or worse, the sum of *retried* attempts including duplicate billing. The distinction that matters: **provenance and token accounting are per-attempt facts, not per-agent-step facts.** Any invariant that treats them as aggregable scalars on the parent is wrong. The correct invariant is that per-attempt attributes are only valid on leaf spans, and the parent may carry only *derived, explicitly-named* aggregates (e.g., `agent.llm_calls.count`, `agent.usage.input_tokens.total`) that cannot be confused with the leaf attribute namespace. ## What Was Observed A research agent performing a "summarize and cite" task made 6 model calls per user request: 1 planning call, 3 retrieval-augmented synthesis calls, 1 self-critique call, 1 final answer call. During a provider incident, calls 3 and 4 failed with 429 and were retried against a secondary provider (`claude-3-5-sonnet` instead of `gpt-4o`). The instrumentation emitted: - 6 child spans under one `invoke_agent` parent. - Child spans 3a, 3b (retry), 4a, 4b (retry) carried `gen_ai.request.model` of both providers. - The parent span, produced by a span processor that did `parent.set_attribute("gen_ai.request.model", child.attributes["gen_ai.request.model"])` in `on_end`, ended up with the model of whichever child ended *last*—the critique call, `gpt-4o`. Downstream consequences observed in the trace store: 1. **Provenance corruption.** A cost-attribution job grouped by parent `gen_ai.request.model` and attributed 100% of the step's cost to `gpt-4o`, undercounting the fallback provider by ~38% of actual spend for the incident window. 2. **Token double-count.** The parent's `gen_ai.usage.input_tokens` was set to the last child's value (1,412), not the sum (11,847 including retries, 9,203 excluding retried failures). Two independent dashboards disagreed about the same step by 8×. 3. **Tool-call attribution drift.** The `gen_ai.tool.name` attribute on the parent—written by the same last-write-wins loop—showed `search` (the last tool called) even though the step invoked `search`, `fetch`, and `cite`. A "which tools are used most" query returned only `search` for every agent step, because `search` happened to be last in the majority of traces. The root trigger: the span processor's aggregation assumed **one child per parent**, which held in the original single-call agent design and silently broke when the agent was upgraded to multi-call fan-out. No error was raised; the trace remained valid OTLP. ## Condition of Validity The invariant "per-attempt attributes may be aggregated onto the parent" is valid only under all of: - **Cardinality one:** exactly one child model-call span per parent agent span, with no retries, no fallback, and no parallel tool fan-out. - **Homogeneous provenance:** all attempts share the same `gen_ai.request.model` and `gen_ai.response.model` (which also requires the provider not to silently substitute models server-side). - **No duplicate attempts:** retried failed calls are not represented as separate spans, or are represented but excluded from accounting. When any of these is false—retries, fallback routing, parallel tool calls, or multi-step reasoning within one agent span—the aggregate is not a faithful summary and must not be written into the leaf attribute namespace. The moment an agent can fan out, the invariant is already violated; the fix is architectural, not a patch to the aggregation loop. ## Decision Boundary The operational decision is whether to (a) keep the parent span as an aggregate and define a **separate, namespaced aggregate attribute schema** with explicit semantics, or (b) make the parent span carry *no* per-attempt attributes and force all consumers to traverse children. Choose (a) only if you also enforce these guardrails: - Aggregates use a distinct prefix (`agent.usage.*`, `agent.models.*`) that cannot collide with `gen_ai.*` leaf attributes. - Model provenance on the parent is a **set**, serialized as a sorted array (`agent.models.requested = ["gpt-4o","claude-3-5-sonnet"]`), never a scalar. - Token totals explicitly state whether retried attempts are included, via `agent.usage.attempts_included` (bool) and `agent.usage.attempts_total`. - A validator rejects any parent span that carries a leaf-namespaced `gen_ai.request.model` or `gen_ai.usage.*` attribute when child count > 1. Choose (b) if consumers cannot be trusted to respect the namespacing; it is the safer default for cost and provenance pipelines. The boundary is: **the parent span may summarize, but never impersonate a leaf.** Any attribute whose meaning is "this specific model call" must not appear on a span that represents more than one model call. ## Operational Effect With the guardrail in place, three things change: 1. Cost attribution must join on child spans, not parent spans, and the join key is `(trace_id, span_id)` of the leaf, with `gen_ai.request.model` taken from the leaf only. Parent-level cost is derived by summing children, and the sum is checkable against `agent.usage.input_tokens.total`. 2. Provenance queries return the set of models actually used, making fallback routing visible instead of invisible. Incident reviews can now answer "did we fall back?" from trace data alone. 3. The validator acts as a **continuity invariant**: it fails the span export (or flags it) when a parent span's child count is > 1 and it carries leaf-namespaced per-attempt attributes. This converts a silent data-quality bug into a loud, actionable signal at instrumentation time. The general lesson: in agent observability, **the unit of provenance is the model call, and the unit of coordination is the agent step.** Semantic conventions that blur these two units produce traces that look well-formed but lie about cost, model, and tool usage—the worst kind of instrumentation failure, because it is invisible until someone reconciles against a bill. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Iterable LEAF_ATTRIBUTE_PREFIXES = ( "gen_ai.request.model", "gen_ai.response.model", "gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens", "gen_ai.tool.name", ) ALLOWED_PARENT_AGGREGATES = frozenset( { "agent.usage.input_tokens.total", "agent.usage.output_tokens.total", "agent.usage.attempts_total", "agent.usage.attempts_included", "agent.models.requested", "agent.models.responded", "agent.llm_calls.count", "agent.tools.invoked", } ) class SpanAttributeCollapseError(RuntimeError): """Raised when a parent agent span carries per-attempt leaf attributes.""" @dataclass class Span: name: str attributes: dict = field(default_factory=dict) children: list["Span"] = field(default_factory=list) def validate_parent_span(parent: Span) -> None: if len(parent.children) <= 1: return # cardinality-one: aggregation is faithful, no violation offending = [ key for key in parent.attributes if key.startswith(LEAF_ATTRIBUTE_PREFIXES) and key not in ALLOWED_PARENT_AGGREGATES ] if offending: raise SpanAttributeCollapseError( f"parent span {parent.name!r} with {len(parent.children)} children " f"carries per-attempt leaf attributes {sorted(offending)}; " f"these must live on child spans only, or be re-emitted under " f"the agent.* aggregate namespace" ) scalar_model = parent.attributes.get("agent.models.requested") if scalar_model is not None and not isinstance(scalar_model, (list, tuple)): raise SpanAttributeCollapseError( "agent.models.requested must be a set/array on fan-out parents, " f"got scalar {scalar_model!r} which hides fallback routing" ) def build_parent_aggregate(children: Iterable[Span]) -> Span: children = list(children) parent = Span(name="invoke_agent") requested = sorted({c.attributes["gen_ai.request.model"] for c in children}) responded = sorted({c.attributes.get("gen_ai.response.model", c.attributes["gen_ai.request.model"]) for c in children}) parent.attributes = { "agent.llm_calls.count": len(children), "agent.models.requested": requested, "agent.models.responded": responded, "agent.usage.input_tokens.total": sum( c.attributes.get("gen_ai.usage.input_tokens", 0) for c in children ), "agent.usage.output_tokens.total": sum( c.attributes.get("gen_ai.usage.output_tokens", 0) for c in children ), "agent.tools.invoked": sorted( {c.attributes["gen_ai.tool.name"] for c in children if "gen_ai.tool.name" in c.attributes} ), } parent.children = children validate_parent_span(parent) return parent ```