Which invariants prevent OTel retry-storm metrics from silently under-counting agent tool failures

**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OpenTelemetry metrics for tool-call latency, retry attempts, and failure SLOs where retries are re-emitted as new spans under a fresh trace/span context. Does not apply to single-attempt, non-retrying tool invocations or to pure log-based (non-metric) observability pipelines.

Core Distinction

The failure is not "metrics are missing." It is that **the retry path re-attributes a failed attempt to a new span identity, so the failure counter and the retry counter observe disjoint populations.** A tool call that fails twice and succeeds on the third attempt produces, in the naive pipeline, one `tool.failure` datapoint (or zero, if the emitter only counts terminal outcomes) and two `tool.retry` datapoints, while the latency histogram records three samples against three distinct span IDs. The SLO — "fraction of tool calls that succeed within budget" — is computed over a denominator that the retry machinery has already fragmented. The invariant that must hold is *attempt-level accounting*: every physical invocation of a tool, regardless of which logical request spawned it, must increment exactly one attempt counter and exactly one outcome counter, keyed to a stable *logical request ID* that survives retry.

The non-obvious part: this is not a bug in OTel. OTel faithfully records what the agent emits. The agent emits retries as child spans of a *new* parent because the retry loop is re-entered from a fresh reasoning step, and the reasoning step creates a new `trace_id` when the previous context was discarded (context-window eviction, checkpoint/resume, or a sub-agent handoff). The metric pipeline then aggregates by `trace_id` for cardinality control, and the fragmentation becomes invisible at the dashboard layer while corrupting the ratio.

What Was Observed

A retrieval-augmented agent using a `search` tool with a 3-attempt retry policy. The tool endpoint returns HTTP 503 under load. Observed sequence for a single user turn:

  1. Reasoning step 1 emits `tool.search` span, `trace_id=A`, attempt=1. Tool returns 503. Retry policy fires.
  2. Retry loop re-enters the agent's tool-dispatch function. Because the prior turn's message history was truncated to fit the context window, the dispatcher constructs a fresh span with `trace_id=B` and `attempt=1` (the retry counter is local to the dispatch call, not propagated).
  3. Step 2's tool call also 503s. Retry fires again, `trace_id=C`, `attempt=1`.
  4. Step 3 succeeds, `trace_id=D`, `attempt=1`.

The OTel metrics backend, configured with `trace_id` as a resource attribute for sampling, records:

The SLO dashboard reads `failures/attempts` = 0.5, which is *arithmetically* right but *operationally* wrong: it reports a 50% failure rate when the logical request succeeded. Worse, the `retries=0` metric means the retry-storm alert never fires, even though the system is in a retry storm — it is just a storm that has been shredded across trace IDs.

The trigger condition is precise: **the retry loop must re-enter through a code path that reconstructs span context rather than propagating it.** This happens when (a) the retry is driven by the model re-emitting a tool-call message rather than by a deterministic retry wrapper, (b) the agent's checkpoint/resume boundary sits inside the retry loop, or (c) a sub-agent is spawned to perform the retry and the handoff does not carry `trace_id` and `attempt` as baggage.

Condition of Validity

The invariant "attempt counters and outcome counters are partition-aligned" holds only if the following three conditions are simultaneously true:

  1. **Logical request identity is monotonic across retries.** The `logical_request_id` is generated once at the user-turn boundary and injected into every span emitted by any retry, sub-agent, or resumed checkpoint within that turn. It is *not* regenerated by the dispatcher.
  2. **Attempt ordinal is carried as span baggage, not as a local variable.** The `attempt` attribute must be set from a propagated counter (e.g., OTel `Baggage` entry `agent.attempt`) that is incremented in the retry wrapper and read by the span emitter, so that even a context-reconstructed span sees `attempt=2`.
  3. **The metric exporter's aggregation key includes `logical_request_id`, not `trace_id`.** If the backend aggregates by `trace_id`, the fragmentation is reintroduced at the storage layer regardless of what the agent emits.

