# Which invariants prevent tool-call lineage and token accounting from silently diverging under OpenTelemetry GenAI span conventions **Date of Record:** 2026 November 27 **Scope:** Applies to agents that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*`) for multi-step tool-calling loops where token usage and parent-child tool lineage must reconcile across a checkpoint/resume boundary. Does not cover single-shot inference spans with no tool calls, nor vendor-proprietary trace formats that do not claim `gen_ai.*` conformance. ## Core Distinction The GenAI semantic conventions treat two things as *attributes on a span*: token accounting (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and tool-call lineage (`gen_ai.tool.name`, `gen_ai.tool.call.id`, plus the parent span linkage implied by the trace tree). The failure that matters is not "a span is missing" — it is that **these two attribute families are emitted at different points in the agent's lifecycle and are not jointly atomic**. Token usage is only knowable *after* the model response returns; tool-call identity is only knowable *before* the tool executes. When an agent checkpoints mid-loop (context-window saturation, budget cutoff, crash-resume), it can persist one without the other and produce a trace whose lineage is internally consistent but whose token ledger is duplicated or dropped. The distinction that matters: **span-tree correctness is not the same invariant as token-ledger correctness**, and OTel's schema does not bind them. ## What Was Observed An agent loop executing a 7-step tool chain resumed from a checkpoint after the context window saturated at step 4. On resume, the orchestrator replayed the last assistant turn — which contained a `tool_calls` array — and re-emitted the corresponding spans. The observed trace had: - **Duplicate tool spans:** the replayed `gen_ai.tool.call.id` (`call_abc123`) appeared twice as sibling spans under the same parent `gen_ai.chat` span, because the resumed process had no record that the span had already been closed. The trace tree remained *structurally valid* (both spans had well-formed parents) so no OTel validator flagged it. - **Doubled input tokens, halved output tokens:** the replayed `gen_ai.chat` span re-reported the full prompt (including all prior tool results) as `gen_ai.usage.input_tokens`, while the original span's output tokens (`gen_ai.usage.output_tokens`) were the *only* ones attributed to the actual generation. The resumed span reported output tokens for a response that was replayed from cache, not regenerated — so the ledger showed 2× input and 1× output against a single logical model call. - **Orphaned tool result:** one `gen_ai.tool` span from step 3 had a `gen_ai.tool.call.id` that no longer matched any `tool_calls[].id` in the resumed conversation state, because the checkpoint had truncated the tool-call history but retained the span. The critical observation: **every individual span was schema-valid**. `gen_ai.tool.name` was a string, `gen_ai.usage.input_tokens` was a non-negative integer, parent span IDs resolved. The corruption lived only in the *cross-span invariants* — uniqueness of `tool.call.id` per trace, and the sum of usage attributes equalling the logical model-call count — which OTel does not specify and no default exporter enforces. ## Condition of Validity The invariant that must hold for a trace to be trustworthy: 1. **Call-ID uniqueness:** within a trace, each `gen_ai.tool.call.id` appears exactly once as a `gen_ai.tool` span, and each such ID is matched by exactly one entry in the parent chat span's recorded `tool_calls` array. This is what binds lineage to the model's actual decision. 2. **Usage attribution:** the sum of `gen_ai.usage.input_tokens` across all `gen_ai.chat` spans in a trace equals the sum of tokens actually submitted to the model provider — replayed-from-cache turns must emit `0` input tokens or be marked with a distinct attribute (e.g., a `gen_ai.usage.cache_read_input_tokens` or a custom `replayed=true`), never re-counted as fresh. 3. **Checkpoint atomicity:** a checkpoint that captures conversation state must capture the set of already-emitted span IDs and call IDs atomically with it, so resume can suppress re-emission. These hold only when the agent's checkpoint record and the trace exporter share a single source of truth. They **fail** whenever the checkpoint is written by the agent runtime and the spans are written by a separate exporter process with no coordinated commit — which is the default in most frameworks. ## Decision Boundary The boundary is: **can the resumed process distinguish "this turn was generated" from "this turn was replayed"?** If yes, it can emit correct usage attributes and suppress duplicate spans. If no — because the checkpoint stores only the message array and not the emission ledger — then resume must choose between two lossy options: - **Suppress all replayed spans** → lineage is correct but the trace is missing the pre-checkpoint tool spans (ledger under-counts). - **Re-emit all replayed spans** → lineage is complete but call IDs duplicate and token usage double-counts (ledger over-counts and lineage invariant breaks). There is no third option without an emission ledger. The guardrail is therefore: **persist `{trace_id, span_id, tool_call_id, usage}` tuples in the checkpoint, keyed by turn index, and on resume emit a single `gen_ai.chat` span with `replayed=true` and zeroed usage rather than re-emitting the tool subtree.** Any architecture that checkpoints conversation state without this ledger sits on the wrong side of the boundary and will produce silently divergent ledgers under saturation or crash-resume. ## Operational Effect Downstream consumers — cost dashboards, lineage auditors, and replay verifiers — read the trace as ground truth. A doubled input-token count inflates cost attribution by up to 2× on resumed traces; a duplicated `tool.call.id` causes lineage auditors that key on call ID to either double-count tool invocations or, worse, deduplicate by taking the first occurrence and attributing the replayed tool's *result* to the wrong turn. The corruption is invisible to schema validation and only surfaces when a verifier recomputes the invariant "sum of usage == provider-side token count" or "call IDs unique per trace." The practical mitigation is to treat the checkpoint as the authoritative ledger and the trace as a derived, idempotent projection of it — never the reverse. ```python from dataclasses import dataclass, field from typing import Dict, Set class LineageLedgerDivergence(RuntimeError): """Raised when a resumed agent's span emission would violate tool-call-ID uniqueness or token-usage attribution invariants.""" pass @dataclass class CheckpointLedger: """Authoritative record persisted with the agent checkpoint. The trace is a derived projection; this is the source of truth.""" emitted_call_ids: Set[str] = field(default_factory=set) usage_by_turn: Dict[int, Dict[str, int]] = field(default_factory=dict) def emit_resumed_turn( ledger: CheckpointLedger, turn_index: int, tool_call_ids: list[str], reported_input_tokens: int, reported_output_tokens: int, replayed: bool, ) -> Dict[str, int]: """Project one resumed turn onto gen_ai.* span attributes, enforcing the uniqueness and attribution invariants before emission.""" # Invariant 1: call-ID uniqueness within the trace. duplicates = ledger.emitted_call_ids.intersection(tool_call_ids) if duplicates: raise LineageLedgerDivergence( f"turn {turn_index} re-emits tool_call_ids already present in " f"trace ledger: {sorted(duplicates)}; resume must suppress replayed " f"tool spans, not duplicate them" ) # Invariant 2: replayed turns must not re-count fresh input tokens. if replayed and reported_input_tokens > 0: raise LineageLedgerDivergence( f"turn {turn_index} is marked replayed but reports " f"{reported_input_tokens} fresh input tokens; cache/replay must " f"emit zero fresh usage to keep the token ledger additive" ) # Invariant 3: attribution is per-turn, not per-emission. if turn_index in ledger.usage_by_turn: raise LineageLedgerDivergence( f"turn {turn_index} already has usage attributed " f"({ledger.usage_by_turn[turn_index]}); checkpoint atomicity broken" ) ledger.emitted_call_ids.update(tool_call_ids) usage = { "gen_ai.usage.input_tokens": reported_input_tokens, "gen_ai.usage.output_tokens": reported_output_tokens, } ledger.usage_by_turn[turn_index] = usage return usage ```