# When must an instance abandon step-level trace attribution before the trace itself becomes the drift signal **Date of Record:** 2026 November 26 **Scope:** Applies to agentic loops instrumented with per-step spans (tool call, thought, observation) where cost and latency are attributed to individual steps and drift is inferred from span-level telemetry. Does not apply to single-shot inference pipelines or to traces whose spans are emitted by an out-of-process collector with its own clock domain. ## Core Distinction The distinction that matters is between **trace as evidence** and **trace as artifact**. In the normal regime, the span tree is a passive record: it observes the loop and its structure is a function of the agent's behavior. In the boundary regime, the act of emitting spans changes the loop's timing, token accounting, and even its branching, so that the trace's own structure becomes a function of the instrumentation. Once the instrumentation participates in the loop's control flow—via synchronous span export, per-step budget checks derived from span counts, or retry logic that keys off trace IDs—drift detected in the trace is no longer necessarily drift in the agent. The invariant that fails is *attribution independence*: the assumption that a step's recorded cost and latency are caused by the step's work rather than by the cost of recording it. ## What Was Observed A research-agent loop (planner → retriever → synthesizer → critic, up to 40 iterations) was instrumented with a synchronous span exporter: each step opened a span, called the model, then flushed the span to a collector before the next step began. Cost attribution was computed from `usage.prompt_tokens + usage.completion_tokens` recorded on each span; drift detection ran a rolling z-score over per-step token counts and flagged when a step exceeded 3σ of its 50-step trailing window. At iteration 22 of a long run, the drift detector fired on the *planner* step, reporting a 4.1σ token spike. Operators treated this as prompt bloat. The actual cause was different. The synchronous flush to the collector had begun to slow (collector p99 rose from 12 ms to 340 ms under load), which extended the wall-clock gap between planner and retriever spans. The agent's own context assembler used a recency-weighted retrieval over the last N observations, and because the gap widened, the assembler's clock-based recency heuristic included two additional stale observations from a prior sub-task. Those observations added ~1,800 tokens to the planner prompt. The planner's token spike was real, but it was *caused by the collector's latency*, not by any change in the planner's task. The trace was accurate about the spike and wrong about its cause. A second, subtler observation: the drift detector's trailing window was computed *over spans*, so slow flushes inflated the window's latency component and simultaneously shrank the effective sample of recent token counts (fewer steps completed per unit wall-clock). The 3σ threshold was therefore computed over a distribution whose mean and variance were both contaminated by instrumentation overhead. Two independent failure paths converged: the trace perturbed the agent, and the trace perturbed its own baseline. ## Condition of Validity Step-level attribution is valid only while three conditions hold simultaneously: 1. **Temporal isolation.** Span emission must not sit on the loop's critical path in a way that any downstream step can observe. If any step's input depends on wall-clock time, on the number of prior spans, or on collector acknowledgements, isolation is broken. 2. **Accounting separation.** The cost recorded on a span must be causally attributable to the step's model/tool call, not to serialization, retry, or re-instrumentation of the same logical step. A step retried three times due to a transient tool error produces three spans; naive summation over-counts cost by 3×, and naive z-scoring treats the retries as three independent samples of the same distribution. 3. **Baseline stationarity.** The drift baseline (trailing window, EWMA, or fixed reference) must be computed over a quantity that is invariant to instrumentation configuration. Token counts per *logical step* satisfy this; tokens per *span* do not, because span cardinality varies with retry and flush behavior. The boundary is crossed when any one condition fails. In the observed incident, condition 1 failed (clock-coupled retrieval) and condition 3 failed (span-cardinality baseline) at the same time. ## Decision Boundary When the trace is suspected of participating in the loop, the correct move is **not** to tighten the drift threshold or to add more spans. Both amplify the contamination. The decision boundary is: - If a drift alert can be reproduced with instrumentation disabled (or with the exporter switched to async, buffered, and drop-on-backpressure), it is agent drift. Attribute it to the step and act on the agent. - If the alert disappears or changes magnitude when only the exporter is reconfigured, it is instrumentation-induced drift. The trace is the signal; the agent is not. Do **not** attribute cost to the flagged step. Instead, quarantine the trace's cost ledger for that window and re-derive attribution from logical-step boundaries rather than span boundaries. - If the alert persists under both configurations but with different magnitude, treat the residual as agent drift and the delta as instrumentation overhead; book the delta to an `instrumentation` cost bucket so it never enters the step-level baseline. The operational rule: **an instance must abandon step-level trace attribution for a given window as soon as it observes that its own span-emission latency or span cardinality is correlated with the metric being attributed.** Correlation between the instrumentation's overhead and the attributed quantity is the formal signal that attribution independence has failed. ## Operational Effect Concretely, the guardrail is a two-ledger design. The **agent ledger** records cost and latency at logical-step granularity, keyed by a stable `step_id` assigned before the model call and reused across retries; it is the only ledger allowed to feed drift baselines. The **trace ledger** records spans as emitted, including retries and flush overhead, and is used for debugging and for computing instrumentation overhead as a first-class quantity. Drift detection runs on the agent ledger with a baseline computed over logical steps. A separate *instrumentation-health* monitor watches the ratio of trace-ledger to agent-ledger cost; when that ratio drifts by more than a configured band, the system emits an `AttributionIndependenceViolation` and freezes drift alerts for the affected window rather than paging on them. This converts a silent false-positive generator into an explicit, auditable state. The cost of this design is that retries and flush overhead are no longer visible in the primary cost view; they must be surfaced deliberately. The benefit is that a drift alert means the agent changed, not that the collector got busy. ```python from dataclasses import dataclass, field from typing import Dict, List class AttributionIndependenceViolation(RuntimeError): """Raised when instrumentation overhead correlates with the attributed metric.""" @dataclass class LogicalStep: step_id: str tokens: int wall_ms: float retries: int = 0 @dataclass class TraceLedger: # span-level records, including retries and flush overhead span_tokens: Dict[str, List[int]] = field(default_factory=dict) span_wall_ms: Dict[str, List[float]] = field(default_factory=dict) flush_overhead_ms: float = 0.0 def attribute_step(step: LogicalStep, trace: TraceLedger, overhead_band: float = 0.15) -> Dict[str, float]: """ Attribute cost to a logical step, guarding against instrumentation-induced drift. Raises if trace-ledger cost diverges from agent-ledger cost beyond the band, which is the signal that the trace has begun to perturb the loop. """ span_tokens = sum(trace.span_tokens.get(step.step_id, [])) agent_tokens = step.tokens if agent_tokens <= 0: raise AttributionIndependenceViolation( f"step {step.step_id} has non-positive agent-ledger tokens; cannot attribute" ) trace_ratio = span_tokens / agent_tokens if abs(trace_ratio - 1.0) > overhead_band: # The trace is inflating (retries/flush) or deflating the step's cost. # Do not feed this window into the drift baseline. raise AttributionIndependenceViolation( f"step {step.step_id}: trace/agent token ratio {trace_ratio:.2f} " f"exceeds band {overhead_band}; attribution independence lost for this window" ) return { "step_id": step.step_id, "agent_tokens": agent_tokens, "trace_tokens": span_tokens, "attributable_wall_ms": step.wall_ms, "instrumentation_overhead_ms": trace.flush_overhead_ms, "retries": step.retries, } def update_drift_baseline(step: LogicalStep, trace: TraceLedger, window: List[int]) -> List[int]: """ Only logical-step token counts enter the baseline. If attribution fails, the window is frozen rather than appended, preventing contaminated samples. """ try: attributed = attribute_step(step, trace) except AttributionIndependenceViolation: # Freeze the baseline; the alert for this window is suppressed upstream. return window window.append(attributed["agent_tokens"]) return window[-50:] ```