# When must an instance abandon a parent span: cross-process trace-context propagation loss in OpenTelemetry GenAI agent spans during tool-call fan-out **Date of Record:** 2026 November 25 **Scope:** Applies to multi-process or multi-runtime agent architectures where an orchestrator LLM emits tool calls that execute in separate worker processes (sandboxes, sub-agents, MCP servers) and where each worker emits `gen_ai.*` spans that must attach to the orchestrator's trace. Does not apply to single-process agents where all spans share one `TracerProvider` and one in-memory context. ## Core Distinction A trace-context propagation failure is not the same as a missing span. When a worker process loses the W3C `traceparent` (or the `tracestate` carrying the `gen_ai.conversation.id` and vendor baggage), it still emits a *syntactically valid* span — with a fresh `trace_id`, a fresh `span_id`, and a `parent_span_id` pointing at nothing the collector has ever seen. The telemetry pipeline does not error. The span is accepted, indexed, and billed. The failure is silent and only detectable by comparing `gen_ai.usage.input_tokens` aggregated at the trace root against the sum of `gen_ai.usage.*` on descendant spans. The distinction that matters operationally: a *dropped* span is an observability gap you can alert on; a *re-rooted* span is a cost-attribution lie that reconciles to zero and looks healthy. ## What Was Observed An orchestrator agent (`gen_ai.operation.name = "invoke_agent"`, `gen_ai.system = "openai"`, `gen_ai.request.model = "gpt-4o"`) ran a plan-execute loop. Each step dispatched a tool call to a subprocess worker via a local queue. The orchestrator serialized the tool arguments as JSON and injected the current span context into the message envelope as a `traceparent` header string. The propagation worked for the first N steps of every run and failed deterministically at step 7 — the first step whose tool call was *retried*. On retry, the orchestrator's retry wrapper reconstructed the envelope from the persisted `ToolCall` record rather than from the live `Context`. The persisted record had been written *before* the span was started (to survive a crash mid-dispatch), so it carried no `traceparent`. The worker, seeing no header, called `trace.set_span_in_context(trace.INVALID_SPAN)` and started a root span. Observed span graph for a single logical task: - Root: `invoke_agent` span, `trace_id = A`, `gen_ai.usage.input_tokens = 1840`. - Steps 1–6: tool spans, `trace_id = A`, `parent_span_id` = root. Usage attributes present and correct. - Step 7 (retry): tool span, `trace_id = B`, `parent_span_id = 0000000000000000`. `gen_ai.usage.input_tokens = 612`. - Steps 8+: back on `trace_id = A` (live context was available again). The collector's per-trace cost rollup for `trace_id = A` reported 1840 input tokens. The true task cost was 2452. The 612-token retry was attributed to an orphan trace `B` that no human or agent ever queried, because alerting was keyed on `trace_id = A`. The retry was also the most expensive single step (it re-sent the full prior context), so the *unattributed* fraction was disproportionately large — 25% of true cost, 0% of reported cost. A second, subtler loss: the `gen_ai.conversation.id` attribute lived in `tracestate` baggage, not in the span body. When the worker re-rooted, it re-derived a conversation id from a fresh UUID. Downstream episodic-memory distillation keyed on `conversation.id` split the task into two conversations, and the retry's tool output — which contained the corrected argument — was never joined back to the plan that needed it. ## Condition of Validity The invariant that must hold for cost telemetry to be trustworthy: > For every span S with `gen_ai.operation.name` in {`execute_tool`, `invoke_agent`, `chat`}, if S is causally descended from a root agent span R, then `S.trace_id == R.trace_id`, and the sum of `gen_ai.usage.*` over all descendants equals the root's reported usage within the model's accounting tolerance. This invariant holds only when context propagation is *derived from live execution state at dispatch time*, not from any persisted or reconstructed record. The moment a retry, a replay, a checkpoint-resume, or a queue redelivery reconstructs the dispatch envelope from storage, the invariant is at risk, because persisted records are written at a different point in the lifecycle than the span is started. The boundary is precise: propagation is valid iff the `Context` object handed to the worker is the *same object* (or a descendant of it) that was active when the parent span was created. Any serialization boundary that drops `tracestate` silently converts a child into a root. A secondary condition: `gen_ai.usage` attributes must be emitted on the span that *incurred* the tokens, not copied to the root. If the orchestrator aggregates usage onto the root span and the worker also emits usage on its own span, the rollup double-counts. The convention's intent is per-span accounting with rollup at query time; violations are indistinguishable from propagation loss when both bugs coexist. ## Decision Boundary An instance must decide, per dispatch, between two behaviors when it cannot attach a valid `traceparent` to a tool call: 1. **Fail closed** — refuse to dispatch, surface a `PropagationLossError`, and let the orchestrator checkpoint and retry with a freshly minted context. Correct for any call that mutates external state or whose cost must be attributable. 2. **Dispatch with an explicit orphan marker** — send a synthetic `traceparent` whose `trace_id` is the *parent's* trace id but with a span id that the collector will later reconcile, and tag the worker span `gen_ai.propagation.degraded = true`. The boundary condition that forces the choice: **is the missed cost recoverable by reconciliation?** If the worker's span carries `gen_ai.conversation.id` and the orchestrator's root carries the same, a collector-side join can reattach orphaned usage. If the conversation id was in `tracestate` and was lost (as in the observed case), no join key exists and the cost is permanently unattributable. Therefore the decision rule is: fail closed whenever `tracestate` (or any join-key baggage) cannot be reconstructed; degrade-with-marker only when a durable join key survives in the span body. ## Operational Effect Implementing fail-closed dispatch on missing trace context converts a silent 25% cost leak into a loud, retryable error at step 7 — the orchestrator's existing checkpoint/resume machinery handles it, and the retried call carries a valid context because it is now dispatched from live state. The cost of the guardrail is one extra retry on the rare reconstruction path; the benefit is that `trace_id`-keyed cost rollups become exact and that episodic-memory joins on `conversation.id` never split. The deeper operational effect: any agent that persists a dispatch envelope for crash-safety must persist it *after* the span is started and must include the serialized `traceparent` + `tracestate` in the envelope. The persistence point and the span-start point must be ordered such that the persisted record is a superset of the live context. This is a one-line ordering constraint that, when violated, produces telemetry that passes every schema validator and every uptime check while lying about where the money went. ```python import re from dataclasses import dataclass class PropagationLossError(RuntimeError): """Raised when a tool-call dispatch cannot carry a valid trace context.""" _TRACEPARENT_RE = re.compile( r"^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$" ) @dataclass(frozen=True) class DispatchEnvelope: tool_name: str args_json: str traceparent: str | None tracestate: str | None conversation_id: str | None def build_dispatch_envelope( tool_name: str, args_json: str, live_traceparent: str | None, live_tracestate: str | None, live_conversation_id: str | None, is_retry: bool, ) -> DispatchEnvelope: """Construct an envelope for a tool dispatch from LIVE execution state. The invariant: traceparent and tracestate must come from the active Context at dispatch time. If we are on a retry path that reconstructed state from a persisted record, the context may be absent -- in which case we must fail closed rather than let the worker start a root span. """ if not live_traceparent: raise PropagationLossError( f"dispatch of tool={tool_name!r} (retry={is_retry}) has no " "traceparent; refusing to emit an orphan root span" ) match = _TRACEPARENT_RE.match(live_traceparent) if not match: raise PropagationLossError( f"malformed traceparent for tool={tool_name!r}: " f"{live_traceparent!r}" ) # A join key must survive for reconciliation to be possible. If the # conversation id lived only in tracestate and tracestate was lost, # cost attribution is permanently broken -- fail closed. if not live_conversation_id and not live_tracestate: raise PropagationLossError( f"tool={tool_name!r} has neither conversation_id nor " "tracestate; orphaned usage would be unattributable" ) return DispatchEnvelope( tool_name=tool_name, args_json=args_json, traceparent=live_traceparent, tracestate=live_tracestate, conversation_id=live_conversation_id, ) def reconcile_trace_cost(root_usage: int, descendant_usages: list[int], tolerance: float = 0.02) -> None: """Guardrail: verify per-trace usage rollup matches root accounting.""" total = sum(descendant_usages) if root_usage == 0: raise PropagationLossError("root span reports zero usage; cannot reconcile") drift = abs(total - root_usage) / root_usage if drift > tolerance: raise PropagationLossError( f"usage reconciliation failed: root={root_usage} " f"descendants={total} drift={drift:.1%} > {tolerance:.0%}" ) ```