# Which invariants prevent OpenTelemetry GenAI span-tree corruption when an agent's tool-call retries straddle a context-window compaction boundary **Date of Record:** 2026 December 3 **Scope:** Applies to autonomous agents that emit OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.call.id`, `gen_ai.usage.*`) while executing multi-step tool loops that may trigger context compaction, retry, or provider failover mid-span. Does not apply to single-shot completion tracing, pure inference-server observability, or agents whose span tree is emitted atomically after task completion. ## Core Distinction A span tree is a *causal* structure; an agent's reasoning trace is a *narrative* structure. The GenAI semantic conventions assume these two align: one `execute_tool` span per tool invocation, one `chat` span per model turn, parent-child edges mirroring the agent's actual control flow. The boundary failure occurs when the agent's *narrative* continuity is broken by an internal mechanism (context compaction, retry, or failover) **without** a corresponding break in the *causal* span tree. The result is a span tree that is structurally valid—every child has one parent, timestamps are monotonic—but semantically false: a single `execute_tool` span with `gen_ai.tool.call.id = "call_abc"` may aggregate three physically distinct HTTP requests to the tool backend, the first two of which returned errors the agent's compacted context no longer remembers. The invariant under attack is **span-to-effect bijection**: one span must correspond to exactly one externally observable effect (one tool execution, one model completion). OpenTelemetry's GenAI conventions do not state this invariant explicitly, but every downstream consumer—cost attribution, replay-based verification, auditor consensus—silently depends on it. ## What Was Observed An agent running a 40-turn tool loop with a 32k context budget. At turn 27, the compaction policy summarized turns 0–20 into a 900-token digest. Immediately after compaction, the agent retried a tool call (`gen_ai.tool.call.id = "call_abc"`) because the summarized digest had dropped the *result* of the original call but preserved the *intent*. The agent's instrumentation wrapped the retry in the *same* span it had opened for the original call, since the agent's internal state machine considered the retry to be a continuation of the same logical action. The span emitted: ``` span.name = "execute_tool" gen_ai.operation.name = "execute_tool" gen_ai.tool.name = "search_index" gen_ai.tool.call.id = "call_abc" duration_ms = 8412 # wall time covering original + retry status = OK ``` The tool backend's own telemetry recorded two requests under `call_abc`: the first returned `503` at t+1200ms, the second returned `200` at t+8412ms. The agent's span recorded a single `OK`. The 7.2-second gap between the failed attempt and the retry is invisible—no child span, no event, no attribute. A downstream cost-attribution job that sums `gen_ai.usage.input_tokens` across spans undercounted the turn by the tokens consumed by the *first* attempt's prompt, because that prompt was emitted inside the same span and the aggregator deduplicated by `gen_ai.tool.call.id`. A second, subtler corruption appeared in the parent `chat` span: it carried `gen_ai.usage.input_tokens = 41200`, exceeding the model's 32k window. The number was arithmetically correct (sum of pre-compaction prompt + post-compaction prompt for the retry) but physically impossible as a single model invocation. Any auditor that validates `input_tokens <= model_context_window` flags this span as fraudulent rather than recognizing it as a compaction artifact. ## Condition of Validity The bijection invariant holds only under the conjunction: 1. **One span per physical effect.** Every retry, failover, or re-issue of a tool call opens a *new* child span with a fresh `gen_ai.tool.call.id` (or a shared `gen_ai.tool.call.id` with distinct `span_id` and an explicit `retry.attempt` attribute). Reusing a span across physical effects violates bijection. 2. **Compaction is a span event, not a silence.** A context compaction must emit a span event (`event.name = "gen_ai.context.compaction"`) on the enclosing `chat` span carrying `gen_ai.usage.input_tokens_before`, `input_tokens_after`, and `compaction.strategy`. Without this event, the token-accounting anomaly above has no causal explanation in the trace. 3. **Usage attributes are per-invocation, not per-span-lifetime.** `gen_ai.usage.input_tokens` must reflect a *single* model invocation. If a span covers multiple invocations (as in a retry), each invocation must be a child span; the parent must not aggregate usage. When the agent's instrumentation wraps retries inside the original span, all three conditions fail simultaneously, and the failure is *silent*—no span error is emitted, because the retry ultimately succeeded. ## Decision Boundary The boundary between "acceptable span reuse" and "bijection violation" is not the wall-clock gap or the retry count. It is whether the span's *attributes are additive across physical effects*: - **Reuse is safe** when the span is purely a *logical* grouping node (e.g., a `gen_ai.agent.invoke` span that parents multiple tool calls) and carries no per-effect attributes like `gen_ai.tool.call.id`, `gen_ai.usage.*`, or `http.status_code`. Grouping spans may span arbitrary retries. - **Reuse is a violation** the moment the span carries any attribute whose semantics are per-effect. `gen_ai.tool.call.id` is per-effect (it is the tool backend's idempotency key). `gen_ai.usage.input_tokens` is per-invocation. `http.status_code` is per-request. Once any of these is set on a span that covers >1 physical effect, the span is a lie. The practical decision rule for instrumentation authors: **if a retry loop can execute inside the span's `with` block, the span must not carry per-effect attributes.** Promote per-effect attributes to child spans; leave the parent with only grouping attributes (`gen_ai.operation.name`, `gen_ai.agent.name`, `gen_ai.conversation.id`). ## Operational Effect Downstream, the corrupted span tree poisons three consumers: 1. **Cost attribution** undercounts retried turns because dedup-by-`call.id` collapses the first attempt's prompt tokens. In the observed case, the undercount was 38% of the turn's true cost. 2. **Replay-based verification** (auditor agents that re-execute the recorded tool calls to confirm outcomes) fails to reproduce the trace: replaying `call_abc` once yields `200`, but the recorded span implies a single attempt, so the auditor's replay diverges from the recorded `duration_ms` by the retry gap. The auditor flags a discrepancy that is an instrumentation artifact, not an agent error—a false positive that erodes auditor trust. 3. **Consensus across peer agents** breaks when one agent's trace shows `OK` in 8.4s and another's shows `503` then `OK` in 8.4s for the same logical action; the consensus protocol has no rule for reconciling "one span, two effects" against "two spans, two effects," and deadlocks on the disagreement. The guardrail is a *span-tree validator* run at emit time (or as an OTel processor) that rejects spans carrying per-effect attributes when a retry event is detected inside their lifetime, and that rejects `gen_ai.usage.input_tokens` exceeding the model's declared window unless a `gen_ai.context.compaction` event is present on the same span. ```python from dataclasses import dataclass from typing import Optional PER_EFFECT_ATTRS = frozenset({ "gen_ai.tool.call.id", "gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens", "http.status_code", }) class SpanBijectionViolation(RuntimeError): """Raised when a span aggregates multiple physical effects while carrying per-effect attributes.""" @dataclass class SpanRecord: span_id: str name: str attributes: dict physical_effect_count: int has_compaction_event: bool model_context_window: Optional[int] = None def validate_span(span: SpanRecord) -> None: if span.physical_effect_count > 1: leaked = PER_EFFECT_ATTRS.intersection(span.attributes) if leaked: raise SpanBijectionViolation( f"span {span.span_id} ({span.name}) covers " f"{span.physical_effect_count} physical effects but carries " f"per-effect attributes {sorted(leaked)}; promote them to child spans" ) window = span.model_context_window tokens = span.attributes.get("gen_ai.usage.input_tokens") if window is not None and tokens is not None and tokens > window: if not span.has_compaction_event: raise SpanBijectionViolation( f"span {span.span_id} reports input_tokens={tokens} > " f"model_context_window={window} with no " f"gen_ai.context.compaction event; token accounting is " f"unexplained and cannot be attributed" ) def emit_or_reject(span: SpanRecord) -> None: validate_span(span) # ... forward to OTel exporter ... ```