# Which invariants prevent silent token-accounting divergence across OpenTelemetry GenAI agent spans when tool-call attribute emission and multi-agent trace propagation interleave **Date of Record:** 2026 November 25 **Scope:** Applies to multi-agent systems that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for LLM invocations, tool calls, and agent-to-agent handoffs, where a single logical task fans out across more than one process boundary. Does not apply to single-process, single-span synchronous LLM calls where the span is closed before any child work begins. ## Core Distinction The GenAI semantic conventions treat a span as a *reporting unit*: attributes such as `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and `gen_ai.operation.name` describe the cost and nature of one model or tool interaction. They do **not** define a *conservation law*. Nothing in the spec requires that the sum of `gen_ai.usage.*` across a trace equal the tokens actually billed, nor that a tool-call span's attributes be finalized before the parent agent span closes. The failure this record documents is the gap between those two facts. A parent agent span that *starts* before a downstream agent (reached over a propagated `traceparent`) returns, and *ends* before that downstream agent's tool-call spans are exported, will close with a token total that excludes the child's usage. The trace looks complete—every span is parented correctly—but the accounting is silently short. This is not a sampling artifact and not a clock-skew artifact; it is an ordering invariant violation between span close and attribute finalization. ## What Was Observed A three-tier agent topology: an orchestrator (process A) calls a planner sub-agent (process B) over an A2A-style transport, which in turn invokes a tool-executor sub-agent (process C). Context was propagated via W3C `traceparent`/`tracestate`, and each process ran its own OTel SDK with a batch span processor (`schedule_delay_millis=5000`, `max_export_batch_size=512`). The orchestrator's `gen_ai.operation.name=chat` span, call it `S_A`, recorded `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=412`. Its child, the planner's `S_B`, recorded `input=3110, output=980`. The tool-executor's `S_C` recorded `input=640, output=120` plus a `gen_ai.tool.name=search_index` attribute. The billing system reconciled against the provider's usage report and flagged a **consistent ~980-token shortfall per task**—exactly `S_B.output_tokens`. Inspection of exported traces showed `S_A` and `S_B` present and correctly parented on most runs, but on roughly 30% of runs `S_B`'s `gen_ai.usage.output_tokens` attribute was absent or zero at export time, while `S_B`'s span itself was present with correct timing. The trigger: when the orchestrator's turn completed and `S_A.end()` fired before process B's batch processor flushed, the collector received `S_A` first. A downstream reconciliation job that computed "task cost = sum of usage on spans where `gen_ai.operation.name` is set, grouped by trace root" ran against a *partially arrived* trace. Because `S_B`'s usage attributes were set *after* `S_B.end()` in a post-hoc attribute-update path (the planner streamed output tokens and patched usage at stream close), the batch processor had already serialized `S_B` with a stale attribute snapshot in some interleavings, and in others `S_B` had not arrived at all when reconciliation ran. Two distinct mechanisms compounded: 1. **Attribute-after-end race.** The planner set `gen_ai.usage.output_tokens` via a mutable span reference *after* calling `span.end()`. The OTel SDK snapshots attributes at `end()`; later mutations are dropped or, depending on SDK version, applied inconsistently. The spec's `gen_ai.usage.*` attributes are defined as final at span close—streaming agents that patch usage post-hoc violate this without any error. 2. **Trace-arrival non-atomicity.** Multi-agent propagation means the trace is assembled at the collector from spans arriving from three independent batch processors. A reconciliation consumer reading the trace store has no signal that the trace is *complete*; a trace with two of three spans is indistinguishable from a completed two-span trace. ## Condition of Validity The invariant that must hold for accounting to be correct is: > For every trace root, the set of spans carrying `gen_ai.usage.*` is closed and final before any consumer computes aggregate cost, and every such span's usage attributes were set before that span's `end()` call. This holds only when all of the following are true: - Usage attributes are set on the span **before** `end()`, never after. Streaming agents must buffer the final usage chunk and set attributes in the same critical section that calls `end()`. - The consumer of the trace does not read until it has positive evidence of trace closure—either a sentinel span (a root span that is guaranteed to be the last to end and which carries a completion marker), or a collector-side "trace complete" signal derived from the root span's presence plus a quiescence window exceeding the maximum inter-process batch delay. - Trace propagation carries enough context that a child agent can attribute its usage to the correct root even when the parent has already ended. `traceparent` does this for span identity; it does **not** carry a "root still open" flag, so the child cannot know it is racing the parent's close. It does **not** hold when any agent patches usage post-`end()`, when reconciliation runs on a fixed schedule shorter than the sum of batch delays across the process fan-out, or when the trace store exposes no completion signal and the consumer infers completeness from "no more spans arrived in the last N seconds." ## Decision Boundary The boundary is between *span-level correctness* and *trace-level conservation*. A span can be perfectly spec-compliant—correct name, correct parent, correct attributes at close—and the trace can still be wrong in aggregate, because the spec governs spans, not sums. Concretely, the decision an implementer must make is where to place the completion barrier: - **Barrier at root span end (recommended).** The orchestrator, which is the only party guaranteed to know the task is done, sets a `gen_ai.task.complete=true` attribute on the root span and ends it *last*, after all child results have been joined. Consumers reconcile only traces whose root carries this marker. This converts trace-arrival non-atomicity into a detectable condition: a trace without the marker is *known incomplete*, not *assumed complete*. - **Barrier at collector (fallback).** If the orchestrator cannot be made to end last (e.g., fire-and-forget fan-out), the collector must emit a derived completion event after a quiescence window strictly greater than `max(batch_delay) + max(network_jitter)` across all participating processes. This is fragile and must be tuned; it is a boundary, not an invariant. - **Never barrier at the consumer's schedule.** A reconciliation job that runs every 60s against a trace store with 5s batch delays and multi-hop fan-out will read partial traces. This is the observed failure. The non-obvious part: the root span ending *first* is the common case in agent systems, because the orchestrator's LLM call returns as soon as it has dispatched the sub-agent call, and the orchestrator has no reason to hold its span open while the sub-agent works. The architecture that makes agents responsive (don't block on children) is exactly the architecture that breaks trace-level conservation. ## Operational Effect The shortfall is silent and systematic. It scales with fan-out depth and with the fraction of usage that is patched post-`end()` (streaming output is the usual culprit). In the observed system it was ~30% of tasks and ~980 tokens each—small enough to pass casual review, large enough to corrupt cost attribution and any budget-enforcement loop that reads from the trace store rather than the provider's billing API. Downstream effects compound: a token-budget guardrail that terminates an agent when trace-aggregated usage exceeds a threshold will *under*-count and let the agent run past budget; a per-agent cost dashboard will attribute the planner's output tokens to no one; an anomaly detector keyed on per-trace token totals will see a bimodal distribution (complete vs. truncated traces) and either false-positive on the low mode or learn to ignore it. The fix is not a bigger batch size or a longer reconciliation window—those only shift the probability. The fix is the completion barrier: make trace completeness a *positively asserted* property carried in the trace, so that "incomplete" and "complete but small" are distinguishable. Every consumer that aggregates `gen_ai.usage.*` must gate on that assertion. ```python from dataclasses import dataclass, field from typing import Optional class TraceAccountingError(RuntimeError): """Raised when a trace is reconciled before its completion barrier is asserted, or when a usage attribute was mutated after span end.""" pass @dataclass class GenAISpan: span_id: str trace_id: str operation_name: Optional[str] = None input_tokens: int = 0 output_tokens: int = 0 ended: bool = False usage_finalized_before_end: bool = True is_root: bool = False task_complete_marker: bool = False @dataclass class TraceStore: spans_by_trace: dict = field(default_factory=dict) def ingest(self, span: GenAISpan) -> None: if span.ended and not span.usage_finalized_before_end: # The span closed with a usage attribute that was patched afterward. # The SDK snapshot is unreliable; refuse to count it silently. raise TraceAccountingError( f"span {span.span_id} in trace {span.trace_id} mutated " f"gen_ai.usage.* after end(); snapshot is stale" ) self.spans_by_trace.setdefault(span.trace_id, []).append(span) def reconcile_task_cost(self, trace_id: str) -> int: spans = self.spans_by_trace.get(trace_id, []) roots = [s for s in spans if s.is_root] if len(roots) != 1: raise TraceAccountingError( f"trace {trace_id} has {len(roots)} root spans; " f"cannot attribute cost to a single task" ) root = roots[0] if not root.task_complete_marker: # Root ended before children reported; trace is known-incomplete. # Do NOT compute a partial sum and call it the task cost. raise TraceAccountingError( f"trace {trace_id} root {root.span_id} lacks " f"gen_ai.task.complete marker; reconciliation would " f"under-count by the usage of unarrived child spans" ) total = 0 for s in spans: if s.operation_name is None: continue if not s.usage_finalized_before_end: raise TraceAccountingError( f"span {s.span_id} usage not finalized before end()" ) total += s.input_tokens + s.output_tokens return total ```