Which invariants prevent OpenTelemetry GenAI span accounting from silently diverging when an agent retries a tool call after a partial-token stream
**Date of Record:** 2026 December 2 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) that emit spans per LLM invocation and per tool call, where a single logical tool invocation may be retried, resumed, or replayed across spans. Does not apply to single-shot, non-retrying LLM calls whose span closes exactly once per provider response.
Core Distinction
The OpenTelemetry GenAI conventions describe *what to record on a span* — `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`. They do **not** describe *how a retried or resumed execution maps onto span cardinality*. The failure boundary is not "wrong attribute value" — it is **span multiplicity versus logical-call identity**.
When an agent retries a tool call after a partial token stream (provider closed mid-chunk, timeout, or a client-side guard tripped on a truncated JSON argument), the naive instrumentation opens a *new* span for the retry. Each span carries its own `gen_ai.usage.*` counts. The sum over spans is then arithmetically correct per span and arithmetically wrong per logical call. No span is malformed; the aggregate is a lie. This is the non-obvious part: schema validation passes, dashboards render, and the token bill diverges from the provider invoice by exactly the retried partials.
What Was Observed
A retrieval-augmented agent issued a `search` tool call whose argument was a large JSON object streamed as tokens. At chunk 340 of an expected ~700, the transport reset. The agent's retry wrapper re-invoked the model with the same prompt. The model, being non-deterministic, produced a *slightly different* argument this time and a *different* `gen_ai.tool.call.id` because the SDK generated the id client-side per attempt.
Observed span sequence:
- Span A: `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=search`, `gen_ai.tool.call.id=call_7f3a`, `gen_ai.usage.output_tokens=340`, status `ERROR` (transport reset).
- Span B: `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=search`, `gen_ai.tool.call.id=call_9c11`, `gen_ai.usage.output_tokens=712`, status `OK`.
The provider billed 340 + 712 = 1052 output tokens for what the agent's own task graph records as **one** tool call. The trace backend's "tokens per tool call" panel summed per-span and reported 1052. The agent's cost ledger, keyed on logical call id, reported 712. Both are "correct" against their own schema. The divergence is invisible until reconciled against the invoice.
Worse: the retry produced a *different* argument (`query:"Q3 revenue 2024"` vs. the truncated `query:"Q3 rev"`). The first partial call had, in fact, already been executed server-side before the stream reset — the tool ran, returned, and the response was lost in transport. So span A's `ERROR` status misrepresents a *side effect that occurred*. A downstream deduplication guard keyed on `gen_ai.tool.call.id` saw two distinct ids and permitted the second execution, duplicating a non-idempotent write.
Condition of Validity
The invariant that must hold for any aggregate token or tool-call metric to be meaningful is:
> **For every logical agent action, exactly one span carries `gen_ai.usage.*` accounting for the provider-side cost, and every retry attempt is a child span that carries attempt-local usage but is excluded from logical-call aggregation by an explicit parent reference.**
This requires three things the base conventions do not mandate:
- A **stable logical-call identifier** propagated across attempts (not the per-attempt `gen_ai.tool.call.id`, which the SDK mints fresh). Typically a `gen_ai.conversation.id` plus an agent-authored `logical.call.id` attribute.
- An **attempt index** attribute (`retry.attempt`) so aggregation can select `attempt == 0` or sum only billed attempts.
- **Side-effect reconciliation**: if the tool executed server-side before the stream reset, the retry must be gated by an idempotency key derived from the logical call id, not the transport-level call id.
The condition of validity fails the moment retries are modeled as sibling spans with fresh ids and no shared logical key. It also fails when a resumed stream (provider supports continuation) is instrumented as a fresh span rather than a continuation of the original, because then `output_tokens` on the continuation span is *cumulative* while the retry span is *delta* — mixed semantics in the same attribute.
Decision Boundary
The boundary is between **attempt-scoped accounting** (what the conventions natively support) and **action-scoped accounting** (what cost reconciliation, idempotency, and audit require). Crossing it requires the instrumentation layer — not the semantic conventions — to enforce:
- **On retry:** open a child span under the logical call span; do not re-mint `gen_ai.tool.call.id`; set `retry.attempt=n`; mark `gen_ai.usage.*` as attempt-local.
- **On resume:** if the provider continues the same completion, *update* the original span's usage to cumulative rather than emitting a second span, or emit a continuation span with `gen_ai.usage.*` explicitly flagged `cumulative=true`.
- **On side-effect uncertainty:** if the transport reset occurred after the request was sent but before any response token, mark the span `outcome=INDETERMINATE` and force the retry through an idempotency-keyed path. Do not trust `ERROR` to mean "did not happen."
The decision is: *does the retry wrapper own the span lifecycle, or does the model SDK?* If the SDK owns it, you get sibling spans with fresh ids and silent divergence. If the wrapper owns it, the wrapper must suppress the SDK's auto-span and emit the logical/attempt hierarchy itself.
Operational Effect
With the invariant enforced, the token ledger and the invoice reconcile to within the provider's own retry accounting, and non-idempotent tools are executed once per logical call. Without it, three failures compound silently:
- **Token overcount** proportional to retry rate — typically 3–15% in agents with aggressive timeouts, invisible because every span validates.
- **Duplicate side effects** on any non-idempotent tool whose transport failed post-execution — the `ERROR` status is a *transport* signal, not an *execution* signal, and dedup keyed on `gen_ai.tool.call.id` cannot catch it.
- **Cost attribution drift** between the trace backend (per-span sum) and the agent's own ledger (per logical call) — a gap that grows with retry rate and is only detectable by invoice reconciliation, which is too late.
The guardrail is a single rule: **the logical call id, not the transport call id, is the unit of accounting and idempotency.** Everything else is a consequence.
class GenAISpanAccountingError(RuntimeError):
"""Raised when a retried/resumed GenAI tool span would break logical-call accounting."""
pass
def close_tool_span(span, logical_call_id, attempt, usage, prior_attempts):
"""
Enforce: one logical call -> one accounting owner; retries are attempt-local children.
prior_attempts: list of dicts with keys {attempt, output_tokens, executed_server_side}
"""
if span.attributes.get("gen_ai.tool.call.id") is None:
raise GenAISpanAccountingError("tool span missing gen_ai.tool.call.id")
if attempt > 0:
# Retry: must be a child of the logical call, must not re-own accounting.
if span.parent is None or span.parent.attributes.get("logical.call.id") != logical_call_id:
raise GenAISpanAccountingError(
f"retry attempt {attempt} for {logical_call_id} is not parented to the "
f"logical call span; token aggregate will double-count"
)
if not span.attributes.get("retry.attempt"):
raise GenAISpanAccountingError(
"retry span missing retry.attempt; aggregation cannot exclude it"
)
# If a prior attempt may have executed server-side, retry must be idempotency-gated.
if any(p.get("executed_server_side") for p in prior_attempts):
if not span.attributes.get("idempotency.key"):
raise GenAISpanAccountingError(
f"prior attempt for {logical_call_id} may have executed server-side; "
f"retry lacks idempotency.key and risks duplicate side effect"
)
# Mixed cumulative/delta usage in one attribute is unrecoverable.
if usage.get("cumulative") and attempt > 0:
raise GenAISpanAccountingError(
"resumed stream reported cumulative usage on a retry span; "
"would mix delta and cumulative semantics under gen_ai.usage.*"
)
span.set_attribute("logical.call.id", logical_call_id)
span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"])
span.set_attribute("accounting.owner", attempt == 0)
return span
def reconcile(logical_calls, spans):
"""Sum only accounting-owner spans; assert one owner per logical call."""
owners = {}
for s in spans:
if s.attributes.get("accounting.owner"):
lc = s.attributes["logical.call.id"]
if lc in owners:
raise GenAISpanAccountingError(
f"multiple accounting owners for {lc}: "
f"{owners[lc]} and {s.span_id}"
)
owners[lc] = s.span_id
missing = set(logical_calls) - set(owners)
if missing:
raise GenAISpanAccountingError(f"logical calls with no accounting owner: {missing}")
return sum(s.attributes["gen_ai.usage.output_tokens"]
for s in spans if s.attributes.get("accounting.owner"))