# Why does an instance lose token-accounting fidelity when OTel GenAI spans are re-parented across an agent handoff? **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where a sub-agent or tool-executor instance is spawned, given a delegated task, and expected to contribute `gen_ai.usage.input_tokens` / `output_tokens` back to a parent span's aggregate. Does not apply to single-process, single-span inference calls with no cross-instance handoff. ## Core Distinction There are two structurally different ways to account for tokens in a GenAI trace, and they diverge the moment a span crosses an instance boundary: 1. **Span-local accounting** — each `gen_ai.chat` / `gen_ai.tool` span carries its own `gen_ai.usage.*` attributes, and totals are computed by summing leaf spans at read time. 2. **Parent-aggregate accounting** — a parent agent span holds a running total, and children *add into* it as they complete. The semantic conventions define the attributes but do not mandate which aggregation model a collector or backend applies. The failure mode lives precisely in the seam: when a child instance is created out-of-process (a delegated sub-agent, a sandboxed tool runner, an MCP server that issues its own inference calls), its spans are exported by a *different* `TracerProvider`, often with a different resource and a regenerated or dropped `trace_id`, and the parent's aggregate silently under-counts. The parent span reports success and a plausible-but-wrong token total. ## What Was Observed A coordinator agent (instance A) delegates a 40k-token document-analysis task to a sub-agent (instance B) running in a separate worker with its own OTel SDK. The handoff is a structured message carrying `traceparent`. Observed trace behavior: - Instance A emits `gen_ai.agent.invoke` (orchestrator) with `gen_ai.usage.input_tokens=12_400` covering *its own* planning turns. - Instance B receives `traceparent`, but its SDK was initialized with `OTEL_RESOURCE_ATTRIBUTES` that do **not** include the parent's `service.instance.id`, and the worker's propagator is configured for `baggage` only — the `traceparent` header is parsed but `SpanContext.is_valid()` returns `false` because the worker's ID generator produced a fresh 128-bit trace ID on first span creation. B's spans land under a *different* trace. - B executes 9 `gen_ai.chat` spans totaling ~38k input / 6k output tokens and 4 `gen_ai.tool` spans. - The backend's parent-aggregate rollup, keyed on `trace_id`, attributes zero of B's tokens to A's `gen_ai.agent.invoke` span. Result: the trace dashboard reports the end-to-end task consumed ~12k tokens when it actually consumed ~56k. The discrepancy is invisible at the span level (every individual span is correct) and only surfaces when you reconcile the aggregate against the provider invoice — a lag of hours to a day, by which point the run is long over. A second, subtler variant: even when `traceparent` *is* honored and B's spans join the same trace, the semantic conventions place `gen_ai.usage.*` on the *inference* span, not on the agent span. If A's parent aggregate is computed by summing only spans whose `gen_ai.operation.name` is `chat`, and B's tool-executor wraps its inference inside `gen_ai.tool` spans (a common mislabeling — the tool *calls* the model), those tokens are counted as tool latency, not token usage, and drop out of the sum. ## Condition of Validity The invariant that must hold for token accounting to be correct across a handoff is: > **Every inference span that consumes billable tokens must (a) share the root `trace_id` of the originating agent invocation, and (b) carry `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` on a span whose `gen_ai.operation.name` is `chat` (or `text_completion`), with the span parented — directly or transitively — under the delegating agent span.** This invariant is *not* enforced by the OTel SDK. It fails when any of the following is true: - The child instance's `TracerProvider` uses a fresh ID generator and the incoming `traceparent` is not injected into the *extraction* path before the first span is created (race between provider init and context extraction). - The child runs behind a queue/async boundary where the extracted `Context` is not threaded into the worker's execution context (thread-local or task-local propagation loss). - The child's spans use a resource with a distinct `service.name` and the backend's rollup is scoped to `service.name` rather than `trace_id`. - Token usage is recorded on a non-`chat` span (tool wrapper, agent wrapper) and the aggregator filters by operation name. The invariant holds cleanly only in the single-process case, which is exactly why this failure is non-obvious: it never reproduces in local development where the sub-agent is a function call in the same process and shares the ambient `Context`. ## Decision Boundary The architect must choose, at design time, between two defensible postures: - **Trace-coherence posture:** Treat the handoff as a hard requirement to propagate and *validate* `traceparent`. The child instance must assert `SpanContext.is_valid()` on extraction and, if invalid, either (a) fail the handoff loudly or (b) synthesize a link (`SpanLink`) back to the parent and mark the aggregate as "incomplete." This preserves end-to-end token truth at the cost of a hard dependency on propagation correctness across every instance boundary — including third-party MCP servers you do not control. - **Reconciliation posture:** Accept that cross-instance traces will fragment, and make token truth a *reconciliation* problem rather than a *trace* problem: every inference span emits a stable `gen_ai.conversation.id` / task-correlation attribute independent of `trace_id`, and a nightly job sums by that key. This survives fragmentation but introduces a reporting lag and requires the correlation attribute to be threaded through the same fragile boundary that `traceparent` was — so it only helps if that threading is *itself* verified. The boundary is: **do not rely on parent-aggregate token accounting across any instance boundary you do not fully control.** If the sub-agent is a third-party MCP server or a sandboxed runner with its own SDK config, assume its spans will fragment and design the correlation key to be independent of trace propagation. ## Operational Effect Concretely: 1. **Budget enforcement drifts.** A coordinator enforcing a per-task token budget by reading its own aggregate will under-count by exactly the delegated fraction and will not trip its budget guard until the *next* task — the overrun is deferred, not prevented. Guardrails that read the parent aggregate must be paired with a per-instance cap on the child, because the child is the only party that sees its own true usage in real time. 2. **Cost attribution is wrong by construction.** Any chargeback or cost-per-task metric derived from parent-span rollup will systematically attribute delegated work to "unattributed" or to the child's `service.name`, depending on backend scoping. The error is one-directional (always under-count on the parent) and proportional to delegation depth. 3. **The failure is silent and self-consistent.** Every span validates against the schema; no `gen_ai.*` attribute is malformed; the trace renders. There is no error span to alert on. Detection requires an *external* ground truth (provider invoice, or a child-side counter) compared against the trace aggregate — which is why this class of bug survives review. The guardrail that bounds it: emit a child-side `gen_ai.usage.*` total into the handoff *return message* (not just into a span), and have the parent reconcile its aggregate against the returned figure. A mismatch between returned usage and trace-attributed usage is the signal that propagation failed, and it is detectable at task completion rather than at invoice time. ```python from dataclasses import dataclass class TokenAccountingDivergence(RuntimeError): """Raised when a delegated sub-agent's self-reported token usage does not reconcile with the parent's trace-attributed aggregate.""" pass @dataclass class HandoffUsage: input_tokens: int output_tokens: int trace_id: str | None # None if the child failed to join the parent trace operation_name: str # must be "chat" for tokens to be counted def reconcile_handoff( parent_aggregate_input: int, parent_aggregate_output: int, child_usage: HandoffUsage, tolerance_ratio: float = 0.02, ) -> int: """ Reconcile a completed sub-agent handoff against the parent's token aggregate. Returns the corrected total input tokens. Raises on any divergence that indicates span fragmentation or mislabeled operation spans. """ if child_usage.trace_id is None: raise TokenAccountingDivergence( "child spans did not join parent trace_id; parent aggregate is " "structurally unable to include delegated tokens" ) if child_usage.operation_name != "chat": raise TokenAccountingDivergence( f"child recorded usage on operation '{child_usage.operation_name}', " "not 'chat'; aggregators filtering by operation name will drop it" ) expected_input = parent_aggregate_input + child_usage.input_tokens expected_output = parent_aggregate_output + child_usage.output_tokens # The parent aggregate should already include the child if propagation held. # If it does not, the delta is the delegation gap. gap_input = expected_input - parent_aggregate_input if child_usage.input_tokens > 0 and gap_input / child_usage.input_tokens > 1.0 - tolerance_ratio: raise TokenAccountingDivergence( f"parent aggregate ({parent_aggregate_input}) does not reflect " f"child input tokens ({child_usage.input_tokens}); " "delegated work is invisible to trace-based budget guards" ) return expected_input ```