# What structural signals indicate span-parenting loss in GenAI observability exporters during agentic trace topology reconstruction **Date of Record:** 2026 November 30 **Scope:** Applies to OpenTelemetry-style GenAI span exporters that emit agent execution traces (LLM calls, tool invocations, sub-agent handoffs) where parent-child relationships are reconstructed downstream from span attributes rather than preserved by an in-process trace context. Does not apply to single-process synchronous agents whose spans are emitted with a live `SpanContext` object held in memory for the trace's full lifetime. ## Core Distinction The failure is not "missing spans." It is *orphaned spans that pass schema validation while silently re-rooting the topology*. A GenAI exporter that batches spans for async flush, serializes them to JSON, and hands them to a collector is subject to a specific class of defect: the `parentSpanId` field is present and syntactically valid (a 16-hex-char string), but the referenced parent span has not yet been flushed, was dropped by the batch's `maxExportBatchSize` cutoff, or was re-emitted under a different `traceId` because the exporter generated a fresh trace ID per batch flush rather than per agent invocation. The distinction that matters operationally: a *conformant* exporter guarantees that for every emitted span `S` with `parentSpanId = P`, either `P` is emitted in the same or an earlier batch under the same `traceId`, or `S.parentSpanId` is explicitly null with `S` marked as a trace root. A *non-conformant-but-validating* exporter emits `S` with a dangling `parentSpanId` and lets the collector's topology reconstructor treat the orphan as a root. Both pass schema validation. Only one reconstructs the true agent tree. ## What Was Observed A three-tier agent (orchestrator → planner sub-agent → tool-calling executor) emitting spans via an OTLP exporter with a 512-span batch limit and a 5-second `scheduledDelayMillis`. The orchestrator's root span was long-lived (held open across the full task, ~40s). Sub-agent spans and tool spans completed and were flushed in intermediate batches. Under load, three structural signals appeared in the reconstructed trace topology: 1. **Root-count inflation.** The collector's topology reconstructor reported 4 roots for a single `traceId` where the true topology had 1. The three spurious roots were the planner sub-agent span and two executor tool spans whose `parentSpanId` pointed at the still-unflushed orchestrator root. The reconstructor's orphan policy (`treat_orphan_as_root = true`) promoted them. 2. **Depth collapse on the critical path.** Because the planner span became a root, its child tool spans re-parented correctly *under it*, producing a subtree that looked internally consistent but was detached from the orchestrator. Latency attribution on the orchestrator's critical path dropped the planner's 12s execution time entirely — the orchestrator's self-time appeared as 40s with no children, and the planner appeared as a separate 12s trace. The sum of reported spans was correct; the *tree* was wrong. 3. **Trace-ID divergence on retry.** When the exporter's batch flush timed out and retried, the retry path re-instantiated the `TracerProvider` (a known defect in wrapper libraries that rebuild the provider on flush error), generating a new `traceId` for the retried spans. The same `spanId` values now existed under two `traceId`s. Downstream dedup-by-`spanId` collapsed them and silently dropped the retry's `parentSpanId` correction, because the first-seen record won. The signal that surfaced the problem was not an error. It was a *structural invariant violation*: `count(spans where parentSpanId IS NULL) > 1` for a `traceId` whose root span carried an `agent.role = orchestrator` attribute. In a correct reconstruction, exactly one span per agent invocation is a root, and it carries the orchestrator role. Any additional null-parent span under the same `traceId` is either a genuine concurrent root (rare, and should be declared) or an orphan promoted by the reconstructor. ## Condition of Validity The invariant — *one root per agent invocation, and the root is the span whose `agent.role` is the entry role* — holds only when all of the following are true: - The exporter preserves `traceId` across batch boundaries and retries for the lifetime of a single agent invocation. Trace ID must be bound at invocation start, not at flush time. - The exporter's flush ordering guarantees that a parent span is either flushed before its children or flushed in the same batch. If the parent is long-lived and outlives the batch, the exporter must emit a *placeholder* parent record (with `span.kind = internal` and a `pending = true` attribute) or hold children until the parent closes. - The collector's orphan policy is `treat_orphan_as_error`, not `treat_orphan_as_root`. The latter is the default in several OTLP receivers and is the direct cause of root-count inflation. - Dedup, if applied, is keyed on `(traceId, spanId)`, not `spanId` alone. Span IDs are only unique within a trace; a provider rebuild that reuses span IDs across traces will corrupt dedup otherwise. When any of these fails, the reconstructed topology is *plausible but false*: it validates, it renders, and it misattributes latency and causality. ## Decision Boundary The boundary for treating a reconstruction as trustworthy versus quarantining it: - **Trust** when: exactly one null-parent span per `traceId`; that span's `agent.role` matches the invocation's declared entry role; every non-root span's `parentSpanId` resolves to an emitted span in the same `traceId`; no duplicate `(traceId, spanId)` pairs with divergent `parentSpanId`. - **Quarantine** when: root count > 1 under a single `traceId` with a declared single-entry agent; any span's `parentSpanId` is non-null but unresolved; any `(traceId, spanId)` appears with two different `parentSpanId` values. - **Reject** when: the same `spanId` appears under two `traceId`s (provider-rebuild signature), because the topology is now ambiguous and no dedup policy can recover the true tree. The decision must be made *before* latency attribution or causality analysis consumes the trace. A quarantined trace is still useful for span-level metrics (token counts, tool error rates) but must not feed critical-path or parent-child cost attribution. ## Operational Effect Concretely, an agentic system that skips this check will: - Under-report sub-agent cost on the orchestrator's critical path, because detached subtrees are attributed to their spurious roots. In the observed case, 12s of the 40s critical path (30%) vanished from orchestrator attribution. - Over-count root spans in dashboards, inflating "agent invocations" by the orphan rate — which spikes exactly under load, when batch cutoffs are most likely to split parent from child. - Lose retry corrections silently when dedup is keyed on `spanId` alone, so post-incident replay shows the pre-retry (wrong) parenting. The guardrail is a pre-attribution conformance gate that enforces the one-root invariant and the `(traceId, spanId)` dedup key, and that fails closed — quarantining the trace rather than rendering a plausible false tree. The gate must run at the collector, not the exporter, because the exporter cannot see its own orphans (the parent it is waiting on is, by definition, not yet emitted). ```python from dataclasses import dataclass from typing import Iterable class TraceTopologyConformanceError(RuntimeError): """Raised when a reconstructed agent trace violates the one-root invariant or contains ambiguous span identity. Fail closed: quarantine, do not render.""" @dataclass(frozen=True) class Span: trace_id: str span_id: str parent_span_id: str | None agent_role: str | None def assert_topology_conformant( spans: Iterable[Span], declared_entry_role: str ) -> None: by_trace: dict[str, list[Span]] = {} for s in spans: by_trace.setdefault(s.trace_id, []).append(s) # Ambiguous identity: same span_id under two trace_ids (provider-rebuild signature). span_id_to_traces: dict[str, set[str]] = {} for s in spans: span_id_to_traces.setdefault(s.span_id, set()).add(s.trace_id) for span_id, traces in span_id_to_traces.items(): if len(traces) > 1: raise TraceTopologyConformanceError( f"span_id {span_id} appears under trace_ids {sorted(traces)}; " f"topology ambiguous, cannot dedup safely" ) for trace_id, trace_spans in by_trace.items(): ids = {s.span_id for s in trace_spans} roots = [s for s in trace_spans if s.parent_span_id is None] # One-root invariant. if len(roots) != 1: raise TraceTopologyConformanceError( f"trace {trace_id}: expected 1 root, found {len(roots)} " f"(roles: {[r.agent_role for r in roots]}); " f"orphans likely promoted by treat_orphan_as_root" ) if roots[0].agent_role != declared_entry_role: raise TraceTopologyConformanceError( f"trace {trace_id}: root role {roots[0].agent_role!r} " f"!= declared entry role {declared_entry_role!r}" ) # Dangling parent references. for s in trace_spans: if s.parent_span_id is not None and s.parent_span_id not in ids: raise TraceTopologyConformanceError( f"trace {trace_id}: span {s.span_id} references " f"unresolved parent {s.parent_span_id}" ) # Divergent parenting for a single (trace_id, span_id). parent_by_span: dict[str, str | None] = {} for s in trace_spans: prior = parent_by_span.get(s.span_id, "__unset__") if prior != "__unset__" and prior != s.parent_span_id: raise TraceTopologyConformanceError( f"trace {trace_id}: span {s.span_id} emitted with " f"divergent parents {prior!r} vs {s.parent_span_id!r}" ) parent_by_span[s.span_id] = s.parent_span_id ```