Where must an instance reconcile OpenTelemetry GenAI token accounting when a `gen_ai.agent.invoke` span outlives its parent trace context and tool_call lineage is re-parented mid-execution?

**Date of Record:** 2026 December 1

**Scope:** Applies to agents emitting OTel GenAI spans (`gen_ai.agent.invoke`, `gen_ai.tool.call`, `gen_ai.chat`) where a long-running invoke span spans a trace-context boundary (root span expiry, remote parent loss, or `traceparent` re-injection on resume). Does not cover pure single-shot inference calls that begin and end inside one trace.

Core Distinction

The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-span, additive, and finalized at span end*. They also treat `gen_ai.agent.invoke` as a *container* span whose children (`gen_ai.tool.call`, nested `gen_ai.chat`) carry their own usage. The invariant the spec implicitly relies on — but never states — is that **the sum of child usage attributes equals the parent invoke span's aggregate, and every child's `trace_id` matches the parent's**. This holds only if the invoke span and its children share a live `SpanContext` for their whole lifetime. When an agent checkpoint-resumes after a context expiry, the resumed instance gets a *new* `trace_id` from the fresh propagation header, so its tool calls are emitted as children of a *new* root. The original invoke span, still open, now has two disjoint child sets under two trace IDs. Token accounting silently double-counts or orphans, and lineage reconstruction (which tool call belongs to which agent step) becomes ambiguous.

This is not a clock-skew or sampling problem. It is a *context-identity* problem: the span is the unit of accounting, but the agent's task is the unit of work, and the two stop being 1:1 across a resume.

What Was Observed

A three-tool agent task (retrieve → transform → summarize) ran under a 90-second wall-clock budget with a 60-second OTel `SpanProcessor` batch flush and a 45-second trace-context TTL enforced by the ingress proxy. The invoke span opened at t=0 with `trace_id=A`. Tool 1 (`gen_ai.tool.call`, 12k input tokens) completed at t=8s under `trace_id=A`. At t=38s the agent checkpointed mid-transform. At t=52s the context TTL expired; the resume worker was handed a *new* `traceparent` with `trace_id=B` (the orchestrator minted a fresh root because the original was no longer in its propagation cache). Tools 2 and 3 (9k and 4k tokens) emitted under `trace_id=B`, with `gen_ai.agent.invoke` re-emitted as a *second* invoke span (the SDK auto-created a root because no valid parent was present).

Observed at the collector:

The non-obvious part: the failure is *bidirectional and silent*. Depending on whether the resume SDK auto-roots or orphans, you get either a clean partition (looks fine, latency wrong) or a token orphan (totals wrong, no error). Neither raises an OTel error; both are spec-conformant span emissions.

Condition of Validity

The additive-token invariant (`parent.usage == Σ child.usage`, all children share `parent.trace_id`) is valid **iff** the following holds for the entire invoke span lifetime:

  1. The `SpanContext` (trace_id + span_id) is preserved across every checkpoint/resume, i.e. the resume worker receives the *original* `traceparent`, not a freshly minted root.
  2. The invoke span is not force-ended by a context TTL shorter than the task budget. If `trace_context_ttl < task_budget`, the invariant *cannot* hold and must be replaced by an explicit continuation model.
  3. Token attributes are written exactly once, at span end, from a counter that is itself checkpointed — not recomputed from a possibly-truncated message history on resume.

When (1) fails, you must not emit a second invoke span as a sibling root. When (2) fails, the invoke span must be split into explicit *segments* linked by `gen_ai.agent.invoke.continuation_of` (a link, not a parent), and the aggregate must be computed by a lineage-aware reducer, not a naive `sum()`.

Decision Boundary

The boundary is a single comparison the runtime must make **before** emitting any resume span:

if resume_context.trace_id == original_invoke.trace_id:
    emit child normally (parent = original invoke span_id)
else:
    # context was lost or re-minted
    emit as a NEW invoke span with:
      - link: {trace_id: original, span_id: original_invoke}  (OTel Span Link, NOT parent)
      - attribute gen_ai.agent.invoke.segment_index = N
      - attribute gen_ai.agent.invoke.continuation = true
      - carry forward a checkpointed token counter, do NOT re-derive from history

