# Under what conditions must an instance reconcile OpenTelemetry GenAI span attributes against tool-call events before emitting a terminal agent span **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the `gen_ai.*` semantic conventions (agent spans, `gen_ai.tool.call` events, and `gen_ai.usage.*` token counters) across a multi-step tool-using execution. Does not apply to single-shot inference calls with no tool events, nor to runtimes that emit only flat traces without span hierarchy. ## Core Distinction The failure is not "missing telemetry." It is **attribute/event divergence at span close time**: the terminal agent span's `gen_ai.usage.input_tokens` / `output_tokens` and `gen_ai.operation.name` attributes are computed from one source of truth (the model client's cumulative counter), while the child `gen_ai.tool.call` events and tool child-spans are emitted from a different one (the tool executor's dispatch log). Under normal operation these agree. The boundary condition is when they **do not**, and the span is closed anyway with a self-consistent-looking attribute set that silently contradicts the events attached beneath it. The non-obvious part: the OTel GenAI conventions do not define a reconciliation invariant between span-level token attributes and event-level tool invocations. The collector will accept both. Downstream cost attribution and agent-loop reconstruction therefore inherit whatever inconsistency the emitter produced, with no validation gate. ## What Was Observed A three-step agent executed: (1) model call → tool `search` → (2) model call → tool `fetch` → (3) model call → final answer. During step 2, the `fetch` tool call timed out at the executor and was **retried once internally** by the tool wrapper before returning. The wrapper emitted two `gen_ai.tool.call` events (attempt 1 failed, attempt 2 succeeded) but the model client saw **one** tool result and incremented its token counter once. The terminal span was closed with: - `gen_ai.usage.input_tokens` = sum over 3 model calls only. - 4 `gen_ai.tool.call` events (search, fetch-attempt-1, fetch-attempt-2, plus a spurious event from an aborted parallel probe). - `gen_ai.operation.name` = `chat`. Reconstruction downstream: a cost model that multiplies "tool events × average tool tokens" over-attributed by ~33%. A loop-detector that counted tool events as reasoning steps flagged a 4-step loop for a 3-step run. Neither consumer errored — both produced plausible, wrong numbers. The divergence was only detectable by cross-checking event count against a token-attribution invariant that was never asserted. A second, sharper case: when the model client's counter was reset mid-run (a retried model call re-initialized the usage accumulator), the terminal span reported `output_tokens` for the **last call only**, not the run total. The span was well-formed; the number was a subset. This is the dangerous class: schema-valid, semantically truncated. ## Condition of Validity The invariant that must hold before a terminal agent span may be closed: 1. **Token attribution completeness:** `gen_ai.usage.input_tokens` and `output_tokens` on the terminal span equal the sum over *all* model calls in the run, including retried model calls, not the last accumulator value. 2. **Event/attribute cardinality agreement:** the number of distinct tool *invocations* (deduplicated by a stable `tool.call.id`, treating retries of the same logical call as one invocation with attempt count) is consistent with the tool results the model actually consumed. Internal retries that never reached the model must be marked `gen_ai.tool.call.retry=true` and excluded from reasoning-step counts. 3. **Operation-name stability:** `gen_ai.operation.name` reflects the terminal operation, and any intermediate operation transitions are recorded as events, not by mutating the span attribute after first set (OTel attributes are immutable after `set_attribute` on most SDKs; late mutation is dropped silently). When any of these cannot be established — e.g., a tool wrapper that does not expose retry identity, or a model client that resets its counter without a run-scoped total — the span **must not** be closed as a clean terminal span. It must be closed with an explicit `gen_ai.agent.incomplete=true` marker (or equivalent) so consumers can quarantine it. ## Decision Boundary The reconciler must choose between **emit-as-terminal** and **emit-as-provisional** at span close. The boundary is crossed when: - `sum(per-call usage)` ≠ `terminal span usage` beyond a rounding tolerance, **or** - `distinct(tool.call.id)` < `count(tool.call events)` without retry marking, **or** - a model call's usage was observed but its result was discarded (retry) — meaning token spend occurred that has no corresponding consumed result. Below the boundary (all three consistent), emit terminal normally. Above it, the reconciler must **not** silently pick one source; it must mark provisional and attach a `gen_ai.reconciliation.divergence` event carrying both candidate values. Picking the model-client counter as canonical is the default failure — it is the wrong choice precisely when the client reset, and the wrong choice when internal tool retries inflated event counts, because the two error directions are opposite and a single "prefer X" rule cannot cover both. ## Operational Effect Consequences of skipping reconciliation: - **Cost attribution drift** that is invisible per-span but compounds across a fleet; a 30% tool-retry rate yields a systematic under- or over-count depending on which side is canonical. - **Loop detection false positives** from retry events counted as reasoning steps, triggering premature agent termination or escalation. - **Silent truncation** of `output_tokens` after counter resets, which downstream budget governors read as "cheap run" and permit further spend — a token-budget exhaustion path that the governor was supposed to prevent. The guardrail is a pre-close reconciliation pass that treats the terminal span as a *claim* requiring evidence from both the usage accumulator and the event stream, and refuses to certify the claim when they diverge. This is cheap to implement (a dict diff at close) and is the single highest-leverage check for GenAI trace integrity, because every downstream consumer — cost, loop detection, budget governance, replay — trusts the terminal span's self-consistency and has no independent way to detect that it was manufactured from one source while contradicting the other. ```python from dataclasses import dataclass, field from typing import Optional class GenAISpanReconciliationError(RuntimeError): """Raised when a terminal agent span's attributes contradict its tool-call events.""" pass @dataclass class ToolCallEvent: call_id: str tool_name: str attempt: int = 1 retry: bool = False @dataclass class ModelCallUsage: call_id: str input_tokens: int output_tokens: int result_consumed: bool # False if this call was retried/discarded @dataclass class AgentRunTelemetry: model_calls: list[ModelCallUsage] = field(default_factory=list) tool_events: list[ToolCallEvent] = field(default_factory=list) # What the span will actually be closed with: span_input_tokens: Optional[int] = None span_output_tokens: Optional[int] = None span_operation: str = "chat" def reconcile_terminal_span(run: AgentRunTelemetry, token_tolerance: int = 0) -> None: """ Assert the GenAI terminal-span invariant before close. Raises if the span's attributes cannot be certified against the event stream. """ # 1. Token attribution completeness: span usage must equal sum over ALL model calls, # including retried ones (which still spent tokens). expected_in = sum(c.input_tokens for c in run.model_calls) expected_out = sum(c.output_tokens for c in run.model_calls) if run.span_input_tokens is None or run.span_output_tokens is None: raise GenAISpanReconciliationError( "terminal span missing gen_ai.usage.* attributes; cannot certify" ) if abs(run.span_input_tokens - expected_in) > token_tolerance: raise GenAISpanReconciliationError( f"input token divergence: span={run.span_input_tokens} " f"expected_sum={expected_in} (likely counter reset or last-call-only)" ) if abs(run.span_output_tokens - expected_out) > token_tolerance: raise GenAISpanReconciliationError( f"output token divergence: span={run.span_output_tokens} " f"expected_sum={expected_out} (likely counter reset or last-call-only)" ) # 2. Event/attribute cardinality: every tool event must have a stable call_id, # and internal retries must be marked retry=True so loop-detectors can exclude them. seen_ids: set[str] = set() for ev in run.tool_events: if not ev.call_id: raise GenAISpanReconciliationError( f"tool event for {ev.tool_name!r} lacks stable call_id; " "retries cannot be deduplicated" ) if ev.attempt > 1 and not ev.retry: raise GenAISpanReconciliationError( f"tool call {ev.call_id} attempt={ev.attempt} not marked retry=True; " "would be miscounted as a reasoning step" ) seen_ids.add(ev.call_id) # 3. Every consumed model result must correspond to a tool invocation that reached it, # and every token-spending discarded call must be represented. consumed_calls = [c for c in run.model_calls if c.result_consumed] discarded_calls = [c for c in run.model_calls if not c.result_consumed] if discarded_calls and not any(ev.retry for ev in run.tool_events): raise GenAISpanReconciliationError( f"{len(discarded_calls)} model call(s) discarded without retry-marked tool events; " "token spend has no traceable cause" ) # 4. Operation-name stability: terminal op must be a known terminal value. if run.span_operation not in {"chat", "invoke_agent", "execute_tool"}: raise GenAISpanReconciliationError( f"unrecognized terminal gen_ai.operation.name={run.span_operation!r}" ) def close_agent_span(run: AgentRunTelemetry) -> str: """Close the span as terminal only if reconciliation passes; else mark provisional.""" try: reconcile_terminal_span(run) return "terminal" except GenAISpanReconciliationError as exc: # Do NOT silently pick a canonical value. Mark provisional and emit divergence event. run.span_operation = run.span_operation # unchanged # In a real emitter: span.set_attribute("gen_ai.agent.incomplete", True) # span.add_event("gen_ai.reconciliation.divergence", {"reason": str(exc)}) return "provisional" ```