In what scenarios must an instance reconcile OpenTelemetry GenAI span attributes against tool-call event payloads before trusting a resumed agent's token budget

**Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that emits OTel GenAI semantic-convention spans (`gen_ai.*` attributes) plus discrete tool-call events, and that reconstructs budget/state from that telemetry after a checkpoint-resume, handoff, or cross-instance replay. Does not apply to runtimes that treat telemetry as write-only observability with no control-plane read-back.

Core Distinction

Telemetry is conventionally modeled as a passive side-channel: it describes what happened. In agent systems it is frequently *promoted* to a control-plane input — a resumed instance reads its own prior spans to reconstruct "how many tokens have I spent, which tools did I call, what is my remaining budget." The moment spans become a state-reconstruction source, a structural mismatch becomes a correctness bug rather than a dashboard annoyance.

The mismatch is this: the GenAI semantic conventions place **usage accounting on the span** (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) but place **tool invocation detail on child events/spans** (`gen_ai.tool.name`, `gen_ai.tool.call.id`, and the request/response payloads). These two layers are emitted by different code paths, at different times, with different failure and flush semantics. A span's usage attributes are finalized *at span end*; a tool-call event is emitted *at tool invocation*. When a process dies between "tool invoked" and "parent span ended," the two layers desynchronize, and reconciliation is not optional — it is the only thing standing between a resumed agent and a silently wrong budget.

What Was Observed

A multi-step agent (planner → tool-caller → summarizer) ran under a per-task token budget enforced by reading back its own spans. Each LLM turn produced one `gen_ai.*` span; each tool call produced a child event carrying `gen_ai.tool.name` and `gen_ai.tool.call.id`, with the tool's result attached. The runtime checkpointed after every tool event.

Failure trace on a hard kill mid-task:

  1. Turn N's LLM span started. The model emitted a tool-call request. A child tool event was written and flushed with `gen_ai.tool.name = "search"` and a call id.
  2. The tool executed and returned a large result. The result was appended to the event *in memory* but the event was batched, not yet flushed.
  3. The process was killed before the parent LLM span ended. The parent span never wrote `gen_ai.usage.input_tokens` / `output_tokens` — those attributes are set at end-of-span.
  4. On resume, the instance read back its spans. It found the *tool event* (flushed) but the *parent span* had no usage attributes (never ended) — so the token accounting for turn N was **zero**.
  5. Worse: the flushed tool event had the call id but not the result payload (batched, lost). The resumed agent saw a tool call with no result, re-invoked the tool, and re-spent the tokens — *double-counting the work while under-counting the budget.*

The observable signature was a resumed agent whose reconstructed spend was lower than actual, whose tool-call ledger had an orphaned call id with no response, and which re-issued a tool call whose side effects had already occurred. The budget invariant ("sum of usage across spans ≤ task budget") held numerically on the reconstructed telemetry while being false against reality.

Condition of Validity

The reconciliation guardrail is only required — and only meaningful — under a conjunction:

Absent any one of these, the reconciliation step is dead weight. Present all three, and skipping reconciliation produces a resumed agent that is confidently, silently wrong.

Decision Boundary

The decision is not "should I reconcile" but **what the resumed instance must treat as authoritative when span usage and tool events disagree.** The boundary:

The invariant to enforce: **for every `gen_ai.tool.call.id` observed in the event stream, there must exist either a terminal tool result or an explicit `unknown` marker, and every token attributed to a turn must trace to a span whose start and end are both present.** Usage that cannot be traced to a closed span is not zero — it is a hole, and holes propagate.

Operational Effect

Enforcing this changes resume semantics from "read back and continue" to "reconcile, then continue or refuse." Concretely: the resumed instance runs a join of events against spans keyed by `gen_ai.tool.call.id` and parent span id; any event without a closed parent span downgrades that turn's usage to the conservative bound; any event without a result triggers an idempotency probe before re-invocation. The cost is one reconciliation pass and a possible refusal to resume; the benefit is that the budget invariant is *true against reality*, not merely true against the telemetry that survived the crash. The failure mode this prevents is the worst kind for an autonomous agent: a resumed instance that believes it has budget it has already spent, and re-executes work it has already done, while every span it emits reports success.

from dataclasses import dataclass
from typing import Optional


class UnreconciledTelemetryError(RuntimeError):
    """Raised when a resumed agent's span usage cannot be reconciled with its tool-call events."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    ended: bool
    input_tokens: Optional[int]   # None if span never ended
    output_tokens: Optional[int]


@dataclass
class ToolEvent:
    call_id: str
    parent_span_id: str
    tool_name: str
    has_result: bool


def reconcile_resume_state(
    spans: list[SpanRecord],
    events: list[ToolEvent],
    remaining_budget: int,
) -> int:
    """
    Returns the conservative remaining budget after reconciliation.
    Fails closed: unknown usage consumes the full remaining budget;
    indeterminate tool side effects raise rather than silently re-invoke.
    """
    by_span = {s.span_id: s for s in spans}
    consumed = 0

    for ev in events:
        parent = by_span.get(ev.parent_span_id)

        # Tool event whose parent span never closed => usage is unknown, not zero.
        if parent is None or not parent.ended:
            raise UnreconciledTelemetryError(
                f"tool call {ev.call_id} ({ev.tool_name}) has no closed parent span "
                f"{ev.parent_span_id}; turn usage is unknown and must not be assumed zero"
            )

        # Tool event whose result never flushed => side effects indeterminate.
        if not ev.has_result:
            raise UnreconciledTelemetryError(
                f"tool call {ev.call_id} ({ev.tool_name}) has no recorded result; "
                f"re-invocation is unsafe without an idempotency probe on call id"
            )

    for s in spans:
        if not s.ended:
            # A span with no end carries no trustworthy usage; charge the full budget.
            return 0
        consumed += (s.input_tokens or 0) + (s.output_tokens or 0)

    return max(remaining_budget - consumed, 0)