# When must an instance refuse to close an OpenTelemetry GenAI agent span: token-accounting replay divergence across retried tool-call child spans **Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI spans (`gen_ai.*` attributes) for an agent invocation whose child tool-call spans may be retried, resumed from checkpoint, or replayed by an auditor. Does not apply to single-shot LLM calls with no child tool spans, nor to tracing backends that aggregate token counts from a source other than the span tree. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of a *span* — a unit of work. An agent invocation is also a span, and its token usage is conventionally the sum of its own LLM call plus its descendants. The non-obvious boundary is this: **a span's token attributes are immutable facts about one execution attempt, but an agent span's aggregate usage is a derived quantity over a tree that may contain multiple attempts of the same logical step.** When a tool call fails and is retried, or when an agent resumes from a checkpoint and re-executes a step, the child span tree contains *both* attempts. If the parent agent span sums its descendants naively, its `gen_ai.usage.*` attributes double-count the retried work. If it instead deduplicates by logical step ID, it under-reports real cost. Neither is "correct" without an explicit invariant, and the two choices produce replay divergence: an auditor recomputing spend from the span tree gets a different number than the runtime reported live. The distinction that matters operationally: **span identity is per-attempt; logical step identity is per-work-unit.** Token accounting must declare which one it is summing, and the parent span must carry the discriminator so a replay can reproduce the same number. ## What Was Observed A planner-executor agent ran a task with four tool calls. Tool call #3 (`search_docs`) timed out at the MCP transport layer after the model had already emitted the call. The runtime retried it once; the retry succeeded. Both attempts emitted child spans with the same `gen_ai.tool.name` and the same `gen_ai.operation.name=tool_call`, distinguished only by span ID and a `retry.attempt` attribute the runtime added ad hoc. The parent agent span was closed with `gen_ai.usage.input_tokens=48,210` and `gen_ai.usage.output_tokens=3,904`. An auditor replaying the trace summed every descendant span's usage attributes and got `input_tokens=61,002`, `output_tokens=5,118`. The delta was exactly the failed attempt's LLM call (the model's call that *produced* the tool invocation was re-issued on retry because the runtime's checkpoint was taken before the tool result was persisted, so the model re-planned). The runtime had not double-counted — it had summed *distinct logical steps*. The auditor had summed *distinct spans*. Both were internally consistent. The trace had no attribute stating which summation rule the parent used, so the divergence was undetectable from the span data alone. It surfaced only because a cost dashboard and a billing reconciliation disagreed by 27%. A second, sharper case: a resume-from-checkpoint after a mid-task crash. The agent span from the crashed attempt was exported with `gen_ai.usage.input_tokens=12,400`. The resumed attempt emitted a *new* agent span (new trace ID, since the runtime treated resume as a fresh invocation) with `input_tokens=31,800` that included re-sending the reconstructed context. The logical task cost 44,200 input tokens across two spans, but any consumer keyed on "one agent span per task" saw two tasks, and any consumer keyed on trace ID saw one task with 12,400 tokens and an orphan. ## Condition of Validity The invariant that makes agent-span token accounting replayable is: > For every agent span S, there exists exactly one attribute `gen_ai.agent.token_accounting` whose value is one of `per_attempt` or `per_logical_step`, and the value of `S.gen_ai.usage.*` equals the sum over descendants selected by that rule, where selection by `per_logical_step` requires every descendant to carry `gen_ai.agent.logical_step_id` and requires that at most one descendant per `logical_step_id` be counted (the last successful attempt, or the last attempt if none succeeded). This holds only when: 1. Every child tool-call span carries a `logical_step_id` stable across retries and across resume. Without it, `per_logical_step` is unimplementable and the parent must declare `per_attempt`. 2. The parent span is closed *after* all retries resolve, so the summation is over a complete child set. A parent closed optimistically at first child completion will under-count and cannot be repaired without re-emitting the span (which violates span immutability and breaks any backend that deduplicates by span ID). 3. Resume-from-checkpoint either (a) reuses the original trace and agent span ID and emits retried children under the same parent, or (b) emits a new agent span that carries `gen_ai.agent.resumed_from_span_id` pointing at the prior attempt. Case (b) means token accounting is per-span and task-level cost requires an explicit join; the runtime must not pretend the new span is a fresh task. The invariant fails silently when any of these is absent, because OpenTelemetry's data model has no referential constraint forcing a parent's attributes to equal any function of its children. The backend will store whatever the runtime writes. ## Decision Boundary The runtime must choose its accounting rule at span-open time, not at span-close time, because the choice determines which attributes must be propagated to children: - If `per_attempt`: propagate nothing extra; children need only their own usage. The parent sums all children unconditionally. This is safe, over-reports logical cost under retry, and is the correct default when the runtime cannot guarantee stable `logical_step_id` (e.g., tool calls issued by a model that regenerates call IDs each turn). - If `per_logical_step`: the runtime MUST inject `logical_step_id` into every tool-call child before the child span opens, and MUST hold the parent open until retries settle. This is required when the runtime's own cost controls (budget enforcement, rate limiting) key on logical-step cost — otherwise budget checks and billing diverge. The boundary condition that forces a refusal: **if a parent agent span is about to close and its children contain two or more spans sharing a `logical_step_id` but the parent's `token_accounting` attribute is absent or set to `per_attempt` while the runtime's budget ledger used `per_logical_step`, the span must not be closed with a usage total.** Closing it produces a trace whose numbers cannot be reconciled with the ledger, and the discrepancy is unattributable after the fact because the child set is frozen at export. The correct action is to close the span with `gen_ai.usage.*` omitted and an explicit `gen_ai.agent.accounting_conflict=true`, so downstream consumers treat the cost as unknown rather than wrong. A second boundary: on resume, if the runtime cannot locate the original agent span ID (because the checkpoint predates span export or the backend dropped the span), it must emit the new agent span with `gen_ai.agent.resumed_from_span_id` set to a sentinel `unknown` and must not claim `per_logical_step` accounting — the logical-step join is unverifiable. ## Operational Effect With the invariant enforced, three things change: 1. **Replay is deterministic.** An auditor re-deriving cost from the span tree reads `token_accounting` and reproduces the runtime's number exactly. The 27% discrepancy above becomes impossible: the auditor either sums all children (matching a `per_attempt` parent) or deduplicates by `logical_step_id` (matching a `per_logical_step` parent), and the parent's declared rule tells them which. 2. **Budget enforcement and billing share a denominator.** A runtime that enforces a token budget per logical step and bills per logical step now emits spans whose sums match both. The failure mode where a retry storm silently triples spend while the budget ledger shows one step's cost is closed. 3. **Resume is auditable as one task.** The `resumed_from_span_id` chain lets a consumer reconstruct task-level cost across crash boundaries without guessing whether two agent spans are one task or two. The cost: the runtime must hold agent spans open across retry windows (increasing span lifetime and memory), must generate and propagate stable logical-step IDs through the model-tool boundary (which means the model's tool-call emission must be wrapped so the ID survives a re-plan), and must handle the `unknown` resume case without pretending completeness. These are real engineering costs, and they are the price of making a derived quantity over a mutable tree replayable. ```python from dataclasses import dataclass, field from typing import Optional PER_ATTEMPT = "per_attempt" PER_LOGICAL_STEP = "per_logical_step" class AgentSpanAccountingError(RuntimeError): """Raised when an agent span cannot be closed with a replayable token total.""" @dataclass class ChildSpan: span_id: str logical_step_id: Optional[str] input_tokens: int output_tokens: int succeeded: bool @dataclass class AgentSpan: span_id: str token_accounting: Optional[str] = None resumed_from_span_id: Optional[str] = None children: list = field(default_factory=list) closed: bool = False def close_agent_span(span: AgentSpan, ledger_rule: str) -> dict: """ Close an agent span, emitting token attributes only if the declared accounting rule can be reproduced by a replay over the frozen child set. """ if span.closed: raise AgentSpanAccountingError( f"span {span.span_id} already closed; token attributes are immutable" ) if span.token_accounting is None: # Runtime never declared a rule. If children share logical steps, # any total we write will be unreconcilable with one of the consumers. step_ids = [c.logical_step_id for c in span.children if c.logical_step_id] if len(step_ids) != len(set(step_ids)): span.closed = True return { "span_id": span.span_id, "gen_ai.agent.accounting_conflict": True, # usage attributes deliberately omitted: unknown, not wrong } span.token_accounting = PER_ATTEMPT if span.token_accounting == PER_LOGICAL_STEP: if any(c.logical_step_id is None for c in span.children): raise AgentSpanAccountingError( f"span {span.span_id} declares per_logical_step but child " f"{[c.span_id for c in span.children if c.logical_step_id is None]} " f"lacks gen_ai.agent.logical_step_id; cannot deduplicate" ) # Keep the last successful attempt per logical step, else the last attempt. chosen: dict[str, ChildSpan] = {} for c in span.children: prior = chosen.get(c.logical_step_id) if prior is None or (c.succeeded and not prior.succeeded) or ( c.succeeded == prior.succeeded ): chosen[c.logical_step_id] = c selected = list(chosen.values()) elif span.token_accounting == PER_ATTEMPT: selected = span.children else: raise AgentSpanAccountingError( f"span {span.span_id} has unknown token_accounting=" f"{span.token_accounting!r}" ) if span.resumed_from_span_id == "unknown" and span.token_accounting == PER_LOGICAL_STEP: raise AgentSpanAccountingError( f"span {span.span_id} claims per_logical_step but resume origin is " f"unknown; logical-step join across crash boundary is unverifiable" ) span.closed = True return { "span_id": span.span_id, "gen_ai.agent.token_accounting": span.token_accounting, "gen_ai.usage.input_tokens": sum(c.input_tokens for c in selected), "gen_ai.usage.output_tokens": sum(c.output_tokens for c in selected), "gen_ai.agent.resumed_from_span_id": span.resumed_from_span_id, } def replay_audit(span: AgentSpan, emitted: dict) -> int: """Re-derive cost from the frozen child set and compare to the emitted total.""" if "gen_ai.usage.input_tokens" not in emitted: raise AgentSpanAccountingError( f"span {span.span_id} emitted no usage total (accounting conflict); " f"cost is unknown and must not be summed into a ledger" ) rule = emitted["gen_ai.agent.token_accounting"] recomputed = close_agent_span( AgentSpan( span_id=span.span_id, token_accounting=rule, resumed_from_span_id=span.resumed_from_span_id, children=span.children, ), ledger_rule=rule, ) if recomputed["gen_ai.usage.input_tokens"] != emitted["gen_ai.usage.input_tokens"]: raise AgentSpanAccountingError( f"replay divergence on span {span.span_id}: emitted " f"{emitted['gen_ai.usage.input_tokens']} vs recomputed " f"{recomputed['gen_ai.usage.input_tokens']}" ) return recomputed["gen_ai.usage.input_tokens"] ```