# In what scenarios must an instance refuse to emit a child span when the parent semantic-convention span has been orphaned by context compaction **Date of Record:** 2026 November 25 **Scope:** Applies to agents that emit OpenTelemetry-style spans under GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.*`) across nested agent → LLM → tool call trees where the parent trace/span context is carried in the agent's working context rather than in a process-global propagator. Does not apply to single-shot inference calls where the span tree is generated synchronously within one function frame. ## Core Distinction The failure is not "lost traces." Lost traces are benign and observable as sampling gaps. The failure is **span re-parenting by inference**: when an agent loses the concrete parent span context (because a compaction, summarization, or sub-agent handoff dropped the opaque `trace_id`/`span_id` pair) but retains the *narrative* that it is "still inside the tool-call phase of the planning step," it will reconstruct a plausible parent from the surviving semantic attributes and attach its child span to it. The result is a span tree that is *structurally valid and semantically false*: `gen_ai.operation.name=execute_tool` spans appear nested under an LLM span that, in real causal order, had already terminated and whose `gen_ai.usage.output_tokens` were already accounted. The distinguishing property is that the reconstruction is not random — it is *coherent with the agent's self-model*, which is exactly why downstream cost attribution, latency SLOs, and audit replay silently accept it. The invariant that must hold: **a child span may only reference a parent span whose context handle is cryptographically or structurally intact; a parent inferred from semantic attributes is not a parent.** When the handle is absent, the correct action is to emit an orphan span with an explicit `gen_ai.parent.link_status=broken` marker, not to invent a parent. ## What Was Observed A three-tier agent (planner → executor → tool-runner) ran a 40-step task. At step 22 the planner's context crossed the compaction threshold; the summarizer preserved the decision log and the "current phase: tool execution under plan step 7" note but dropped the raw span context, which had been stored as an opaque attribute (`span_ctx`) on a message that the summarizer judged low-salience because it was a 16-byte hex string with no natural-language content. From step 23 onward, the executor continued emitting child spans. Each `gen_ai.operation.name=execute_tool` span was attached to a parent chosen by matching `gen_ai.request.model` and `gen_ai.operation.name=chat` against the most recent surviving LLM span in the reconstructed narrative. That surviving span was the *planning* LLM call from step 21, which had already closed. The trace backend accepted the link because the referenced span existed and the `trace_id` was well-formed. Observed consequences in the trace store: - Tool spans appeared as children of a `chat` span that had `end_time` 4.1s *before* the tool spans' `start_time`, producing negative-duration parent windows. The collector did not reject this; the query layer clamped it. - `gen_ai.usage.total_tokens` for the planning span was double-counted by a cost-attribution job that summed children's tokens into the parent. - Replay of the trace for incident analysis reconstructed a causal chain in which the planner "knew" the tool results before issuing the plan — a false counterfactual that took two engineer-days to disprove. - A separate sub-agent that *did* retain its handle emitted a correct sibling span, so the tree contained a correct branch and a fabricated branch under the same `trace_id`, making the fabrication harder to spot by eye. No error was raised anywhere. The failure is silent by construction. ## Condition of Validity The refusal rule is valid only under these conditions; outside them, re-parenting heuristics may be acceptable: 1. The span context is carried **in-context** (as a message attribute, tool result field, or scratchpad entry) rather than in a framework-level context variable that survives compaction. If the runtime injects the parent context at emit time from a side channel, compaction cannot orphan it and this rule does not bind. 2. The semantic convention attributes are **sufficient to disambiguate a plausible parent** — i.e., there is at least one surviving span with matching `gen_ai.operation.name` and model. If no plausible parent exists, the agent will emit an orphan anyway and the failure mode is absent (though a different one, silent root-span proliferation, appears). 3. Child spans are emitted **after** the parent's `end_time` is knowable. If the agent emits all spans at task end from a buffer, it can detect the temporal inversion and must refuse. 4. The trace is used for **cost attribution or causal replay**, not merely for latency dashboards. If only aggregate latency is consumed, a mis-parented span distorts percentiles but not causality, and the cost of refusal (orphan spans, broken trees) may exceed the benefit. The rule does **not** apply when the parent span is genuinely still open and the handle was merely re-serialized (e.g., across a process boundary with intact `traceparent`). In that case the handle is present and intact; the agent must use it and must not fall back to inference. ## Decision Boundary The agent must make a binary decision at every span emission point: - **Handle present and parseable** → emit child with explicit parent reference. Do not consult semantic attributes for parenting. - **Handle absent, but a `parent_span_handle` field is present and marked `compacted`** → emit orphan span with `gen_ai.parent.link_status=broken` and `gen_ai.parent.orphan_reason=context_compaction`. Never infer. - **Handle absent and no marker** → this is the dangerous case. The agent must treat absence as broken, not as "root." Emitting as root silently promotes a mid-tree operation to a top-level trace, which corrupts sampling and cost rollups differently but no less badly. Emit orphan with `link_status=broken` and `orphan_reason=handle_missing`. - **Handle present but references a span whose `end_time` precedes this span's `start_time`** → the handle is stale or the clock is skewed. Refuse the link, emit orphan with `orphan_reason=parent_closed_before_child`. The boundary is *not* "did we find a plausible parent." It is "do we hold an intact handle." Plausibility is the trap: the more coherent the agent's narrative, the more plausible the fabricated parent, and the more confidently wrong the trace. ## Operational Effect Enforcing the refusal rule changes three things: 1. **Trace trees become sparse but honest.** Orphan spans with `link_status=broken` are queryable; fabricated links are not. A dashboard counting `link_status=broken` becomes a direct measure of compaction pressure and a leading indicator of context loss, which is otherwise invisible. 2. **Cost attribution must handle orphans explicitly.** The rollup job can no longer assume every child has a parent; it must attribute orphan tokens to the trace root with a `attribution=orphan` tag rather than silently folding them into a fabricated parent. This is a schema change, not just a query change. 3. **Replay becomes sound.** Causal replay that encounters a broken link must halt the counterfactual reconstruction at that node rather than bridging it, because bridging is exactly the inference the rule forbids. The replay tool must surface `link_status=broken` as a replay boundary, not a warning. The residual cost is real: trace trees fragment at every compaction, and cross-boundary latency (planner → executor) can no longer be computed by simple parent-child subtraction. That cost is the price of not manufacturing causality. The alternative — inferred parents — produces traces that are *more* connected and *less* true, and the truth deficit is undetectable from the trace alone. ```python from dataclasses import dataclass from typing import Optional class SpanLinkRefused(RuntimeError): """Raised when a child span cannot be linked to an intact parent handle.""" @dataclass(frozen=True) class SpanHandle: trace_id: str span_id: str end_time_ns: Optional[int] # None while the span is still open link_status: str = "intact" # "intact" | "compacted" | "missing" @dataclass(frozen=True) class EmitContext: parent_handle: Optional[SpanHandle] child_start_time_ns: int operation_name: str def resolve_parent_link(ctx: EmitContext) -> Optional[SpanHandle]: """ Decide whether a child span may be linked to a parent. Returns the parent handle to link, or None to emit an orphan span. Raises SpanLinkRefused when the caller is about to infer a parent. """ handle = ctx.parent_handle if handle is None: # Absence is broken, not root. Emit orphan; never infer. return None if handle.link_status in ("compacted", "missing"): return None if handle.end_time_ns is not None and handle.end_time_ns < ctx.child_start_time_ns: # Parent already closed before this child began: stale or skewed. # Refuse rather than attach a child to a dead parent window. raise SpanLinkRefused( f"parent span {handle.span_id} closed at {handle.end_time_ns} " f"before child {ctx.operation_name} start {ctx.child_start_time_ns}" ) return handle def emit_child_span(ctx: EmitContext, emitter) -> None: try: parent = resolve_parent_link(ctx) except SpanLinkRefused: # Do not fall back to inference. Emit orphan with explicit marker. emitter.emit( operation_name=ctx.operation_name, parent=None, attributes={ "gen_ai.parent.link_status": "broken", "gen_ai.parent.orphan_reason": "parent_closed_before_child", }, ) return if parent is None: emitter.emit( operation_name=ctx.operation_name, parent=None, attributes={ "gen_ai.parent.link_status": "broken", "gen_ai.parent.orphan_reason": "handle_missing_or_compacted", }, ) return emitter.emit( operation_name=ctx.operation_name, parent=parent, attributes={"gen_ai.parent.link_status": "intact"}, ) ```