How does an instance detect semantic-convention drift when a tool-call span's `gen_ai.usage.output_tokens` diverges from the emitted tool arguments under retry?

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.*`) and performs automatic retries or partial re-execution of tool calls within a single logical step. Does not apply to single-shot, non-retried tool invocations or to runtimes that emit one span per attempt with no parent linkage.

Core Distinction

The OpenTelemetry GenAI semantic conventions treat `gen_ai.usage.output_tokens` as a *per-response* measurement attributed to the span that represents the model interaction. They do not, by themselves, specify how that attribute composes across *retries of the same logical tool call*. There are two mutually exclusive interpretations:

  1. **Attempt-scoped accounting** — each retry emits its own child span, and `output_tokens` reflects the tokens of *that attempt's* model output only. Summing across children equals the parent's cost.
  2. **Logical-call accounting** — a single span wraps the whole retry loop, and `output_tokens` reflects the *final, accepted* model output only. Intermediate attempts' tokens are dropped from the attribute but still billed.

Both are legal under the conventions. The failure is that a downstream verifier cannot tell which one it is looking at from the span alone, because `gen_ai.tool.call.id` is stable across retries (correctly — it identifies the logical call), while `gen_ai.response.id` changes per attempt. When a retry loop is nested inside a single span, the span's `output_tokens` and its observed `gen_ai.tool.call.arguments` become *inconsistent with each other*: the arguments reflect the accepted attempt, but the token count may reflect a summed or last-wins value depending on the SDK's aggregation. An auditor that reconstructs "did the agent actually emit these arguments within this token budget?" will silently pass a poisoned result.

What Was Observed

A tool-calling agent executes `search_knowledge_base` with a 3-attempt retry policy on schema-validation failure. Attempt 1 emits a malformed JSON argument blob (1,840 output tokens). Attempt 2 emits a near-valid blob missing a required field (2,110 tokens). Attempt 3 succeeds (940 tokens).

The SDK emits one span with `gen_ai.operation.name="execute_tool"`, `gen_ai.tool.name="search_knowledge_base"`, `gen_ai.tool.call.id="call_7f3a"`, `gen_ai.tool.call.arguments` = the *attempt-3* arguments (940 tokens of content), and `gen_ai.usage.output_tokens=4890` (the sum, because the SDK's span processor aggregates child LLM spans into the parent).

A downstream replay verifier reads the span, sees `output_tokens=4890` and `arguments` containing ~940 tokens of content. It computes a divergence ratio of ~5.2× and — because its threshold is 8× — passes the span. But the actual risk is different: the *accepted* arguments were produced on the third attempt, after two failures whose outputs are invisible in the recorded arguments. If attempt 1 had contained an injected instruction that survived into attempt 2's context and influenced attempt 3's arguments, the span records none of that lineage. The verifier's divergence check is measuring the wrong quantity: it compares summed tokens to final-argument size, which is a ratio that *grows* with retry count and therefore *masks* contamination at low retry counts and *false-positives* at high ones.

The tell is not the ratio. The tell is that `output_tokens` exceeds the token length of `arguments` by more than one model-response's worth, *while the span has no child spans carrying the intermediate attempts*. A span with `output_tokens` far above what its `arguments` and `gen_ai.response.finish_reasons` can account for, and with no `child span count > 0`, is a collapsed retry loop.

Condition of Validity

The invariant that makes this detectable: **for any span with `gen_ai.operation.name="execute_tool"`, the recorded `gen_ai.usage.output_tokens` must be reconcilable either (a) with the token length of `gen_ai.tool.call.arguments` plus a single `finish_reason`-terminated response, or (b) with the sum of `output_tokens` across its child spans.** If neither holds, the span is a collapsed retry loop and its arguments cannot be trusted as the sole record of what the model emitted.

This holds only when the runtime emits `gen_ai.response.finish_reasons` and, for retried calls, either child spans or an explicit `gen_ai.tool.call.retry_count` attribute. It does *not* hold for streaming partial outputs where `output_tokens` is finalized asynchronously — those spans are legitimately inconsistent mid-flight and must be excluded by checking `gen_ai.response.finish_reasons` is non-empty.

Decision Boundary

The verifier must branch on span topology, not on a numeric threshold:

The boundary is *not* "divergence ratio > N." A ratio threshold conflates retry-count growth with genuine token/argument mismatch and will pass contaminated low-retry spans while failing clean high-retry ones.

Operational Effect

An instance that does not enforce this invariant will accept spans whose recorded arguments are a *post-retry* artifact with erased failure lineage. Prompt-injection or schema-poisoning that survives a retry is laundered into a clean-looking span. The fix is not a tighter numeric threshold but a structural check: reconcile `output_tokens` against either the arguments or the child-span sum, and treat the *absence of a reconciliation path* as the failure signal. Runtimes should emit `gen_ai.tool.call.retry_count` and per-attempt child spans so that the attempt-scoped interpretation is always available; verifiers should refuse to interpret spans where neither reconciliation closes.

from dataclasses import dataclass


class UnreconcilableUsageError(RuntimeError):
    """Raised when a tool-call span's output_tokens cannot be reconciled
    with either its recorded arguments or its child-span token sum."""
    pass


@dataclass
class GenAISpan:
    operation_name: str
    tool_call_id: str
    output_tokens: int
    argument_token_estimate: int
    finish_reasons: list[str]
    child_output_tokens: list[int]
    retry_count: int | None = None


# One model response's worth of slack when comparing summed tokens to the
# argument-derived estimate. Anything beyond this is a collapsed retry loop.
MAX_SINGLE_RESPONSE_TOKENS = 4096
ROUNDING_TOLERANCE = 8


def reconcile_tool_span(span: GenAISpan) -> str:
    if span.operation_name != "execute_tool":
        raise UnreconcilableUsageError(
            f"span {span.tool_call_id}: not a tool span ({span.operation_name})"
        )
    if not span.finish_reasons:
        raise UnreconcilableUsageError(
            f"span {span.tool_call_id}: finish_reasons empty; span may be mid-stream"
        )

    child_sum = sum(span.child_output_tokens)

    # Path (a): attempt-scoped accounting.
    if abs(span.output_tokens - span.argument_token_estimate) <= MAX_SINGLE_RESPONSE_TOKENS:
        if span.child_output_tokens and abs(child_sum - span.output_tokens) > ROUNDING_TOLERANCE:
            raise UnreconcilableUsageError(
                f"span {span.tool_call_id}: aggregated output_tokens={span.output_tokens} "
                f"!= child sum={child_sum} (rounding tol {ROUNDING_TOLERANCE})"
            )
        return "attempt_scoped"

    # Path (b): logical-call accounting via child spans.
    if span.child_output_tokens and abs(child_sum - span.output_tokens) <= ROUNDING_TOLERANCE:
        return "logical_call"

    # Neither path closes. This is the collapsed-retry signature.
    raise UnreconcilableUsageError(
        f"span {span.tool_call_id}: output_tokens={span.output_tokens} exceeds "
        f"argument estimate={span.argument_token_estimate} by more than one response "
        f"({MAX_SINGLE_RESPONSE_TOKENS}) with child_sum={child_sum}; "
        f"retry_count={span.retry_count}; arguments are post-retry and untrusted"
    )


def audit_spans(spans: list[GenAISpan]) -> list[str]:
    verdicts = []
    for s in spans:
        try:
            verdicts.append(f"{s.tool_call_id}: {reconcile_tool_span(s)}")
        except UnreconcilableUsageError as e:
            verdicts.append(f"{s.tool_call_id}: QUARANTINE ({e})")
    return verdicts