# Why does an instance's span tree silently fork when OpenTelemetry GenAI semconv attributes are emitted from a resumed agent after a mid-task checkpoint **Date of Record:** 2026 November 27 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.*`) and persist execution state across process boundaries (checkpoint/resume, worker restart, cold-start replay). Does not cover single-process, never-interrupted agents, nor non-OTel tracing backends that ignore `trace_id`/`span_id` linkage. ## Core Distinction There is a difference between *recording* an agent's execution and *reconstructing* its causal trace. The GenAI semconv (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.system`) describes what happened in each span. It does **not** define how a resumed agent re-attaches its new spans to the parent context that existed before the checkpoint. That linkage lives entirely in the W3C Trace Context (`traceparent`/`tracestate`) carried in the span context — and that context is *not* part of the persisted agent state unless you explicitly serialize it. The boundary failure: when an agent checkpoints mid-task, the `trace_id` and the active `span_id` (the parent) are held in in-process OTel context, not in the durable checkpoint. On resume, a fresh process starts with no active context, the tracer mints a **new** `trace_id`, and every subsequent span — tool calls, token-accounting spans, the final `gen_ai.operation.name=invoke_agent` span — is parented under a new root. The trace tree forks. Both halves are individually well-formed and semconv-valid; the causal chain between them is severed. ## What Was Observed A multi-step tool-using agent (planner → 4 tool calls → synthesis) was checkpointed after tool call #2 during a worker drain. The checkpoint contained: message history, tool-call ledger, token counters, and a `resume_seq` integer. It did **not** contain the OTel `SpanContext`. On resume: - The pre-checkpoint trace (`trace_id=A`) held `invoke_agent` root, plan span, and tool spans #1–#2, with `gen_ai.usage.input_tokens` accumulated to that point. - The resumed process minted `trace_id=B`. Tool spans #3–#4, the synthesis span, and a *second* `invoke_agent` root span landed under `B`. - Token accounting double-counted: the resumed process re-emitted `gen_ai.usage.input_tokens` for the reconstructed prompt (history replay) while the pre-checkpoint span already recorded the original prompt tokens. Downstream cost dashboards summed `A.usage + B.usage` and reported ~1.7× actual consumption. - The synthesis span in trace `B` referenced tool outputs produced in trace `A` via `gen_ai.tool.call.id`, but no span link connected the two traces. A trace-based verifier that walks parent→child edges saw an orphaned synthesis with no producing tool calls and flagged the run as "hallucinated tool use." The failure is silent: no span is malformed, the OTel SDK raises nothing, and the collector exports both traces as valid. The corruption is purely in the *topology* and in the *aggregate token attribution*. ## Condition of Validity The fork is guaranteed to occur whenever all of the following hold: 1. The agent's durable checkpoint omits the serialized `SpanContext` (specifically `trace_id`, current `span_id`, `trace_flags`, and `tracestate`). 2. The resume path uses `tracer.start_span(...)` or `start_as_current_span(...)` without an explicit `context=` carrying the restored remote parent. 3. Token counters are reconstructed by replaying message history into a new request rather than carried forward as a delta, so `gen_ai.usage.*` is re-measured against the replayed prompt. It does *not* occur if the checkpoint stores the `traceparent` string and the resume path calls `trace.set_span_in_context(otel_context.attach(...))` or uses OTel's `Link` API (`links=[Link(restored_span_context)]`) to bridge the two traces. Note: a `Link` preserves reference but does **not** restore parent-child causality — a verifier walking parent edges still sees two roots. Only re-attaching the actual parent context (via `NonRecordingSpan` reconstructed from the stored `SpanContext` and passed as `context=`) keeps a single tree. ## Decision Boundary The invariant to enforce: **an agent's durable checkpoint must be a superset of its OTel active context at checkpoint time, or the resumed spans must be explicitly linked with a declared `resume_of` attribute and the token counters must be carried as a delta, not re-measured.** Choose between two bounded designs: - **Single-tree resume** (preferred when a verifier walks parent edges): serialize `SpanContext` into the checkpoint; on resume, reconstruct a `NonRecordingSpan` from it and pass as the parent `context=`. Do **not** re-emit `gen_ai.usage.*` for replayed history — carry the accumulated counters forward and emit only the *delta* for the new turn. This keeps `trace_id` stable and prevents double-counting. - **Linked-fork resume** (acceptable when a verifier understands `Link`): allow the new `trace_id`, but attach `links=[Link(pre_checkpoint_span_context)]` to the resumed root and set `gen_ai.agent.resume_of=`. Downstream token aggregation MUST dedupe on `(checkpoint_id, turn_index)` rather than summing raw `gen_ai.usage` spans. The boundary is crossed — and the failure is silent — the moment a resume path emits an `invoke_agent` span with neither a restored parent nor a `Link` to the checkpoint span. That is the exact condition a guard must reject before export. ## Operational Effect Downstream consumers of the trace — cost attribution, trace-based hallucination verifiers, latency SLOs computed per root span — all degrade without any error signal. Cost dashboards over-report by the replay factor. Verifiers that require every synthesis span to have a producing tool-call ancestor reject valid runs. Latency SLOs computed per `invoke_agent` root see two short roots instead of one long one and under-report tail latency. The instrumentation is "green" (all spans exported, all semconv attributes present) while the operational truth it is supposed to encode is wrong. The guardrail is to validate, at span-end for any `invoke_agent` span with `gen_ai.agent.resume_of` or a fresh root after a checkpoint, that either a restored parent `SpanContext` is present or a `Link` to the checkpoint span exists — and to fail the export (or quarantine the span) otherwise, so the fork surfaces as a hard error rather than as quietly wrong dashboards. ```python from dataclasses import dataclass, field from typing import Optional class TraceContextForkError(RuntimeError): """Raised when a resumed agent emits a root span with no bridge to its checkpoint span.""" pass @dataclass class SpanContext: trace_id: str span_id: str trace_flags: int = 1 @dataclass class Checkpoint: checkpoint_id: str resume_seq: int # The field whose absence causes the silent fork: span_context: Optional[SpanContext] = None accumulated_input_tokens: int = 0 accumulated_output_tokens: int = 0 @dataclass class EmittedSpan: name: str trace_id: str parent_span_id: Optional[str] links: list = field(default_factory=list) gen_ai_input_tokens: int = 0 gen_ai_output_tokens: int = 0 attributes: dict = field(default_factory=dict) def resume_agent_span(checkpoint: Checkpoint, new_trace_id: str, replayed_prompt_tokens: int) -> EmittedSpan: """ Emit the resumed invoke_agent span, enforcing the continuity invariant: either restore the parent SpanContext, or declare a Link to the checkpoint span. Also forbid re-measuring replayed prompt tokens into gen_ai.usage. """ has_parent = checkpoint.span_context is not None has_link = bool(checkpoint.span_context) and checkpoint.attributes_link_declared() if hasattr(checkpoint, "attributes_link_declared") else False span = EmittedSpan( name="invoke_agent", trace_id=new_trace_id, parent_span_id=checkpoint.span_context.span_id if has_parent else None, links=[checkpoint.span_context] if (not has_parent and checkpoint.span_context) else [], attributes={"gen_ai.agent.resume_of": checkpoint.checkpoint_id}, ) if not has_parent and not span.links: raise TraceContextForkError( f"resume of checkpoint {checkpoint.checkpoint_id!r} emitted a root span " f"with no restored parent SpanContext and no Link to the checkpoint span; " f"trace tree will silently fork (expected parent trace, got {new_trace_id})" ) # Token accounting: do NOT re-emit replayed prompt tokens as new usage. if replayed_prompt_tokens > 0: raise TraceContextForkError( f"resume re-measured {replayed_prompt_tokens} replayed prompt tokens into " f"gen_ai.usage.input_tokens; carry accumulated counters as a delta instead " f"(checkpoint already recorded {checkpoint.accumulated_input_tokens})" ) span.gen_ai_input_tokens = checkpoint.accumulated_input_tokens span.gen_ai_output_tokens = checkpoint.accumulated_output_tokens return span ```