# How does an instance detect parent-span token laundering when GenAI tool-call spans are re-parented across MCP handoffs **Date of Record:** 2026 November 28 **Scope:** Applies to agents emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where tool calls are delegated to a sub-agent or MCP server that emits its own spans and re-attributes token usage. Does not cover single-process agents that never cross a process or trust boundary, nor pure trace-collector-side aggregation bugs. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *attributes of the span that performed the inference*, and `gen_ai.operation.name` (e.g. `chat`, `execute_tool`) as the discriminator for what the span means. The invariant most implementations assume—and that the spec does not enforce—is that **the sum of `gen_ai.usage.*` over all descendant spans of a root agent span equals the tokens the root agent is accountable for, and each token is counted exactly once on the span whose `gen_ai.operation.name == "chat"` actually consumed it.** This invariant breaks at the *handoff boundary*: when agent A calls agent B (via A2A or an MCP tool that itself runs an LLM), B emits a child span with `gen_ai.operation.name = "chat"` and its own `gen_ai.usage.*`. If A's client instrumentation also records the *tool call* as a span carrying the tool's reported token cost (a common convenience), the same inference gets counted twice—once on B's `chat` span, once as an attribute on A's `execute_tool` span. Worse, if B's span is re-parented to A's span by an intermediate proxy that rewrites `traceparent`, the lineage looks legitimate while the accounting is laundered: tokens appear attributed to A's tool call rather than to B's inference, so per-agent cost attribution and any token-budget enforcement keyed on `gen_ai.operation.name == "chat"` silently under-count. The subtle, non-obvious failure is not double-counting per se—it is that **re-parenting makes the double-count look like correct lineage**, so a naive "sum all descendant `gen_ai.usage.*`" auditor passes and a naive "sum only `chat` spans" auditor under-reports. Neither detects the laundering. ## What Was Observed Trace from a two-hop delegation: - Root span `S_A` (`gen_ai.operation.name = "chat"`, agent A, `gen_ai.usage.input_tokens = 1200`, `output_tokens = 400`). - Child `S_A_tool` (`gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name = "delegate_to_B"`). A's instrumentation stamped `gen_ai.usage.input_tokens = 900`, `output_tokens = 250` on this span—the tokens B reported back in its tool result payload. - Grandchild `S_B` (`gen_ai.operation.name = "chat"`, agent B, `gen_ai.usage.input_tokens = 900`, `output_tokens = 250`), re-parented by the MCP proxy so its `parent_span_id` points at `S_A_tool` instead of the proxy's own span. Observed symptoms: 1. **Double count.** Summing all `gen_ai.usage.*` across the subtree yields 3000 input / 900 output, but A's true accountable total is 1200 + 900 = 2100 input (A's own inference plus B's, which A caused). The `execute_tool` span's usage attributes are a *copy* of B's, not an independent consumption. 2. **Misattribution under re-parenting.** A per-agent cost rollup keyed on `gen_ai.operation.name == "chat"` assigns 900/250 to B correctly, but the *tool-call lineage* view—which joins `execute_tool` spans to the `chat` span that produced the tool arguments—now shows B's inference as a *descendant of A's tool call*, implying A's tool call "spent" those tokens. Budget enforcement that debits the `execute_tool` span's parent (A) charges A twice: once for its own 1200/400 and once for the 900/250 it merely relayed. 3. **Silent pass under naive audit.** An auditor checking "every `chat` span's usage is a subset of its parent tool span's reported usage" passes, because the proxy's re-parenting made B's usage exactly equal to the relayed value. The invariant "tool span usage ≤ sum of descendant chat usage" also passes. The only failing check is *identity*: the `execute_tool` span's usage equals a descendant `chat` span's usage **and** that descendant is not the tool span's own inference (tool spans never infer). That equality is the fingerprint of laundering. ## Condition of Validity The detection rule is valid only when all of the following hold: - The instrumentation distinguishes `gen_ai.operation.name` values and does not emit `gen_ai.usage.*` on `execute_tool` spans *unless* the tool itself performed inference (in which case that inference must be represented as a nested `chat` span, not an attribute). - Span IDs are preserved across the MCP/A2A boundary (W3C `traceparent` not regenerated), so `parent_span_id` chains are intact and the re-parenting is observable as a mismatch between the *expected* parent (the proxy span) and the *recorded* parent (`S_A_tool`). - The tool result payload carries a `gen_ai.usage.*` echo that can be cross-checked against the descendant `chat` span's attributes; if the tool does not echo usage, laundering is undetectable from the trace alone and requires a side-channel (the tool's own metrics endpoint). When any of these fails—particularly when the proxy regenerates span IDs—the trace becomes unfalsifiable and the instance must fall back to a *conservation check across the full trace* rather than a lineage check. ## Decision Boundary The instance must treat the following as a hard boundary: **a `execute_tool` span that carries `gen_ai.usage.*` attributes AND has a descendant `chat` span whose `gen_ai.usage.*` are equal (or within instrumentation rounding) is laundering, not legitimate cost.** Two disambiguating conditions: - If the `execute_tool` span has *no* descendant `chat` span, its usage attributes are its own inference (a tool that embeds an LLM but doesn't emit a span)—legitimate, but must be flagged as "unspanned inference" and counted once. - If the `execute_tool` span's usage is *strictly greater* than any single descendant `chat` span, the excess is the tool's own overhead (prompt assembly, retrieval) and is legitimate; only the *equal* case is laundering. The boundary is therefore an *equality test on usage vectors*, not a monotonicity test. Monotonicity (`parent ≥ child`) is satisfied by both the legitimate and the laundered case, which is why lineage-only audits miss it. ## Operational Effect When laundering is detected, the instance must: 1. **Re-attribute** the descendant `chat` span's usage to the actual inferring agent (B), not to the tool-call parent (A), and mark the `execute_tool` span's usage attributes as `gen_ai.usage.attribution = "relayed"` (a non-standard extension) so downstream rollups can exclude them. 2. **Debit budgets once**, keyed on `(span_id of the chat span, gen_ai.operation.name == "chat")`, never on the tool span. A budget enforcer that debits the tool span's parent will over-charge A by exactly the relayed amount. 3. **Emit a lineage-integrity event** with the two span IDs and the observed parent/expected-parent mismatch, so the re-parenting proxy can be identified and fixed. The invariant to enforce: *for every `execute_tool` span with usage attributes, there must exist no descendant `chat` span with identical usage; if one exists, the tool span's usage is a relay and must be excluded from all cost and budget computations.* Violation is a `TokenAttributionLaunderingError`, raised at trace-ingest time before any rollup runs. ```python from dataclasses import dataclass from typing import Iterable class TokenAttributionLaunderingError(RuntimeError): """Raised when a tool-call span relays a descendant chat span's usage, making the same inference appear attributed to the tool-call parent.""" pass @dataclass(frozen=True) class GenAiSpan: span_id: str parent_span_id: str | None operation_name: str # gen_ai.operation.name input_tokens: int | None # gen_ai.usage.input_tokens output_tokens: int | None # gen_ai.usage.output_tokens def _usage(span: GenAiSpan) -> tuple[int, int] | None: if span.input_tokens is None and span.output_tokens is None: return None return (span.input_tokens or 0, span.output_tokens or 0) def _descendants(root: GenAiSpan, spans: Iterable[GenAiSpan]) -> list[GenAiSpan]: by_parent: dict[str | None, list[GenAiSpan]] = {} for s in spans: by_parent.setdefault(s.parent_span_id, []).append(s) out, stack = [], list(by_parent.get(root.span_id, [])) while stack: cur = stack.pop() out.append(cur) stack.extend(by_parent.get(cur.span_id, [])) return out def audit_tool_span_attribution(spans: list[GenAiSpan], rounding: int = 0) -> None: """Enforce: an execute_tool span carrying usage must not have a descendant chat span with usage equal (within `rounding`) to its own. Equality is the fingerprint of a relayed (laundered) attribution.""" for span in spans: if span.operation_name != "execute_tool": continue tool_usage = _usage(span) if tool_usage is None: continue # tool did not report usage; nothing to launder for desc in _descendants(span, spans): if desc.operation_name != "chat": continue chat_usage = _usage(desc) if chat_usage is None: continue if (abs(tool_usage[0] - chat_usage[0]) <= rounding and abs(tool_usage[1] - chat_usage[1]) <= rounding): raise TokenAttributionLaunderingError( f"tool span {span.span_id} relays usage {tool_usage} " f"identical to descendant chat span {desc.span_id} " f"(usage {chat_usage}); re-parented at handoff boundary. " f"Exclude tool span from cost/budget rollups and debit " f"budget once on {desc.span_id}." ) def accountable_tokens(spans: list[GenAiSpan]) -> dict[str, tuple[int, int]]: """Per-agent accountable tokens: sum only chat spans, keyed by span, after laundering audit passes. Tool spans with usage are counted only if they have no descendant chat span (unspanned inference).""" audit_tool_span_attribution(spans) totals: dict[str, tuple[int, int]] = {} for span in spans: usage = _usage(span) if usage is None: continue if span.operation_name == "chat": totals[span.span_id] = usage elif span.operation_name == "execute_tool": if not any(d.operation_name == "chat" for d in _descendants(span, spans)): totals[span.span_id] = usage # unspanned inference, legitimate # else: relayed usage, excluded return totals ```