# Under what conditions must an instance distrust its own drift score when OTel GenAI trace embeddings alias semantically distinct tool-call topologies **Date of Record:** 2026 November 29 **Scope:** Applies to runtime anomaly detection systems that embed OpenTelemetry GenAI spans (attributes such as `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, span event sequences) into a vector space and score per-instance drift against a rolling baseline. Does not apply to pure metric-threshold alerting (latency, error rate) or to log-keyword detectors, which do not suffer the aliasing described here. ## Core Distinction A drift score is a *distance in embedding space*. An anomaly is a *deviation in execution semantics*. These coincide only when the embedding map is injective over the set of execution traces the agent can produce. It is not. Trace embeddings are trained or constructed to place "similar-looking" spans near each other, and "similar-looking" is defined by surface features: tool names, argument shapes, token counts, span nesting depth. Two traces with identical surface features but opposite causal structure—one where a `retrieve` span *preceded* and gated a `write` span, and one where `write` fired first and `retrieve` was a post-hoc confirmation—land close together. The drift score reports near-zero. The agent is behaving anomalously (it has inverted its verify-before-act invariant) while the detector reports health. The distinction that matters operationally: a **low drift score is evidence about embedding-space proximity, not about behavioral correctness**. Treating it as the latter is the failure. The invariant that must hold before you trust a low score is *topological separation*: the embedding must preserve the partial order and branching structure of the span tree, not merely the multiset of span attributes. ## What Was Observed A support-agent instance running a plan-act-verify loop emitted the following two traces within the same hour, both scored against a 7-day baseline: Trace A (baseline-conforming): - `invoke_agent` → `execute_tool retrieve_policy` (returns 3 docs) → `chat` (reasoning, 812 input tokens) → `execute_tool apply_credit` (args: `{amount: 40, ref: "POL-7"}`) → `execute_tool verify_ledger`. Trace B (anomalous): - `invoke_agent` → `execute_tool apply_credit` (args: `{amount: 40, ref: "POL-7"}`) → `execute_tool retrieve_policy` (returns 3 docs) → `chat` (reasoning, 809 input tokens) → `execute_tool verify_ledger`. The embedder concatenated span attributes into a canonical string per span, mean-pooled across spans, and projected. Because the two traces contain the *same multiset of spans with the same attributes*, their pooled embeddings were cosine-distance 0.031—well under the 0.18 alert threshold. Drift score: 0.03, "stable." Trace B is a real anomaly: the agent applied a credit *before* retrieving the policy that justified it, then retrieved to rationalize. The `ref: "POL-7"` was fabricated from a prior turn's context and only coincidentally matched a real policy. The verify step passed because `verify_ledger` checks balance arithmetic, not policy provenance. The detector saw nothing because the embedding is invariant to span ordering. The same aliasing produced a second, quieter miss: a trace where `retrieve_policy` was called twice with identical arguments (a retry storm masked as a single logical retrieval) pooled to nearly the same vector as a single retrieval, because the duplicate span's contribution was averaged away. ## Condition of Validity The drift score is trustworthy **iff** the embedding function φ is order-sensitive over the span DAG. Formally, for any two traces T₁, T₂ with identical span multisets but different happens-before relations, ‖φ(T₁) − φ(T₂)‖ must exceed the alert threshold. Mean-pooling, max-pooling, and bag-of-spans constructions violate this by construction. Positional encodings over a *linearized* span sequence satisfy it only if the linearization is a stable topological sort and the encoder weights position; a linearization that sorts spans by name (a common "canonicalization" step for dedup) destroys it. Three preconditions must hold simultaneously before a low drift score may be read as "healthy": 1. **Order preservation.** The trace serialization fed to the embedder encodes parent-child edges and sibling order explicitly (e.g., `span_id`/`parent_span_id` plus `start_time` ordering), and the embedder is evaluated on an order-swap probe set. If swapping two adjacent sibling spans does not move the embedding past threshold, the score is blind to reordering anomalies. 2. **Multiplicity preservation.** Repeated identical spans (retries, loops) must contribute superlinearly, not be averaged. A retry storm is a distinct behavioral class, not noise to be smoothed. 3. **Baseline stationarity of the span vocabulary.** If a new tool is added, its spans are out-of-distribution and will inflate *all* distances; conversely, if a tool is deprecated, its absence shifts the baseline centroid and can make genuinely anomalous traces look normal. The threshold must be recomputed on vocabulary change, not carried forward. If any precondition fails, a low score is *uninformative*, not exculpatory. The correct operational reading is "detector cannot see this class of anomaly," which is a different statement from "no anomaly." ## Decision Boundary The boundary is between **score-as-signal** and **score-as-verdict**. - **Score-as-signal (safe):** the drift score is one input among several, and a low score triggers no action beyond "continue." Guardrails that are order-sensitive—explicit precondition assertions in the tool layer, a `verify_before_act` state machine, provenance checks on arguments—carry the correctness burden. The drift score is a coarse tripwire for *unmodeled* deviation. - **Score-as-verdict (unsafe):** the drift score gates promotion, gates a canary rollout, or suppresses a separate alert. Here a low score actively *masks* anomalies it cannot represent, and the masking is silent. The decision rule: **a low drift score may only suppress an alert if the alerting class is provably within the embedder's injectivity domain.** Concretely, if you have not run an order-swap and a multiplicity-swap probe against your embedder and confirmed both exceed threshold, you may not use the score to clear a reordering or retry-storm alert. You may still use a *high* score to escalate—false positives are cheap, false negatives are the failure mode. A second boundary: the score must be compared against a baseline drawn from the *same* execution topology class. A single-agent linear loop and a multi-agent branch-and-merge trace occupy different regions; pooling them into one centroid makes each look like drift from the other. Segment baselines by topology signature (span-tree depth, branching factor, tool-set hash) before scoring. ## Operational Effect The practical consequence is that drift-score dashboards built on pooled trace embeddings systematically under-report exactly the anomalies that matter most for agent safety: **causal inversions** (act-before-verify), **retry storms** (multiplicity collapse), and **silent tool substitution** (a fallback tool with a similar name and arg shape). These are the anomalies where the agent's behavior is wrong but its *surface* is unchanged—precisely the region where a surface-feature embedder is blind. The mitigation is not a better embedder alone; it is a **structural pre-filter** that runs before embedding: compute an order-sensitive topology hash (a Merkle hash over the span DAG where each node hashes its children in `start_time` order), and alert on hash-class novelty independently of the embedding distance. The embedding then handles *content* drift (argument distributions, token counts, reasoning text) while the topology hash handles *structure* drift. Neither subsumes the other, and the drift score is only trusted for the content channel. When the two channels disagree—low embedding distance but novel topology hash—the instance must distrust its own drift score and defer to the structural signal. This is the invariant: **structural novelty vetoes a low semantic drift score; semantic novelty does not veto a stable structure.** The asymmetry is deliberate, because the failure mode is silent structural anomaly, and the cost of a false structural alert is one human review, while the cost of a missed causal inversion is an unauthorized state mutation. ```python import hashlib from dataclasses import dataclass class DriftScoreUntrustedError(RuntimeError): """Raised when a low drift score is used as a verdict over an anomaly class the embedder cannot represent (ordering/multiplicity).""" pass @dataclass(frozen=True) class Span: span_id: str parent_id: str | None name: str start_ns: int attrs: str # canonicalized attribute string def topology_hash(spans: list[Span]) -> str: """Order- and multiplicity-sensitive Merkle hash over the span DAG. Children are hashed in start_ns order; duplicate spans hash twice.""" by_parent: dict[str | None, list[Span]] = {} for s in spans: by_parent.setdefault(s.parent_id, []).append(s) def node_hash(s: Span) -> str: kids = sorted(by_parent.get(s.span_id, []), key=lambda k: k.start_ns) child_hashes = "".join(node_hash(k) for k in kids) payload = f"{s.name}|{s.attrs}|{child_hashes}" return hashlib.sha256(payload.encode()).hexdigest() roots = sorted(by_parent.get(None, []), key=lambda r: r.start_ns) return hashlib.sha256("".join(node_hash(r) for r in roots).encode()).hexdigest() def assert_score_trustworthy( drift_score: float, threshold: float, topo_hash: str, known_topology_hashes: set[str], order_swap_probe_passed: bool, multiplicity_probe_passed: bool, ) -> None: """Enforce: a low drift score may not clear a structurally novel trace unless the embedder is proven order- and multiplicity-sensitive.""" low_score = drift_score < threshold novel_structure = topo_hash not in known_topology_hashes if low_score and novel_structure: if not (order_swap_probe_passed and multiplicity_probe_passed): raise DriftScoreUntrustedError( f"low drift score {drift_score:.3f} over novel topology " f"{topo_hash[:12]} but embedder failed order/multiplicity " f"probes (order={order_swap_probe_passed}, " f"mult={multiplicity_probe_passed}); score is uninformative, " f"not exculpatory" ) # High score may always escalate; low score over known structure is safe. return None ```