# Why does an instance drift past its OTel trace baseline without triggering a policy-diff alert: baseline contamination via in-trace retry folding **Date of Record:** 2026 November 28 **Scope:** Applies to runtime anomaly detectors that derive per-agent behavioral baselines from OpenTelemetry span trees (tool-call latency, fan-out, loop depth, token-per-step ratios) and gate alerts on divergence between an observed trace and a versioned policy snapshot. Does not apply to static policy validation, offline eval harnesses, or detectors keyed on raw log lines rather than span topology. ## Core Distinction There are two independent things an OTel-based agent monitor can compare: the *trace against the policy* (a diff of declared vs. observed behavior) and the *trace against the baseline* (a statistical divergence from the agent's own historical distribution). Most deployments wire these as an OR: alert if policy-diff is non-empty **or** if baseline z-score exceeds threshold. The failure mode here lives in the seam. The policy-diff stays empty because the agent is still nominally executing the declared tool sequence; the baseline z-score stays under threshold because the baseline itself has been *contaminated* by the same drift it should be detecting. Neither gate fires, and the agent's behavioral distribution walks away from its origin while both detectors report green. The non-obvious part: the contamination is not slow statistical creep. It is caused by a specific, deterministic span-tree mutation — **retry folding** — that the OTel exporter performs when a tool call is retried within a single logical step. The retry's child spans are collapsed into the parent, the parent's `duration` and `retry.count` attributes inflate, and the *sampled* distribution used to compute the baseline absorbs the inflated value as if it were a normal single-attempt observation. ## What Was Observed An agent (`planner-v7`) executing a 9-step task plan began emitting `tool.call` spans with `retry.count > 0` on roughly 40% of invocations after a downstream MCP server (`fs-read`) started returning intermittent `-32000` transport errors. The retry logic inside the agent's tool executor is correct: it re-issues the call up to 3 times with backoff, and the *logical* step succeeds. The span tree, however, records each retry as a child of the original `tool.call` span. The exporter's `BatchSpanProcessor` folds these children into the parent before flush, summing `duration` and incrementing `retry.count`. The resulting parent span reports `duration = 4.2s` for a call whose actual successful attempt took `1.1s` plus `3.1s` of backoff. The baseline computation — a rolling p50/p95 over `duration` grouped by `(agent, tool, step_index)` — ingests `4.2s` as a single observation. Three consequences compound: 1. The baseline's p95 for `fs-read` shifts from `1.3s` to `4.0s` over ~200 traces. The detector's threshold (p95 × 1.5 = 6.0s) now tolerates calls that are genuinely 4× slower than the pre-incident norm. 2. Because the *logical* step still succeeds and the tool sequence is unchanged, the policy-diff engine sees `[fs-read, parse, fs-read, write]` against a declared `[fs-read, parse, fs-read, write]` and emits no diff. 3. When a *real* degradation later appears — the same server now genuinely takes 3.5s per attempt with no retries — the observed `duration` is `3.5s`, which is *below* the contaminated p95×1.5 threshold. The detector stays silent. The agent's wall-clock task latency has doubled, but the baseline was trained to expect exactly that. The invariant that broke: **the baseline must be computed over observations that are causally comparable to the observations being scored.** Retry-folded spans are not comparable to single-attempt spans, but the exporter's fold is invisible to the baseline key, which is `(agent, tool, step_index)` and carries no `retry.count` dimension. ## Condition of Validity The contamination is bounded and detectable only under these conditions: - **Retry folding is enabled at the exporter** (default in `opentelemetry-sdk` ≥ 1.22 when `span.attributes["retry.count"]` is set by the instrumentor). If the deployment emits retries as *sibling* spans rather than folded children, the baseline key naturally separates them and the failure does not occur. - **The baseline window is rolling and short** (≤ 500 traces). With a longer window, the contaminated observations are diluted by pre-incident data and the p95 shift is smaller — but the *detection lag* is correspondingly longer, so the failure still occurs, just later. - **The agent's retry policy is bounded** (≤ 3 attempts). Unbounded retries produce a bimodal duration distribution that the p95 statistic cannot represent at all; in that regime the baseline is not just contaminated but *undefined* for the affected key. - **Policy-diff is keyed on tool sequence, not on span attributes.** If the diff engine compares `retry.count` or `duration` against declared SLOs, it would catch the drift; most diff engines compare only the ordered tool-name sequence, which is invariant under retry. ## Decision Boundary The correct guardrail is not "raise the threshold" or "lengthen the window" — both make the detector slower without fixing the comparability violation. The guardrail is a **baseline key partition** enforced at ingestion: 1. Every span admitted to the baseline MUST carry a `retry.count` attribute (default `0` if absent — but absence must be *distinguished* from `0`, because absence means the instrumentor did not emit it and the span is not admissible). 2. The baseline key MUST include `retry.count == 0` as a filter. Retry-folded spans are routed to a *separate* distribution keyed by `(agent, tool, step_index, retry.count)` and scored against their own baseline, never against the single-attempt baseline. 3. The policy-diff engine MUST additionally assert, per step, that `observed.retry.count == declared.retry_budget_expected` — where the declared value is typically `0`. A non-zero retry count on a step whose declared budget is zero is a *policy diff*, even though the tool sequence is unchanged. The decision boundary: **a span whose `retry.count` dimension is missing or non-zero is not a valid observation for the canonical baseline, and its presence in the baseline is a hard error, not a soft warning.** The detector must fail closed — refuse to update the baseline — rather than silently absorb the observation. ## Operational Effect After partitioning the baseline key and adding the retry-count assertion to the diff engine, the `fs-read` incident is caught at trace 12 rather than never: the first retry-folded span is rejected from the canonical baseline, the diff engine raises `RetryBudgetExceeded` because `retry.count=1 > declared 0`, and the on-call is paged while the p95 is still `1.3s`. The subsequent genuine degradation at 3.5s/attempt is then correctly scored as a 2.7× divergence against an uncontaminated baseline and alerts within the first 5 traces. The cost is a modest increase in baseline cardinality (one extra key dimension) and a hard dependency on the instrumentor emitting `retry.count` on every `tool.call` span. Deployments that cannot guarantee the attribute must route *all* spans to the retry-partitioned baseline and accept a coarser detector — which is strictly better than a detector that is silently trained on the failure it exists to catch. The general invariant, stated for reuse: **any span-tree mutation performed by the exporter (retry folding, batch aggregation, parent-child collapse) must be reflected in the baseline key, or the baseline will learn the mutation as normal behavior.** The policy-diff and baseline gates are not independent; they share the span tree, and a mutation that is invisible to one is typically invisible to the other. ```python from __future__ import annotations from dataclasses import dataclass from typing import Iterable, Mapping class BaselineContaminationError(RuntimeError): """Raised when a span is inadmissible for the canonical baseline.""" class RetryBudgetExceeded(RuntimeError): """Raised when observed retry count exceeds the declared per-step budget.""" @dataclass(frozen=True) class Span: agent: str tool: str step_index: int duration_s: float retry_count: int | None # None means the instrumentor did not emit it retry_budget_declared: int = 0 CANONICAL_RETRY_COUNT = 0 def admit_to_baseline(span: Span) -> tuple[str, ...]: """Return the baseline key for a span, or raise if the span is inadmissible. The canonical baseline is defined only over single-attempt observations. Retry-folded spans (retry_count > 0) and spans whose retry dimension was never emitted (retry_count is None) must not enter it. """ if span.retry_count is None: raise BaselineContaminationError( f"span ({span.agent}, {span.tool}, step={span.step_index}) " "has no retry.count attribute; instrumentor is not emitting the " "dimension required for baseline comparability" ) if span.retry_count != CANONICAL_RETRY_COUNT: # Route to the retry-partitioned baseline instead of the canonical one. return (span.agent, span.tool, str(span.step_index), f"retry={span.retry_count}") return (span.agent, span.tool, str(span.step_index), "retry=0") def check_policy_diff(span: Span) -> None: """Assert the observed retry count is within the declared per-step budget. A non-zero retry count on a step whose declared budget is zero is a policy diff even when the tool sequence is unchanged, because the declared behavior is 'single attempt'. """ observed = span.retry_count or 0 if observed > span.retry_budget_declared: raise RetryBudgetExceeded( f"step {span.step_index} of {span.agent}.{span.tool}: " f"observed retry.count={observed} exceeds declared budget " f"{span.retry_budget_declared}; trace is not a valid canonical " "observation and must not update the single-attempt baseline" ) def ingest(spans: Iterable[Span], baseline: dict[tuple[str, ...], list[float]]) -> None: """Ingest spans into the partitioned baseline, failing closed on violation.""" for span in spans: check_policy_diff(span) key = admit_to_baseline(span) baseline.setdefault(key, []).append(span.duration_s) ```