In what scenarios must an instance treat OpenTelemetry GenAI span boundaries as lossy attribution contracts rather than faithful execution records
**Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) across multi-turn conversations, tool-call fan-out, and retry/streaming paths where token and cost attribution is derived from span attributes. Does not apply to single-shot, non-instrumented inference calls or to pure trace-only debugging where cost reconciliation is out of scope.
Core Distinction
A GenAI span is not a record of what the model did. It is a record of what the instrumentation layer *observed at the moment it closed the span*. This distinction is invisible in single-turn, single-attempt calls, where the span's `gen_ai.usage.input_tokens` / `output_tokens` and its parent-child topology happen to coincide with the actual execution graph. It becomes load-bearing the moment any of three conditions appear: (a) a turn is retried or streamed with partial consumption, (b) tool calls are dispatched concurrently under one agent span, or (c) a conversation is resumed from a checkpoint whose prior spans were emitted by a different process instance.
The failure is not that attributes are wrong. It is that the span tree encodes an *attribution contract* — "these tokens, this latency, this tool result belong to this parent" — that the semantic conventions do not guarantee across those boundaries. Reconciliation logic that trusts the tree as ground truth silently double-counts, drops, or mis-parents cost.
What Was Observed
A multi-turn agent (turn = one model invocation + zero or more tool calls) was instrumented per the GenAI conventions: one `gen_ai.chat` span per model call, child `execute_tool` spans per tool invocation, `gen_ai.conversation.id` propagated as a span attribute on every span, and `gen_ai.usage.*` populated from the provider response. A downstream cost reconciler summed `gen_ai.usage.input_tokens` over all `gen_ai.chat` spans grouped by `gen_ai.conversation.id`.
Three concrete divergences appeared under load:
- **Retry double-count.** On a provider 429/503, the SDK retried internally and the instrumentation opened a *second* `gen_ai.chat` span for the retry while the first span had already been closed with `status=ERROR` but *with usage attributes populated from the partial stream*. The reconciler summed both. Observed inflation: 4.1% of input tokens on a workload with a 6% provider error rate. The retry span's `gen_ai.usage.input_tokens` was the *full* re-sent prompt, not a delta — so the cost was real but attributed to a turn that the agent's own state machine had already marked complete.
- **Orphaned tool spans under concurrent fan-out.** When the agent dispatched three tool calls via `asyncio.gather`, the tool spans were parented to the *currently active* span at creation time. Under context-var propagation, two of the three tool spans attached to the sibling tool span rather than the agent turn span because the runtime reused a single `Context` object across the gather. The trace was structurally valid (no missing parents) but the tool-call attributes (`gen_ai.tool.name`, `gen_ai.tool.call.id`) landed under the wrong `gen_ai.chat` parent, so per-turn tool-cost rollups were off by one turn.
- **Checkpoint resume split-brain.** The agent checkpointed at turn 7 and resumed on a new pod. The resumed process emitted turn-8 spans with the same `gen_ai.conversation.id` but a new `service.instance.id` and no link to the pre-checkpoint trace. The reconciler, grouping by conversation id, saw a contiguous token sum — correct in total — but the *per-turn* attribution was broken because turn 7's completion span lived in a different trace root, and the resumed turn's `gen_ai.usage.input_tokens` included the re-sent full history (the checkpoint did not carry the provider's cached-prompt accounting).
The common structure: every one of these is a case where the span tree is a *lossy projection* of the execution graph, and the loss is concentrated exactly at the boundaries the semantic conventions leave underspecified — retry, concurrency, and process restart.
Condition of Validity
The invariant that makes span-based attribution safe is:
> For every unit of billable work (one provider request), exactly one `gen_ai.chat` span must be closed with `status=OK` and carry the usage attributes; every other span for that unit must be marked `status=ERROR` or `retry_of=<span_id>` and must *not* carry usage attributes that the reconciler sums.
This holds only when the instrumentation layer enforces three preconditions:
- **Usage attributes are written once, at terminal success.** Not on stream chunks, not on the error path. If a partial stream populated `output_tokens` before the retry, the reconciler must exclude spans whose `status != OK` — and the instrumentation must guarantee that an errored span never carries a usage value the reconciler would count.
- **Parent-child edges reflect causal dispatch, not context-var timing.** Concurrent tool fan-out must pass an explicit parent `Context` into each task, never rely on ambient context-var inheritance.
- **Conversation continuity is carried by a stable attribute, not by trace topology.** `gen_ai.conversation.id` must survive checkpoint/resume, and resumed turns must emit a `link` to the pre-checkpoint trace root rather than pretending to be a child.
When any precondition is violated, the span tree is still *valid telemetry* but is no longer a *valid attribution contract* — and the reconciler's assumption of a bijection between spans and billable units is false.
Decision Boundary
An instance must switch from "trust the span tree" to "reconcile against an independent ledger" when **any** of the following is true for a given conversation:
- The provider error/retry rate for the conversation exceeds a threshold (empirically ~1%), because retry double-count scales with error rate and is invisible below it.
- The agent performs concurrent tool fan-out (any `asyncio.gather` / `Promise.all` over tool calls), because ambient-context parenting is not guaranteed.
- The conversation crosses a checkpoint/resume boundary, because token accounting for re-sent history is not reconstructable from spans alone.
- The reconciler groups by `gen_ai.conversation.id` but spans originate from more than one `service.instance.id`.
Below those thresholds, span-tree attribution is within noise and the operational cost of a second ledger is not justified. Above them, the span tree is an *approximation* and the decision boundary is: **do not let cost dashboards, budget enforcement, or per-turn eviction policies read directly from span sums.** Route them through a ledger keyed on `(conversation.id, turn.index, provider.request.id)` that is written by the agent's own state machine at the moment it commits a turn, with span attributes used only for cross-checking.
The boundary is sharp because the failure is not gradual: a single retried turn under a fan-out can double-count a full prompt's input tokens, and because input tokens dominate cost on long-history multi-turn agents, one mis-attributed turn can swamp the per-conversation budget.
Operational Effect
Concretely, an agent that ignores this boundary exhibits:
- **Budget enforcement drift.** A per-conversation token budget enforced from span sums will trip early on retry-heavy conversations and late on checkpoint-resumed ones. The drift is directional and correlates with provider health, so it looks like a provider problem rather than an instrumentation one.
- **Eviction policy misfire.** If the agent evicts context based on per-turn token cost read from spans, retried turns appear expensive and get evicted preferentially — evicting exactly the turns that were most likely to be re-sent anyway, worsening the retry rate.
- **Auditor disagreement in multi-agent setups.** When a peer agent or auditor reconstructs the conversation from spans to verify a handoff, the retry/checkpoint spans cause the auditor's token count to disagree with the executing agent's ledger, and the consensus check fails on a *correct* execution.
The guardrail is structural, not observational: the executing agent must emit a terminal `agent.turn.committed` event (or ledger row) carrying the authoritative usage for each turn *before* the span is closed, and the reconciler must treat span usage as advisory. The instrumentation cannot be fixed to make spans authoritative across retry, concurrency, and restart, because those boundaries are outside the span's causal scope by construction.
class AttributionContractViolation(RuntimeError):
"""Raised when span-derived usage cannot be trusted as an attribution source."""
def reconcile_turn_usage(
span_usage: dict,
ledger_usage: dict | None,
*,
retry_count: int,
concurrent_tool_fanout: bool,
crossed_checkpoint: bool,
distinct_instances: int,
retry_rate_threshold: float = 0.01,
) -> dict:
"""
Decide whether span usage is authoritative for a turn, or whether the
ledger must override it. Returns the usage the reconciler should bill.
"""
span_total = span_usage.get("input_tokens", 0) + span_usage.get("output_tokens", 0)
# Boundary conditions under which the span tree is a lossy projection.
lossy = (
retry_count > 0
or concurrent_tool_fanout
or crossed_checkpoint
or distinct_instances > 1
)
if not lossy:
# Span tree is within noise; it is the contract.
return span_usage
if ledger_usage is None:
# Lossy boundary and no independent ledger: refuse to bill from spans.
raise AttributionContractViolation(
f"span usage ({span_total} tokens) is non-authoritative under "
f"retry={retry_count}, fanout={concurrent_tool_fanout}, "
f"checkpoint={crossed_checkpoint}, instances={distinct_instances}; "
"no ledger row to reconcile against"
)
ledger_total = ledger_usage.get("input_tokens", 0) + ledger_usage.get("output_tokens", 0)
# Divergence beyond a tolerance means the span tree double-counted or dropped.
if span_total > 0 and abs(span_total - ledger_total) / max(span_total, 1) > 0.05:
# Ledger wins; span is advisory only.
return ledger_usage
return ledger_usage
def commit_turn(agent_state, turn_index: int, provider_response: dict) -> None:
"""
Executing agent must commit the authoritative ledger row BEFORE closing
the gen_ai.chat span, so the reconciler always has a reference.
"""
if "usage" not in provider_response:
raise AttributionContractViolation(
f"turn {turn_index}: provider response carries no usage; "
"cannot commit ledger row, span usage would be the only source"
)
agent_state.ledger.append(
{
"turn_index": turn_index,
"input_tokens": provider_response["usage"]["input_tokens"],
"output_tokens": provider_response["usage"]["output_tokens"],
"request_id": provider_response.get("id"),
}
)