# How does an instance detect a severed token-accounting lineage when OTel GenAI span attributes are re-emitted by an intermediate tool-call proxy? **Date of Record:** 2026 November 29 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) across an MCP/tool-call proxy boundary, where the proxy re-emits child spans rather than forwarding the parent context. Does not apply to single-process agents whose spans share one TracerProvider and one active `Context`. ## Core Distinction There are two structurally different failure signatures when GenAI telemetry is examined: 1. **Missing spans** — the child span was never created; the trace is short but internally consistent. Cost and token totals are low but *accurate for what exists*. 2. **Severed lineage** — the child span *exists* with valid `gen_ai.usage.input_tokens`/`output_tokens` attributes, but it was re-emitted by an intermediary that did not propagate the W3C `traceparent`/`tracestate` and did not copy the parent's `gen_ai.conversation.id` or `gen_ai.agent.id`. The span is well-formed in isolation and orphaned in aggregate. The second is the dangerous one. A cost dashboard built on `sum(gen_ai.usage.*)` over spans grouped by `trace_id` silently under-reports, because the proxy's re-emitted spans land under a *new* trace root. Nothing errors. Nothing logs. The invariant that breaks is: **for any agent invocation, the sum of token usage over the span subtree rooted at the invocation's `gen_ai.agent.id` must equal the sum reported by the model provider's billing surface for that invocation window.** When lineage is severed, the left side of that invariant is a strict subset. ## What Was Observed An agent instance (`agent.id = planner-v3`) dispatched a tool call through a sidecar MCP proxy that wrapped a downstream model-backed retrieval summarizer. The planner emitted its own `gen_ai.chat` span with `gen_ai.usage.input_tokens=1840`, `output_tokens=312`. The proxy, on forwarding the summarizer request, created a *fresh* `TracerProvider` (a common sidecar misconfiguration: the OTel SDK defaults to a no-op provider when `OTEL_EXPORTER_OTLP_ENDPOINT` is set but `OTEL_PROPAGATORS` is unset, and the sidecar's manual span creation used `trace.get_tracer("proxy")` against that fresh provider). The summarizer's span reported `input_tokens=9200`, `output_tokens=1100` — a 10× larger cost than the planner's own turn. In the collector, the summarizer span appeared under a distinct `trace_id`, with `gen_ai.operation.name=chat` and full usage attributes, but with: - no `gen_ai.conversation.id` - no `gen_ai.agent.id` - a `parent_span_id` of `0000000000000000` (root) Downstream aggregation keyed on `(trace_id, gen_ai.agent.id)` attributed the 9200/1100 tokens to `agent.id = `. The planner's per-invocation cost was reported at ~18% of true cost. The discrepancy only surfaced 40 minutes later when a budget-anomaly auditor compared provider invoice lines against span-derived totals and found a 5.4× gap concentrated in a single tool-call class. The failure trace, precisely: 1. Planner span `S_p` created, `traceparent` header attached to outbound tool-call envelope. 2. Proxy receives envelope; parses payload but **drops** the `traceparent` header when reconstructing the downstream HTTP request (a common bug: the proxy rebuilds headers from an allowlist that omits `traceparent`). 3. Downstream model call executes; proxy wraps it in span `S_c` created against a provider that has no remote parent (because `extract()` was never called on the inbound headers). 4. `S_c` exports with `parent_span_id=0`, new `trace_id`, but *correct* `gen_ai.usage.*` attributes copied from the model response. 5. Aggregator groups by `trace_id`; `S_c` forms its own singleton trace; cost attribution to `planner-v3` never occurs. ## Condition of Validity The invariant "subtree token sum = provider invoice" holds **only if** every hop that creates a GenAI span satisfies three conditions simultaneously: - **(a) Context extraction:** the hop calls `propagator.extract(carrier=inbound_headers)` before creating any span, so the new span's parent is the inbound `span_id`. - **(b) Attribute inheritance:** the hop copies `gen_ai.conversation.id` and `gen_ai.agent.id` from the inbound context (or from an envelope field) onto the child span. OTel GenAI semconv does not auto-propagate these; they are span attributes, not baggage, unless explicitly placed in `tracestate` or baggage. - **(c) Usage attribution:** `gen_ai.usage.input_tokens` / `output_tokens` are recorded on the span *that actually incurred them*, not hoisted to the parent. Any hop that satisfies (a) but not (b) produces a trace that is structurally connected but semantically unattributable. Any hop that satisfies (b) but not (a) produces a span that is attributable by attribute but orphaned in the trace graph. The failure above violated (a) and (b) together, which is why *both* trace-tree reconstruction and attribute-grouped aggregation missed it. The condition is **not** valid when the proxy is a pure pass-through with no span emission — in that case there is nothing to sever, and the invariant is trivially preserved by the absence of an intermediate span. ## Decision Boundary An instance must decide, at span-emission time, whether it is a **lineage-preserving hop** or a **lineage-rooting hop**, and the decision is not free: - If the instance is a **transparent tool-call proxy** (forwards model calls on behalf of a caller), it MUST be lineage-preserving: extract context, inherit `agent.id`/`conversation.id`, and never create a root span. Violating this is the failure above. - If the instance is a **genuine orchestration root** (a new agent invocation with no upstream caller — e.g., a cron-triggered auditor), it is legitimately lineage-rooting and MUST mint a fresh `gen_ai.conversation.id` and `gen_ai.agent.id` rather than inheriting a stale one. The boundary is crossed when a proxy *believes* it is rooting (because its local `Context` is empty) when it is actually forwarding. The empty local context is the symptom, not the license. The guardrail: **a hop that received inbound `traceparent` headers is forbidden from emitting a root span**, regardless of whether its local `Context` is populated. The inbound header is the authoritative signal of upstream lineage; local context state is not. Concretely, the runtime must enforce: `if inbound_headers contains traceparent and extracted_span_context.is_valid() and emitted_span.parent is None: raise`. This is checkable at emission time and catches the exact misconfiguration observed. ## Operational Effect The effect of a severed lineage is not a crash but a **silent cost-attribution deficit that scales with the ratio of proxied-model cost to planner-turn cost**. In the observed case the deficit was 82% of true spend because the summarizer's context (9200 input tokens) dwarfed the planner's (1840). Systems where the proxy handles cheap calls show a 2–5% deficit that is easy to dismiss as noise; systems where the proxy handles retrieval-augmented or long-context calls show 50–90% deficits that only surface at invoice reconciliation. The second-order effect is worse: once a budget-anomaly auditor flags the gap, the natural remediation — "add `gen_ai.agent.id` to the proxy's spans" — fixes attribution but *not* trace-tree continuity. The auditor's next query, "show me the full span tree for the invocation that cost 11k tokens," still returns a singleton. The correct remediation is to fix extraction (a) *and* inheritance (b) together, and to add an emission-time guard so the severed-lineage condition cannot recur silently. The guard is the durable artifact; the attribute backfill is a one-time patch. ## Guard implementation The following guard runs in the proxy's span-emission path and refuses to export a GenAI span that received upstream lineage but emitted as a root, or that dropped the inherited agent/conversation identity. ```python from __future__ import annotations from dataclasses import dataclass from typing import Mapping, Optional class LineageSeveranceError(RuntimeError): """Raised when a GenAI span is emitted as a root despite inbound traceparent, or when inherited gen_ai.agent.id / gen_ai.conversation.id are dropped.""" @dataclass(frozen=True) class InboundLineage: traceparent_present: bool extracted_trace_id: Optional[str] extracted_span_id: Optional[str] inherited_agent_id: Optional[str] inherited_conversation_id: Optional[str] @property def has_valid_upstream(self) -> bool: return ( self.traceparent_present and self.extracted_trace_id not in (None, "0" * 32) and self.extracted_span_id not in (None, "0" * 16) ) @dataclass(frozen=True) class EmittedSpan: trace_id: str span_id: str parent_span_id: Optional[str] attributes: Mapping[str, object] operation_name: str def assert_lineage_preserved( inbound: InboundLineage, emitted: EmittedSpan, ) -> None: """Enforce the severed-lineage invariant at emission time. A hop that received a valid upstream traceparent MUST emit a non-root span whose parent matches the extracted upstream span_id, and MUST carry forward gen_ai.agent.id and gen_ai.conversation.id. Any deviation is a severance. """ if not emitted.operation_name.startswith("gen_ai."): return if not inbound.has_valid_upstream: # Legitimate lineage-rooting hop. No severance possible. return if emitted.parent_span_id in (None, "0" * 16): raise LineageSeveranceError( f"span {emitted.span_id} for {emitted.operation_name} emitted as root " f"despite inbound traceparent trace_id={inbound.extracted_trace_id} " f"span_id={inbound.extracted_span_id}; proxy dropped context extraction" ) if emitted.parent_span_id != inbound.extracted_span_id: raise LineageSeveranceError( f"span {emitted.span_id} parent={emitted.parent_span_id} does not match " f"extracted upstream span_id={inbound.extracted_span_id}; " f"context was re-parented mid-hop" ) if emitted.trace_id != inbound.extracted_trace_id: raise LineageSeveranceError( f"span {emitted.span_id} trace_id={emitted.trace_id} diverged from " f"inbound trace_id={inbound.extracted_trace_id}; lineage forked" ) if inbound.inherited_agent_id is not None: emitted_agent = emitted.attributes.get("gen_ai.agent.id") if emitted_agent != inbound.inherited_agent_id: raise LineageSeveranceError( f"span {emitted.span_id} gen_ai.agent.id={emitted_agent!r} " f"dropped inherited value {inbound.inherited_agent_id!r}; " f"cost will be attributed to " ) if inbound.inherited_conversation_id is not None: emitted_conv = emitted.attributes.get("gen_ai.conversation.id") if emitted_conv != inbound.inherited_conversation_id: raise LineageSeveranceError( f"span {emitted.span_id} gen_ai.conversation.id={emitted_conv!r} " f"dropped inherited value {inbound.inherited_conversation_id!r}; " f"conversation-level token rollup will under-count" ) # Usage attributes must be present on the span that incurred them. for required in ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens"): if required not in emitted.attributes: raise LineageSeveranceError( f"span {emitted.span_id} missing {required}; token accounting " f"cannot be reconciled against provider invoice" ) ```