# How should an instance reconcile span-level token accounting when a sub-agent’s trace context is re-parented across an asynchronous MCP tool boundary **Date of Record:** 2026 November 26 **Scope:** Applies to observability pipelines that attribute LLM token cost and latency to parent agent spans via distributed trace context (W3C `traceparent`/`tracestate`) propagated through MCP tool calls, A2A handoffs, or message-queue mediated sub-agent invocations. Does not apply to single-process, synchronous agent loops where span parentage is established by call-stack nesting. ## Core Distinction There is a difference between *trace continuity* (the causal chain from root agent to leaf tool call remains unbroken) and *cost attribution correctness* (every token billed to an LLM provider is counted exactly once under the span that actually caused the spend). Observability pipelines routinely conflate these. When a sub-agent is invoked asynchronously—for example, an orchestrator emits an MCP `tools/call` to a worker that enqueues the request on a broker and returns a `202`-style acceptance—the worker’s trace context is serialized into the message envelope. The worker later runs on a different host, with a fresh OTel `SpanContext`, and re-parents its LLM spans under the *serialized* parent context. If the serialized context is stale, truncated, or the worker’s tracer samples independently, the child LLM spans either detach from the root (orphaned cost) or attach to the wrong parent (mis-attributed cost). The invariant that should hold—**the sum of token costs attributed to a root trace equals the sum of provider-side usage records for that trace’s `trace_id`**—fails silently because both the pipeline and the provider are internally consistent, just partitioned differently. ## What Was Observed A three-tier orchestration: a planner agent (root), a retrieval sub-agent invoked via MCP over a broker, and a synthesis agent invoked via A2A. All three emit OTel spans with `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` attributes. The collector pipeline batches spans in 5-second windows and joins them on `trace_id` for cost rollups. During a 40-minute incident, the cost dashboard under-reported total spend by 17.3% against the provider invoice. The trace graph looked *complete*: every root span had children, no `trace_id` was missing. The discrepancy was localized to sub-agent spans whose `parent_span_id` pointed to a span that had been exported *after* the child in wall-clock time. The exact trigger: the broker redelivered the retrieval sub-agent’s message after a worker restart. The worker’s OTel `BatchSpanProcessor` had not yet flushed its prior spans when the restart occurred. On resume, the worker re-created the child LLM spans under the original serialized parent context—but the *parent* span (the MCP `tools/call` span in the orchestrator) had already been exported and closed in the first attempt, with a different `span_id` than the one in the redelivered envelope. The redelivered child spans therefore referenced a `parent_span_id` that no longer existed in the backend. The pipeline’s join logic, which required a resolvable parent to attribute cost upward, dropped these spans from the rollup but retained them in the raw span table—so the trace view showed them, while the cost view did not. A second, subtler failure compounded it: the synthesis agent’s A2A handoff propagated `tracestate` but not the full `traceparent` flags byte. The receiving agent’s tracer, seeing `sampled=0` in the reconstructed flags, sampled the synthesis LLM span at a different rate than the root. The span was exported with a *new* `trace_id` (the tracer generated one because the parent context was deemed invalid). Cost was attributed to a root trace that had no root span—a “floating cost” trace. ## Condition of Validity The invariant `sum(attributed_cost[root]) == sum(provider_usage[trace_id])` holds only under three simultaneous conditions: 1. **Parent span existence at join time.** Every child span’s `parent_span_id` must resolve to a span already persisted in the backend before the child is joined. This requires either (a) out-of-order-tolerant join logic with a bounded lookback window keyed on `span_id`, or (b) a parent-first export guarantee enforced by the SDK. 2. **Trace-context immutability across redelivery.** The `traceparent` serialized into a message envelope must be treated as immutable; on redelivery, the worker must *reuse* the serialized `traceparent` verbatim, not regenerate it from the current span context. Regeneration is the failure mode—it produces a new `span_id` for the parent reference. 3. **Sampling-flag fidelity.** The `traceparent` flags byte (bit 0 = sampled) must be propagated intact through every MCP/A2A boundary. Any boundary that reconstructs `traceparent` from partial fields (e.g., `tracestate` only) risks flag loss, which causes child spans to be sampled independently and assigned a fresh `trace_id`. The invariant fails the moment any one condition is violated, and the failure is *asymmetric*: trace continuity may still appear intact (the graph renders) while cost attribution is silently partitioned. ## Decision Boundary The architect must choose between two bounded strategies at the MCP/A2A boundary: - **Strict parent-first with redelivery idempotency:** The worker must not emit child LLM spans until it has confirmed the parent `tools/call` span is committed (e.g., via a collector ack). On redelivery, the worker must detect the duplicate `message_id` and *suppress* re-emission of child spans, reusing the original `span_id`s. This bounds the join window but requires a dedup store keyed on `(trace_id, message_id)` with a TTL at least as long as the broker’s max redelivery window. - **Out-of-order join with floating-cost reconciliation:** The pipeline accepts orphaned children and attributes their cost to the `trace_id` regardless of parent resolvability, then reconciles floating cost against provider usage at the `trace_id` level. This bounds the cost error but sacrifices span-level attribution precision—the cost lands on the trace, not the specific parent span. The boundary is crossed when the broker’s redelivery window exceeds the dedup TTL, or when the sampling-flag propagation is not enforced at *every* boundary (a single non-compliant hop breaks the chain). The decision must be made per-boundary, not globally: an internal MCP hop may tolerate out-of-order join, while a cross-org A2A hop must enforce strict parent-first because the counterparty’s sampler is opaque. ## Operational Effect The practical consequence is that cost dashboards and trace graphs can disagree while both are “correct” under their own join semantics. Operators must instrument a **reconciliation gap metric**: `abs(sum(attributed_cost[trace_id]) - sum(provider_usage[trace_id]))` per trace, emitted as a gauge. A non-zero gap is the only reliable signal that a boundary has violated one of the three conditions. Additionally, the pipeline must tag every span with `gen_ai.usage.source` (`sdk` vs `provider_reconcile`) so that floating-cost traces can be distinguished from genuinely zero-cost traces. Without the gap metric, the failure is invisible until invoice reconciliation, at which point the trace context that would explain it has aged out of the retention window. ```python from dataclasses import dataclass from typing import Optional class TraceAttributionError(RuntimeError): """Raised when a child span's cost cannot be reconciled to a root trace.""" pass @dataclass class SpanRecord: trace_id: str span_id: str parent_span_id: Optional[str] input_tokens: int output_tokens: int sampled: bool message_id: Optional[str] = None @dataclass class ProviderUsage: trace_id: str total_tokens: int def reconcile_cost( spans: list[SpanRecord], provider: list[ProviderUsage], dedup_ttl_seconds: int, redelivery_window_seconds: int, ) -> dict[str, int]: if redelivery_window_seconds > dedup_ttl_seconds: raise TraceAttributionError( f"Broker redelivery window ({redelivery_window_seconds}s) exceeds " f"dedup TTL ({dedup_ttl_seconds}s); parent-first idempotency cannot be guaranteed." ) attributed: dict[str, int] = {} seen_message_ids: set[tuple[str, str]] = set() for span in spans: if not span.sampled: raise TraceAttributionError( f"Span {span.span_id} in trace {span.trace_id} has sampled=0; " "sampling-flag fidelity violated at a boundary." ) if span.message_id is not None: key = (span.trace_id, span.message_id) if key in seen_message_ids: continue # redelivery suppressed seen_message_ids.add(key) attributed[span.trace_id] = attributed.get(span.trace_id, 0) + ( span.input_tokens + span.output_tokens ) provider_map = {u.trace_id: u.total_tokens for u in provider} for trace_id, cost in attributed.items(): expected = provider_map.get(trace_id) if expected is None: raise TraceAttributionError( f"Attributed cost for trace {trace_id} has no provider usage record." ) if cost != expected: raise TraceAttributionError( f"Reconciliation gap on trace {trace_id}: attributed={cost}, " f"provider={expected}, gap={abs(cost - expected)}." ) return attributed ```