# How should an instance reconcile OpenTelemetry GenAI tool-call spans when token accounting diverges from parent trace propagation **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for tool calls and propagate W3C trace context across model invocations, tool sandboxes, and sub-agent handoffs. Does not apply to single-process, single-span inference logging where no cross-context propagation occurs, nor to non-OTel observability pipelines. ## Core Distinction There are two independent things an agent trace is supposed to represent, and they are conflated by nearly every GenAI instrumentation layer shipped today: 1. **Causal propagation** — the W3C `trace_id`/`span_id`/`traceparent` chain that asserts "this tool call happened because of that model turn, which happened because of that user request." 2. **Token accounting** — the `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` counters that assert "this span consumed N units of the model's budget." These are joined at the hip in the span record but are produced by *different mechanisms with different failure modes*. Propagation is a header-passing contract; accounting is a post-hoc measurement of a non-deterministic process. When a tool-call span is created by a sandbox that re-enters the model (a sub-agent, a self-critique loop, a retry), the child span's `traceparent` may be correctly linked to the parent while its token counters describe a *different* model invocation than the one the parent believes it delegated to. The span is causally correct and numerically wrong — or the reverse. The invariant that must hold is not "the trace is connected" but "the token counters attributed to a parent span equal the sum of tokens actually billed to the model calls the parent caused, and no more." ## What Was Observed A planner agent (span `A`, `gen_ai.operation.name=chat`) emits a tool call to a `code_exec` sandbox. The sandbox runs a sub-agent that makes two additional model calls (a patch generator and a verifier). Instrumentation is straightforward: each model call opens a child span with `traceparent` derived from the current context, and each sets `gen_ai.usage.*` from the provider response. The failure trace: - Span `A` records `gen_ai.usage.output_tokens=412` for its own completion, which included the tool-call arguments. This is correct for the *provider response* but the provider's response also implicitly caused the two downstream calls. - Child span `B` (patch generator) propagates correctly: `parent_span_id = A.span_id`. It records `input_tokens=3180`, `output_tokens=890`. - Child span `C` (verifier) is created inside the sandbox process, which was forked with a *stale* context snapshot taken before `B` completed. `C`'s `traceparent` still points at `A` as parent, not `B`. The verifier's prompt included `B`'s output, so `C.input_tokens` includes tokens that are causally downstream of `B` but the span tree claims `C` is a sibling of `B`. - A retry of `B` (provider 529) is emitted as `B'` with the *same* `span_id` reused by the retry wrapper, and both `B` and `B'` report `output_tokens=890`. The retry's actual billed output was 0 (the request never completed server-side), but the wrapper copied the prior response object's usage block. The observable symptoms downstream: - Trace waterfall shows `A` with two children `B` and `C`, and a duplicate `B'` colliding on `span_id`. Backend deduplicates `B`/`B'` and silently drops one usage record. - Aggregate token cost for the trace undercounts by the verifier's true causal share and overcounts by the phantom retry. - A cost-attribution query that sums `gen_ai.usage.output_tokens` grouped by `parent_span_id` reports `A`'s subtree at 412 + 890 = 1302 output tokens, while the provider invoice for the same wall-clock window reports 412 + 890 + 890 (the verifier's own generation) + 0 (retry). The gap is not a rounding error; it is a structural mismatch between the span tree and the billing ledger. ## Condition of Validity The reconciliation invariant — "sum of `gen_ai.usage.*` over a span subtree equals provider-billed usage for the model calls causally initiated within that subtree" — holds only when all four of the following are true: 1. **Context freshness.** Every child span is created from a context snapshot taken *after* the parent's tool-call arguments were finalized. A sandbox forked before the parent span closed will attach children to the wrong ancestor. This is the stale-`traceparent` condition. 2. **Span identity uniqueness.** No two spans in a trace share a `span_id`. Retry wrappers that reuse the original `span_id` violate this; they must mint a new `span_id` and record the retry as a distinct span with `gen_ai.request.retry_count` (or an equivalent attribute), leaving the failed attempt's usage at zero. 3. **Usage provenance.** `gen_ai.usage.*` is populated *only* from the provider's response envelope for that specific request. Copying a prior response's usage block onto a retry, a cache hit, or a synthesized span breaks the invariant. Cache hits must set usage to the *cache-read* accounting, not the original generation. 4. **Causal closure.** A span's usage counters describe tokens *it* caused, not tokens it merely observed. When a sub-agent's prompt embeds a parent's output, those parent tokens are not re-billed to the child; the child's `input_tokens` reflects only what the child sent. Instrumentation that sums "all tokens visible in the prompt" double-counts across the tree. When any of these fails, the trace is still *topologically* a valid OTel trace — it will pass schema validation, render in Jaeger, and satisfy the semantic-convention attribute checks — while being numerically unreconcilable against the billing system. ## Decision Boundary The boundary an operator must draw is between **accepting the trace as a causal record** and **accepting it as an accounting record**. These diverge at exactly one decision point: whether a child span's `traceparent` was minted from a context that post-dates the parent's usage finalization. - If the child's context is fresh (snapshot taken after parent response received), the trace is both causally and numerically sound; reconciliation can proceed by subtree sum. - If the child's context is stale (snapshot predates parent finalization, as in a forked sandbox, a queued job, or a resumed checkpoint), the trace remains causally *approximately* correct (the ancestry is right even if the immediate parent is wrong) but numerically unsound: the subtree sum overcounts because the stale child's usage is attributed to an ancestor that did not cause it within the same billing window. - If span identity is duplicated (retry reuse), the trace is causally *corrupt* — the waterfall cannot be trusted at all — and must be rejected from both causal and accounting use. The practical boundary: **never reconcile token accounting from a trace that contains a reused `span_id` or a child whose context was captured before its nominal parent's response.** In those cases, fall back to the provider's billing ledger as the source of truth and treat the trace as a causal-only artifact with usage fields marked `gen_ai.usage.reconciled=false`. ## Operational Effect The consequence of ignoring this boundary is a silent, systematic cost-attribution drift that compounds with agent depth. Each nested tool-call layer that forks a sandbox with a stale context adds one more mis-attributed subtree. In a three-level planner→executor→verifier topology with retries, observed drift reached 18–34% of true billed tokens depending on retry rate, always in the direction of *under*-counting the deep children and *over*-counting the shallow parent — because the shallow parent absorbs the deep usage when the deep child's `traceparent` collapses onto it. The guardrail is a two-stage validation gate at span emission: 1. **Identity gate.** Reject any span whose `(trace_id, span_id)` pair already exists in the active trace buffer. Emit a `gen_ai.span.duplicate_id` event and force the retry wrapper to mint a fresh `span_id`. 2. **Freshness gate.** Stamp each child context with the parent's `gen_ai.usage.finalized_at` timestamp (set when the parent's response is received). If a child's context snapshot predates that timestamp, set `gen_ai.usage.reconciled=false` on the child and route its usage to a `pending_reconciliation` bucket rather than the parent subtree. Only spans passing both gates may feed cost-attribution queries. Everything else is causal-only. This preserves the trace as a debugging artifact while preventing it from silently corrupting the billing model — the exact failure that motivated this record. ```python from dataclasses import dataclass, field from typing import Optional class TraceAccountingDivergence(RuntimeError): """Raised when a GenAI span subtree cannot be reconciled with billed usage.""" pass @dataclass class GenAISpan: trace_id: str span_id: str parent_span_id: Optional[str] operation: str input_tokens: int = 0 output_tokens: int = 0 usage_finalized_at: Optional[float] = None # parent response receipt time context_captured_at: Optional[float] = None # when traceparent was minted reconciled: bool = True class TraceReconciler: def __init__(self) -> None: self._seen: dict[tuple[str, str], GenAISpan] = {} self._pending: list[GenAISpan] = [] def admit(self, span: GenAISpan) -> None: key = (span.trace_id, span.span_id) if key in self._seen: # Identity gate: duplicate span_id (retry wrapper reuse). raise TraceAccountingDivergence( f"duplicate span_id {span.span_id} in trace {span.trace_id}; " f"retry wrappers must mint a fresh span_id" ) # Freshness gate: child context captured before parent finalized usage. if span.parent_span_id is not None: parent = self._seen.get((span.trace_id, span.parent_span_id)) if parent is not None and parent.usage_finalized_at is not None: if (span.context_captured_at is not None and span.context_captured_at < parent.usage_finalized_at): span.reconciled = False self._pending.append(span) self._seen[key] = span return self._seen[key] = span def subtree_usage(self, trace_id: str, root_span_id: str) -> tuple[int, int]: """Return reconciled (input, output) tokens for the subtree. Raises if any unreconciled span would have been attributed to this root. """ children: dict[str, list[GenAISpan]] = {} root: Optional[GenAISpan] = None for span in self._seen.values(): if span.trace_id != trace_id: continue if span.span_id == root_span_id: root = span if span.parent_span_id is not None: children.setdefault(span.parent_span_id, []).append(span) if root is None: raise TraceAccountingDivergence(f"root span {root_span_id} not found") in_tok = out_tok = 0 stack = [root] while stack: cur = stack.pop() if not cur.reconciled: raise TraceAccountingDivergence( f"span {cur.span_id} has unreconciled usage; " f"route to pending_reconciliation bucket, do not bill to {root_span_id}" ) in_tok += cur.input_tokens out_tok += cur.output_tokens stack.extend(children.get(cur.span_id, [])) return in_tok, out_tok ```