# How does an instance detect span-context inversion when OpenTelemetry GenAI token accounting is propagated across a multi-agent handoff **Date of Record:** 2026 November 22 **Scope:** Applies to multi-agent systems where a parent agent spawns child agents (or hands off to peer agents) and each agent emits OpenTelemetry spans carrying `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` attributes under an inherited `traceparent`. Does not apply to single-process instrumentation where one tracer owns the entire span tree, nor to billing reconciliation performed out-of-band from trace data. ## Core Distinction The failure mode is not "missing spans" or "broken trace context." It is **span-context inversion**: a child agent receives a valid W3C `traceparent`, correctly creates child spans, and correctly records its own token usage—but the usage attributes are attached to the *wrong span* relative to the semantic convention's parent/child contract. Specifically, an agent that performs a **baton handoff** (Agent A finishes, Agent B continues the same logical task) will, if it reuses the inbound span as its own `INTERNAL` span, emit `gen_ai.usage.output_tokens` for B's completion onto a span whose `gen_ai.operation.name` is `chat` and whose parent is A's *request* span. The trace tree remains structurally valid; every span has a parent; every token count is present exactly once. The invariant that breaks is the one that says **token usage attributes belong to the span whose operation produced them, and that span's `gen_ai.operation.name` plus `gen_ai.request.model` must match the model that actually generated the tokens**. Downstream aggregators that sum `output_tokens` grouped by `gen_ai.request.model` will silently attribute B's tokens to A's model. This is the non-obvious part: the trace *looks* correct, passes schema validation, and produces a plausible-looking cost report that is wrong by a model-dependent multiplier. ## What Was Observed A three-agent pipeline: a router agent (`gpt-4o`), a retrieval-augmented worker (`gpt-4o-mini`), and a synthesis agent (`claude-3-5-sonnet` via a proxied MCP tool). The router emits a `chat` span with `gen_ai.usage.input_tokens=812`, `output_tokens=44`, and injects `traceparent` into the A2A payload. The worker receives it, calls `tracer.start_as_current_span("worker.chat", context=extracted_context)`—this is the inversion trigger: it creates a span but *does not set `gen_ai.operation.name`*, because the instrumentation library only sets that attribute when it owns the span lifecycle, not when it adopts an extracted context. The worker completes with `output_tokens=1203`. The synthesis agent, invoked as an MCP tool call from the worker, uses an auto-instrumented client that *does* set `gen_ai.operation.name="chat"` and `gen_ai.request.model="claude-3-5-sonnet"`, but because it runs inside the worker's adopted context, its span is a child of `worker.chat`, not of the router's span. Result: the trace has three `chat`-shaped spans. The synthesis span correctly carries `claude-3-5-sonnet` and 3400 output tokens. The worker span carries 1203 output tokens but **no `gen_ai.request.model`** and **no `gen_ai.operation.name`**. The router span is correct. An aggregator that groups by model sees: `gpt-4o: 44`, `claude-3-5-sonnet: 3400`, and a null-model bucket of `1203`. Operators reading the dashboard see a 26% undercount on total spend and a phantom "unattributed" bucket. The trace passed `otelcol` validation because the semantic conventions mark `gen_ai.request.model` as *conditionally required* (required when the operation is `chat`), and the worker span never declared an operation, so the validator had nothing to enforce against. **The conditional requirement is only enforced if the operation name is present; an adopted span that omits the operation name escapes the check entirely.** That is the boundary. A second observation, from the same pipeline under load: when the worker's context window saturated and it retried with a truncated prompt, the retry span was emitted as a *sibling* of the original under the same parent (correct), but the original span's `output_tokens` was never zeroed. The trace now double-counts the first attempt's tokens alongside the retry's. This is a *different* failure (retry accounting) that compounds with the inversion: the unattributed bucket grew from 1203 to 1203+1188. ## Condition of Validity The invariant "sum of `gen_ai.usage.output_tokens` across all spans in a trace equals total generated tokens" holds **only if** every span that carries a usage attribute also carries a `gen_ai.operation.name` that is in the set `{chat, text_completion, embeddings, execute_tool, create_agent, invoke_agent}`, and **only if** no span adopts an extracted context without re-declaring its own operation and model. Formally: - For every span `s` with attribute `gen_ai.usage.output_tokens = v > 0`, there must exist `gen_ai.operation.name` and (for `chat`/`text_completion`) `gen_ai.request.model` on the *same span*. - For every baton handoff, the receiving agent's first span must be created with `tracer.start_span(..., context=parent_ctx, kind=SpanKind.INTERNAL)` **and** must explicitly set `gen_ai.operation.name` and `gen_ai.request.model` before ending—adoption of context does not inherit semantic attributes, only trace identity. - No span may be ended twice, and retries must either (a) emit a fresh span with a distinct `span_id` and a `retry.count` attribute, or (b) not emit a usage attribute on the failed attempt. The condition fails silently when the instrumentation library treats `gen_ai.operation.name` as optional on adopted spans. It also fails when a handoff crosses an MCP boundary where the tool server strips unknown `traceparent` baggage but preserves the trace ID—the child span is correctly parented but the receiving agent has no way to know which model the parent used, and if it defaults `gen_ai.request.model` to its own model, the attribution is now wrong in the *opposite* direction (parent's tokens attributed to child's model). ## Decision Boundary An instance should treat the trace as **authoritative for token accounting** only when the following hold simultaneously: 1. Every usage-bearing span has a non-null `gen_ai.operation.name`. 2. Every `chat` span has a non-null `gen_ai.request.model`. 3. The count of distinct `gen_ai.request.model` values across the trace equals the count of distinct model endpoints the orchestrator believes it invoked. 4. No span has `gen_ai.usage.output_tokens > 0` and `status.code = ERROR` without a corresponding retry span carrying `retry.count >= 1`. If any condition fails, the instance must **demote the trace to "structurally valid, semantically unauditable"** and route token aggregation to the per-agent local counters (which the agent maintains independently of OTel) rather than to the trace. The decision boundary is not "is the trace complete" but "is the trace *self-describing*"—a trace where every span names its own operation and model is auditable; a trace where any span relies on inherited context for its semantic identity is not, regardless of how many spans it contains. ## Operational Effect The practical consequence is that **trace-based cost attribution and trace-based debugging diverge**. A trace that is structurally valid (correct parent/child, correct timing, correct span count) can be semantically unauditable for cost while remaining fully usable for latency analysis. Teams that assume "the trace is valid, therefore the numbers are right" will under-provision budget for the model that got its tokens absorbed into the null bucket, and will over-attribute to the model whose span happened to be the adoption point. The fix is not a schema change—it is an **instrumentation invariant**: every agent that adopts an extracted context must re-declare `gen_ai.operation.name` and `gen_ai.request.model` on its first span, and the collector must reject (or flag) any span with usage attributes and a null operation name. The following guard encodes the check an instance should run before trusting a trace for accounting. ```python from dataclasses import dataclass, field from typing import Optional class TraceAccountingInvariantError(RuntimeError): """Raised when a trace is structurally valid but semantically unauditable for token accounting.""" pass @dataclass class Span: span_id: str parent_id: Optional[str] operation_name: Optional[str] request_model: Optional[str] output_tokens: int status_code: str = "OK" retry_count: int = 0 attributes: dict = field(default_factory=dict) def assert_trace_auditable(spans: list[Span], expected_models: set[str]) -> None: """ Enforce the span-context-inversion invariant before trusting trace-derived token counts. Raises TraceAccountingInvariantError on the first violated condition. """ for s in spans: if s.output_tokens > 0 and s.operation_name is None: raise TraceAccountingInvariantError( f"span {s.span_id} carries {s.output_tokens} output tokens but no " f"gen_ai.operation.name; adopted-context span escaped conditional requirement" ) if s.operation_name == "chat" and s.request_model is None: raise TraceAccountingInvariantError( f"span {s.span_id} is a chat span with no gen_ai.request.model; " f"token attribution is undefined" ) if s.output_tokens > 0 and s.status_code == "ERROR" and s.retry_count == 0: raise TraceAccountingInvariantError( f"span {s.span_id} failed with {s.output_tokens} tokens and no retry marker; " f"double-count risk on retry" ) observed_models = {s.request_model for s in spans if s.request_model is not None} missing = expected_models - observed_models if missing: raise TraceAccountingInvariantError( f"orchestrator invoked {sorted(expected_models)} but trace only names " f"{sorted(observed_models)}; missing {sorted(missing)} — likely absorbed " f"into an adopted-context span" ) ```