# Which invariants prevent causal trace corruption when OpenTelemetry GenAI spans cross agent handoff boundaries **Date of Record:** 2026 November 24 **Scope:** Applies to multi-agent systems that emit OpenTelemetry GenAI semantic-convention spans and propagate `traceparent`/`tracestate` across agent handoffs (A2A, MCP, or custom bus). Does not cover single-process instrumentation, metrics-only pipelines, or log-based tracing without span context propagation. ## Core Distinction There are two distinct notions of "causal linkage" in a multi-agent trace, and conflating them is the root of the failure this record documents. The first is **context propagation**: the W3C `traceparent` header carrying `trace-id`, `parent-id`, and `trace-flags`. This is a *transport* invariant — it says "these bytes were emitted in the lexical scope of that span." It is cheap, stateless, and survives any hop that forwards headers verbatim. The second is **semantic causality**: the claim that span B's output *caused* span A's input — the `gen_ai.*` attributes (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.response.finish_reasons`) plus the logical parent relationship that a trace viewer renders as an edge. This is a *reasoning* invariant. It says "the token B produced was consumed by A's prompt." Context propagation is enforced by the OTel SDK. Semantic causality is *not* — the SDK will happily serialize a `traceparent` whose `parent-id` points to a span that was sampled out, dropped by a batch exporter, or generated by a different agent instance that has since been checkpointed and resumed under a new identity. The trace remains structurally valid (every `parent-id` resolves to *some* `span-id` in the store, or the backend synthesizes a placeholder) while being causally false. This is the boundary condition: **a trace can be well-formed and wrong.** ## What Was Observed A three-agent pipeline: Planner → Retriever → Synthesizer. Each agent is a separate process behind an A2A endpoint. The Planner emits a span `plan.generate`, then calls the Retriever with a propagated `traceparent`. The Retriever emits `retrieve.search` with `gen_ai.operation.name=chat` (it uses an LLM to rewrite the query), returns results, then calls the Synthesizer. The Synthesizer was configured with a **batch span processor** with a 5-second export deadline and a queue cap of 2048. Under load, the Retriever's `retrieve.search` span — a long-running LLM call averaging 8–12 seconds — was still *open* when the Retriever forwarded the `traceparent` to the Synthesizer. The Synthesizer's `synth.generate` span was created with `parent-id = retrieve.search.span-id`. Correct so far. Then the Retriever hit its queue cap and the batch processor dropped the `retrieve.search` span on export (OTel's default `drop` policy on `max_queue_size` overflow, logged only as `dropped_spans` on an internal counter nobody scraped). The Synthesizer's span arrived at the backend with a `parent-id` that never materialized. The backend's behavior — this is the non-obvious part — was not to orphan the span. It **re-parented** it to the nearest resolvable ancestor: `plan.generate`. The rendered trace now showed `synth.generate` as a direct child of `plan.generate`, with a latency that (because the backend computes parent duration from child span timestamps) appeared to be 14 seconds instead of the actual 2 seconds of synthesis. An operator investigating a latency regression spent a day chasing a phantom 14-second generation step that was actually the Retriever's dropped span's wall-clock time being attributed upward. The causal lie: the trace asserted that the Synthesizer consumed the Planner's output directly. It did not. It consumed the Retriever's output, which was derived from a query rewrite the trace no longer records. ## Condition of Validity The invariant that must hold for a GenAI trace to be causally truthful is: > **For every span S with `parent-id = P`, the span P must be exported to the same backend with the same `trace-id`, and S's `gen_ai.prompt`/input payload must be byte-identical to a value that appears in P's `gen_ai.completion`/output payload (or in P's declared outbound message attributes).** Three conditions make this hold, and each is independently violable: 1. **Export atomicity across the parent chain.** A span may not be exported before its parent is durably accepted, or the parent must be exported in the same batch. The OTel batch processor does not guarantee this — children can flush before parents when the parent is still open. Fix: use a `SpanProcessor` that buffers children keyed by `parent-id` until the parent's `on_end` fires, or emit the parent as a "start" event and reconcile at the collector. 2. **Payload continuity.** The Synthesizer's input must be traceable to the Retriever's output. This requires the Retriever to record its *outbound* message as an attribute (e.g., `gen_ai.retrieval.output_hash` or the full completion under a redaction policy), not just its inbound prompt. Most GenAI instrumentation records `gen_ai.prompt` and `gen_ai.completion` for the *LLM call* but not the *agent-to-agent message* that carries the result forward. The gap between "what the LLM said" and "what the agent sent" is where causality silently breaks. 3. **Identity stability across resume.** If an agent is checkpointed mid-task and resumed as a new process, its `service.instance.id` changes. If the trace context is not carried in the checkpoint (only the task state is), the resumed agent's spans get a fresh `trace-id` and the pre-checkpoint and post-checkpoint halves of the task appear as two unrelated traces. The causal chain is not broken — it is *severed*, which is worse, because there is no orphan to detect. ## Decision Boundary The decision an operator faces is whether to treat a re-parented span as a **data-quality incident** (alert, block the trace from the latency dashboard) or a **benign gap** (accept it, the causal edge is approximate). The boundary is determined by whether the downstream consumer of the trace makes *causal* claims or only *aggregate* claims. - If the trace feeds a latency SLO computed as `max(child.end) - parent.start` per span, re-parenting **corrupts the SLO** because a dropped intermediate span's duration is absorbed into the surviving ancestor. This is a hard boundary: re-parented traces must be excluded from per-span latency aggregation, or the aggregation must use `span.start`/`span.end` deltas rather than parent-relative durations. - If the trace feeds a token-accounting rollup that sums `gen_ai.usage.input_tokens` over all spans in a `trace-id`, re-parenting is **harmless** — the sum is invariant to tree shape. The boundary here is permissive. - If the trace feeds an auditor agent that reconstructs "which model saw which input" to verify a policy, re-parenting is **fatal** — the auditor will conclude the Synthesizer saw the Planner's raw output, which may contain PII the Retriever was supposed to strip. This is the highest-severity case and the one most often missed, because the auditor's own reasoning is probabilistic and will confabulate a plausible chain rather than flag the missing span. The guardrail: **the trace consumer must declare, per query, whether it depends on tree shape.** A consumer that depends on shape must reject any trace containing a span whose `parent-id` does not resolve to an exported span with a matching `trace-id`, rather than accepting the backend's re-parented rendering. This requires the consumer to query the raw span store, not the pre-rendered trace view. ## Operational Effect The practical consequence is that **trace completeness must be verified at the consumer, not assumed from the producer.** Three concrete changes bound the failure: 1. Emit a `gen_ai.agent.handoff` span at each agent boundary, sibling to (not parent of) the downstream agent's root span, carrying `handoff.from_service`, `handoff.to_service`, and a `handoff.payload_digest`. This span is short-lived and small, so it survives queue pressure that drops the long-running LLM span. When the LLM span is dropped, the handoff span still records that the edge existed, and the consumer can detect the missing intermediate. 2. Set the batch processor's `max_export_batch_size` and queue cap such that the *longest expected span* (the LLM call) cannot be in-flight when its child is created. In practice this means either (a) close the parent span before forwarding the `traceparent`, which requires the agent to emit its output before the downstream call rather than after, or (b) use a synchronous exporter for spans that will be parents of cross-process children. Option (a) is the architectural fix; option (b) is a latency tax most teams won't pay. 3. Carry the full `traceparent` *and* the `service.instance.id` of the emitting span in the checkpoint payload, so a resumed agent can rejoin the original trace rather than starting a new one. The resume path must validate that the checkpoint's `trace-id` matches the `traceparent` it will emit; a mismatch is a hard error, not a warning. The invariant, stated once: **a causal trace is only as truthful as its weakest export, and the OTel SDK does not enforce that the weakest export is causally load-bearing.** The consumer must. ```python class CausalTraceIntegrityError(RuntimeError): """Raised when a GenAI trace asserts a causal edge that the span store cannot substantiate.""" pass def validate_causal_chain(spans: list[dict], trace_id: str) -> None: """ Reject traces where any span's parent-id does not resolve to an exported span in the same trace. Re-parented traces (backend-synthesized edges) are treated as integrity failures, not benign gaps, because downstream latency and audit consumers depend on tree shape. spans: raw span records from the store, each with keys 'span_id', 'parent_id', 'trace_id', 'name', 'start', 'end', and optionally 'gen_ai.operation.name'. """ by_id = {s["span_id"]: s for s in spans if s["trace_id"] == trace_id} if not by_id: raise CausalTraceIntegrityError( f"no spans found for trace_id={trace_id}; cannot validate causality" ) unresolved: list[tuple[str, str]] = [] for span in by_id.values(): parent = span.get("parent_id") if parent is None: continue # root span if parent not in by_id: unresolved.append((span["span_id"], parent)) if unresolved: detail = ", ".join(f"{child}->{parent}" for child, parent in unresolved) raise CausalTraceIntegrityError( f"trace {trace_id} contains {len(unresolved)} span(s) whose parent " f"is not exported: {detail}. Backend re-parenting would fabricate a " f"causal edge; exclude this trace from latency and audit consumers." ) # Payload continuity check: every non-root span must declare an inbound # digest that matches a declared outbound digest on its parent. for span in by_id.values(): parent_id = span.get("parent_id") if parent_id is None: continue inbound = span.get("gen_ai.agent.inbound_digest") parent_outbound = by_id[parent_id].get("gen_ai.agent.outbound_digest") if inbound is not None and parent_outbound is not None and inbound != parent_outbound: raise CausalTraceIntegrityError( f"payload discontinuity on edge {parent_id}->{span['span_id']}: " f"child inbound digest {inbound} != parent outbound digest " f"{parent_outbound}. The recorded causal edge is false." ) def aggregate_span_latency(spans: list[dict], trace_id: str) -> dict[str, float]: """Per-span wall-clock latency, safe against re-parenting because it uses span-local start/end deltas rather than parent-relative durations.""" validate_causal_chain(spans, trace_id) return { s["span_id"]: s["end"] - s["start"] for s in spans if s["trace_id"] == trace_id and "end" in s and "start" in s } ```