# What structural signals indicate OpenTelemetry GenAI span trees have silently dropped a tool-call child span during agent handoff, invalidating token accounting and trace continuity **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for multi-step tool-calling and inter-agent handoffs, where child spans are created asynchronously or across process/transport boundaries (MCP, A2A, HTTP). Does not apply to single-process, synchronous, single-agent traces where parent and child spans share one context object and one exporter queue. ## Core Distinction The distinction that matters is between **span loss** and **span orphaning**, because the two produce opposite diagnostic signatures and require different guardrails. A *lost* span is never exported: the child `execute_tool` span (or the downstream agent's `invoke_agent` span) is created, but its `on_end` callback never fires before the process boundary is torn down, or the context object that carried the parent `SpanContext` is discarded during handoff. The parent span still closes cleanly, still carries its `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` attributes, and still appears in the trace — so nothing *looks* wrong at the parent level. An *orphaned* span is exported but with a `parent_span_id` that points to a span the backend never received; it appears as a root or as a detached subtree. The GenAI semantic conventions make this distinction load-bearing because token accounting is defined **per span**, not per trace. `gen_ai.usage.input_tokens` on the parent `chat` span reflects only the tokens of *that* model invocation. When a tool-call child span is lost, the tokens consumed by the tool-augmented follow-up turn — the second `chat` span that consumes the tool result — are still attributed correctly *if that span survives*. But the handoff span that should have carried `gen_ai.operation.name = "execute_tool"` and linked the two turns is gone, so a trace-level sum of `gen_ai.usage.*` no longer reconciles with the billing ledger, and no span-level attribute explains the gap. The structural signal is therefore not "a span is missing" (you cannot observe a span you never received) but **a parent whose declared child count, tool-call sequence, or token arithmetic cannot be reconstructed from its descendants**. ## What Was Observed A three-agent pipeline (planner → retriever → synthesizer) using A2A handoffs over HTTP, each agent in its own container, each emitting GenAI spans to a shared OTLP collector via a batch span processor with a 5-second export interval and a 2048-span queue. The planner's `invoke_agent` span carried `gen_ai.agent.name = "planner"` and three child `chat` spans. The third `chat` span declared a tool call to the retriever agent via `gen_ai.tool.name = "a2a_handoff_retriever"`, and the retriever's own `invoke_agent` span arrived at the collector with `parent_span_id` set to the planner's tool-call span — but that tool-call span itself never arrived. The trigger was a container lifecycle race, not a code bug in span creation. The planner's tool-call span was created with `start_as_current_span` wrapping the outbound A2A request. The A2A client returned as soon as the HTTP response headers arrived (202 Accepted, async handoff). The span context manager exited and called `span.end()`, which enqueued the span in the batch processor. The planner container was then scaled down by the orchestrator before the 5-second batch flush completed. The batch processor's shutdown hook is registered on `SIGTERM`, but the container received `SIGKILL` after a 3-second grace period — shorter than the export interval. The span was dropped from the queue with no `dropped_spans` counter increment visible to the application, because the counter is an SDK-internal metric that was never exported either. The observable signature at the backend was threefold and only visible when cross-referencing: 1. The retriever's `invoke_agent` span had a `parent_span_id` (`0x7f3a...`) that resolved to no span in the trace — an orphan, not a root. 2. The planner's `invoke_agent` span had `gen_ai.usage.input_tokens = 4120` and `output_tokens = 890` summed across its three `chat` children, but the third `chat` child reported `gen_ai.usage.input_tokens = 0` for the tool-result turn — because the tool-result turn's `chat` span was *also* created inside the dropped tool-call context and inherited the same fate. 3. The trace's total `gen_ai.usage.output_tokens` (planner 890 + retriever 2210 + synthesizer 1540 = 4640) undercounted the ledger by exactly the retriever's tool-result synthesis turn (1180 tokens), which had been emitted but whose parent chain was broken at export time. The critical point: **no single span was malformed**. Every span that arrived was schema-valid against the GenAI conventions. The failure was purely structural — a hole in the parent-child graph that token accounting and trace continuity both depend on but neither validates. ## Condition of Validity The invariant that must hold for GenAI span trees to be trustworthy is: > For every span `S` with `gen_ai.operation.name` in `{execute_tool, invoke_agent, chat}`, if `S.parent_span_id` is non-null, then a span with `span_id == S.parent_span_id` must exist in the same trace, and the parent's `gen_ai.usage.*` attributes must be reconstructible as a function of its descendants' usage plus its own model-invocation usage. This invariant is *valid* only when three conditions hold simultaneously: - **Export durability across the handoff boundary.** The child span's export must complete before the parent process's context is destroyed. With async handoffs (202-style), the parent's span ends before the child agent even starts, so the parent's export is racing the container lifecycle — not the child's execution. - **Context propagation completeness.** The `SpanContext` (trace_id, span_id, trace_flags) must survive the transport. A2A and MCP carry it in `traceparent` headers, but only if the client injects it *before* the async return and the server extracts it *before* creating its own root span. A common failure: the server's framework creates a root span on request entry, then the extracted context is attached as a *link* rather than a *parent*, silently converting the intended child into a sibling. - **Token attribution locality.** `gen_ai.usage.*` must be emitted on the span that actually performed the model invocation, not aggregated upward. When a parent aggregates child usage and a child is lost, the parent's number is *correct for what it saw* but *wrong for the trace* — and the trace-level reconciliation has no way to detect the discrepancy without an external ledger. The invariant is *invalid* (and this article does not apply) when spans are exported synchronously with `SimpleSpanProcessor` and the process is guaranteed to outlive the export, or when the backend performs server-side span stitching from `traceparent` headers independent of the SDK's parent assignment. ## Decision Boundary The decision boundary for an operator is: **at what point does a broken parent-child edge become a token-accounting incident rather than a cosmetic trace gap?** The boundary is crossed when the sum of `gen_ai.usage.input_tokens + output_tokens` over all *received* spans in a trace diverges from an independent token ledger (provider billing, gateway metering, or a sidecar counter) by more than the loss tolerance. The loss tolerance is bounded by the maximum tokens a single dropped span can account for — which, for a `chat` span, is the full context window of one model invocation. In the observed case the divergence was 1180 tokens against a 4640-token trace sum, a 25% undercount, well past any reasonable tolerance. Below the boundary, a single orphaned `execute_tool` span with zero token attributes is a trace-hygiene issue: dashboards show a detached node, but the token sum reconciles because the tool call itself consumed no model tokens. Above the boundary, the orphan is a *token-bearing* span — a `chat` or `invoke_agent` span — and its loss corrupts the accounting invariant. The decision rule an agent should apply when it detects an orphan (a span whose `parent_span_id` resolves to nothing): ``` if orphan.gen_ai.operation.name in {"chat", "invoke_agent"}: reconcile against external ledger; if divergence > tolerance: RAISE else: log trace-hygiene warning; do not block ``` The asymmetry is deliberate: `execute_tool` spans carry no `gen_ai.usage.*` and their loss is structurally detectable but economically inert; `chat` and `invoke_agent` spans carry the token accounting and their loss is both structurally and economically load-bearing. ## Operational Effect The operational effect of an undetected lost token-bearing span is a **silent accounting drift that compounds across handoffs**. Each async handoff is an independent opportunity for a batch-flush race, so a pipeline with `N` handoffs has `N` independent loss points, and the drift is cumulative and one-directional (always an undercount, never an overcount, because lost spans are never double-counted). Over a day of traffic this manifests as a persistent gap between trace-derived token sums and provider billing that grows with handoff volume — and because every received span is schema-valid, standard GenAI convention validation (which checks attribute presence and type, not graph completeness) passes cleanly. The guardrail that bounds it is a **handoff-scoped flush barrier**: before the parent process tears down its context, it must force-flush the batch processor and *confirm* the flush completed (via the `force_flush()` return value, not fire-and-forget), and the orchestrator's `SIGTERM` grace period must exceed the export interval. The second guardrail is **graph-completeness validation at the collector**: reject or flag any trace where a non-root span's `parent_span_id` is unresolved *and* the span carries `gen_ai.usage.*`, routing it to a quarantine queue rather than the accounting pipeline. The third is **ledger reconciliation as a first-class check**, not a dashboard afterthought: token sums from traces must be continuously diffed against the provider ledger, with the divergence rate treated as an SLO. ```python import logging from dataclasses import dataclass from typing import Optional logger = logging.getLogger("genai.trace.integrity") # GenAI semantic-convention operation names that carry token accounting. TOKEN_BEARING_OPS = frozenset({"chat", "invoke_agent"}) # Operations whose loss is structurally detectable but economically inert. INERT_OPS = frozenset({"execute_tool"}) class OrphanedTokenBearingSpanError(RuntimeError): """Raised when a received span's parent is unresolved AND the span carries gen_ai.usage.* attributes, meaning trace-level token accounting is corrupt.""" @dataclass class ReceivedSpan: span_id: str parent_span_id: Optional[str] operation_name: str input_tokens: int = 0 output_tokens: int = 0 @property def total_tokens(self) -> int: return self.input_tokens + self.output_tokens def validate_trace_integrity( spans: list[ReceivedSpan], external_ledger_tokens: int, loss_tolerance: int, ) -> int: """Validate parent-child graph completeness and token reconciliation. Returns the reconciled trace token sum. Raises if a token-bearing span is orphaned or if the trace sum diverges from the external ledger beyond tolerance. """ known_ids = {s.span_id for s in spans} trace_sum = 0 for span in spans: trace_sum += span.total_tokens if span.parent_span_id is None: continue # legitimate root if span.parent_span_id in known_ids: continue # edge intact # Parent unresolved. Classify by whether the span bears tokens. if span.operation_name in TOKEN_BEARING_OPS: raise OrphanedTokenBearingSpanError( f"span {span.span_id} ({span.operation_name}) has unresolved " f"parent {span.parent_span_id} and carries " f"{span.total_tokens} tokens; trace token accounting is corrupt" ) elif span.operation_name in INERT_OPS: logger.warning( "trace-hygiene: orphaned inert span %s (%s), parent %s missing", span.span_id, span.operation_name, span.parent_span_id, ) else: logger.warning( "trace-hygiene: orphaned span %s with unknown op %r", span.span_id, span.operation_name, ) divergence = abs(trace_sum - external_ledger_tokens) if divergence > loss_tolerance: raise OrphanedTokenBearingSpanError( f"trace token sum {trace_sum} diverges from external ledger " f"{external_ledger_tokens} by {divergence} > tolerance " f"{loss_tolerance}; a token-bearing span was likely dropped " f"at an async handoff boundary" ) return trace_sum def force_flush_or_fail(batch_processor, timeout_ms: int = 5000) -> None: """Handoff-scoped flush barrier. Must be called before context teardown.""" if not batch_processor.force_flush(timeout_millis=timeout_ms): raise OrphanedTokenBearingSpanError( f"batch span processor failed to flush within {timeout_ms}ms; " f"queued GenAI spans will be dropped on process teardown" ) ```