In what scenarios must an instance treat OpenTelemetry GenAI span boundaries as a correctness constraint rather than a logging convenience
**Date of Record:** 2026 December 1
**Scope:** Applies to any LLM agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for tool invocations, token accounting, and multi-turn agent attribution, where span lifecycle is bound to the agent's execution lifecycle. Does not apply to pure request-scoped inference proxies that never resume, replay, or fan out an agent turn across processes.
Core Distinction
The GenAI semantic conventions model a span as a *record of a completed operation*: `gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and for tool calls a span with `gen_ai.operation.name = "execute_tool"` and `gen_ai.tool.name`/`gen_ai.tool.call.id`. This modeling assumes a one-to-one mapping between a logical agent operation and a span's start/end timestamps. The failure mode lives in the gap: an agent turn is *not* an operation with a well-defined end. It is a re-entrant, resumable, potentially forked computation whose true boundaries are checkpoint boundaries, not span boundaries.
The distinction that matters operationally: a span is **observability metadata** when the agent's correctness does not depend on it, and a **correctness constraint** when downstream logic (token budget enforcement, turn attribution for billing/audit, replay-based verification, cost-based throttling) reads span-derived aggregates back as authoritative state. The moment any component treats `sum(gen_ai.usage.output_tokens)` across spans as the agent's consumed budget, span boundary errors become *semantic* errors, not cosmetic ones.
What Was Observed
A tool-using agent resumed from a mid-turn checkpoint. The original process had emitted a `gen_ai.chat` span for the model turn that produced a tool call, then crashed before the `execute_tool` child span closed. On resume, the runtime re-executed the model turn (because the checkpoint was taken before the tool result was committed), producing a *second* `gen_ai.chat` span with its own `gen_ai.usage.output_tokens`, and then a fresh `execute_tool` span with the *same* `gen_ai.tool.call.id` because the tool call ID was deterministically derived from the turn index.
The resulting trace contained:
- Two `gen_ai.chat` spans under the same logical turn, both claiming `gen_ai.usage.output_tokens` for reasoning that was only paid for once at the provider (the second call was served from a prompt-cache hit, but the span recorded the full output token count because the runtime read it from the response object, not from the cache-aware usage block).
- Two `execute_tool` spans sharing one `gen_ai.tool.call.id`, one with `status.code = UNSET` (orphaned by the crash) and one with `status.code = OK`.
- A parent turn span whose `gen_ai.usage.input_tokens` reflected only the *resumed* context window, not the pre-crash context, so the sum of children exceeded the parent.
The budget enforcer, which summed `gen_ai.usage.output_tokens` across all `gen_ai.chat` spans with `gen_ai.operation.name = "chat"` in the trace, double-counted the turn and tripped the per-task token ceiling at ~60% of actual consumption. The agent was killed mid-execution and restarted from the *previous* checkpoint, which replayed the same fork. This is a stable limit cycle: the observability layer's token accounting drives a control decision that regenerates the condition that corrupts the accounting.
Condition of Validity
The invariant that holds under normal operation, and breaks here, is:
> **For a given `trace_id`, the sum of `gen_ai.usage.output_tokens` over spans with `gen_ai.operation.name = "chat"` equals the provider-billed output tokens for that agent task.**
This holds only when three conditions are simultaneously true:
- **Span cardinality matches logical-call cardinality.** No span is emitted for an attempt that was discarded (crash, retry, speculative fork, cache hit re-served). In practice this requires the runtime to emit spans *after* the attempt is committed, or to mark discarded attempts with an explicit attribute (e.g., `gen_ai.attempt.disposition = "discarded"`) that the aggregator filters on.
- **Usage attributes are read from the cache-aware usage block, not the response envelope.** Providers report cached input tokens separately (`gen_ai.usage.cache_read_input_tokens` in the conventions); a runtime that copies `usage.total_tokens` into `gen_ai.usage.output_tokens` inflates accounting on every resumed or deduplicated call.
- **Tool-call identity is unique per logical invocation.** `gen_ai.tool.call.id` must be stable across resume *only if* the resume reuses the prior result; if the resume re-executes, it must mint a new call ID, otherwise the trace cannot distinguish "retried the same call" from "called twice."
The failure above violates all three at once, which is why it is non-obvious: each violation in isolation is a minor logging defect; together they form a closed loop where the accounting error is *load-bearing* for a control decision.
Decision Boundary
The boundary is not "should we emit spans on resume" — you always should. The boundary is **whether span-derived aggregates are permitted to feed back into agent control flow without a reconciliation step.**
Concretely, a span aggregate may be treated as authoritative for budget/throttle decisions only if the runtime can guarantee the three conditions above at emission time. When it cannot (any resumable, forking, or speculative-execution agent), the aggregate must pass through a **reconciliation gate** that:
- Deduplicates by `(trace_id, turn_index, gen_ai.tool.call.id, attempt_disposition)` rather than by span count.
- Prefers the *committed* attempt's usage over discarded attempts, using an explicit commit marker rather than `status.code = OK` (an OK status on a lost span is not evidence of commitment).
- Reconciles child `gen_ai.usage.*` against the parent turn span, and if children exceed the parent, treats the *parent* as under-reported rather than the children as over-reported — the parent is the one that lost pre-crash context.
The guardrail is a **span-commit protocol**: a span for a model call or tool call is only emitted (or only marked authoritative) after the corresponding state mutation is durable in the checkpoint store. Observability must trail durability, never lead it. This is the same ordering discipline as write-ahead logging, applied to telemetry: the trace is a *derived* artifact of the checkpoint log, not a parallel source of truth.
Operational Effect
Without the commit protocol, the failure is not merely a noisy trace. It is a **self-reinforcing accounting divergence**: the corrupted aggregate triggers a control action (kill, throttle, restart) that regenerates the corruption. The agent's effective token budget shrinks with each replay cycle until it can no longer complete the task, and the trace looks *healthy* (all spans present, no error statuses) while the agent is in a livelock.
With the commit protocol, the trace becomes monotonic: each logical operation contributes exactly one authoritative usage record, discarded attempts are visible but quarantined by `attempt_disposition`, and the reconciliation gate converts a child-exceeds-parent condition into an explicit `SpanAccountingDivergence` signal rather than silently trusting the sum. The operational rule: **if any control decision reads a `gen_ai.*` aggregate, that aggregate must be reconstructable from the checkpoint log alone.** If it cannot be, the trace is a convenience, and the control decision must not depend on it.
from dataclasses import dataclass, field
from typing import Iterable
class SpanAccountingDivergence(RuntimeError):
"""Raised when a span-derived token aggregate cannot be reconciled against
the committed checkpoint log, i.e. observability has led durability."""
@dataclass
class GenAISpan:
trace_id: str
turn_index: int
operation: str # "chat" | "execute_tool"
tool_call_id: str | None
output_tokens: int
input_tokens: int
attempt_disposition: str # "committed" | "discarded" | "orphaned"
status_ok: bool
@dataclass
class TurnCheckpoint:
trace_id: str
turn_index: int
committed_output_tokens: int
committed_input_tokens: int
committed_tool_call_ids: set[str] = field(default_factory=set)
def reconcile_turn_usage(
spans: Iterable[GenAISpan],
checkpoint: TurnCheckpoint,
) -> dict[str, int]:
"""Reconstruct authoritative usage for one turn from spans, then verify it
against the committed checkpoint. Raises if the aggregate the budget
enforcer would read disagrees with durable state."""
committed_chat = [
s for s in spans
if s.operation == "chat"
and s.attempt_disposition == "committed"
and s.turn_index == checkpoint.turn_index
]
if len(committed_chat) != 1:
raise SpanAccountingDivergence(
f"turn {checkpoint.turn_index} has {len(committed_chat)} committed "
f"chat spans; expected exactly 1 (attempt disposition not set at emission?)"
)
span = committed_chat[0]
if span.output_tokens != checkpoint.committed_output_tokens:
raise SpanAccountingDivergence(
f"turn {checkpoint.turn_index}: span output_tokens={span.output_tokens} "
f"!= checkpoint committed={checkpoint.committed_output_tokens}; "
f"observability led durability (cache-aware usage block likely ignored)"
)
tool_ids = {
s.tool_call_id for s in spans
if s.operation == "execute_tool"
and s.turn_index == checkpoint.turn_index
and s.attempt_disposition == "committed"
}
if tool_ids != checkpoint.committed_tool_call_ids:
raise SpanAccountingDivergence(
f"turn {checkpoint.turn_index}: committed tool_call_ids {tool_ids} "
f"!= checkpoint {checkpoint.committed_tool_call_ids}; "
f"resume minted duplicate call IDs"
)
return {
"input_tokens": span.input_tokens,
"output_tokens": span.output_tokens,
"tool_calls": len(tool_ids),
}