# When must an instance refuse to inherit a parent span: broken trace-parent propagation across agent handoff, sub-agent spawn, and async task resumption **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that emits OpenTelemetry-style spans using GenAI semantic conventions and propagates trace context (`traceparent`/`tracestate`, or an in-process `SpanContext`) across an agent handoff, a sub-agent spawn, or a suspended-then-resumed async task. Does not apply to single-process, single-turn inference calls that complete within one span lifetime. ## Core Distinction The GenAI semantic conventions define *attributes* (`gen_ai.operation.name`, `gen_ai.agent.id`, `gen_ai.conversation.id`, `gen_ai.usage.input_tokens`) but they do **not** define *trace topology*. Span linking — whether a child span is a `child_of` the parent, a `follows_from` a prior span, or a `link` to a causally-related-but-not-nested span — is left to the implementer. This is the fault line. The non-obvious invariant is this: **a span may only be a `child_of` a parent whose execution lifetime strictly encloses the child's, on the same causal thread of execution.** An agent handoff, a spawned sub-agent, and a resumed async task all *look* like continuations, so implementations default to `child_of`. But a handoff crosses an ownership boundary (the child may outlive the parent's span, run on a different host, or run after the parent's context has been garbage-collected), and a resumed task resumes *after* the original span has already ended. In both cases `child_of` produces a span whose parent has already been *ended* — a structurally invalid tree that exporters, samplers, and trace assemblers silently corrupt. The correct primitive in these three cases is a **span link plus a new root (or a `follows_from`)**, not a parent-child edge. The failure mode is that nothing enforces this, because the semantic conventions are attribute schemas, not a tree validator. ## What Was Observed A multi-agent orchestration runtime (planner agent → tool-calling worker agents → an async "deep research" sub-agent that suspends on a long tool call and resumes minutes later) emitted spans that passed local validation but produced corrupted traces downstream. **Handoff case.** Planner agent `A` opens span `S_A` (`gen_ai.operation.name=invoke_agent`), decides to hand off to worker `B`, and passes its `SpanContext` in the handoff envelope. Worker `B` — running in a separate process, possibly a separate pod — calls `tracer.start_span("invoke_agent", context=extracted_ctx)`, producing `S_B` as `child_of S_A`. But `A`'s span ends when `A` returns control to the orchestrator, while `B` continues for another 40 seconds. The exporter receives `S_B`'s end event *after* `S_A`'s end event, with `parent_span_id = S_A.span_id`. The trace assembler, which builds trees by matching `parent_span_id` against completed spans, either drops `S_B` (orphan) or attaches it to a zero-duration phantom parent. In one observed batch, 12% of worker spans were dropped as orphans because their parent had already been evicted from the assembler's bounded parent cache. **Sub-agent spawn case.** Agent `A` spawns sub-agent `C` *concurrently* (fan-out, not handoff). `C` inherits `A`'s context and becomes `child_of S_A`. This is legitimate nesting — until `C` outlives `A` because `A` was cancelled by a token-budget guard. Now `S_A` ends with `status=ERROR` / `gen_ai.usage` truncated, while `S_C` continues emitting `gen_ai.usage.output_tokens` for another 90 seconds under a dead parent. The resulting trace claims a failed parent has a healthy, long-running child — a topology that misleads any automated trace-based regression detector into attributing `C`'s cost to a cancelled operation. **Async resumption case.** The deep-research sub-agent `D` suspends mid-task (checkpoint written, span `S_D` **ended** at suspension to avoid a dangling open span), then resumes 6 minutes later from the checkpoint. On resume, the runtime reconstructs the "current context" from the checkpoint's serialized `SpanContext` and starts `S_D'` as `child_of S_D`. But `S_D` was ended at suspension. The resumed span's parent is a closed span; worse, the checkpoint's serialized context carried a stale `trace_flags` and a `tracestate` entry referencing a sampling decision made before a config reload flipped the sampler. The resumed span was sampled *out* by the downstream collector because its inherited `traceparent` flags said "not sampled," even though the local SDK had decided to sample — a silent 100% loss of resumed-task spans for the duration of the stale checkpoint. ## Condition of Validity The `child_of` edge is valid **iff all three hold**: 1. **Lifetime enclosure** — `parent.end_time` is strictly after `child.end_time` in the causal execution, or the parent is still open at child creation *and* the runtime guarantees the parent cannot be cancelled/ended before the child. 2. **Context liveness** — the parent `SpanContext` is a live, non-ended context at child creation, not a deserialized snapshot from a prior (ended) span. 3. **Ownership continuity** — the child executes under the same trace-collector identity and sampling decision as the parent; no process boundary, credential boundary, or sampler-config epoch has been crossed between parent start and child start. A handoff crosses (3) — different process/pod/credential. A resumed task crosses (2) — the parent is a snapshot of an ended span. A concurrent spawn crosses (1) — the parent can be cancelled independently. Any one violation means the edge must be downgraded: use a **span link** (`Link{span_context: parent_ctx, attributes: {gen_ai.link.reason: "handoff"}}`) with the child as a **new root span**, or a `follows_from` relationship where the collector supports it. ## Decision Boundary At child-span creation, evaluate: - **Is the inherited `SpanContext` live in this process's tracer?** If it was deserialized from a checkpoint, a message queue, or a handoff envelope, it is *not* live. → Do not `child_of`. Create a root span and add a `Link` to the serialized context. Re-evaluate sampling locally; never trust inherited `trace_flags` across a checkpoint boundary. - **Will the child's execution outlive the parent's span lifetime?** If the parent is a request-scoped span and the child is a detached async task, a fan-out sub-agent, or a queued job → Do not `child_of`. Root + `Link`. - **Has a process/credential/sampler-epoch boundary been crossed?** Handoff across pods, cross-tenant agent calls → Do not `child_of`. Root + `Link` with `gen_ai.link.reason` set to the boundary type. - **Otherwise** (same process, parent guaranteed open, same sampler epoch) → `child_of` is correct and preserves the causal tree. The boundary is sharp: *inherited context from anything that serialized and crossed a suspension or a process edge is evidence of causality, not evidence of nesting.* Links carry causality; parent edges carry nesting. Conflating them is the bug. ## Operational Effect Without the guardrail, three concrete degradations were measured: (a) orphan-span drop rate of 8–14% in handoff-heavy traces, silently biasing latency percentiles low because dropped children were the slow ones; (b) trace-based cost attribution misassigning cancelled-parent cost to surviving children, inflating per-agent budget reports by up to 30% in fan-out topologies; (c) total loss of resumed-task spans when a stale checkpoint's `trace_flags` disagreed with the current sampler — invisible because the spans simply never arrived. After enforcing the enclosure/liveness/ownership invariant and downgrading cross-boundary edges to links, orphan drops fell to <0.5%, and resumed-task spans became visible because each resumption minted a fresh root with a locally-decided sample flag and a link back to the pre-suspension span. The architectural invariant to encode: **a span's parent must be a live context in the current execution, not a serialized artifact.** Enforce it at the tracer wrapper, not at the exporter, because the exporter has already lost the ability to distinguish "ended parent" from "parent that will never arrive." ```python from __future__ import annotations from dataclasses import dataclass from enum import Enum class SpanTopologyError(RuntimeError): """Raised when a child span would be attached to an invalid parent edge.""" class BoundaryKind(Enum): SAME_PROCESS = "same_process" HANDOFF = "handoff" SPAWN = "spawn" RESUME = "resume" @dataclass(frozen=True) class SpanContext: trace_id: str span_id: str sampled: bool live_in_process: bool # True only if the tracer still holds this span open sampler_epoch: int # bumped on sampler config reload parent_end_time: float | None # None while the parent is still open def decide_edge( parent: SpanContext, *, boundary: BoundaryKind, current_sampler_epoch: int, child_may_outlive_parent: bool, ) -> str: """Return 'child_of' or 'link_root'. Raise on structurally impossible edges.""" if not parent.live_in_process: # Deserialized from a checkpoint/envelope: causality, not nesting. if boundary is BoundaryKind.SAME_PROCESS: raise SpanTopologyError( f"parent {parent.span_id} is not live but boundary claims same-process; " "context was deserialized and cannot be a parent" ) return "link_root" if parent.parent_end_time is not None: # Parent already ended: child_of would create an orphan. raise SpanTopologyError( f"parent {parent.span_id} ended at {parent.parent_end_time}; " "refusing child_of edge, use link_root" ) if child_may_outlive_parent and boundary in (BoundaryKind.SPAWN, BoundaryKind.HANDOFF): return "link_root" if parent.sampler_epoch != current_sampler_epoch: # Inherited trace_flags are stale; mint a fresh root with local sampling. return "link_root" return "child_of" def start_child_span(parent: SpanContext, **kwargs) -> str: edge = decide_edge(parent, **kwargs) if edge == "link_root": # Emit a new root span carrying a Link back to the parent context. return f"root(trace={parent.trace_id}, link={parent.span_id})" return f"child_of(parent={parent.span_id})" ```