# What happens when an instance records tool-call spans before the GenAI semantic convention attributes resolve, and the parent invocation span closes with a token count that no longer reconciles **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where a model-invocation span is the parent of one or more tool-execution spans, and where token usage attributes are computed after tool calls complete. Does not apply to single-shot completions with no tool calls, nor to runtimes that buffer the entire trace in-process and emit it atomically after the run terminates. ## Core Distinction The GenAI semantic conventions model a model invocation as a span carrying `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, and `gen_ai.response.finish_reasons`. A tool call is modeled as a *child* span (`execute_tool`) whose `gen_ai.tool.name` and `gen_ai.tool.call.id` bind it to the invocation that requested it. The convention treats these as independent records joined by trace topology. The non-obvious boundary is this: **the invocation span's token accounting is not causally closed at the moment the invocation span ends.** When an agent loop executes tool calls *between* the model's response and the model's next turn, the output tokens that the model emitted to *request* those tool calls are already known, but the input tokens for the *continuation* invocation are not — and if the runtime attributes continuation input to the parent invocation span (a common shortcut when the loop is modeled as one logical "turn"), the parent's `input_tokens` becomes a value that depends on events that occur *after* the parent span has been ended and exported. The span is immutable once `end()` returns; the attribute set at that instant is the attribute set forever. Any later reconciliation is a lie told to the backend. ## What Was Observed A retrieval-augmented agent executed a four-step loop: plan → `search_docs` → synthesize → `write_file`. The runtime wrapped the whole loop in a single `gen_ai.chat` span (the invocation), with two `execute_tool` children. Token accounting was accumulated in a mutable counter on the invocation context and flushed to span attributes in the span's `on_end` handler. The trace exported cleanly. Then three downstream consumers diverged: 1. **Cost dashboard** reported `input_tokens` for the invocation as the sum of the plan prompt *plus* the synthesis prompt, because the counter had been updated by the time `end()` fired. This is arithmetically the sum of two separate model calls, but the span claims to be *one* invocation. The dashboard's per-invocation cost is therefore double-counted against the per-turn budget, and the ratio `output/input` is wrong because output tokens only reflect the first call's tool-call request, not the synthesis output. 2. **Trace-based evaluation** joined `execute_tool` children to the parent by `gen_ai.tool.call.id` and asserted that every tool call's `gen_ai.tool.call.id` appeared in the parent's `gen_ai.response.finish_reasons`-adjacent metadata. For the second tool call (`write_file`), the parent span had already been ended with `finish_reasons=["tool_calls"]` from the *first* model response. The assertion failed: the parent claimed a single finish reason while parenting two tool calls that came from two distinct model responses. 3. **A replay harness** re-ran the trace from the recorded spans and reconstructed a single model call with a merged prompt. The merged prompt exceeded the model's context window by 14%, and the replay diverged from the original run at step two. The root cause in all three: the invocation span was used as a *container* for a multi-call loop, but the GenAI conventions define it as a *single* model invocation. The span's identity (one call) and its payload (aggregated across calls) were inconsistent, and the inconsistency was frozen at `end()`. ## Condition of Validity The invariant that makes GenAI invocation spans sound is: > **A `gen_ai.chat` span's token attributes and `finish_reasons` describe exactly one model response, and the span must end before any downstream tool execution that the response requested begins its own span.** This holds only when the agent loop emits one invocation span *per model call*, with each tool-call span as a child of the invocation that *requested* it, and the *next* invocation as a sibling (or, in nested-loop models, a child of a separate `gen_ai.agent.turn` wrapper span that carries no token attributes of its own). The wrapper span is the correct place for aggregated accounting; the invocation span is not. The invariant breaks under three conditions, each of which we observed: - **Deferred attribute mutation.** The runtime holds a reference to the invocation span and mutates `gen_ai.usage.*` after `end()` via a post-hoc exporter processor. Some SDKs silently drop post-end attribute writes; others accept them but the value is not part of the span's immutable record and is lost on retry or sampling. Either way the exported value is non-deterministic across collectors. - **Loop-as-span collapse.** The runtime models the whole tool loop as one invocation to reduce span cardinality. This is the failure above. It is tempting because it halves span count and makes traces readable, but it makes the span's semantics a lie. - **Token attribution ambiguity.** When the model's response includes both text and a tool call, `output_tokens` covers both. If the runtime attributes the tool-call portion of output to the child `execute_tool` span (because "the tool produced it"), the parent's `output_tokens` under-reports and the child's `gen_ai.usage` is populated with tokens the *model* emitted, not tokens the *tool* consumed. The convention has no attribute for tool token consumption; `execute_tool` spans carry no `gen_ai.usage.*` at all. Populating them is a schema violation that some backends reject and others silently coerce to zero. ## Decision Boundary The runtime must choose, at span-construction time, between two models, and it must choose *before* the first token is emitted: - **Per-call invocation spans** (conformant). One `gen_ai.chat` span per model response. Token attributes set exactly once, at `end()`, from the response object. Tool-call spans are children of the requesting invocation. Aggregation, if needed, lives on a separate wrapper span with no `gen_ai.usage.*` attributes. Cost is higher span cardinality; correctness is total. - **Loop-as-invocation** (non-conformant but sometimes chosen). One `gen_ai.chat` span per loop. Token attributes are aggregates. This is only sound if the runtime *also* emits a per-call breakdown as span events (`gen_ai.chat.call` events with their own token attributes), so consumers can reconstruct the per-call truth. Without the event breakdown, the span is uninterpretable. The boundary is crossed the moment the runtime writes a token attribute whose value depends on a model call that has not yet returned. That is detectable: instrument the attribute-writing path and assert that every `gen_ai.usage.*` write occurs in the same synchronous frame as the response parse, with no intervening `await` on a tool executor. If an `await` intervenes, the attribute is deferred and the span is at risk. A second boundary: the `gen_ai.response.finish_reasons` attribute must be a single-element list for a single-call span. A multi-element list (`["tool_calls", "stop"]`) on a span with token attributes is a signal that the span has been collapsed across calls and should be rejected by the collector or flagged by the evaluator. ## Operational Effect The practical consequence is that **trace-based cost and evaluation are only as trustworthy as the span's causal closure at `end()`.** A trace that looks complete — every span has tokens, every tool call has a parent — can be systematically wrong in a way that no schema validator catches, because the schema validates *presence* of attributes, not their *provenance*. Downstream consumers that assume per-invocation semantics (cost dashboards, context-window replay, finish-reason-based routing) will silently mis-attribute, and the error compounds across a multi-step run: a four-step loop with collapsed spans reports roughly 4× the input tokens per "invocation" and 1× the output tokens, so the input/output ratio is off by the loop depth, and any budget guard keyed on that ratio fires at the wrong threshold. The guardrail is a **provenance assertion at span end**: the invocation span must record, as a span event or attribute, the `gen_ai.response.id` (or equivalent response identifier) of the single response it describes, and the collector must reject any `gen_ai.chat` span whose token attributes cannot be traced to exactly one response identifier. Tool-call spans must carry `gen_ai.tool.call.id` matching a `tool_calls` entry in the parent's single response. If a parent has two children whose call IDs come from different responses, the parent is a collapsed loop and must be split or annotated as such before export. ```python from dataclasses import dataclass, field from typing import Optional class InvocationSpanClosureError(RuntimeError): """Raised when a gen_ai.chat span's token attributes are not causally closed at end() — i.e. they depend on a model response that had not returned when the span was ended, or the span parents tool calls from more than one response.""" @dataclass class InvocationSpan: response_id: Optional[str] = None input_tokens: Optional[int] = None output_tokens: Optional[int] = None finish_reasons: list = field(default_factory=list) tool_call_ids: list = field(default_factory=list) # from this response only ended: bool = False _ended_at_response_id: Optional[str] = None def record_response(self, response_id: str, input_tokens: int, output_tokens: int, finish_reasons: list, tool_call_ids: list) -> None: if self.ended: raise InvocationSpanClosureError( f"attempted to write token attributes to span after end(); " f"span was closed against response {self._ended_at_response_id!r}, " f"new write references response {response_id!r}. " f"Deferred attribute mutation is non-deterministic across collectors." ) if self.response_id is not None and self.response_id != response_id: raise InvocationSpanClosureError( f"span already bound to response {self.response_id!r}; " f"refusing to fold response {response_id!r} into the same " f"invocation span (loop-as-span collapse). Emit a sibling " f"invocation span or a wrapper span with no gen_ai.usage.*." ) self.response_id = response_id self.input_tokens = input_tokens self.output_tokens = output_tokens self.finish_reasons = list(finish_reasons) self.tool_call_ids = list(tool_call_ids) def end(self) -> None: if self.response_id is None: raise InvocationSpanClosureError( "invocation span ended with no bound response; " "gen_ai.usage.* attributes have no provenance." ) if len(self.finish_reasons) != 1: raise InvocationSpanClosureError( f"invocation span carries {len(self.finish_reasons)} finish " f"reasons {self.finish_reasons!r}; a single-call span must " f"carry exactly one. Multi-reason spans are collapsed loops." ) self.ended = True self._ended_at_response_id = self.response_id def attach_tool_child(self, call_id: str) -> None: if not self.ended: raise InvocationSpanClosureError( "tool-call child attached before invocation span ended; " "the requesting response has not been recorded, so the " "call_id cannot be validated against the parent response." ) if call_id not in self.tool_call_ids: raise InvocationSpanClosureError( f"tool call {call_id!r} is not among the tool_calls of " f"response {self.response_id!r} ({self.tool_call_ids!r}); " f"the child likely belongs to a different invocation span." ) ```