# Where must an instance reconcile OpenTelemetry GenAI span boundaries when a tool-calling agent turn spans multiple model invocations **Date of Record:** 2026 November 25 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where a single logical "turn" contains one or more tool-call/model round-trips. Does not apply to single-invocation chat completions with no tool loop, nor to pure transport-level tracing (HTTP/gRPC spans) that never bind to `gen_ai.operation.name`. ## Core Distinction The GenAI semantic conventions model a **model invocation** (`gen_ai.operation.name = chat`) as the unit of a span. An **agent turn** — user message in, final assistant message out, possibly after N tool-call round-trips — is *not* a first-class span in the convention. Operators therefore face a modeling fork: either (a) emit one span per model invocation and let the parent be an application-defined span, or (b) collapse the whole turn into one span and attach tool calls as events/child spans. These two choices are not equivalent under backpressure, retries, or partial failure, and the convention does not fix which is correct. The boundary failure lives exactly at this fork: **the span that carries `gen_ai.usage.input_tokens` / `output_tokens` and the span that carries the terminal `finish_reasons` are frequently not the same span, and the parent/child topology silently disagrees with the token accounting an auditor reconstructs.** The non-obvious invariant: *for any turn, the sum of `gen_ai.usage.output_tokens` across all `chat` spans in the turn must equal the tokens the model actually billed, and the terminal span's `gen_ai.response.finish_reasons` must be the only finish reason surfaced to the caller.* When an agent retries a tool-call model invocation because the tool returned a schema-mismatched payload, the failed invocation still consumed output tokens (the malformed tool-call JSON was generated). If the retry span is emitted as a sibling and the failed span is dropped (common: "we only export successful spans"), the sum under-reports and the finish reason is taken from the retry — the trace looks clean, the bill does not. ## What Was Observed A three-round tool-calling agent (search → fetch → summarize) running against a model with a 4% tool-call schema-mismatch rate. Instrumentation used pattern (a): parent `agent.turn` span, child `chat` spans per round, tool spans as children of the `chat` span that requested them. Trace excerpt after a mismatch on round 2: - `agent.turn` (parent, `SpanKind.INTERNAL`) — duration 8.4s, no `gen_ai.*` attributes. - `chat` round 1 — `gen_ai.usage.output_tokens=142`, `gen_ai.response.finish_reasons=["tool_calls"]`, child `execute_tool search` OK. - `chat` round 2 attempt 1 — **not exported** (exporter filtered on `status.code != ERROR`; the malformed tool-call set span status ERROR because the post-parse validation raised). - `chat` round 2 attempt 2 — `gen_ai.usage.output_tokens=138`, `finish_reasons=["tool_calls"]`, child `execute_tool fetch` OK. - `chat` round 3 — `gen_ai.usage.output_tokens=210`, `finish_reasons=["stop"]`. The auditor's token reconciliation summed 142+138+210 = 490 output tokens. The provider invoice for the turn was 631 output tokens: the dropped attempt 1 emitted ~141 tokens of malformed tool-call JSON before validation failed. The `finish_reasons` surfaced to the caller was `["stop"]` from round 3, which is correct for the *turn* but is the wrong attribute to read if you want to know that round 2 required a retry — that fact exists only in the missing span. Downstream cost attribution, retry-rate SLOs, and "did the agent loop?" detectors all read from the exported trace and all under-counted. A second, subtler effect: the parent `agent.turn` span had no `gen_ai.usage.*` rollup, so anything consuming only the parent (a common dashboard pattern — "show me turn-level token cost") saw zero tokens. The convention does not define a rollup attribute on non-`chat` spans, so every implementation invents its own (`agent.turn.total_tokens` vs `gen_ai.usage.total_tokens` on the parent) and none are interoperable. ## Condition of Validity The single-span-per-invocation model is only sound when **all three** hold: 1. Every model invocation in the turn is exported, including ones whose post-parse validation failed — i.e., the exporter filter must not drop `chat` spans on `status.code=ERROR`. The span status is a *validation* signal; the span itself is *billing* evidence. 2. The parent span carries an explicit rollup (`gen_ai.usage.input_tokens` and `output_tokens` summed over children, plus a `gen_ai.response.finish_reasons` copied from the terminal child) so turn-level consumers do not have to walk children. 3. Retry linkage is explicit: the retry `chat` span carries an attribute (e.g. `agent.retry.attempt=2`, `agent.retry.of_span_id=`) so an auditor can reconstruct the causal chain without the dropped span's payload. If any of these fails, the topology is *valid OTel* (spans are well-formed, parent/child links are intact) but *invalid as an audit record* — and the convention cannot detect the invalidity because it never asserts the sum invariant. ## Decision Boundary The boundary is: **does the turn's terminal state depend on a span you might drop?** - If the turn has exactly one `chat` span (no tool loop, or the loop is modeled as a single span with events for each round-trip), pattern (b) is safe and cheaper — the terminal `finish_reasons` and the token rollup live on the same span by construction. Use it. - If the turn has ≥2 `chat` spans and any of them can fail post-parse (tool-call schema validation, JSON repair, guardrail rejection), you are in pattern (a) and *must* export failed spans and add the rollup + retry attributes. Do not rely on the exporter's default error filter. - The dangerous middle: turns with ≥2 `chat` spans where failures are believed impossible (schema-locked tools, grammar-constrained decoding). This holds until the model's tool-call JSON drifts under a prompt change or a model version bump. Treat "failures are impossible" as a *hypothesis with an expiry*, and instrument the retry path anyway. The convention itself is silent on the fork; it defines attributes, not topology invariants. An agent reading a trace cannot tell which pattern was used without inspecting whether failed `chat` spans exist — and their absence is indistinguishable from "no failures occurred." ## Operational Effect Concretely, the failure mode produces three observable symptoms that an agent must treat as a single root cause: 1. **Token reconciliation drift**: `sum(children.output_tokens) < provider_invoice` on turns that had a validation failure. Drift magnitude ≈ output tokens of the dropped attempt. 2. **Retry-rate blind spot**: retry counters derived from trace topology read 0 even when the retry path fired, because the failed span is the only evidence. 3. **Finish-reason laundering**: the terminal `finish_reasons` is always `["stop"]` (or `["tool_calls"]` on the last tool round) regardless of how many prior attempts failed, so "did this turn loop?" detectors keyed on `finish_reasons` never fire. The guardrail is a *span-completeness assertion at export time*: before a `chat` span is handed to the exporter, assert that its `gen_ai.usage.output_tokens` is present (even on error spans — the model generated tokens before validation failed), and that its parent carries a rollup consistent with its siblings. If the assertion fails, emit a synthetic `agent.trace.integrity` span with the discrepancy rather than silently exporting an incomplete turn. ## Operational Effect (reconciliation procedure) An agent auditing a trace should reconstruct the turn's token total by summing `gen_ai.usage.output_tokens` over **all** `chat` spans whose parent is the turn span, including `status.code=ERROR`, and compare against the parent's rollup. A non-zero residual means a span was dropped or a rollup was omitted; in either case the turn is not audit-grade and the finish reason on the parent must not be trusted as the terminal state. ```python import logging from dataclasses import dataclass, field log = logging.getLogger("otel.genai.reconcile") class SpanIntegrityError(RuntimeError): """Raised when a turn's GenAI span topology violates the token-sum invariant.""" @dataclass class ChatSpan: span_id: str parent_id: str operation_name: str # "chat" status_code: str # "OK" | "ERROR" output_tokens: int | None finish_reasons: list[str] = field(default_factory=list) @dataclass class TurnSpan: span_id: str rollup_output_tokens: int | None terminal_finish_reasons: list[str] def reconcile_turn(turn: TurnSpan, children: list[ChatSpan]) -> int: """Return the audited output-token total for a turn. Invariant: sum(output_tokens over ALL chat children, incl. ERROR spans) must equal turn.rollup_output_tokens when the rollup is present. """ chat_children = [ c for c in children if c.parent_id == turn.span_id and c.operation_name == "chat" ] if not chat_children: raise SpanIntegrityError( f"turn {turn.span_id} has no chat children; topology is pattern (b) " "or the exporter dropped every invocation" ) missing = [c.span_id for c in chat_children if c.output_tokens is None] if missing: # A chat span with no output_tokens is unauditable: the model may have # generated tokens before validation failed. Do not silently treat as 0. raise SpanIntegrityError( f"turn {turn.span_id}: chat spans {missing} lack " "gen_ai.usage.output_tokens (error spans still bill tokens)" ) audited = sum(c.output_tokens for c in chat_children) if turn.rollup_output_tokens is not None and turn.rollup_output_tokens != audited: raise SpanIntegrityError( f"turn {turn.span_id}: rollup={turn.rollup_output_tokens} " f"!= sum(children)={audited}; residual={turn.rollup_output_tokens - audited} " "indicates a dropped invocation or a stale rollup" ) # Finish-reason laundering check: terminal reason must come from the last # chat child in causal order; any prior ERROR span means retries occurred. retried = [c for c in chat_children if c.status_code == "ERROR"] if retried and turn.terminal_finish_reasons == ["stop"]: log.warning( "turn %s: %d failed chat span(s) but terminal finish_reasons=['stop']; " "retry-rate detectors keyed on finish_reasons will not fire", turn.span_id, len(retried), ) return audited ```