# What structural signals indicate span-to-trace correlation collapse when agent orchestrators re-parent LLM spans across async tool boundaries **Date of Record:** 2026 November 30 **Scope:** Applies to observability pipelines that infer parent/child relationships for LLM spans from ambient context (contextvars, thread-locals, OTel `Context`) rather than from explicit propagated trace headers, in agent systems where tool calls cross async task, thread-pool, or callback boundaries. Does not apply to pipelines using explicit W3C `traceparent` injection at every tool dispatch, nor to single-threaded synchronous chains. ## Core Distinction There are two ways an observability pipeline learns that an LLM span belongs to a parent orchestration span: 1. **Structural correlation** — the parent-child edge is carried as data: a `traceparent` header, a `parent_span_id` field, or an explicit `link` attribute written by the orchestration runtime at dispatch time. 2. **Ambient correlation** — the edge is inferred from whatever execution context happens to be active when the span is emitted: the current `contextvars.Context`, the active `asyncio.Task`, the thread-local OTel context, or a global "current agent" singleton. The failure mode is not the well-known "context lost across threads" bug. It is subtler: **context is not lost but silently re-bound to a different logical parent**. When an orchestrator fans out tool calls into a thread pool, a `BackgroundTasks` queue, or an `asyncio.create_task` per tool, the ambient context is *copied* at spawn time. But if the orchestrator reuses worker threads across multiple concurrent agents (a common pool-sizing optimization), the copied context can be overwritten by whichever task acquired the worker next. The LLM span then emits with a valid, non-null parent — just the wrong one. Correlation does not fail loudly; it succeeds *wrongly*, and cost attribution inherits the error. ## What Was Observed A supervisor agent dispatched three sub-agents (A, B, C) via a shared `ThreadPoolExecutor(max_workers=2)`. Each sub-agent made LLM calls through a shared client whose span processor read `opentelemetry.context.get_current()` to derive `parent_span_id`. The pipeline reported: - Sub-agent A's LLM spans: parent = supervisor span (correct, 100% of calls). - Sub-agent B's LLM spans: parent = sub-agent A's tool span (wrong, ~40% of calls). - Sub-agent C's LLM spans: parent = sub-agent B's tool span (wrong, ~65% of calls). Total token cost was conserved — every span appeared exactly once — but per-sub-agent cost was inflated for A and deflated for C by a factor of 1.4–1.9x. The trace tree remained a valid DAG with a single root; no orphan spans, no missing parents. A naive integrity check ("every span has a parent that exists in the trace") passed. The tell was a **structural signal**, not an error: the wrong-parent spans had `parent_span_id` values whose `end_time` preceded the child's `start_time` by a margin *smaller than the LLM call latency*, and the parent's `service.name` attribute differed from the child's declared `agent.id` resource attribute. In other words, the *resource attributes* (stamped at span creation from the agent's own identity) disagreed with the *ambient parent* (stamped from execution context). That disagreement is the invariant violation. ## Condition of Validity Ambient correlation is only sound under a conjunction of conditions that agent runtimes routinely violate: - **Exclusive context ownership:** the execution context active during span emission is uniquely owned by the logical parent for the span's entire lifetime. Thread pools with reuse, `asyncio` tasks sharing a loop with `contextvars` mutation, and callback queues all break this. - **Context immutability across the boundary:** no code between dispatch and emission reassigns the current context (e.g., a retry wrapper that re-enters a fresh context, a middleware that calls `context.attach()`). - **Parent liveness:** the parent span is still open when the child emits, or the pipeline explicitly permits post-hoc parenting. Late-emitted spans (async LLM streaming that flushes after the parent closes) violate this and get re-parented to the trace root or to a sibling. - **Single logical parent:** fan-out that shares one context across N children produces N children under one parent, which is *valid* structurally but destroys per-child cost attribution when the parent is a shared dispatcher rather than a logical agent. When any of these is false, ambient correlation degrades from "sometimes missing" to "confidently misattributed." The pipeline cannot detect this from span shape alone; it requires a cross-check against resource identity. ## Decision Boundary The boundary is between **tolerating ambient correlation with a post-hoc reconciliation pass** and **refusing to emit a span whose ambient parent disagrees with its resource identity**. Reconciliation is acceptable when: - The pipeline can join spans to an authoritative dispatch log (the orchestrator's own record of `(child_span_id, intended_parent_span_id)`), and - Cost attribution is computed from the reconciled tree, not the raw tree, and - The reconciliation is idempotent and re-runnable. Refusal is required when: - Cost attribution feeds billing, quota enforcement, or per-tenant chargeback, where a 1.4x misattribution is a financial defect, or - The trace tree is used for causal debugging (which sub-agent caused the failure), where a wrong parent inverts the causal direction. The non-obvious part: the decision must be made **at span emission**, not at pipeline ingestion. Once the span is exported with a `parent_span_id`, downstream reconciliation is fighting the exporter's own serialization. The correct guardrail is a span processor that, before export, compares `resource.attributes["agent.id"]` against the `agent.id` recorded in the ambient parent span's resource, and either rewrites the parent to the dispatch-log value or drops the ambient edge and emits a `link` instead of a `parent`. ## Operational Effect With the guardrail in place, the observed effects were: - Misattributed spans dropped from 40–65% to 0% on the affected sub-agents, at the cost of ~3% of spans being emitted with `link` instead of `parent` (those where the dispatch log had no record — genuinely orphaned async work). - Per-sub-agent cost variance across replays of the same workload fell from 1.4–1.9x to <2%, restoring the ability to compare sub-agent efficiency. - The pipeline gained a new failure signal: a rising rate of `link`-instead-of-`parent` emissions indicates an orchestrator path that dispatches work outside the dispatch-log instrumented boundary — a real bug surfaced by the guardrail rather than hidden by it. The invariant to carry forward: **a span's parent edge must be justified by data that traveled with the work, not by context that happened to be ambient when the work finished.** Any pipeline that cannot state, for a given span, *which* mechanism justified its parent edge, is one thread-pool reuse away from silently inverting its cost attribution. ```python from dataclasses import dataclass from typing import Optional class SpanCorrelationCollapse(RuntimeError): """Raised when a span's ambient parent contradicts its resource identity.""" pass @dataclass class Span: span_id: str parent_span_id: Optional[str] agent_id: str # from resource attributes, stamped at creation ambient_parent_agent_id: Optional[str] # from execution context at emission dispatch_log_parent: Optional[str] # authoritative, from orchestrator log def resolve_parent(span: Span, require_dispatch_log: bool = True) -> Optional[str]: """ Decide the parent edge for a span before export. Invariant: the parent edge must be justified by data that traveled with the work (dispatch log), not by ambient context alone. """ ambient = span.ambient_parent_agent_id logged = span.dispatch_log_parent if ambient is not None and ambient != span.agent_id: # Ambient parent belongs to a different logical agent: the context # was re-bound by a reused worker / shared task. Do not trust it. if logged is None: if require_dispatch_log: raise SpanCorrelationCollapse( f"span {span.span_id} (agent={span.agent_id}) has ambient " f"parent agent={ambient} but no dispatch-log record; " f"refusing to emit a parent edge that would invert cost " f"attribution" ) # Degrade to a link, not a parent. return None return logged if logged is not None and logged != span.parent_span_id: # Dispatch log disagrees with the serialized parent: the exporter # already wrote the wrong edge. Rewrite before export. return logged return span.parent_span_id def emit(span: Span) -> Span: span.parent_span_id = resolve_parent(span) return span ```