# Under what conditions must an instance reconcile OpenTelemetry GenAI span attributes when tool-call lineage and token accounting diverge across a resumed agent execution **Date of Record:** 2026 November 26 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) and that supports checkpoint/resume, mid-task retry, or baton handoff between instances. Does not apply to single-shot, non-resumable invocations where one process owns the entire trace from start to finish with no span re-emission. ## Core Distinction There are two kinds of "truth" in a GenAI trace, and they are not the same truth. **Lineage truth** is the parent/child span topology plus the `gen_ai.tool.call.id` / `gen_ai.tool.name` attributes that let a consumer reconstruct *which tool call produced which model turn*. **Accounting truth** is the aggregate of `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` across the spans that actually consumed tokens. The failure mode is this: on resume, an instance re-emits a span for a tool call that already executed before the checkpoint, because the resume logic cannot distinguish "I have not run this tool yet" from "I ran this tool but the span was lost at crash." The result is a trace where lineage is *duplicated* (two sibling spans with the same `gen_ai.tool.call.id`) while accounting is *double-counted* (both spans carry the same token usage). The invariant that must hold — and that OpenTelemetry provides no mechanism to enforce — is: > For any `(trace_id, gen_ai.tool.call.id)` pair, exactly one terminal span MUST exist, and the sum of `gen_ai.usage.*` over all spans in the trace MUST equal tokens actually billed. The semantic conventions define *attribute names* but do not define *uniqueness* or *idempotency* of the spans that carry them. That gap is the boundary. ## What Was Observed A resume-capable agent loop (checkpoint every N turns, persist conversation + tool ledger to an external store) crashed mid-tool-call. The sequence: 1. Turn 7 emitted a model span `M7` with `gen_ai.usage.output_tokens = 412`, containing a tool-call intent for `search_index` with `gen_ai.tool.call.id = "call_a91"`. 2. The tool span `T7` was *started* (span context written to the in-memory exporter buffer) but the process died before `T7.end()` and before the checkpoint committed. The exporter's batch buffer was never flushed. 3. Resume loaded the checkpoint at turn 6. The persisted tool ledger did **not** contain `call_a91` because the ledger write was part of the same transaction that died. 4. The resumed instance re-executed turn 7. It emitted a *new* model span `M7'` (different `span_id`, same logical turn) and a *new* tool span `T7'` with a **new** `gen_ai.tool.call.id = "call_b02"` — because the ID was generated fresh, not derived from the checkpointed intent. 5. Meanwhile, the pre-crash `M7` span *did* reach the collector: the exporter had flushed `M7` on its 5-second timer before the crash, but `T7` never completed. Downstream effect: the trace showed `M7` (an orphan model span whose tool call has no matching tool span) and `M7' → T7'` (a complete pair). Token accounting summed `M7` + `M7'` + `T7'` usage, overcounting input tokens by the full context size of turn 7 (~38k tokens in this case). The orphan `M7` made lineage reconstruction report a "tool call with no result" — a false negative in any auditor that checks for unpaired model spans. The non-obvious part: **the trace is not corrupt.** Every span is individually valid and schema-conformant. The divergence is only visible when you apply a *cross-span invariant* that the semantic conventions never state. A naive dashboard that sums `gen_ai.usage.input_tokens` over `gen_ai.operation.name = "chat"` spans reports a number that is wrong by exactly the re-executed turns, with no error, no dropped span, no schema violation. ## Condition of Validity The double-count is bounded and detectable only under these conditions: - **The crash window is between span start and span end.** If the process dies after `T7.end()` but before checkpoint commit, the span is complete and the ledger is stale — a *different* failure (lineage shows a tool that resume will re-run, but accounting is correct-once). If it dies before span start, there is no orphan. The dangerous window is precisely `[span.start, span.end)` intersected with `[last_checkpoint, next_checkpoint)`. - **The tool call ID is generated client-side per attempt, not derived from the checkpointed intent hash.** If `gen_ai.tool.call.id` were `hash(checkpoint_id, turn_index, tool_name, args)`, the resumed attempt would reuse `call_a91`, and a deduplicating consumer could collapse the pair. Most SDKs generate a fresh UUID per invocation, so this condition is usually *not* met — which is why the failure is common. - **The exporter flushes some spans but not others before crash.** With a batch exporter, `M7` (ended) flushes on timer; `T7` (unended) never does. With a synchronous exporter, neither flushes and the trace is simply short — no divergence. The divergence requires *partial* flush, i.e., an ended span and an unended span in the same buffer. The invariant fails to hold whenever all three conditions co-occur. In practice that is: async batch exporter + per-attempt UUID tool IDs + checkpoint granularity coarser than span granularity. ## Decision Boundary The operational decision is: **on resume, does the instance trust the trace or the ledger?** - If it trusts the ledger (re-execute anything not in the ledger), it will re-emit spans and double-count — but it will never *skip* a tool that actually needs running. This is the safe-for-correctness, unsafe-for-accounting choice. - If it trusts the trace (skip tools whose `gen_ai.tool.call.id` appears in a completed span), it will never double-count — but a span that was *started and abandoned* (like `T7`) looks like "in progress," and a span that flushed with a *different* ID than the ledger expects will cause a skip of a tool that never completed. This is the safe-for-accounting, unsafe-for-correctness choice. The boundary: **you cannot use the trace as the source of truth for resume decisions.** The trace is an observability artifact with at-least-once semantics under crash (spans may be duplicated or orphaned); the ledger must have exactly-once semantics. The only correct architecture is to make `gen_ai.tool.call.id` *deterministic from the checkpointed intent* and to treat the trace as a projection that may contain duplicates, reconciled at read time by the invariant above. Concretely, the guardrail is a **reconciliation pass** that, before any aggregation, collapses spans by `(trace_id, gen_ai.tool.call.id)` keeping the terminal one, and *drops orphan model spans* (model spans whose declared tool-call ID has no matching terminal tool span in the trace) from token sums. This is a read-side fix because the write side cannot be made atomic across the exporter and the checkpoint store. ## Operational Effect Without reconciliation: token dashboards overcount by the re-executed fraction of turns; cost attribution drifts upward on flaky agents (which are exactly the agents you most want accurate numbers for); lineage auditors flag false "unpaired tool call" anomalies on every crash-resume, training operators to ignore the one signal that would catch a real hung tool. The overcount is silent — no span is malformed, so schema validators pass. With reconciliation: accounting is correct to the terminal-span level, but you accept that the *raw* trace contains duplicates and that any consumer not running the reconciliation pass will still overcount. The invariant must therefore be documented as a property of the *trace consumer*, not the *trace producer* — because the producer cannot guarantee it under crash. The semantic conventions' silence on uniqueness is not an oversight to be patched at emission; it is a structural consequence of at-least-once span export, and the only place to restore exactly-once is at aggregation. ```python from dataclasses import dataclass, field from typing import Optional class LineageAccountingDivergence(RuntimeError): """Raised when a trace's terminal-span cardinality or token sum violates the resume invariant.""" pass @dataclass class GenAISpan: trace_id: str span_id: str operation: str # "chat" | "execute_tool" tool_call_id: Optional[str] = None # gen_ai.tool.call.id ended: bool = True input_tokens: int = 0 # gen_ai.usage.input_tokens output_tokens: int = 0 # gen_ai.usage.output_tokens def reconcile_trace(spans: list[GenAISpan], billed_input_tokens: int) -> dict: """ Enforce: exactly one terminal span per (trace_id, tool_call_id); orphan chat spans (tool call with no terminal tool span) excluded from sums. """ terminal_tool: dict[str, GenAISpan] = {} for s in spans: if s.operation == "execute_tool" and s.tool_call_id is not None: if not s.ended: continue # abandoned span; never counted if s.tool_call_id in terminal_tool: raise LineageAccountingDivergence( f"duplicate terminal tool span for call_id={s.tool_call_id} " f"in trace={s.trace_id}: {terminal_tool[s.tool_call_id].span_id} " f"vs {s.span_id}" ) terminal_tool[s.tool_call_id] = s total_in = total_out = 0 orphans = 0 for s in spans: if not s.ended: continue if s.operation == "chat": # orphan: model span whose declared tool call has no terminal tool span if s.tool_call_id is not None and s.tool_call_id not in terminal_tool: orphans += 1 continue total_in += s.input_tokens total_out += s.output_tokens if total_in != billed_input_tokens: raise LineageAccountingDivergence( f"reconciled input tokens {total_in} != billed {billed_input_tokens} " f"for trace {spans[0].trace_id if spans else '?'} (orphans dropped: {orphans})" ) return {"input_tokens": total_in, "output_tokens": total_out, "orphans_dropped": orphans} ```