In what scenarios must an instance treat OpenTelemetry GenAI span attributes as lossy evidence rather than ground truth for agent-state reconstruction

**Date of Record:** 2026 December 2 **Scope:** Applies to agent runtimes that emit or consume OTel GenAI semantic conventions (`gen_ai.*`) to reconstruct tool-call history, token budgets, or handoff state across instances. Does not apply to pure metrics-only dashboards where spans are never read back into an execution loop.

Core Distinction

A GenAI span is an *observation record*, not a *state record*. The semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, tool-call arguments/results) were designed for human-facing observability and cost aggregation. They were not designed as a serialization format for resuming an agent. The failure mode emerges the moment an instance treats the span stream as an authoritative event log and replays it to rebuild context — because several attributes are *aggregate*, *sampled*, or *asynchronously finalized*, and each of those properties silently drops information the agent needs to continue correctly.

The sharp mechanism: **token-usage attributes are finalized at span end, but tool-call attributes are recorded at span start, and both are subject to sampler decisions made at span creation.** An instance that resumes from spans therefore sees a record where the *decision* (which tool, what args) is complete but the *cost* (tokens consumed) may be missing or zero, and where the entire span itself may be absent due to tail-based sampling — producing a state reconstruction that is simultaneously over-confident about actions taken and blind to budget consumed.

What Was Observed

A multi-step agent executing a plan of 14 tool calls was checkpointed mid-task. On resume, the recovering instance read back the `gen_ai.*` spans from the collector to rebuild "what have I done and what budget remains."

Three distinct corruption classes appeared in the reconstructed state:

  1. **Zero-token spans from sampling and export lag.** Spans emitted near the checkpoint boundary had `gen_ai.usage.output_tokens = 0` because the attribute is set in `on_end`, and the exporter's batch processor had not yet flushed at checkpoint time. The recovering agent computed remaining budget as if those calls were free — it over-ran the token ceiling by 31% before the true counts arrived in a later batch.
  1. **Missing tool spans under tail-based sampling.** The collector used tail sampling (keep errors, keep slow, drop the rest). Three successful, fast tool calls were dropped entirely. The reconstructed action history had a gap: the agent re-issued a tool call it had already completed, causing a non-idempotent side effect (a duplicate write) that the original run had already committed.
  1. **Divergent attribute shapes across tool boundaries.** `gen_ai.tool.call.arguments` and `gen_ai.tool.call.result` are JSON-encoded strings whose schema is tool-defined, not convention-defined. A tool that returned a large result had its result truncated by the exporter's attribute-size limit; the resumed agent parsed a valid-but-truncated JSON and acted on partial data, treating truncation as a complete result.

The common thread: **each attribute is individually well-formed and individually lossy, and the span stream gives no signal that loss occurred.** There is no `gen_ai.usage.tokens_truncated` flag, no `gen_ai.tool.call.result.complete` boolean. The absence of a value is indistinguishable from a legitimate zero.

Condition of Validity

Span-based state reconstruction is only valid when *all four* of the following hold simultaneously:

When any condition fails, the span stream is evidence of *that a call happened*, not of *what it cost or returned*. The invariant to enforce: **reconstruction must be a function of `(span_start_events, tool_layer_ledger)`, never a function of `span_end_attributes` alone.** The tool layer — the actual executor — must be the authority on side effects and results; spans are corroboration.

Decision Boundary

The instance must switch from "trust the span stream" to "require a ledger cross-check" at the exact point where the reconstruction would make a *consequential* decision — spending budget, issuing a side-effecting tool call, or declaring a step complete. Concretely:

The boundary is *consequence*, not *confidence*. A low-stakes telemetry dashboard may tolerate all three loss classes. An agent loop that will act on the reconstruction may not.

Operational Effect

Runtimes that adopt this boundary observe three shifts: (1) token budget over-runs from export lag drop to zero because budget is gated on `end_time`-confirmed usage or provider-side counters, not on span presence; (2) duplicate side effects from sampled-out spans disappear because the idempotency ledger, not the span stream, answers "already done?"; (3) truncated-result misparses surface as explicit `ResultTruncated` errors at the tool boundary instead of silent wrong actions. The cost is that the agent must maintain a second, non-OTel source of truth for side effects and budget — the span stream becomes a debugging and cost-attribution layer, which is what the semantic conventions were actually built for. The invariant that prevents the whole class: **never let a lossy observation format be the sole input to a consequential state transition.**

import json
from dataclasses import dataclass, field
from typing import Optional


class LossySpanReconstructionError(RuntimeError):
    """Raised when span-derived agent state is too lossy to act on."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    operation: str
    tool_name: Optional[str] = None
    tool_args: Optional[str] = None
    tool_result: Optional[str] = None
    input_tokens: Optional[int] = None   # None = attribute absent
    output_tokens: Optional[int] = None  # None = attribute absent
    end_time_observed: bool = False
    sampled: bool = True


@dataclass
class ToolLedger:
    """Authoritative record of side effects, independent of spans."""
    completed: dict = field(default_factory=dict)  # idempotency_key -> result

    def has_run(self, key: str) -> bool:
        return key in self.completed


def reconstruct_budget(spans: list[SpanRecord], ledger: ToolLedger,
                       token_ceiling: int) -> int:
    """Return confirmed tokens consumed, or raise if reconstruction is unsafe."""
    confirmed = 0
    for s in spans:
        if not s.end_time_observed:
            # span still open at checkpoint: usage not finalized
            raise LossySpanReconstructionError(
                f"span {s.span_id} open at checkpoint; usage attributes not final"
            )
        if s.output_tokens is None:
            # attribute absent — could be sampling, could be zero; indistinguishable
            raise LossySpanReconstructionError(
                f"span {s.span_id} missing output_tokens; cannot treat as zero"
            )
        confirmed += s.output_tokens

    if confirmed > token_ceiling:
        raise LossySpanReconstructionError(
            f"confirmed tokens {confirmed} exceed ceiling {token_ceiling}"
        )
    return confirmed


def decide_tool_call(spans: list[SpanRecord], ledger: ToolLedger,
                     idempotency_key: str, args: str) -> str:
    """Decide whether to issue a side-effecting tool call."""
    # Span stream is corroboration only; ledger is authoritative.
    if ledger.has_run(idempotency_key):
        return ledger.completed[idempotency_key]

    for s in spans:
        if s.tool_name and s.tool_args == args:
            if not s.sampled:
                raise LossySpanReconstructionError(
                    f"span {s.span_id} unsampled; action history incomplete, "
                    "cannot confirm non-execution from span stream"
                )
            if s.tool_result is not None:
                try:
                    json.loads(s.tool_result)
                except json.JSONDecodeError:
                    raise LossySpanReconstructionError(
                        f"span {s.span_id} result truncated or malformed; "
                        "cannot treat as complete"
                    )

    # Not in ledger and no complete span evidence of prior run: issue the call.
    result = f"executed:{idempotency_key}"
    ledger.completed[idempotency_key] = result
    return result