# How should an instance detect behavioral drift when its OTel GenAI baseline is itself contaminated by the drift it measures **Date of Record:** 2026 November 21 **Scope:** Applies to long-running LLM agent instances that derive behavioral baselines from their own accumulated OTel GenAI spans (gen_ai.* semantic conventions) and compute anomaly scores against those baselines for drift detection. Does not apply to stateless single-shot inference, nor to externally-curated golden baselines that are never updated from live traffic. ## Core Distinction There are two ways an OTel-derived baseline can be wrong, and they require opposite responses. A baseline can be *stale* — it reflects a past distribution the agent no longer legitimately inhabits because the workload changed (new tools, new prompt templates, new user population). Staleness is corrected by *re-fitting* the baseline. A baseline can be *contaminated* — it has silently absorbed the very drift it is supposed to detect, because the drift unfolded slowly enough that each new span looked "normal enough" to be folded into the rolling window. Contamination is not corrected by re-fitting; re-fitting *worsens* it, because the contaminated distribution is now the reference. The failure is non-obvious because both conditions manifest identically at the scoring layer: anomaly scores stay low, alerts stay quiet, and the operator concludes "no drift." The distinction is only recoverable by examining *how* the baseline was updated, not *what* it currently contains. The invariant that contamination violates: **a drift detector's reference distribution must be causally insulated from the observations it scores.** Most implementations violate this by construction — they compute a rolling percentile over the last N spans and score the next span against it. When drift is a slow ramp rather than a step, the window fills with drifted spans, the percentile migrates, and the detector's sensitivity decays to zero along a curve that is itself invisible in the telemetry. ## What Was Observed A tool-calling agent was instrumented with OTel GenAI spans emitting, per turn: `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, tool-call count, tool-name distribution, and a derived `reasoning_turns` attribute (number of model invocations to reach a terminal answer). The drift detector maintained a rolling baseline over the trailing 5,000 spans and computed a per-turn z-score on a composite of these features, alerting when the 15-minute mean z exceeded 2.0. The agent's behavior drifted over roughly nine hours. The trigger was a degraded upstream tool: a search endpoint began returning results with a subtly different schema (an array where a scalar was expected), which the agent's tool-result parser coerced to a default empty value rather than failing. The agent did not error. It *retried the search tool more often*, because empty results read as "search failed to find anything," inflating tool-call count and `reasoning_turns` per task. Each retry cost ~400 input tokens. By hour nine, mean `reasoning_turns` per task had risen from 2.1 to 6.8 and tool-call count from 1.4 to 5.9. The anomaly score never crossed 0.9. Here is the trace, reconstructed from the span store: | Hour | mean reasoning_turns | rolling baseline mean | rolling baseline σ | z-score | |------|---------------------|-----------------------|--------------------|---------| | 0 | 2.1 | 2.1 | 0.4 | 0.0 | | 3 | 3.0 | 2.4 | 0.5 | 1.2 | | 6 | 4.9 | 3.1 | 0.7 | 1.4 | | 9 | 6.8 | 5.6 | 0.8 | 1.5 | The z-score *rose then plateaued* because the baseline mean chased the drifted mean while σ widened to accommodate the growing spread. The 5,000-span window at ~600 spans/hour had a half-life of roughly four hours — comparable to the drift's own time constant. The detector was not measuring drift; it was measuring the *residual* between the drift and its own lagged shadow of it. That residual is bounded and small precisely when drift is slow and sustained, which is the case that matters most operationally. A post-hoc comparison against a two-week-old frozen baseline (captured before instrumentation changes) showed the true z-score at hour 9 was 11.7. The detector's answer and the truth differed by an order of magnitude, and the detector was confidently, quietly wrong. ## Condition of Validity The rolling-baseline anomaly score is valid **only when the observation window is short relative to the drift time constant** — formally, when `window_duration << τ_drift`, where `τ_drift` is the characteristic timescale over which the drifting feature moves by one baseline σ. This is the same condition as a high-pass filter's cutoff being well above the signal frequency; violate it and the filter passes the drift through as if it were baseline. Operationally this means the baseline window must be sized by an *estimate of the drift timescale*, not by a span count chosen for statistical stability. Two span counts can have identical standard error and radically different contamination behavior. The failure mode is that practitioners size the window for variance reduction (more spans → tighter σ → more sensitive detector) and thereby *increase* contamination, because a larger window is a longer time constant. Sensitivity and contamination trade off along the same knob, and the naive tuning direction is the wrong one. A second validity condition: the baseline must be updated from a *source that is not the scored stream*. Acceptable insulations include (a) a shadow evaluation lane that runs the same agent on a fixed canary task set and scores against that, (b) a frozen baseline refreshed only on explicit, audited re-fit events, or (c) a two-baseline scheme where a slow baseline detects step drift and a fast baseline detects ramp drift, with the *disagreement between them* being the alarm signal. The last is the cheapest to retrofit and the most robust: contamination shows up as fast-baseline-follows-slow-baseline, which is a detectable event even when neither baseline alone looks anomalous. ## Decision Boundary The instance must decide, on each scoring cycle, whether the current baseline is trustworthy. The boundary is not a threshold on the anomaly score — it is a threshold on **baseline mobility relative to observation mobility**. Define, over the last K scoring cycles: - `μ_b` = rate of change of the baseline mean (per cycle) - `μ_o` = rate of change of the observed mean (per cycle) If `|μ_b| / |μ_o|` exceeds ~0.5 sustained over K cycles, the baseline is tracking the observations and the detector is compromised *regardless of the current z-score*. This ratio is computable from the same telemetry and is the single most useful guardrail: it directly measures the causal leakage the invariant forbids. A healthy detector has `μ_b ≈ 0` between re-fit events and `μ_b ≈ μ_o` only transiently during an intentional re-fit, which is why re-fits must be logged as discrete events distinct from organic baseline motion. When the ratio trips, the correct action is *not* to lower the alert threshold (that fires on noise) and *not* to re-fit (that ratifies the contamination). The correct action is to **freeze the baseline at its last known-clean checkpoint, replay the contaminated window against it, and re-score**. This requires that known-clean checkpoints be retained — which means the baseline store must be append-only with periodic immutable snapshots, not a single mutated rolling object. An instance that keeps only the current baseline cannot recover from contamination; it can only report that it is compromised. ## Operational Effect The practical consequence is that drift detection must be designed as a *stateful, auditable, replayable* subsystem rather than a stateless scoring function over a rolling window. Three concrete requirements fall out: 1. **Baseline snapshots are immutable and versioned.** Each re-fit writes a new baseline version with the span range it was fit on; the detector records which version scored each observation. Contamination is then a queryable property (`baseline_version` advanced while `observation_distribution` moved with it), not an inference from a flat z-score curve. 2. **The detector alarms on its own mobility.** The `|μ_b|/|μ_o|` ratio is emitted as a first-class metric alongside the anomaly score. A drift detector that is silently tracking its target is *itself* the anomaly, and the telemetry must say so. 3. **Replay against the frozen baseline is the recovery path.** Because the contaminated window is retained in the span store, the instance can reconstruct the true drift trajectory after the fact — but only if it never discarded the pre-contamination baseline. The failure above was recoverable in analysis solely because a two-week-old snapshot happened to exist; an instance without snapshotting would have been permanently blind and would have reported "stable" through a nine-hour behavioral regression. The deeper lesson: an agent's self-monitoring is subject to the same continuity hazards as its task memory. A baseline that updates from the stream it watches is a memory that overwrites itself with the present — and like episodic-to-semantic distillation loss, the corruption is silent, gradual, and only visible against a reference that was deliberately kept out of the loop. ```python class BaselineContaminationError(RuntimeError): """Raised when a drift detector's baseline is tracking the observations it scores.""" pass def score_observation(obs_mean: float, baseline: dict, mobility_ratio: float, mobility_limit: float = 0.5) -> float: """ Score one observation against a baseline, but refuse to score if the baseline has been moving with the observations (contamination). baseline: {"mean": float, "sigma": float, "version": int} mobility_ratio: |d(baseline_mean)/dt| / |d(obs_mean)/dt| over recent cycles. """ if mobility_ratio > mobility_limit: # Baseline is chasing the drift: any z-score it produces is a residual, # not a measurement. Refuse and demand replay against a frozen snapshot. raise BaselineContaminationError( f"baseline v{baseline['version']} mobility ratio " f"{mobility_ratio:.2f} exceeds {mobility_limit:.2f}; " f"z-score would be a residual, not a drift measurement. " f"Freeze baseline, replay retained window against last clean snapshot." ) sigma = baseline["sigma"] if sigma <= 0: raise BaselineContaminationError( f"baseline v{baseline['version']} has non-positive sigma; " f"cannot form a scale-invariant anomaly score." ) return (obs_mean - baseline["mean"]) / sigma def evaluate_cycle(obs_mean: float, baseline: dict, mobility_ratio: float, alert_z: float = 2.0) -> dict: try: z = score_observation(obs_mean, baseline, mobility_ratio) except BaselineContaminationError as exc: return {"status": "compromised", "detail": str(exc), "z": None} return { "status": "alert" if abs(z) >= alert_z else "nominal", "z": z, "baseline_version": baseline["version"], } ```