# What happens when an instance reuses a parent span ID across a delegated subtask boundary: orphaned GenAI semantic-convention spans and the trace-correlation break in multi-agent handoffs **Date of Record:** 2026 November 26 **Scope:** Applies to multi-agent systems that emit OpenTelemetry traces using the GenAI semantic conventions (`gen_ai.*` attributes) and correlate child-agent spans to parent spans via `parent_span_id` / `trace_id` propagation across an explicit handoff (A2A, MCP tool-call, or message-queue delegation). Does not apply to single-agent instrumentation where all spans are emitted in-process by one runtime, nor to systems using a flat, correlation-ID-only logging scheme without span trees. ## Core Distinction There are two ways a child agent can be linked into a parent's trace, and they fail differently: 1. **Context propagation** — the parent passes its live `SpanContext` (trace_id + span_id + trace_flags) to the child, and the child's runtime constructs child spans with that context as parent. The span tree is built by the SDK at emit time; the child never invents IDs. 2. **ID reconstruction** — the parent serializes a *reference* to itself (a `trace_id` and a `span_id` field copied into a handoff payload, task envelope, or MCP `_meta` blob) and the child, running in a separate process or even a separate model invocation, *rebuilds* the parent context from those strings before emitting its own spans. The boundary failure lives entirely in case 2. When a delegated instance reconstructs a parent span ID from a serialized payload, it is asserting that the referenced span *exists and is still open* in a collector it cannot see. If the parent span has already ended, or if the child reuses the same `span_id` value for more than one reconstructed parent (because the handoff payload was cached, retried, or fanned out), the resulting `gen_ai.*` spans become **orphans**: they carry a `parent_span_id` that resolves to nothing, or to the wrong logical operation. The trace is still *queryable* by `trace_id`, so dashboards look healthy, but the parent→child edge — the thing that makes a multi-agent trace legible — is silently severed. The non-obvious part: this is not a crash. Nothing raises. The spans are valid OTLP. Only a span-tree integrity check reveals it. ## What Was Observed A three-tier delegation: planner agent → two worker agents (fan-out) → one verifier agent (fan-in). Planner emits `gen_ai.chat` span `S_p` (span_id `a1`). It serializes `{trace_id: T, parent_span_id: a1}` into each worker's task envelope and ends `S_p` immediately after dispatch (correct — the planner's turn is over). Worker 1 reconstructs context from the envelope, emits `gen_ai.tool_call` span `S_w1` with `parent_span_id = a1`. Fine. Worker 2 does the same, emits `S_w2` with `parent_span_id = a1`. Also fine — two children of one parent is legal. The failure appeared in the **retry path**. Worker 2's first invocation timed out at the tool boundary and the orchestrator re-dispatched the *same* envelope (same `parent_span_id = a1`) to a fresh worker instance. The fresh instance, following the same reconstruction logic, emitted `S_w2'` with `parent_span_id = a1` — but it also reused the *task-local* `span_id` value `b2` because the worker's span-ID generator was seeded deterministically from the task ID for replayability. Now two distinct logical operations (`S_w2` and `S_w2'`) share `span_id = b2` under the same `trace_id`. Observed symptoms in the collector: - The verifier's `gen_ai.chat` span, which referenced `b2` as its parent (the worker whose output it checked), attached to `S_w2` — the *failed* attempt — not `S_w2'`. Verification was correlated against the wrong execution. - Span-tree queries for "children of `a1`" returned `S_w1`, `S_w2`, and `S_w2'`, but the duplicate `b2` caused the backend to drop one on dedup, non-deterministically depending on arrival order. - `gen_ai.usage.input_tokens` rolled up under `a1` double-counted the retried worker's prompt, inflating the planner's attributed cost by ~40% on affected traces. The root invariant that broke: **within a trace, `span_id` must be unique.** The GenAI conventions do not restate this (it is inherited from OTel), and reconstruction-from-payload makes it easy to violate because the child treats the payload's `parent_span_id` as authoritative while generating its *own* span IDs from a task-derived seed that survives retries. ## Condition of Validity The orphan/mis-link only manifests when **all** of the following hold: - The child reconstructs parent context from a serialized payload rather than receiving a live `SpanContext` (i.e., process/instance boundary crossed). - The parent span has ended before the child emits (true for any async handoff — the planner does not block on workers). - Span IDs on the child side are derived from a value that is stable across retries (task ID, deterministic seed, cached envelope) rather than a fresh random 64-bit value per span emission. - The collector or backend deduplicates by `(trace_id, span_id)` or joins by `parent_span_id` without validating that the parent exists and is unique. If any one fails, the symptom is masked: live propagation keeps IDs fresh; a non-deterministic ID generator makes the duplicate astronomically unlikely; a backend that tolerates duplicate span IDs hides the collision but still mis-joins the verifier. ## Decision Boundary The architectural choice is **where uniqueness is enforced**: - **Enforce at emit (correct):** every span emission draws a fresh random `span_id` from a CSPRNG; the reconstructed `parent_span_id` is *only ever read*, never written back as a child's own ID. Retries therefore produce distinct `span_id`s and the tree records both attempts as siblings — which is the truth. - **Enforce at handoff (insufficient):** stamping a `span_id` into the envelope and trusting downstream to not collide. This is what failed — the envelope's `parent_span_id` was correct, but the child's *own* ID derivation collided. - **Enforce at query (rejected):** post-hoc dedup in the backend. Non-deterministic and destroys the retry record. The boundary: a child instance may treat `parent_span_id` as an **immutable reference** but must treat its own `span_id` as **freshly minted per emission**, even under replay. Replayability of *content* (deterministic task execution) must not extend to replayability of *identity* (span IDs). Conflating the two is the trap. A second boundary governs the fan-in: the verifier must reference the *specific attempt* it verified. If the verifier reconstructs its parent from the worker's result envelope, that envelope must carry the `span_id` of the attempt that actually produced the result, not the task ID. Otherwise the verifier links to the first attempt by construction. ## Operational Effect Downstream of a broken link: - **Cost attribution drifts.** `gen_ai.usage.*` rollups attribute retried work to the wrong parent, so per-agent cost dashboards under-report workers and over-report planners. - **Verification provenance is lost.** An auditor replaying the trace cannot tell which worker attempt the verifier approved. In an eval or compliance context this is a correctness failure, not a cosmetic one. - **Latency SLOs mis-fire.** Parent span duration excludes the retried child (it attached to the first, faster attempt), so tail latency appears better than reality. - **Silent under normal load.** The collision needs a retry or a cached envelope to surface; healthy-path traces look perfect, so the bug ships. The guardrail is a **span-tree integrity assertion at the collector ingress**: reject or flag any span whose `parent_span_id` is not present in the trace's span set, and any `(trace_id, span_id)` pair seen twice. This is cheap (a set membership check) and catches the invariant violation at the boundary rather than at query time. ## Python ```python import secrets from dataclasses import dataclass, field class SpanLinkIntegrityError(RuntimeError): """Raised when a reconstructed child span would violate span-tree invariants.""" pass @dataclass class Span: trace_id: str span_id: str parent_span_id: str | None name: str @dataclass class Collector: _seen: dict[tuple[str, str], Span] = field(default_factory=dict) def ingest(self, span: Span) -> None: key = (span.trace_id, span.span_id) if key in self._seen: raise SpanLinkIntegrityError( f"duplicate span_id {span.span_id!r} in trace {span.trace_id!r}: " f"already emitted as {self._seen[key].name!r}, now {span.name!r}" ) if span.parent_span_id is not None: parent_key = (span.trace_id, span.parent_span_id) if parent_key not in self._seen: raise SpanLinkIntegrityError( f"orphaned span {span.name!r}: parent {span.parent_span_id!r} " f"not present in trace {span.trace_id!r}" ) self._seen[key] = span def reconstruct_child_span( envelope: dict, name: str, *, deterministic_seed: str | None = None ) -> Span: """Rebuild a child span from a serialized handoff payload. The parent_span_id is read-only. The child's own span_id MUST be fresh per emission; a deterministic_seed that survives retries is the bug. """ if deterministic_seed is not None: raise SpanLinkIntegrityError( "refusing to derive span_id from a retry-stable seed " f"{deterministic_seed!r}: retries would collide on (trace_id, span_id)" ) return Span( trace_id=envelope["trace_id"], span_id=secrets.token_hex(8), parent_span_id=envelope["parent_span_id"], name=name, ) def emit_retried_worker(envelope: dict, collector: Collector) -> Span: # retry path: same envelope, fresh identity span = reconstruct_child_span(envelope, name="gen_ai.tool_call") collector.ingest(span) return span ```