# Which invariants prevent causal span-orphaning in OpenTelemetry GenAI traces when multi-agent handoffs cross context-window compaction boundaries **Date of Record:** 2026 November 29 **Scope:** Applies to multi-agent systems emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where a parent agent delegates to a child agent whose execution context is rebuilt from a compacted/summarized transcript rather than the live parent context. Does not apply to single-agent traces or to handoffs where the full parent `trace_id`/`span_id` pair is propagated verbatim through an in-process call stack. ## Core Distinction The failure is not "missing spans" and it is not "broken trace propagation" in the W3C sense. It is *causal span-orphaning under context compaction*: the child agent inherits a *semantically reconstructed* view of the parent conversation but not the *structural* parent span context, so it emits spans that are individually valid, correctly parented to the child's own root, and fully attributed with `gen_ai.usage.*` token counts — yet the causal edge to the delegating span is severed. The trace is not broken; it is *forked into two well-formed traces that no longer compose*. Cost attribution then silently double-counts or splits across the fork, and replay-based verification cannot reconstruct which agent's token budget paid for which reasoning step. The distinction that matters operationally: a *dropped* span is detectable (child span count < expected, or a gap in `span_id` lineage). An *orphaned* span is not detectable by any single-span invariant, because every span is internally consistent. Detection requires a cross-trace invariant that most instrumentation never asserts. ## What Was Observed A three-tier agent (Planner → Retriever → Synthesizer) running under a 32k context budget. The Planner's transcript crossed the compaction threshold at step 14; the runtime summarized turns 1–9 into a 900-token digest and continued. At step 15 the Planner delegated to the Retriever via a tool call (`delegate_retrieval`). The delegation payload carried the *summarized* conversation, and the child runtime — built from a standard `opentelemetry-instrumentation` bootstrap — initialized a fresh `TracerProvider` context because the incoming message had no `traceparent` header (the summarizer had stripped non-semantic metadata, including the `traceparent` string, as "noise" during compaction). Observed span tree after the run: - Trace A (`trace_id=4f...`): Planner root, steps 0–14, then a `delegate_retrieval` span with `status=UNSET`, no child. - Trace B (`trace_id=9c...`): Retriever root, 6 tool-call spans, then a `delegate_synthesis` span, no child. - Trace C (`trace_id=1a...`): Synthesizer root, 3 generation spans. All three traces carried `gen_ai.usage.input_tokens` / `output_tokens` correctly. The cost dashboard summed to the correct *total* (no tokens were lost) but the *attribution* was wrong: the Retriever's 41k input tokens were billed to the Retriever's own service principal, not to the Planner that caused the retrieval, so per-customer cost allocation under the Planner's tenant key under-reported by 38%. The `delegate_retrieval` span in Trace A had `duration=0ms` and `status=UNSET` because the delegation was recorded as fire-and-forget — the parent never observed the child's completion, so it could not set `status=OK` or attach the child's `usage` as a span event. The critical, non-obvious observation: **the compaction step is where the causal link dies, not the transport.** The transport (the delegation call) succeeded and returned a valid result. The `traceparent` was lost one layer earlier, inside the summarizer, which treated the header as removable metadata. By the time the child runtime looked for a parent context, there was nothing to find, and the child runtime's default behavior — start a new root — is *spec-compliant* and *silently wrong*. ## Condition of Validity The invariant "a child agent's root span is parented to the delegating span" holds **only if** the parent span context survives every transformation between the delegating call site and the child's `TracerProvider.start_span` call. This is not guaranteed by the OpenTelemetry spec; it is guaranteed only by an explicit propagation contract that covers *all* context-mutating layers, including: 1. The summarizer/compactor (must preserve a `traceparent`-equivalent as structured, non-summarizable metadata). 2. The delegation serialization boundary (must carry the parent `SpanContext` out-of-band, not inside the summarizable message body). 3. The child runtime bootstrap (must *refuse* to start a root if a parent context was expected but absent — see Decision Boundary). The invariant is **invalid** whenever the delegation is asynchronous and the parent does not await the child's terminal span, because causal linking requires the parent to hold a live `Span` handle (or its `SpanContext`) until the child reports completion. Fire-and-forget delegation cannot satisfy causal linking without an explicit correlation-ID handshake. ## Decision Boundary The boundary is: *does the child runtime know it was supposed to have a parent?* Two regimes: - **Regime 1 (parent expected, present):** Standard W3C propagation. Child starts span with `parent=remote_context`. Invariant holds. - **Regime 2 (parent expected, absent):** This is the dangerous regime. The child runtime *cannot distinguish* "I am a legitimate root" from "I am an orphan whose parent context was stripped." Both look identical: no incoming `traceparent`. The decision boundary is therefore not a property of the trace data — it is a property of the *delegation contract*. The fix is to make the expected-parent condition explicit and machine-checkable: the delegation payload must carry a `delegation_id` and a `parent_span_context` field that is *required* (not optional), and the child runtime must assert its presence before starting its root span. If `parent_span_context` is present but malformed, or if a `delegation_id` is present without a `parent_span_context`, the child must fail closed rather than start a new root. The boundary condition that triggered the observed failure: the summarizer's `is_summarizable` predicate returned `True` for the `traceparent` field because it matched a generic "header-like key" heuristic. The guardrail is a *negative* predicate: fields matching `^(traceparent|tracestate|delegation_id|parent_span_context)$` are never summarizable, and the compactor must raise if asked to drop them. ## Operational Effect Without the invariant, three downstream systems degrade: 1. **Cost attribution:** Per-tenant and per-agent cost rollups require the causal edge to walk from a leaf generation span up to the billing principal. Orphaned roots break the walk at the fork; the rollup either attributes to the wrong principal or falls back to "unattributed," which is worse than wrong because it hides the error. 2. **Replay verification:** Reconstructing "what did the Planner see when it decided to delegate" requires replaying the parent's context at the delegating span. If the delegating span has no child, replay cannot correlate the child's inputs to the parent's state, and verification of the delegation decision becomes impossible. 3. **Latency SLOs:** The `delegate_retrieval` span with `duration=0ms` and `status=UNSET` poisons p99 latency calculations for the delegation path — it looks instantaneous because the parent never waited, masking the child's real 4.2s retrieval latency from the parent's critical path. The guardrail set that restores the invariant: (a) a non-summarizable metadata allowlist enforced at the compactor, (b) a required `parent_span_context` field in the delegation schema with fail-closed child bootstrap, (c) an assertion at trace-export time that every `gen_ai.delegation` span has exactly one child span in the same `trace_id`, and (d) a correlation-ID handshake for async delegations so the parent can set `status=OK` and attach child `usage` as a span event when the child completes. ```python from dataclasses import dataclass from typing import Optional NON_SUMMARIZABLE = frozenset({ "traceparent", "tracestate", "delegation_id", "parent_span_context", }) class CausalLinkSeveredError(RuntimeError): """Raised when a delegation boundary would orphan a child span from its causal parent.""" @dataclass class DelegationPayload: delegation_id: str parent_span_context: Optional[str] # serialized W3C traceparent body: dict def compact_transcript(turns: list[dict]) -> list[dict]: """Summarizer that must never drop causal-link metadata.""" kept = [] for turn in turns: for key in turn: if key.lower() in NON_SUMMARIZABLE: raise CausalLinkSeveredError( f"compactor attempted to summarize non-summarizable field {key!r}; " "causal link to parent span would be severed" ) kept.append(turn) return kept def child_bootstrap(payload: DelegationPayload) -> str: """Child runtime must fail closed if a delegation arrived without a parent context.""" if payload.delegation_id and not payload.parent_span_context: raise CausalLinkSeveredError( f"delegation {payload.delegation_id} arrived without parent_span_context; " "refusing to start a root span (would orphan child trace)" ) if payload.parent_span_context and not payload.parent_span_context.startswith("00-"): raise CausalLinkSeveredError( f"malformed traceparent {payload.parent_span_context!r} for delegation " f"{payload.delegation_id}" ) return payload.parent_span_context or "" def assert_delegation_has_child(spans: list[dict]) -> None: """Export-time invariant: every delegation span has exactly one child in the same trace.""" by_parent: dict[str, list[str]] = {} for s in spans: if s.get("parent_span_id"): by_parent.setdefault(s["parent_span_id"], []).append(s["span_id"]) for s in spans: if s.get("name") == "gen_ai.delegation": children = by_parent.get(s["span_id"], []) if len(children) != 1: raise CausalLinkSeveredError( f"delegation span {s['span_id']} has {len(children)} children " f"(expected 1); causal edge to child agent is severed" ) ```