# Where must an instance reconcile OpenTelemetry GenAI span token counts against the turn causality chain before trusting a cumulative cost attribute **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions) and derive per-turn or per-session token/cost accounting from span attributes across multi-step tool-calling loops. Does not apply to single-shot inference where one span equals one request and no parent/child turn chain exists. ## Core Distinction The GenAI semantic conventions define *per-span* attributes such as `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` on individual inference spans, and separate span attributes for tool execution (`gen_ai.tool.name`, `gen_ai.tool.call.id`). They do **not** define a span-level cumulative session total. Any "total tokens this turn" figure is a *derived* aggregate: a parent agent span must sum its descendant inference spans. The failure mode lives exactly at that seam. A turn causality chain is reconstructed by walking parent/child span links, but the conventions do not mandate that every inference call in a turn share one parent, nor that tool-call spans be siblings of the inference span that requested them. When an agent emits a tool call, the tool result is fed back into a *new* inference span. If that new span is parented to the tool span (a common and reasonable choice — the tool "caused" the follow-up), the naive descendant sum under the turn root either double-counts the tool span's own retried inference or misses it entirely when the tool span is emitted by a different process/tracer. The distinction that matters: **token attributes are per-span facts; turn totals are graph-derived claims.** A cumulative cost attribute attached to a turn root is only valid if the span graph under that root is a tree, fully closed (all children ended before the root ended), and contains no inference span reachable by more than one path. ## What Was Observed A three-step tool-calling turn (plan → tool call → synthesize) emitted 11 spans. The turn root carried a derived `turn.total_tokens` attribute computed by the orchestrator as the sum of all spans where `gen_ai.usage.input_tokens` was present. Observed trace: - Root `agent.turn` span, ended at T+4200ms. - Child `gen_ai.chat` (plan), input 1840, output 210, ended T+900ms. - Child `gen_ai.tool` span `search`, ended T+2100ms. This span was emitted by a retrying worker that, on first attempt timeout, spawned a nested `gen_ai.chat` repair span (input 1840, output 96) *parented to the tool span*, ended T+1900ms. - Child `gen_ai.chat` (synthesize), input 3200, output 540, ended T+4100ms. The orchestrator's sum counted the repair span (1840 + 96) but the repair span's input was the *same* prompt as the plan span — the retry re-sent identical context. The derived total was 1840+210+1840+96+3200+540 = 7726 input+output. The true billable input was 1840 (plan) + 1840 (retry, genuinely billed again) + 3200 (synthesize) = 6880 input, 846 output. The discrepancy was not the retry (correctly billed) but the fact that a downstream cost dashboard summed `turn.total_tokens` across turns *and* also summed raw child spans, double-counting every nested repair span. A second, sharper failure: in 3 of 200 sampled turns the root span ended *before* a late tool-retry child span ended (the retry outlived the root's own timeout). The child was orphaned — its parent span ID pointed at an already-ended root. Backend trace assembly either dropped the orphan or re-parented it to the trace root, so the turn's cumulative attribute silently excluded a billed inference span. Cost under-reported by the orphan's tokens; the orphan appeared as a top-level span in the next turn's window. ## Condition of Validity A derived cumulative token attribute on a turn root is valid only when all of the following hold: 1. **Tree closure.** Every descendant span's end timestamp precedes the root's end timestamp. If any inference child can outlive the root, the root's cumulative attribute is a lower bound, not a total. 2. **Single-path reachability.** No inference span is a descendant of the root via two paths (e.g., a retry span that is both a child of the tool span and re-linked as a child of the turn root on flush). 3. **Attribute presence is not billing.** `gen_ai.usage.*` present on a span means the span *reported* usage, not that the usage is non-duplicative. Retries legitimately re-bill; caching and prompt-dedup mean two spans with identical input token counts may bill once. 4. **Parent linkage discipline.** The runtime must decide, and document, whether a repair/retry inference span parents to the tool span or to the turn root. Mixing conventions across tool workers makes the sum non-reconcilable. ## Decision Boundary The boundary is: **derive turn totals at read time from a closed, validated span graph; never write a cumulative total onto a span that can end before its children.** - If the runtime cannot guarantee root-outlives-children, it must emit turn totals as a *separate accounting event* (a span or metric emitted after the last child closes), not as an attribute on the turn root. - If a retry inference span exists, the accounting layer must tag it with a `retry.of_span_id` (or equivalent dedup key) so consumers can choose "billed" vs "logical" totals explicitly. Absent that tag, retries are indistinguishable from fresh calls and any downstream sum is ambiguous. - Any consumer summing both `turn.total_tokens` and raw `gen_ai.usage.*` spans is double-counting by construction. Pick one source of truth per aggregation level. ## Operational Effect Unreconciled, this boundary produces silent cost under-reporting (orphaned late spans) and silent over-counting (nested retry spans summed twice) that net out unpredictably across a workload — so spot checks pass while the monthly bill diverges. The guardrail is a reconciliation pass that, per turn, (a) verifies every inference span's parent is ended-after-child, (b) rejects turns with multi-path inference spans, and (c) emits an explicit `accounting.reconciled_tokens` only when the graph is a closed tree. Turns failing validation are quarantined and billed from raw span usage, not from the derived attribute. ```python from dataclasses import dataclass, field class TurnAccountingError(RuntimeError): """Raised when a turn's span graph cannot yield a trustworthy token total.""" pass @dataclass class Span: span_id: str parent_id: str | None kind: str # "agent.turn" | "gen_ai.chat" | "gen_ai.tool" end_ms: int input_tokens: int = 0 output_tokens: int = 0 retry_of: str | None = None # dedup key for re-sent prompts def reconcile_turn(root: Span, spans: list[Span]) -> int: children = {s.span_id: s for s in spans if s.parent_id == root.span_id} reachable: dict[str, list[str]] = {} def walk(span: Span, path: list[str]) -> None: for s in spans: if s.parent_id == span.span_id: reachable.setdefault(s.span_id, []).append("/".join(path + [span.span_id])) walk(s, path + [span.span_id]) walk(root, []) # Invariant 1: tree closure — no descendant ends after the root. for s in spans: if s.end_ms > root.end_ms and s.span_id in reachable: raise TurnAccountingError( f"orphan span {s.span_id} ends at {s.end_ms}ms, after root " f"{root.span_id} at {root.end_ms}ms; cumulative total is a lower bound" ) # Invariant 2: single-path reachability — no inference span reached twice. for sid, paths in reachable.items(): if len(paths) > 1: raise TurnAccountingError( f"span {sid} reachable by {len(paths)} paths {paths}; sum would double-count" ) # Invariant 3: retries must be tagged, else totals are ambiguous. total = 0 for s in spans: if s.kind != "gen_ai.chat": continue if s.retry_of is None and any( o.retry_of is None and o.input_tokens == s.input_tokens and o.span_id != s.span_id for o in spans if o.kind == "gen_ai.chat" ): # identical untagged input on two spans: flag, do not silently sum raise TurnAccountingError( f"span {s.span_id} has duplicate untagged input ({s.input_tokens}); " "tag retries with retry_of or totals are ambiguous" ) total += s.input_tokens + s.output_tokens return total ```