When any of these is false, the SLO ratio is computed over a denominator that mixes attempts from different logical requests, and the retry-storm counter is structurally zero. This is the boundary: the pipeline is valid for *single-attempt* tools and invalid the moment a retry loop re-enters through a context-reconstruction boundary.

Decision Boundary

The architectural decision is whether to **count at the span layer or at the dispatch layer.** Counting at the span layer (the default) is correct only if span context is propagated through every retry path — which is not guaranteed in agent systems where the retry is model-driven. The guardrail is to move the attempt counter *out* of the span emitter and into a deterministic retry wrapper that owns the `logical_request_id` and `attempt` ordinal, and to emit a single `tool.call.completed` metric with attributes `{logical_request_id, attempt, outcome, latency_ms}` from that wrapper. The span remains for tracing; the metric is derived from the wrapper's state machine, not from span lifecycle events.

The decision boundary is crossed when the retry loop can be entered from a code path that does not have access to the wrapper's state — i.e., when the model itself decides to retry by re-emitting a tool call. In that case, the wrapper must be re-entered with the `logical_request_id` from baggage, and the attempt ordinal must be read from baggage rather than reset. If baggage is absent (context eviction, handoff without propagation), the wrapper must *fail closed*: emit a `tool.call.orphaned` metric and refuse to reset the attempt counter, because a reset is indistinguishable from a genuine new request and will silently under-count.

Operational Effect

The observable consequence of getting this wrong is a **retry storm that is invisible to its own alerting.** The system is in a degraded state — every logical request is taking 3× latency and consuming 3× tool quota — but the SLO dashboard shows a stable failure rate and zero retries. The alert on `retries > threshold` never fires because the counter is structurally zero. The latency p99 looks *better* than reality because the long logical request is split into three short spans, each of which individually met the per-attempt latency budget. Capacity planning under-provisions because the attempt count is right but the *logical request* count is inflated 3×, making per-request cost look lower than it is.

The invariant that prevents this is: **every metric datapoint must be attributable to exactly one logical request and exactly one attempt ordinal, and the pair `(logical_request_id, attempt)` must be unique across the metric stream.** When that holds, `failures/attempts` is the true attempt-level failure rate, `retries` is the true storm signal, and the latency histogram can be re-aggregated by `logical_request_id` to recover the end-to-end latency the user actually experienced. When it does not hold, the pipeline is not merely noisy — it is *directionally wrong*, and it will report health during a storm.

from dataclasses import dataclass, field
from typing import Optional

class MetricPartitionViolation(RuntimeError):
    """Raised when an attempt metric cannot be attributed to a unique (logical_request_id, attempt) pair."""
    pass

@dataclass
class AttemptLedger:
    # key: (logical_request_id, attempt) -> outcome
    seen: dict = field(default_factory=dict)

    def record(self, logical_request_id: str, attempt: int, outcome: str) -> None:
        key = (logical_request_id, attempt)
        if key in self.seen:
            raise MetricPartitionViolation(
                f"duplicate attempt datapoint for {key}: "
                f"already recorded {self.seen[key]!r}, now {outcome!r} — "
                f"retry path likely reset attempt ordinal or regenerated logical_request_id"
            )
        if attempt < 1:
            raise MetricPartitionViolation(
                f"attempt ordinal {attempt} for {logical_request_id} is non-monotonic; "
                f"baggage propagation lost"
            )
        self.seen[key] = outcome

def emit_attempt_metric(ledger: AttemptLedger, logical_request_id: Optional[str],
                        attempt: Optional[int], outcome: str) -> None:
    if logical_request_id is None or attempt is None:
        # Fail closed: an orphaned retry (context evicted, handoff without baggage)
        # must not be silently counted as a fresh attempt=1 request.
        raise MetricPartitionViolation(
            "orphaned tool attempt: logical_request_id or attempt missing from baggage; "
            "refusing to emit attempt=1 to avoid under-counting retry storm"
        )
    ledger.record(logical_request_id, attempt, outcome)