Which invariants prevent OpenTelemetry GenAI tool-call spans from silently decoupling token accounting from execution lineage
**Date of Record:** 2026 December 1 **Scope:** Applies to agents emitting OTel GenAI semantic-convention spans (`gen_ai.*`) for tool invocations and token usage, where a parent `gen_ai.chat`/agent span is correlated to child tool-execution spans. Does not cover pure inference-server-side metering, billing reconciliation, or non-OTel tracing backends.
Core Distinction
The GenAI semantic conventions define two *independent* attribute families on the same span tree: **token accounting** (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and their cache/reasoning variants) and **execution lineage** (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, the span parent/child link, and `gen_ai.response.finish_reasons`). The failure mode is not that either family is malformed in isolation. It is that the two families are **attached at different points in the span lifecycle by different code paths**, and nothing in the spec forces them to agree. A span can carry perfectly valid token counts while its lineage attributes describe a different logical operation than the one that actually consumed those tokens.
The invariant operators assume—but the spec does not mandate—is: *for any span carrying `gen_ai.usage.*`, the `gen_ai.operation.name` and parent link must identify the exact model turn that produced those tokens.* When a retry, a fallback model, or a streaming tool-call loop reuses or mutates a span, this invariant silently breaks while every individual attribute remains schema-valid.
What Was Observed
An agent loop using a tool-calling model emitted a `gen_ai.chat` span per turn with `gen_ai.usage.input_tokens`/`output_tokens`, and child spans per tool call with `gen_ai.tool.name` + `gen_ai.tool.call.id`. Under a transient 429 from the model provider, the client SDK retried the *same* HTTP request inside the existing span. The retry succeeded, and the SDK recorded usage from **both** the failed attempt's partial stream and the successful attempt — because the usage-recording hook fired on each `response.completed` event and *added* to the span's token attributes rather than *setting* them.
Simultaneously, the tool-call child spans were created from the successful attempt's `tool_calls` array. The result: a `gen_ai.chat` span whose `output_tokens` was roughly double the true value (failed attempt's partial generation + success), while its child tool spans correctly reflected only the successful attempt. Downstream, a cost-attribution job multiplied the inflated output tokens by the tool-call count, producing a per-tool cost that was ~2x reality. The lineage was clean; the accounting was wrong; and the two disagreed with no attribute to signal the disagreement.
A second variant surfaced with streaming: `finish_reasons` was set to `["stop"]` on the span when the first chunk arrived, but the stream continued and a `tool_use` finish reason was appended later. Consumers filtering on `finish_reasons == ["tool_use"]` missed the span entirely, so its tokens vanished from tool-linked aggregates while remaining in global totals — a lineage/accounting split in the opposite direction.
Condition of Validity
The invariant "token attributes belong to the operation named on the span" holds **only if**:
- Usage attributes are written with **set-once semantics** per logical model turn, keyed by a stable identifier (`gen_ai.response.id` or a synthesized attempt id), not accumulated across retries.
- Retries either (a) produce a **new sibling span** linked to the original via a retry attribute, or (b) are explicitly aggregated under a documented attribute such as `gen_ai.usage.*` *plus* an attempt-count attribute so the doubling is legible.
- `finish_reasons` is written **once, at stream close**, after all chunks are consumed — never on first chunk.
- Tool-call child spans are parented to the specific attempt span whose usage they consumed, so the parent link resolves the ambiguity.
When any of these is absent, the span is schema-valid but semantically unverifiable, and no consumer can detect the mismatch from attributes alone.
Decision Boundary
The boundary is between **treating a span as an atomic accounting unit** versus **treating it as a mutable accumulator**. The spec's attribute model is atomic-by-intent (one span = one operation), but streaming SDKs and retry middleware naturally implement accumulators. The decision rule for instrumentation authors:
- If a code path can emit more than one `response.completed` (or equivalent terminal event) for a single span, it is an accumulator and **must not** write `gen_ai.usage.*` directly to the operation span. It must either fork a child attempt span or gate writes behind a set-once guard keyed on `gen_ai.response.id`.
- If `finish_reasons` can be appended after first write, the span is not atomic and must defer the write to stream close.
For consumers/auditors: any span where `sum(child tool call counts) != output token-derived tool count`, or where `finish_reasons` is absent on a span with nonzero `output_tokens`, must be quarantined from cost attribution rather than trusted.
Operational Effect
Without the set-once guard, retry and streaming paths inflate token counts by the number of attempts, and the inflation is **invisible** because every attribute passes schema validation and the lineage looks correct. Cost dashboards over-report by a factor equal to the retry rate; tool-attribution joins silently double-count. The corrective is a write-guard at the instrumentation layer that raises when a second terminal event targets an already-finalized usage record on the same span — forcing the author to either fork the span or explicitly aggregate with an attempt attribute. This converts a silent accounting/lineage decoupling into a loud, catchable instrumentation fault at emit time, before the span ever reaches the collector.
class UsageLineageDecouplingError(RuntimeError):
"""Raised when token-usage attributes are written more than once for a
single logical model turn on one span, decoupling accounting from lineage."""
class GenAiSpanAccounting:
def __init__(self, span_id: str):
self.span_id = span_id
self._finalized_response_id: str | None = None
self._usage_written = False
def record_usage(
self,
response_id: str,
input_tokens: int,
output_tokens: int,
finish_reason: str,
stream_closed: bool,
) -> None:
# Invariant 3: finish_reasons only valid at stream close.
if not stream_closed:
raise UsageLineageDecouplingError(
f"span {self.span_id}: finish_reason={finish_reason!r} written "
f"before stream close; lineage would not match usage"
)
# Invariant 1: set-once per logical turn, keyed on response id.
if self._usage_written and response_id == self._finalized_response_id:
raise UsageLineageDecouplingError(
f"span {self.span_id}: duplicate usage write for response "
f"{response_id!r} (retry/stream accumulation). Fork a child "
f"attempt span or aggregate with an attempt-count attribute."
)
if self._usage_written and response_id != self._finalized_response_id:
# Different response on same span = accumulator without lineage.
raise UsageLineageDecouplingError(
f"span {self.span_id}: usage for response {response_id!r} "
f"after finalizing {self._finalized_response_id!r}; "
f"token accounting would detach from operation lineage"
)
self._usage_written = True
self._finalized_response_id = response_id
# ... emit gen_ai.usage.* and finish_reasons to span here ...