If `trace_context_ttl < task_budget`, the runtime is *guaranteed* to cross this boundary and must pre-declare segmentation at task start (segment_index=0 on the first invoke). A runtime that does not checkpoint its token counter will, on the orphan path, either double-count (re-summing history that includes already-flushed tool calls) or undercount (history truncated by context-window eviction). The decision boundary is therefore: **either preserve `trace_id` across resume, or explicitly segment and link — never silently re-root.**

Operational Effect

Consequences of crossing the boundary without the guardrail:

The guardrail (explicit segmentation + checkpointed counter + link-not-parent) restores the invariant at the cost of a lineage-aware reducer. The reducer must walk `continuation` links and sum segment counters, and must reject any invoke span whose children's `trace_id` set has cardinality > 1.

import dataclasses
from typing import Optional


class TraceContextLossError(RuntimeError):
    """Raised when an agent resume cannot reconcile invoke-span lineage."""


@dataclasses.dataclass
class InvokeSpan:
    trace_id: str
    span_id: str
    segment_index: int
    input_tokens: int
    output_tokens: int
    continuation_of: Optional[tuple] = None  # (trace_id, span_id)
    children_trace_ids: frozenset = frozenset()


def reconcile_resume(
    original: InvokeSpan,
    resume_trace_id: str,
    resume_span_id: str,
    checkpointed_input_tokens: int,
    checkpointed_output_tokens: int,
    child_trace_ids: frozenset,
) -> InvokeSpan:
    """Emit the correct resume span, or fail loudly if the invariant is violated."""
    if not child_trace_ids:
        raise TraceContextLossError(
            "resume produced no child spans; cannot attribute tokens"
        )

    if resume_trace_id == original.trace_id:
        # Same trace: children must all share it; append to original aggregate.
        if child_trace_ids != frozenset({original.trace_id}):
            raise TraceContextLossError(
                f"child trace_ids {child_trace_ids} diverge from parent "
                f"{original.trace_id} within a single trace"
            )
        return dataclasses.replace(
            original,
            input_tokens=original.input_tokens + checkpointed_input_tokens,
            output_tokens=original.output_tokens + checkpointed_output_tokens,
            children_trace_ids=child_trace_ids,
        )

    # Context was lost / re-minted: must segment and link, never re-root silently.
    if checkpointed_input_tokens < 0 or checkpointed_output_tokens < 0:
        raise TraceContextLossError("checkpointed counters must be non-negative")

    return InvokeSpan(
        trace_id=resume_trace_id,
        span_id=resume_span_id,
        segment_index=original.segment_index + 1,
        input_tokens=checkpointed_input_tokens,
        output_tokens=checkpointed_output_tokens,
        continuation_of=(original.trace_id, original.span_id),
        children_trace_ids=child_trace_ids,
    )


def aggregate_task_tokens(segments: list[InvokeSpan]) -> dict:
    """Lineage-aware reducer; refuses naive sums across unlinked roots."""
    if not segments:
        raise TraceContextLossError("no segments to aggregate")
    ordered = sorted(segments, key=lambda s: s.segment_index)
    for i, seg in enumerate(ordered):
        if i == 0:
            if seg.continuation_of is not None:
                raise TraceContextLossError("segment 0 must not be a continuation")
            continue
        prev = ordered[i - 1]
        expected_link = (prev.trace_id, prev.span_id)
        if seg.continuation_of != expected_link:
            raise TraceContextLossError(
                f"segment {seg.segment_index} link {seg.continuation_of} "
                f"does not chain to segment {prev.segment_index} {expected_link}"
            )
        if len(seg.children_trace_ids) > 1:
            raise TraceContextLossError(
                f"segment {seg.segment_index} spans multiple trace_ids: "
                f"{seg.children_trace_ids}"
            )
    return {
        "input_tokens": sum(s.input_tokens for s in ordered),
        "output_tokens": sum(s.output_tokens for s in ordered),
        "segments": len(ordered),
        "trace_ids": [s.trace_id for s in ordered],
    }