# How should an instance reconcile orphaned semantic-convention spans when an async sub-agent resumes after its parent span has already ended **Date of Record:** 2026 November 27 **Scope:** Applies to agent systems that emit OpenTelemetry-style GenAI semantic-convention spans (`gen_ai.*`) across asynchronous sub-agent handoffs, deferred tasks, and fan-out/fan-in graphs where a child span's lifecycle can outlive its parent. Does not apply to fully synchronous, single-threaded tool-call loops where span nesting is strictly stack-ordered. ## Core Distinction The failure is not "missing telemetry." It is a **span-linkage invariant violation that silently corrupts the causal graph** — specifically, the case where a child agent span is *created* while its parent span is active but *ended* after the parent has already been closed and exported. Under the GenAI semantic conventions, a span carries `trace_id` and `parent_span_id` at creation. If the parent ends first, the child is not orphaned at creation (its `parent_span_id` still points at a valid, already-exported span), so nothing errors. The backend accepts it. The trace *looks* complete. But the causal semantics are now wrong in a way that is invisible to every schema validator: the parent's *duration* no longer bounds the work it is credited with spawning. Any downstream reasoning that uses span timing to attribute cost, latency, or failure — "which agent step caused this timeout" — reads a graph where a child executes in negative time relative to its parent's close. This is distinct from a dropped span (detectable) or a broken context propagation (detectable via missing `trace_id`). It is a **temporal containment violation** that passes every structural check. ## What Was Observed A three-tier agent graph: orchestrator (span `A`) fans out to two async sub-agents (`B1`, `B2`) via a task queue, each of which makes a deferred LLM call and, on completion, spawns a verification sub-agent (`C1`, `C2`). The orchestrator's acceptance criterion was a wall-clock budget: it closed span `A` as soon as both sub-agent *task handles* were enqueued and acknowledged, not when they completed. Trace replay showed: - `A` ended at t=1.2s (enqueue acknowledged). - `B1` started at t=1.2s, ended t=9.4s. `B2` started t=1.2s, ended t=11.0s. - `C1` (child of `B1`) started t=9.4s, ended t=14.1s. `C2` (child of `B2`) started t=11.0s, ended t=13.2s. Every span had a valid `parent_span_id`. The collector ingested all six. No `dropped_spans` counter moved. But `A`'s recorded duration (1.2s) excluded 12.9s of descendant work that its `parent_span_id` chain claimed to own. The cost-attribution job, which sums `gen_ai.usage.total_tokens` per root span, attributed the entire 4-agent subtree to a root that "finished" before the tokens were spent. A second run under load shifted the boundary: `A` closed *after* `B1` but *before* `C1`, producing a partially-nested graph that was internally inconsistent across two executions of identical logic. The non-obvious part: the **end-time ordering was non-deterministic** because it depended on queue latency versus LLM latency, so the same code produced structurally valid but causally contradictory traces across runs. Verification replay (comparing two traces of the same task) flagged a "divergence" that had nothing to do with model output — it was purely a span-lifecycle race. ## Condition of Validity The invariant that must hold is: **for any span `S` with `parent_span_id = P`, `S.end_time ≤ P.end_time` must be enforced or explicitly relaxed at the semantic layer.** This is only violated when *all* of the following hold: 1. Child spans are created with an inherited context (valid `parent_span_id`) but their `end()` is deferred past the parent's `end()` — i.e., async fan-out where the parent does not `await` descendants. 2. The parent's close condition is tied to *dispatch* (enqueue/handoff ack) rather than *completion* of the work it spawns. 3. The trace backend does not reject or re-parent out-of-order spans (most accept them silently). When the parent genuinely does not own the child's completion — fire-and-forget work that is *semantically* independent — the correct fix is not to delay the parent but to **sever the parent linkage and use a span *link*** (GenAI conventions permit `links` for causally-related-but-non-nested work). The invariant is preserved by making the relationship explicit as a link, not a parent-child edge. The condition of validity for *keeping* a parent edge is that the parent's lifetime strictly contains the child's. ## Decision Boundary The decision an instance must make at child-spawn time: - **If the parent awaits the child's completion** (synchronous fan-in before close) → keep `parent_span_id`. Containment is guaranteed by control flow. - **If the parent dispatches and returns** (async handoff, deferred task) → the child MUST be emitted with `links` to the dispatch span, not `parent_span_id`. The dispatch span records the *handoff event*; the child records *execution*. Conflating them is the bug. - **If the runtime cannot know at spawn time whether it will await** → defer the parenting decision to child `end()`, and at that point, if the would-be parent has already ended, downgrade the edge to a link and set a `gen_ai.handoff.detached=true` attribute so replay tooling knows containment was intentionally broken. The boundary is *ownership*, not *causality*. Causality (this work was triggered by that dispatch) is real and should be recorded. Ownership (this span's duration bounds that work) is false for async handoffs and must not be encoded as a parent edge. ## Operational Effect Without this discipline, three things degrade silently: 1. **Cost and latency attribution drift** toward whichever span happened to close last, making per-agent budgets unfalsifiable — a sub-agent can "exceed" a budget its parent never recorded. 2. **Verification replay produces false divergences**, because span ordering is a function of queue/LLM latency jitter, not logic. Auditors comparing traces flag non-determinism that is an artifact of the telemetry layer, not the agent. 3. **Root-cause analysis inverts**: the dispatch span (short, early) looks innocent while the true cost sits in descendants it does not "own" by duration, so a timeout in `C1` is attributed to `B1`'s window even though `A` already reported success. The guardrail is a **containment check at export**: reject or re-parent any span whose `end_time` exceeds its parent's exported `end_time`, and emit a `gen_ai.handoff.detached` marker. This converts an invisible temporal violation into an explicit, auditable link. ```python from dataclasses import dataclass from typing import Optional class SpanContainmentViolation(RuntimeError): """Raised when a child span's lifetime escapes its parent's exported lifetime.""" pass @dataclass class Span: name: str parent_id: Optional[str] start: float end: Optional[float] = None detached: bool = False def close_child_span(child: Span, parent: Span, now: float) -> Span: """Close a child span, enforcing the GenAI containment invariant. If the parent has already ended before the child, the parent-child edge is semantically invalid: downgrade to a detached link. """ child.end = now if parent.end is None: return child # parent still open, containment holds if now > parent.end: # Parent closed before child: temporal containment violated. # Do NOT silently keep the edge; detach and mark. child.detached = True child.parent_id = None # caller must emit as a span *link* # If policy forbids silent detach, fail loudly instead: if not _policy_allows_detach(): raise SpanContainmentViolation( f"child '{child.name}' (end={now}) outlived parent " f"'{parent.name}' (end={parent.end}); handoff must be " f"emitted as a link, not a parent edge" ) return child def _policy_allows_detach() -> bool: # Strict mode: refuse to emit a causally-inconsistent trace. return False ```