# Which invariants prevent tool-call span collapse when GenAI semantic conventions meet retried, streamed, and nested agent invocations **Date of Record:** 2026 November 25 **Scope:** Applies to agents that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`/`output_tokens`, `gen_ai.agent.*`) for tool calls, streaming completions, and nested sub-agent delegation. Does not cover pure inference-server metrics (TTFT histograms) or non-OTel tracing backends. ## Core Distinction The GenAI semantic conventions describe *what an operation was*, not *how many times the runtime attempted it*. A tool-call span is a logical record of one invocation of `gen_ai.tool.name`; a retry is a distinct physical attempt. The conventions provide no attribute that reconciles the two, so the burden falls on the emitter to preserve a **one-span-per-logical-call invariant** and to keep token-usage counters **additive across attempts but non-duplicated across export**. The failure mode is not a crash — it is a silent *span collapse*: retried tool calls, streamed partial completions, and nested agent handoffs all fold into a single span whose `gen_ai.usage.*` attributes and `gen_ai.tool.call.id` describe a state that never existed, poisoning downstream cost attribution and loop-detection. ## What Was Observed A tool-calling agent (`gen_ai.operation.name = "execute_tool"`) issued a `search_documents` call. The transport returned a 503 on attempt 1, a partial stream that terminated mid-`finish_reason` on attempt 2, and a clean result on attempt 3. The emitter was configured with a `BatchSpanProcessor` and a single long-lived span created at the *start of the logical call*, with retries recorded as span events. Observed span after export: - One span, `gen_ai.tool.name = "search_documents"`, `gen_ai.tool.call.id = "call_7f3a"` (the ID from attempt 3). - `gen_ai.usage.input_tokens = 4120` — the *sum* of attempt 1 (1400), attempt 2 (1520 partial), and attempt 3 (1200), because the retry loop added usage on each attempt. - `status.code = UNSET` — the span was never marked `ERROR` because the final attempt succeeded, erasing the two prior failures from the status. - Zero child spans for attempts 1 and 2; their `exception` events were attached to the parent but the exporter's `EventCountLimit` (default 128) was not hit, so they survived — yet no downstream consumer keyed on `gen_ai.tool.call.id` could attribute the 1520 partial tokens to the failed attempt. A second, compounding observation from a nested-agent case: a supervisor agent (`gen_ai.operation.name = "invoke_agent"`) delegated to a worker agent that itself called the same tool. Both agents used the same `gen_ai.tool.call.id` because the worker inherited the parent's correlation ID via context propagation without minting a fresh one. The backend's span deduplication (keyed on `(trace_id, span_id)` but *aggregated* on `gen_ai.tool.call.id` for cost rollups) merged the two distinct tool invocations, halving the reported tool-call count and double-counting the worker's tokens into the supervisor's `gen_ai.agent.name` bucket. ## Condition of Validity The one-span-per-logical-call invariant holds **only if** all of the following are true simultaneously: 1. **Attempt identity is externalized.** Every physical attempt carries a distinct `gen_ai.tool.call.id` (or a child span with its own ID), so the logical call is reconstructable by grouping on a stable logical key, never by assuming span count equals call count. 2. **Usage is additive at the attempt layer, not the logical layer.** `gen_ai.usage.input_tokens` on the logical span must equal the sum of child-attempt spans, and the logical span must not itself carry usage that also appears on children — otherwise a backend summing both layers double-counts. 3. **Streaming partials are terminal.** A stream that ends without `finish_reason` must emit a child span with `status.code = ERROR` and its own usage, because the partial tokens were *billed* even though the logical call succeeded on retry. Dropping them under-reports cost. 4. **Nested agents mint fresh correlation IDs.** `gen_ai.tool.call.id` must be unique per *invocation*, not per *conversation*; context propagation carries `trace_id`/`span_id` but must not carry `gen_ai.tool.call.id` across an agent boundary. The invariant is **violated** the moment any retry loop mutates the parent span's usage attributes in place, or any context propagator forwards `gen_ai.tool.call.id` unchanged into a delegated agent. ## Decision Boundary The emitter must choose, at span-creation time, between two mutually exclusive topologies: - **Flat-logical:** one span per logical call, retries as events, usage summed on the parent, `status.code` reflecting *any* attempt failure via a custom attribute (since OTel status is single-valued). Acceptable only when the backend does not aggregate on `gen_ai.tool.call.id` and when partial-stream tokens are separately exported via a counter metric (`gen_ai.client.token.usage` with `gen_ai.token.type = "input"` and an `attempt.outcome` attribute). - **Hierarchical:** one parent span per logical call with zero usage attributes, one child span per attempt carrying its own `gen_ai.tool.call.id`, usage, and status. This is the only topology that survives backend aggregation and loop-detection replay. The boundary is crossed — and the failure becomes unrecoverable — when the emitter *mixes* topologies: parent carries summed usage *and* children carry per-attempt usage. At that point no consumer can distinguish "summed parent" from "duplicated child" without out-of-band knowledge, and cost dashboards diverge from billing by the retry multiplier. ## Operational Effect Downstream, the collapsed span produces three concrete defects: (a) **cost attribution drift** proportional to retry count, since summed-parent usage is counted once per span but the partial-stream tokens are invisible to per-attempt billing reconciliation; (b) **loop-detection blindness**, because a retry storm and a single slow call are indistinguishable when `gen_ai.tool.call.id` is stable and status is `UNSET`; and (c) **swarm double-counting**, because nested agents sharing a call ID merge into one rollup bucket. The guardrail is to enforce the hierarchical topology by construction and to reject any span that carries both `gen_ai.usage.*` and non-empty child spans with the same `gen_ai.tool.call.id` — a check the emitter must run before `span.end()`, since the BatchSpanProcessor gives no post-hoc correction window. ```python from dataclasses import dataclass, field from typing import Optional class SpanCollapseError(RuntimeError): """Raised when a GenAI span violates the one-span-per-logical-call invariant.""" @dataclass class GenAISpan: name: str operation: str # gen_ai.operation.name tool_call_id: Optional[str] = None # gen_ai.tool.call.id input_tokens: int = 0 # gen_ai.usage.input_tokens output_tokens: int = 0 # gen_ai.usage.output_tokens children: list["GenAISpan"] = field(default_factory=list) status_code: str = "UNSET" def validate_before_end(span: GenAISpan) -> None: # Invariant 1: a logical span must not carry usage that its children also carry. if span.children and (span.input_tokens or span.output_tokens): raise SpanCollapseError( f"span {span.name!r} carries usage {span.input_tokens}/{span.output_tokens} " f"AND {len(span.children)} child attempts; hierarchical topology forbids " f"parent-level usage (double-count risk on rollup)." ) # Invariant 2: every child attempt must have a distinct tool_call_id. child_ids = [c.tool_call_id for c in span.children if c.tool_call_id] if len(child_ids) != len(set(child_ids)): raise SpanCollapseError( f"span {span.name!r} has duplicate gen_ai.tool.call.id across attempts " f"{child_ids}; retries must mint fresh IDs or backend aggregation will merge them." ) # Invariant 3: a streamed partial (no finish_reason) must be ERROR, not UNSET. for child in span.children: if child.status_code == "UNSET" and child.output_tokens == 0 and child.input_tokens > 0: raise SpanCollapseError( f"attempt {child.tool_call_id!r} billed {child.input_tokens} input tokens " f"but emitted no finish_reason and status UNSET; partial-stream tokens " f"must be recorded as ERROR to survive retry reconciliation." ) # Invariant 4: nested agent must not inherit parent tool_call_id unchanged. if span.operation == "invoke_agent" and span.tool_call_id in child_ids: raise SpanCollapseError( f"nested agent {span.name!r} reused parent gen_ai.tool.call.id " f"{span.tool_call_id!r}; delegation must mint a fresh correlation ID." ) def emit(span: GenAISpan) -> None: for child in span.children: emit(child) validate_before_end(span) # span.end() only reached when invariant holds ```