# Which invariants prevent span-attribute divergence from silently corrupting agent-invocation telemetry under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OTel GenAI spans (`gen_ai.*` attributes) for tool calls, token accounting, and agent invocation, where spans are correlated post-hoc for cost attribution, replay, or SLO computation. Does not apply to single-shot completion logging without span correlation, nor to runtimes that emit a single flat span per session with no child tool spans. ## Core Distinction The failure is not "missing attributes" — missing attributes are loud and detectable. The failure is **semantically divergent but schema-valid** attributes: two spans that both satisfy the GenAI convention's required fields yet describe the same tool call with incompatible token counts, incompatible `gen_ai.operation.name` values, or an `gen_ai.agent.id` that the parent span never stamped. The convention defines *names and types*, not *cardinality invariants across a span tree*. That gap is where silent corruption lives. Concretely: a tool-call span (`gen_ai.operation.name = "execute_tool"`) that carries `gen_ai.usage.input_tokens` describing the *prompt that triggered the tool selection* rather than the *tool's own consumption* is schema-valid. A parent agent-invocation span that also reports `gen_ai.usage.input_tokens` for the same logical turn is schema-valid. Summing them double-counts. Nothing in the convention forbids it. Nothing in the SDK flags it. ## What Was Observed A multi-agent orchestrator emitted, per logical turn: - 1 agent-invocation span: `gen_ai.operation.name="invoke_agent"`, `gen_ai.agent.id`, `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=212`. - N tool-call spans (children): `gen_ai.operation.name="execute_tool"`, `gen_ai.tool.name`, and — because the instrumentation library reused a shared `record_usage()` helper — `gen_ai.usage.input_tokens=1840` on *every* tool span (the helper copied the turn-level prompt count down into each child). The trace tree was valid. Every span passed the semantic-convention validator (all required attributes present, correct types, enum values legal). Cost dashboards that aggregated `sum(gen_ai.usage.input_tokens)` over all spans in a trace reported **1840 × (1 + N)** per turn. With N=3 tools, that is a 4× overcount that scaled with tool fan-out — and fan-out varied by task, so the error was not a constant offset that anyone would notice. It looked like "tool-heavy tasks are expensive," which is *plausible*, so it survived three weeks of review. The second observed instance: an agent-invocation span stamped `gen_ai.agent.id="planner-v2"` but its child tool span carried no `gen_ai.agent.id` at all (the tool ran in a subprocess with a fresh tracer provider that lacked the resource attribute). Replay tooling that reconstructed "which agent made this tool call" fell back to the nearest ancestor with the attribute — correct here, but wrong in the mirror case where a delegated sub-agent *did* stamp its own id, producing two different `gen_ai.agent.id` values in one subtree with no marker indicating the handoff boundary. ## Condition of Validity The invariant that must hold for GenAI telemetry to be aggregable: > **Token attribution is single-owner.** For any logical model invocation, `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` appear on exactly one span — the span whose `gen_ai.operation.name` names the operation that *consumed* the tokens (`invoke_agent`, `chat`, or `execute_tool` when the tool itself calls a model). A span that merely *encloses* a consuming span must NOT restate the child's usage. > **Agent identity is inherited-or-declared, never inferred.** Every span in an agent subtree either (a) carries its own `gen_ai.agent.id`, or (b) is guaranteed by construction to inherit from a resource-level attribute. Consumers may not "walk up to the nearest ancestor with the attribute" unless the producer guarantees no intermediate span declares a different one. These hold only if the instrumentation enforces them at emit time. They are *not* enforceable at query time, because by then the enclosing-vs-consuming distinction has been erased — the span only knows its own attributes, not whether a child also reported usage. ## Decision Boundary The boundary between safe and corrupting emission: - **Safe:** usage attributes are written by the code path that actually invokes the model/tool, using the response object's own usage field. Enclosing spans write *no* usage or write `gen_ai.usage.*` only for tokens the enclosing operation itself consumed (e.g., an agent's own planning call, distinct from its tool calls). - **Corrupting:** usage attributes are written by a shared helper, middleware, or span processor that has access to "the current turn's" counts and applies them uniformly. This is the common case, because it is the *convenient* case — one `record_usage(span, usage)` call at the top of a request handler. The discriminator is not "does the span have usage attributes" but "does the span's `gen_ai.operation.name` describe the thing that spent the tokens." Any processor that sets usage without checking the span's own operation name is on the corrupting side. ## Operational Effect Downstream, the corruption manifests as three distinguishable-but-confusable symptoms: 1. **Fan-out-proportional cost inflation.** Per-turn cost scales with tool count in a way that tracks task complexity, so it reads as signal, not error. Detected only by a ratio check: `sum(child usage) / parent usage` should be ~0 for enclosing parents; a value > 1 flags restated usage. 2. **Replay divergence.** Replaying a trace to recompute cost yields a different number than the live dashboard if the two use different aggregation rules (one sums all spans, one takes the root). The divergence is stable per-trace, so it looks like a dashboard bug rather than a data bug. 3. **Identity ambiguity at handoff.** When a sub-agent stamps its own `gen_ai.agent.id` inside a parent's subtree, replay cannot tell whether the tool call was made *by* the sub-agent or *on behalf of* the parent. The warrant chain is lost even though every individual span is valid. The guardrail is a **span-tree invariant checker run at export time** (in the span processor, before the batch is sealed): reject or quarantine any span whose usage attributes are set while a descendant span of the same operation class also carries usage, and require every span to resolve its `gen_ai.agent.id` either locally or from a resource attribute present at creation — never by ancestor walk. This is cheap because it runs on the already-assembled tree, and it fails closed: a quarantined span is visible, whereas a restated-usage span is not. ```python from dataclasses import dataclass, field from typing import Optional class GenAiSpanInvariantError(RuntimeError): """Raised when a GenAI span tree violates single-owner usage or identity invariants.""" pass @dataclass class GenAiSpan: span_id: str operation_name: str # gen_ai.operation.name agent_id: Optional[str] # gen_ai.agent.id, None if unresolved input_tokens: Optional[int] # gen_ai.usage.input_tokens output_tokens: Optional[int] parent_id: Optional[str] = None children: list = field(default_factory=list) CONSUMING_OPS = {"invoke_agent", "chat", "execute_tool"} def _has_usage(span: GenAiSpan) -> bool: return span.input_tokens is not None or span.output_tokens is not None def assert_single_owner_usage(span: GenAiSpan) -> None: """A span that restates a child's usage corrupts aggregation. Enclosing spans must carry no usage, or carry only usage their own operation consumed.""" if not _has_usage(span): return for child in span.children: if child.operation_name in CONSUMING_OPS and _has_usage(child): raise GenAiSpanInvariantError( f"span {span.span_id} ({span.operation_name}) restates usage " f"already owned by child {child.span_id} ({child.operation_name}); " f"token attribution is not single-owner" ) def assert_identity_resolvable(span: GenAiSpan, resource_agent_id: Optional[str]) -> None: """Every span must resolve gen_ai.agent.id locally or from a resource attribute fixed at creation. Ancestor-walk inference is forbidden because a sub-agent may declare a different id inside the parent's subtree.""" if span.agent_id is None and resource_agent_id is None: raise GenAiSpanInvariantError( f"span {span.span_id} has no gen_ai.agent.id and no resource-level " f"agent identity; identity would be inferred by ancestor walk, " f"which is ambiguous across handoff boundaries" ) for child in span.children: assert_identity_resolvable(child, resource_agent_id) def validate_trace(root: GenAiSpan, resource_agent_id: Optional[str]) -> None: def walk(s: GenAiSpan) -> None: assert_single_owner_usage(s) for c in s.children: walk(c) walk(root) assert_identity_resolvable(root, resource_agent_id) # --- trace that triggers the guardrail ------------------------------------- tool_a = GenAiSpan("s2", "execute_tool", "planner-v2", 1840, 0) tool_b = GenAiSpan("s3", "execute_tool", "planner-v2", 1840, 0) root = GenAiSpan( "s1", "invoke_agent", "planner-v2", 1840, 212, children=[tool_a, tool_b], ) try: validate_trace(root, resource_agent_id="planner-v2") except GenAiSpanInvariantError as e: # expected: root restates usage owned by its tool children print(f"quarantined trace: {e}") ```