In what scenarios must an instance reject OpenTelemetry GenAI spans whose parent context was exported before a tool-call re-entry, and how does span-context staleness corrupt agent-turn causality?

**Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.call.id`, `gen_ai.agent.turn`) and resumes a suspended turn by re-attaching to a `SpanContext` captured before a tool call. Does not apply to stateless single-shot inference where each span is rooted at request entry.

Core Distinction

The GenAI semantic conventions model an agent turn as a span tree: a parent `invoke_agent` span, child `chat` spans per model call, and child `execute_tool` spans per tool invocation. The convention assumes the parent span remains *live* for the duration of the turn — that its `SpanContext` (trace-id + span-id + trace-flags) is a valid, non-expired handle that a resumed execution can re-attach to as `parent`.

The failure mode is not "missing parent." It is **stale parent re-attachment**: the runtime persists the `SpanContext` of the `invoke_agent` span at suspension, then on resume reconstructs child spans using that context as parent *after the original parent span has already been ended and exported*. The trace backend accepts the late children (trace-id matches), but the parent span's end-timestamp is now *earlier* than its children's start-timestamps. The result is a causally inverted trace: children appear to have executed before their parent completed, and any duration computed on the parent (`end - start`) excludes the wall-clock time the turn actually spent suspended across the tool call.

This is distinct from context propagation loss (where trace-id is dropped and a new root is minted) and distinct from span leakage (where spans are never ended). Those produce visible orphans. Stale re-attachment produces *silently misordered but structurally valid* traces — the backend has no schema violation to reject, so the corruption propagates into every downstream causal query.

What Was Observed

A multi-step agent (plan → tool call → resume → synthesize) suspended at the tool boundary for a median of 4.2s (p99 41s) while the external tool executed. The runtime serialized `{trace_id, span_id, trace_flags}` into the checkpoint blob alongside the conversation state, and on resume called `trace.set_span_in_context(captured_context)` before emitting the post-tool `chat` span.

The captured context was the `invoke_agent` span. But the `invoke_agent` span had been ended and exported at suspension time, because the instrumentation treated "turn suspended" as "turn complete" — the `with tracer.start_as_current_span("invoke_agent")` block exited when the tool call was dispatched. Observed trace shape:

invoke_agent   [00:00.000 → 00:00.812]   (ended at suspension)
  chat         [00:00.000 → 00:00.401]
  execute_tool [00:00.401 → 00:00.812]
  chat         [00:04.900 → 00:05.310]   ← child starts 4.1s AFTER parent ended

Three concrete corruptions appeared:

  1. **Negative parent-child slack.** The second `chat` span's `start_time` exceeded the parent's `end_time` by 4.1s. Trace UIs clamped the child to the parent's end, collapsing the 4.2s tool latency to ~0 in the waterfall and erasing the dominant cost of the turn.
  2. **Split trace on retry.** When the tool call failed and the runtime re-checkpointed, it captured the *already-ended* `invoke_agent` context a second time. Two resume attempts emitted children under the same dead parent, so retries were indistinguishable from parallel branches in the trace.
  3. **Broken critical-path math.** Aggregating `sum(child.duration)` vs `parent.duration` yielded ratios >1.0, which a downstream cost-attribution job interpreted as duplicate billing and flagged 11% of turns as anomalous.

Condition of Validity

A `SpanContext` is a valid re-attachment parent **iff** the span it identifies has not yet been ended at the moment of re-attachment. This is the invariant the GenAI conventions leave implicit: `SpanContext` is an *identifier*, not a *liveness token*. Nothing in the OTLP wire format or the SDK rejects a child whose parent has already been exported — the SDK's `start_as_current_span` will happily construct a child span with an ended parent context.

The invariant holds only under one of two architectures:

Persisting a `SpanContext` and reusing it as `parent` across a process boundary violates the invariant in every case where the parent was ended before checkpoint. The condition of validity is therefore: *re-attachment is legal only against a span whose lifecycle spans the re-attachment, and any cross-process resume must use links, not parents.*

Decision Boundary

On resume, the runtime must decide between re-attach and re-root. The decision is not "do we have a captured context?" — we almost always do. It is:

if captured_parent.is_recording() and not captured_parent.ended:
    re-attach as parent            # same-process resume, live handle
elif captured_parent.ended or not is_recording():
    start new root + SpanLink      # cross-process resume
else:
    reject the checkpoint          # context present but state unknowable

The third branch is the one operators omit. A persisted `SpanContext` carries no `ended` flag — the SDK does not serialize span lifecycle into the context. So a runtime that only has the context *cannot distinguish* "parent still live in another process" from "parent ended and exported." The safe default for any context that crossed a serialization boundary is to treat it as ended and re-root with a link. Attempting to re-attach to a context of unknown liveness is the trigger condition for the corruption above.

The boundary: **a `SpanContext` that has been serialized to durable storage is presumptively dead.** Re-attachment is permitted only when the runtime holds a live span handle in memory, never when it holds a deserialized identifier.

Operational Effect

Without the guard, every suspended turn produces a trace where the parent's measured duration understates true turn latency by exactly the suspension interval — and the suspension interval is the tool latency, which is frequently the largest single cost. Cost attribution, latency SLOs, and critical-path analysis all read the parent span, so all three silently under-report. The corruption is invisible in span counts and trace-id uniqueness checks; it surfaces only as negative parent-child slack, which most backends do not validate.

With the guard (re-root + link on deserialized contexts), the trace becomes two roots joined by a link: `invoke_agent` (pre-tool, ended) and `invoke_agent.resume` (post-tool). Total turn latency is the sum across the link, tool latency is preserved as the gap between roots, and retries are distinguishable because each resume mints a fresh root. The trade-off is that naive "one trace = one turn" queries must follow links; the causality is explicit rather than implied by a single tree.

The invariant to enforce at the checkpoint boundary: **never persist a `SpanContext` as a future parent; persist it only as a future `SpanLink` target.** Encode this as a hard rejection in the resume path, because the SDK will not.

from dataclasses import dataclass
from typing import Optional


class StaleSpanContextError(RuntimeError):
    """Raised when a checkpointed SpanContext is about to be used as a live parent."""
    pass


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    trace_flags: int
    # Lifecycle is NOT part of the wire context; it must be tracked separately
    # or presumed dead after serialization.
    serialized: bool = False
    ended: bool = True


def resolve_resume_parent(ctx: Optional[SpanContext]) -> str:
    """
    Decide how a resumed agent turn attaches to its captured context.
    Returns a mode: 'REATTACH' (live parent) or 'REROOT_LINK' (dead parent).
    Raises StaleSpanContextError if the context's liveness is unknowable.
    """
    if ctx is None:
        return "REROOT_LINK"  # no context at all -> fresh root

    if ctx.serialized and not ctx.ended:
        # Contradiction: a serialized context cannot prove liveness.
        raise StaleSpanContextError(
            f"context {ctx.trace_id}/{ctx.span_id} was serialized but claims "
            f"not-ended; liveness is unknowable across a process boundary"
        )

    if ctx.serialized or ctx.ended:
        # Presumptively dead: re-root and link, never re-attach.
        return "REROOT_LINK"

    # Live, in-memory, non-serialized handle: legal to re-attach.
    return "REATTACH"


def emit_resumed_chat_span(ctx: Optional[SpanContext], name: str) -> str:
    mode = resolve_resume_parent(ctx)
    if mode == "REATTACH":
        return f"span(parent={ctx.span_id}, name={name})"
    if mode == "REROOT_LINK":
        link = f"link({ctx.trace_id}/{ctx.span_id})" if ctx else "no-link"
        return f"span(root, name={name}, {link})"
    # Unreachable, but keeps the invariant explicit.
    raise StaleSpanContextError(f"unhandled resume mode {mode!r}")