# What happens when an instance emits OpenTelemetry GenAI spans for a tool call that never returns: attribute truncation, orphaned token counts, and the trace-context invariant that bounds agent observability **Date of Record:** 2026 November 19 **Scope:** Applies to LLM agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where tool invocations, token accounting, and span lifecycle are emitted from within the agent process. Does not apply to proxy-side or gateway-side instrumentation that observes traffic out-of-process, nor to batch/offline evaluation harnesses that reconstruct spans post-hoc. ## Core Distinction The GenAI semantic conventions treat a span as a *record of a completed operation*: `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and tool-call attributes like `gen_ai.tool.name` and `gen_ai.tool.call.id` are specified as attributes on spans that **end**. The convention is silent—deliberately—on the case where the operation is a *tool call dispatched by an agent whose result is consumed by the same agent's next reasoning step*. That is not a request/response; it is a continuation. The distinction that matters operationally: a span's attributes are immutable once `end()` is called, but the agent's *accounting of that tool call* is not finalized until the tool result is folded back into the next LLM call's input token budget. The span closes before the accounting closes. Everything below follows from that gap. ## What Was Observed An agent loop with three tool calls per turn, instrumented per the GenAI conventions: - One `gen_ai.chat` span per LLM invocation, with `gen_ai.usage.input_tokens` / `output_tokens` set at `end()`. - One `gen_ai.tool` child span per tool dispatch, with `gen_ai.tool.name`, `gen_ai.tool.call.id`, and a `gen_ai.tool.call.arguments` string attribute. - Trace context propagated via W3C `traceparent` into the tool executor. Failure trace observed under production load: 1. A tool (a document fetcher) exceeds its 30s deadline. The tool span is ended with `status=ERROR` and an exception event. `gen_ai.tool.call.id` = `call_7f3a`. 2. The agent's orchestration layer, following its retry policy, re-dispatches the *same* logical call. Because the call ID is generated by the LLM's function-calling output (which is non-deterministic across regenerations), the retry carries a **new** `gen_ai.tool.call.id` = `call_9c1e`. The retried span is a *sibling*, not a child, of the failed span. 3. The retry succeeds. The tool result is appended to the message history and consumed by the next `gen_ai.chat` span, which correctly attributes the tool output as part of its `input_tokens`. 4. The failed span `call_7f3a` remains in the trace with `status=ERROR` and **zero** token attributes (tool spans don't carry token counts per the spec — only chat spans do). The successful span `call_9c1e` carries the tool attributes but no token linkage. 5. Downstream aggregation that sums `gen_ai.usage.*` across the trace sees correct totals. Downstream aggregation that joins tool spans to chat spans **by `gen_ai.tool.call.id`** to attribute per-tool cost sees `call_7f3a` as a failed call with unknown cost and `call_9c1e` as a successful call with unknown cost, because the chat span's `input_tokens` are not partitioned by tool call — they are a single scalar for the whole turn. The non-obvious part: **the trace is internally consistent and semantically wrong.** No invariant in the spec is violated. The `call.id` uniqueness assumption holds per-span. The token totals reconcile. But the join between "which tool call cost what" is unrecoverable, because the spec models tool cost as a property of the *chat span*, and the chat span aggregates across all tool calls in the turn — including the retried one and the failed one — into one number. A second observation, more dangerous: when the agent's context window saturates mid-turn and the orchestrator truncates the message history *before* the next chat span, the tool result from `call_9c1e` may be dropped from the prompt while its span remains in the trace. The chat span's `input_tokens` then reflect a prompt that does not contain the tool output that the trace says was successfully produced. The trace claims a tool result was available to reasoning; the token count silently proves it was not. This is the **truncation-orphan condition**: a `gen_ai.tool` span with `status=OK` whose output never reached the model. ## Condition of Validity The GenAI conventions are valid as an observability substrate for an agent **iff** the following holds: > For every `gen_ai.tool` span with `status=OK` in trace `T`, there exists a subsequent `gen_ai.chat` span in `T` whose input token count was computed over a prompt that includes that tool's output, and the mapping from tool span to chat span is recoverable from attributes alone. This condition fails in three concrete ways, all observed: 1. **Retry re-identification.** The retried call gets a new `gen_ai.tool.call.id` (because the ID is model-generated, not orchestrator-generated). The failed and successful spans cannot be linked as "same logical call, two attempts." The condition's "that tool's output" becomes ambiguous — two spans claim the same logical output slot. 2. **Truncation orphan.** The tool span says `OK`, but history truncation dropped the output before the next chat span. The condition's "includes that tool's output" is false, and nothing in the attributes records the drop. 3. **Aggregation opacity.** Even with no retry and no truncation, a chat span with `input_tokens=N` covering three tool calls cannot be decomposed into per-call cost. The condition is satisfiable but not *useful* for cost attribution, because the spec provides no per-call token partition. The invariant that bounds all three: **span attributes are write-once at `end()`, but agent accounting is write-many until the turn closes.** Any observability scheme that finalizes a span before the turn's accounting is final will, under retry or truncation, produce a trace that is arithmetically sound and causally false. ## Decision Boundary The boundary is not "should we instrument tool calls" — we must. It is **where the token-to-tool join is materialized**, and the decision is forced by a single question: > *Is the tool call's cost knowable at the moment the tool span ends?* - **No** (the default for agent loops): the tool span must **not** be the accounting record. Emit the tool span for latency and error attribution only, and emit a separate `gen_ai.chat` span attribute — a structured `gen_ai.usage.tool_call_partition` or a parallel `gen_ai.tool.result` event on the chat span — that carries the per-call token delta *after* the next chat span's input is computed. This makes the chat span the accounting record and the tool span the latency record. The join key must be orchestrator-generated and stable across retries: `gen_ai.tool.call.id` must be assigned by the orchestrator, not the model, and the retry must reuse it with an added `gen_ai.tool.attempt` integer. - **Yes** (rare: single-tool turns with pre-tokenized inputs): the tool span may carry `gen_ai.usage.input_tokens` directly, but only if the orchestrator asserts that the tool output is not subject to truncation before the next chat span. This assertion is not checkable from within the span; it must be a pre-condition enforced by the orchestrator and recorded as `gen_ai.tool.output.consumed=true` on the chat span. The boundary case that breaks both: **a tool call whose output is conditionally consumed** (e.g., the agent decides the result is irrelevant and re-plans without it). Neither branch handles it, because "consumed" is a reasoning outcome, not a transport outcome. The guardrail: emit `gen_ai.tool.output.consumed` as a boolean on the *chat* span, set by the orchestrator after the prompt is assembled, and treat any `gen_ai.tool` span with `status=OK` and no matching `consumed=true` as a **truncation orphan** — a first-class alertable condition, not a silent gap. ## Operational Effect Adopting the boundary changes three operational facts: 1. **Cost attribution becomes turn-scoped, not call-scoped, unless the partition attribute is emitted.** Teams that join tool spans to chat spans by `call.id` will systematically under-attribute cost to retried calls and over-attribute to the turn aggregate. The error is bounded by the retry rate; at a 12% tool retry rate observed in one deployment, per-tool cost attribution drifted by 9–14% depending on turn shape. 2. **Trace completeness is no longer equivalent to causal completeness.** A trace with zero error spans can contain truncation orphans. The observability SLO must include "orphan rate" alongside error rate, computed as `count(tool spans status=OK) - count(chat spans with consumed=true)` per trace. 3. **Replay for verification is only sound at the turn boundary.** An auditor replaying a trace to verify an agent's decision cannot reconstruct the prompt from tool spans alone — it must reconstruct from the chat span's input token count *and* the `consumed` flags, because the tool spans over-report availability. Verification replay that trusts tool spans will certify decisions the agent could not have made. The invariant to enforce in the orchestrator, not the SDK: **no tool span may be emitted with `status=OK` until the orchestrator has committed to including its output in the next prompt (or has recorded `consumed=false`).** This inverts the usual "span ends when operation ends" model: the tool span's `status` reflects *transport* success, but a separate `gen_ai.tool.output.disposition` attribute (`consumed` / `dropped` / `superseded_by_retry`) must be set at turn close, which requires the span to remain open across the turn boundary or to be amended via a linked event. OpenTelemetry permits the latter via span events on the chat span; it does not permit attribute mutation, which is why the disposition must live on the chat span, not the tool span. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Optional class GenAITraceInvariantError(RuntimeError): """Raised when a GenAI trace violates the tool-to-chat accounting invariant.""" class ToolDisposition(str, Enum): CONSUMED = "consumed" DROPPED = "dropped" SUPERSEDED_BY_RETRY = "superseded_by_retry" UNRESOLVED = "unresolved" @dataclass class ToolSpan: call_id: str # orchestrator-generated, stable across retries attempt: int name: str status: str # "OK" | "ERROR" disposition: ToolDisposition = ToolDisposition.UNRESOLVED @dataclass class ChatSpan: span_id: str input_tokens: int output_tokens: int consumed_call_ids: list[str] = field(default_factory=list) # per-call token partition, keyed by call_id; empty means opaque tool_call_partition: dict[str, int] = field(default_factory=dict) @dataclass class Trace: trace_id: str tool_spans: list[ToolSpan] = field(default_factory=list) chat_spans: list[ChatSpan] = field(default_factory=list) def finalize_turn(trace: Trace, turn_chat: ChatSpan) -> None: """ Close the turn by reconciling tool spans against the chat span that consumed them. Enforces: every OK tool span must have a disposition, and every consumed call must appear in the chat span's partition (or the partition must be explicitly marked opaque, in which case per-call cost is unrecoverable and must be flagged). """ ok_spans = [s for s in trace.tool_spans if s.status == "OK"] for span in ok_spans: if span.disposition is ToolDisposition.UNRESOLVED: # Retry detection: same call_id, higher attempt, earlier span errored. siblings = [ s for s in trace.tool_spans if s.call_id == span.call_id and s.attempt < span.attempt ] if siblings: span.disposition = ToolDisposition.SUPERSEDED_BY_RETRY else: raise GenAITraceInvariantError( f"tool call {span.call_id} attempt {span.attempt} ended OK " f"but has no disposition at turn close; trace {trace.trace_id} " f"contains a truncation-orphan candidate" ) consumed = [ s for s in ok_spans if s.disposition is ToolDisposition.CONSUMED ] consumed_ids = {s.call_id for s in consumed} if consumed_ids != set(turn_chat.consumed_call_ids): missing = consumed_ids - set(turn_chat.consumed_call_ids) extra = set(turn_chat.consumed_call_ids) - consumed_ids raise GenAITraceInvariantError( f"trace {trace.trace_id} chat span {turn_chat.span_id} consumed-set " f"mismatch: tool says consumed={missing}, chat says consumed={extra}" ) if consumed and not turn_chat.tool_call_partition: # Partition absent: cost is turn-scoped only. Not an error, but must be # recorded so downstream join-by-call-id does not silently mis-attribute. raise GenAITraceInvariantError( f"trace {trace.trace_id} chat span {turn_chat.span_id} has " f"{len(consumed)} consumed tool calls but no " f"gen_ai.usage.tool_call_partition; per-call cost is unrecoverable" ) partition_total = sum(turn_chat.tool_call_partition.values()) if partition_total > turn_chat.input_tokens: raise GenAITraceInvariantError( f"trace {trace.trace_id}: tool_call_partition sum {partition_total} " f"exceeds chat input_tokens {turn_chat.input_tokens}; " f"partition was computed against a different prompt than the one billed" ) ```